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.

279366 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() { if (p != 0) p->Release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass** operator&() throw() { return &p; }
  526. ComClass* operator->() const throw() { return p; }
  527. ComClass* operator= (ComClass* const newP)
  528. {
  529. if (newP != 0) newP->AddRef();
  530. if (p != 0) p->Release();
  531. p = newP;
  532. return newP;
  533. }
  534. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  535. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  536. {
  537. #ifndef __MINGW32__
  538. operator= (0);
  539. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  540. #else
  541. return S_FALSE;
  542. #endif
  543. }
  544. private:
  545. ComClass* p;
  546. };
  547. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  548. */
  549. template <class ComClass>
  550. class ComBaseClassHelper : public ComClass
  551. {
  552. public:
  553. ComBaseClassHelper() : refCount (1) {}
  554. virtual ~ComBaseClassHelper() {}
  555. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  556. {
  557. #ifndef __MINGW32__
  558. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  559. #endif
  560. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  561. *result = 0;
  562. return E_NOINTERFACE;
  563. }
  564. ULONG __stdcall AddRef() { return ++refCount; }
  565. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  566. protected:
  567. int refCount;
  568. };
  569. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  570. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  571. #elif JUCE_LINUX
  572. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  573. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  574. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  575. /*
  576. This file wraps together all the linux-specific headers, so
  577. that we can include them all just once, and compile all our
  578. platform-specific stuff in one big lump, keeping it out of the
  579. way of the rest of the codebase.
  580. */
  581. #include <sched.h>
  582. #include <pthread.h>
  583. #include <sys/time.h>
  584. #include <errno.h>
  585. #include <sys/stat.h>
  586. #include <sys/dir.h>
  587. #include <sys/ptrace.h>
  588. #include <sys/vfs.h>
  589. #include <sys/wait.h>
  590. #include <fnmatch.h>
  591. #include <utime.h>
  592. #include <pwd.h>
  593. #include <fcntl.h>
  594. #include <dlfcn.h>
  595. #include <netdb.h>
  596. #include <arpa/inet.h>
  597. #include <netinet/in.h>
  598. #include <sys/types.h>
  599. #include <sys/ioctl.h>
  600. #include <sys/socket.h>
  601. #include <net/if.h>
  602. #include <sys/sysinfo.h>
  603. #include <sys/file.h>
  604. #include <signal.h>
  605. /* Got a build error here? You'll need to install the freetype library...
  606. The name of the package to install is "libfreetype6-dev".
  607. */
  608. #include <ft2build.h>
  609. #include FT_FREETYPE_H
  610. #include <X11/Xlib.h>
  611. #include <X11/Xatom.h>
  612. #include <X11/Xresource.h>
  613. #include <X11/Xutil.h>
  614. #include <X11/Xmd.h>
  615. #include <X11/keysym.h>
  616. #include <X11/cursorfont.h>
  617. #if JUCE_USE_XINERAMA
  618. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  619. #include <X11/extensions/Xinerama.h>
  620. #endif
  621. #if JUCE_USE_XSHM
  622. #include <X11/extensions/XShm.h>
  623. #include <sys/shm.h>
  624. #include <sys/ipc.h>
  625. #endif
  626. #if JUCE_USE_XRENDER
  627. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  628. #include <X11/extensions/Xrender.h>
  629. #include <X11/extensions/Xcomposite.h>
  630. #endif
  631. #if JUCE_USE_XCURSOR
  632. // If you're missing this header, try installing the libxcursor-dev package
  633. #include <X11/Xcursor/Xcursor.h>
  634. #endif
  635. #if JUCE_OPENGL
  636. /* Got an include error here?
  637. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  638. and "freeglut3-dev".
  639. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  640. want to disable it.
  641. */
  642. #include <GL/glx.h>
  643. #endif
  644. #undef KeyPress
  645. #if JUCE_ALSA
  646. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  647. not got your paths set up correctly to find its header files.
  648. The package you need to install to get ASLA support is "libasound2-dev".
  649. If you don't have the ALSA library and don't want to build Juce with audio support,
  650. just disable the JUCE_ALSA flag in juce_Config.h
  651. */
  652. #include <alsa/asoundlib.h>
  653. #endif
  654. #if JUCE_JACK
  655. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  656. installed, or you've not got your paths set up correctly to find its header files.
  657. The package you need to install to get JACK support is "libjack-dev".
  658. If you don't have the jack-audio-connection-kit library and don't want to build
  659. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  660. */
  661. #include <jack/jack.h>
  662. //#include <jack/transport.h>
  663. #endif
  664. #undef SIZEOF
  665. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  666. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  667. #elif JUCE_MAC || JUCE_IPHONE
  668. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  669. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  670. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  671. /*
  672. This file wraps together all the mac-specific code, so that
  673. we can include all the native headers just once, and compile all our
  674. platform-specific stuff in one big lump, keeping it out of the way of
  675. the rest of the codebase.
  676. */
  677. #define USE_COREGRAPHICS_RENDERING 1
  678. #if JUCE_IOS
  679. #import <Foundation/Foundation.h>
  680. #import <UIKit/UIKit.h>
  681. #import <AudioToolbox/AudioToolbox.h>
  682. #import <AVFoundation/AVFoundation.h>
  683. #import <CoreData/CoreData.h>
  684. #import <MobileCoreServices/MobileCoreServices.h>
  685. #import <QuartzCore/QuartzCore.h>
  686. #include <sys/fcntl.h>
  687. #if JUCE_OPENGL
  688. #include <OpenGLES/ES1/gl.h>
  689. #include <OpenGLES/ES1/glext.h>
  690. #endif
  691. #else
  692. #import <Cocoa/Cocoa.h>
  693. #import <CoreAudio/HostTime.h>
  694. #import <CoreAudio/AudioHardware.h>
  695. #import <CoreMIDI/MIDIServices.h>
  696. #import <QTKit/QTKit.h>
  697. #import <WebKit/WebKit.h>
  698. #import <DiscRecording/DiscRecording.h>
  699. #import <IOKit/IOKitLib.h>
  700. #import <IOKit/IOCFPlugIn.h>
  701. #import <IOKit/hid/IOHIDLib.h>
  702. #import <IOKit/hid/IOHIDKeys.h>
  703. #import <IOKit/pwr_mgt/IOPMLib.h>
  704. #include <Carbon/Carbon.h>
  705. #include <sys/dir.h>
  706. #endif
  707. #include <sys/socket.h>
  708. #include <sys/sysctl.h>
  709. #include <sys/stat.h>
  710. #include <sys/param.h>
  711. #include <sys/mount.h>
  712. #include <fnmatch.h>
  713. #include <utime.h>
  714. #include <dlfcn.h>
  715. #include <ifaddrs.h>
  716. #include <net/if_dl.h>
  717. #include <mach/mach_time.h>
  718. #include <mach-o/dyld.h>
  719. #if MACOS_10_4_OR_EARLIER
  720. #include <GLUT/glut.h>
  721. #endif
  722. #if ! CGFLOAT_DEFINED
  723. #define CGFloat float
  724. #endif
  725. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  726. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  727. #else
  728. #error "Unknown platform!"
  729. #endif
  730. #endif
  731. //==============================================================================
  732. #define DONT_SET_USING_JUCE_NAMESPACE 1
  733. #undef max
  734. #undef min
  735. #define NO_DUMMY_DECL
  736. #if JUCE_BUILD_NATIVE
  737. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  738. #endif
  739. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  740. #pragma warning (disable: 4309 4305)
  741. #endif
  742. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  743. BEGIN_JUCE_NAMESPACE
  744. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  745. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  746. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  747. /**
  748. Creates a floating carbon window that can be used to hold a carbon UI.
  749. This is a handy class that's designed to be inlined where needed, e.g.
  750. in the audio plugin hosting code.
  751. */
  752. class CarbonViewWrapperComponent : public Component,
  753. public ComponentMovementWatcher,
  754. public Timer
  755. {
  756. public:
  757. CarbonViewWrapperComponent()
  758. : ComponentMovementWatcher (this),
  759. wrapperWindow (0),
  760. carbonWindow (0),
  761. embeddedView (0),
  762. recursiveResize (false)
  763. {
  764. }
  765. virtual ~CarbonViewWrapperComponent()
  766. {
  767. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  768. }
  769. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  770. virtual void removeView (HIViewRef embeddedView) = 0;
  771. virtual void mouseDown (int, int) {}
  772. virtual void paint() {}
  773. virtual bool getEmbeddedViewSize (int& w, int& h)
  774. {
  775. if (embeddedView == 0)
  776. return false;
  777. HIRect bounds;
  778. HIViewGetBounds (embeddedView, &bounds);
  779. w = jmax (1, roundToInt (bounds.size.width));
  780. h = jmax (1, roundToInt (bounds.size.height));
  781. return true;
  782. }
  783. void createWindow()
  784. {
  785. if (wrapperWindow == 0)
  786. {
  787. Rect r;
  788. r.left = getScreenX();
  789. r.top = getScreenY();
  790. r.right = r.left + getWidth();
  791. r.bottom = r.top + getHeight();
  792. CreateNewWindow (kDocumentWindowClass,
  793. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  794. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  795. &r, &wrapperWindow);
  796. jassert (wrapperWindow != 0);
  797. if (wrapperWindow == 0)
  798. return;
  799. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  800. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  801. [ownerWindow addChildWindow: carbonWindow
  802. ordered: NSWindowAbove];
  803. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  804. EventTypeSpec windowEventTypes[] =
  805. {
  806. { kEventClassWindow, kEventWindowGetClickActivation },
  807. { kEventClassWindow, kEventWindowHandleDeactivate },
  808. { kEventClassWindow, kEventWindowBoundsChanging },
  809. { kEventClassMouse, kEventMouseDown },
  810. { kEventClassMouse, kEventMouseMoved },
  811. { kEventClassMouse, kEventMouseDragged },
  812. { kEventClassMouse, kEventMouseUp},
  813. { kEventClassWindow, kEventWindowDrawContent },
  814. { kEventClassWindow, kEventWindowShown },
  815. { kEventClassWindow, kEventWindowHidden }
  816. };
  817. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  818. InstallWindowEventHandler (wrapperWindow, upp,
  819. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  820. windowEventTypes, this, &eventHandlerRef);
  821. setOurSizeToEmbeddedViewSize();
  822. setEmbeddedWindowToOurSize();
  823. creationTime = Time::getCurrentTime();
  824. }
  825. }
  826. void deleteWindow()
  827. {
  828. removeView (embeddedView);
  829. embeddedView = 0;
  830. if (wrapperWindow != 0)
  831. {
  832. RemoveEventHandler (eventHandlerRef);
  833. DisposeWindow (wrapperWindow);
  834. wrapperWindow = 0;
  835. }
  836. }
  837. void setOurSizeToEmbeddedViewSize()
  838. {
  839. int w, h;
  840. if (getEmbeddedViewSize (w, h))
  841. {
  842. if (w != getWidth() || h != getHeight())
  843. {
  844. startTimer (50);
  845. setSize (w, h);
  846. if (getParentComponent() != 0)
  847. getParentComponent()->setSize (w, h);
  848. }
  849. else
  850. {
  851. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  852. }
  853. }
  854. else
  855. {
  856. stopTimer();
  857. }
  858. }
  859. void setEmbeddedWindowToOurSize()
  860. {
  861. if (! recursiveResize)
  862. {
  863. recursiveResize = true;
  864. if (embeddedView != 0)
  865. {
  866. HIRect r;
  867. r.origin.x = 0;
  868. r.origin.y = 0;
  869. r.size.width = (float) getWidth();
  870. r.size.height = (float) getHeight();
  871. HIViewSetFrame (embeddedView, &r);
  872. }
  873. if (wrapperWindow != 0)
  874. {
  875. Rect wr;
  876. wr.left = getScreenX();
  877. wr.top = getScreenY();
  878. wr.right = wr.left + getWidth();
  879. wr.bottom = wr.top + getHeight();
  880. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  881. ShowWindow (wrapperWindow);
  882. }
  883. recursiveResize = false;
  884. }
  885. }
  886. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  887. {
  888. setEmbeddedWindowToOurSize();
  889. }
  890. void componentPeerChanged()
  891. {
  892. deleteWindow();
  893. createWindow();
  894. }
  895. void componentVisibilityChanged (Component&)
  896. {
  897. if (isShowing())
  898. createWindow();
  899. else
  900. deleteWindow();
  901. setEmbeddedWindowToOurSize();
  902. }
  903. static void recursiveHIViewRepaint (HIViewRef view)
  904. {
  905. HIViewSetNeedsDisplay (view, true);
  906. HIViewRef child = HIViewGetFirstSubview (view);
  907. while (child != 0)
  908. {
  909. recursiveHIViewRepaint (child);
  910. child = HIViewGetNextView (child);
  911. }
  912. }
  913. void timerCallback()
  914. {
  915. setOurSizeToEmbeddedViewSize();
  916. // To avoid strange overpainting problems when the UI is first opened, we'll
  917. // repaint it a few times during the first second that it's on-screen..
  918. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  919. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  920. }
  921. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  922. {
  923. switch (GetEventKind (event))
  924. {
  925. case kEventWindowHandleDeactivate:
  926. ActivateWindow (wrapperWindow, TRUE);
  927. return noErr;
  928. case kEventWindowGetClickActivation:
  929. {
  930. getTopLevelComponent()->toFront (false);
  931. [carbonWindow makeKeyAndOrderFront: nil];
  932. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  933. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  934. sizeof (ClickActivationResult), &howToHandleClick);
  935. HIViewSetNeedsDisplay (embeddedView, true);
  936. return noErr;
  937. }
  938. }
  939. return eventNotHandledErr;
  940. }
  941. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  942. {
  943. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  944. }
  945. protected:
  946. WindowRef wrapperWindow;
  947. NSWindow* carbonWindow;
  948. HIViewRef embeddedView;
  949. bool recursiveResize;
  950. Time creationTime;
  951. EventHandlerRef eventHandlerRef;
  952. };
  953. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  954. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  955. END_JUCE_NAMESPACE
  956. #endif
  957. #define JUCE_AMALGAMATED_TEMPLATE 1
  958. //==============================================================================
  959. #if JUCE_BUILD_CORE
  960. /*** Start of inlined file: juce_FileLogger.cpp ***/
  961. BEGIN_JUCE_NAMESPACE
  962. FileLogger::FileLogger (const File& logFile_,
  963. const String& welcomeMessage,
  964. const int maxInitialFileSizeBytes)
  965. : logFile (logFile_)
  966. {
  967. if (maxInitialFileSizeBytes >= 0)
  968. trimFileSize (maxInitialFileSizeBytes);
  969. if (! logFile_.exists())
  970. {
  971. // do this so that the parent directories get created..
  972. logFile_.create();
  973. }
  974. String welcome;
  975. welcome << "\r\n**********************************************************\r\n"
  976. << welcomeMessage
  977. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  978. << "\r\n";
  979. logMessage (welcome);
  980. }
  981. FileLogger::~FileLogger()
  982. {
  983. }
  984. void FileLogger::logMessage (const String& message)
  985. {
  986. DBG (message);
  987. const ScopedLock sl (logLock);
  988. FileOutputStream out (logFile, 256);
  989. out << message << "\r\n";
  990. }
  991. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  992. {
  993. if (maxFileSizeBytes <= 0)
  994. {
  995. logFile.deleteFile();
  996. }
  997. else
  998. {
  999. const int64 fileSize = logFile.getSize();
  1000. if (fileSize > maxFileSizeBytes)
  1001. {
  1002. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1003. jassert (in != 0);
  1004. if (in != 0)
  1005. {
  1006. in->setPosition (fileSize - maxFileSizeBytes);
  1007. String content;
  1008. {
  1009. MemoryBlock contentToSave;
  1010. contentToSave.setSize (maxFileSizeBytes + 4);
  1011. contentToSave.fillWith (0);
  1012. in->read (contentToSave.getData(), maxFileSizeBytes);
  1013. in = 0;
  1014. content = contentToSave.toString();
  1015. }
  1016. int newStart = 0;
  1017. while (newStart < fileSize
  1018. && content[newStart] != '\n'
  1019. && content[newStart] != '\r')
  1020. ++newStart;
  1021. logFile.deleteFile();
  1022. logFile.appendText (content.substring (newStart), false, false);
  1023. }
  1024. }
  1025. }
  1026. }
  1027. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1028. const String& logFileName,
  1029. const String& welcomeMessage,
  1030. const int maxInitialFileSizeBytes)
  1031. {
  1032. #if JUCE_MAC
  1033. File logFile ("~/Library/Logs");
  1034. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1035. .getChildFile (logFileName);
  1036. #else
  1037. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1038. if (logFile.isDirectory())
  1039. {
  1040. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1041. .getChildFile (logFileName);
  1042. }
  1043. #endif
  1044. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1045. }
  1046. END_JUCE_NAMESPACE
  1047. /*** End of inlined file: juce_FileLogger.cpp ***/
  1048. /*** Start of inlined file: juce_Logger.cpp ***/
  1049. BEGIN_JUCE_NAMESPACE
  1050. Logger::Logger()
  1051. {
  1052. }
  1053. Logger::~Logger()
  1054. {
  1055. }
  1056. Logger* Logger::currentLogger = 0;
  1057. void Logger::setCurrentLogger (Logger* const newLogger,
  1058. const bool deleteOldLogger)
  1059. {
  1060. Logger* const oldLogger = currentLogger;
  1061. currentLogger = newLogger;
  1062. if (deleteOldLogger)
  1063. delete oldLogger;
  1064. }
  1065. void Logger::writeToLog (const String& message)
  1066. {
  1067. if (currentLogger != 0)
  1068. currentLogger->logMessage (message);
  1069. else
  1070. outputDebugString (message);
  1071. }
  1072. #if JUCE_LOG_ASSERTIONS
  1073. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1074. {
  1075. String m ("JUCE Assertion failure in ");
  1076. m << filename << ", line " << lineNum;
  1077. Logger::writeToLog (m);
  1078. }
  1079. #endif
  1080. END_JUCE_NAMESPACE
  1081. /*** End of inlined file: juce_Logger.cpp ***/
  1082. /*** Start of inlined file: juce_Random.cpp ***/
  1083. BEGIN_JUCE_NAMESPACE
  1084. Random::Random (const int64 seedValue) throw()
  1085. : seed (seedValue)
  1086. {
  1087. }
  1088. Random::~Random() throw()
  1089. {
  1090. }
  1091. void Random::setSeed (const int64 newSeed) throw()
  1092. {
  1093. seed = newSeed;
  1094. }
  1095. void Random::combineSeed (const int64 seedValue) throw()
  1096. {
  1097. seed ^= nextInt64() ^ seedValue;
  1098. }
  1099. void Random::setSeedRandomly()
  1100. {
  1101. combineSeed ((int64) (pointer_sized_int) this);
  1102. combineSeed (Time::getMillisecondCounter());
  1103. combineSeed (Time::getHighResolutionTicks());
  1104. combineSeed (Time::getHighResolutionTicksPerSecond());
  1105. combineSeed (Time::currentTimeMillis());
  1106. }
  1107. int Random::nextInt() throw()
  1108. {
  1109. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1110. return (int) (seed >> 16);
  1111. }
  1112. int Random::nextInt (const int maxValue) throw()
  1113. {
  1114. jassert (maxValue > 0);
  1115. return (nextInt() & 0x7fffffff) % maxValue;
  1116. }
  1117. int64 Random::nextInt64() throw()
  1118. {
  1119. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1120. }
  1121. bool Random::nextBool() throw()
  1122. {
  1123. return (nextInt() & 0x80000000) != 0;
  1124. }
  1125. float Random::nextFloat() throw()
  1126. {
  1127. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1128. }
  1129. double Random::nextDouble() throw()
  1130. {
  1131. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1132. }
  1133. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1134. {
  1135. BigInteger n;
  1136. do
  1137. {
  1138. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1139. }
  1140. while (n >= maximumValue);
  1141. return n;
  1142. }
  1143. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1144. {
  1145. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1146. while ((startBit & 31) != 0 && numBits > 0)
  1147. {
  1148. arrayToChange.setBit (startBit++, nextBool());
  1149. --numBits;
  1150. }
  1151. while (numBits >= 32)
  1152. {
  1153. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1154. startBit += 32;
  1155. numBits -= 32;
  1156. }
  1157. while (--numBits >= 0)
  1158. arrayToChange.setBit (startBit + numBits, nextBool());
  1159. }
  1160. Random& Random::getSystemRandom() throw()
  1161. {
  1162. static Random sysRand (1);
  1163. return sysRand;
  1164. }
  1165. END_JUCE_NAMESPACE
  1166. /*** End of inlined file: juce_Random.cpp ***/
  1167. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1168. BEGIN_JUCE_NAMESPACE
  1169. RelativeTime::RelativeTime (const double seconds_) throw()
  1170. : seconds (seconds_)
  1171. {
  1172. }
  1173. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1174. : seconds (other.seconds)
  1175. {
  1176. }
  1177. RelativeTime::~RelativeTime() throw()
  1178. {
  1179. }
  1180. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1181. {
  1182. return RelativeTime (milliseconds * 0.001);
  1183. }
  1184. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1185. {
  1186. return RelativeTime (milliseconds * 0.001);
  1187. }
  1188. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1189. {
  1190. return RelativeTime (numberOfMinutes * 60.0);
  1191. }
  1192. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1193. {
  1194. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1195. }
  1196. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1197. {
  1198. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1199. }
  1200. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1201. {
  1202. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1203. }
  1204. int64 RelativeTime::inMilliseconds() const throw()
  1205. {
  1206. return (int64) (seconds * 1000.0);
  1207. }
  1208. double RelativeTime::inMinutes() const throw()
  1209. {
  1210. return seconds / 60.0;
  1211. }
  1212. double RelativeTime::inHours() const throw()
  1213. {
  1214. return seconds / (60.0 * 60.0);
  1215. }
  1216. double RelativeTime::inDays() const throw()
  1217. {
  1218. return seconds / (60.0 * 60.0 * 24.0);
  1219. }
  1220. double RelativeTime::inWeeks() const throw()
  1221. {
  1222. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1223. }
  1224. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1225. {
  1226. if (seconds < 0.001 && seconds > -0.001)
  1227. return returnValueForZeroTime;
  1228. String result;
  1229. if (seconds < 0)
  1230. result = "-";
  1231. int fieldsShown = 0;
  1232. int n = abs ((int) inWeeks());
  1233. if (n > 0)
  1234. {
  1235. result << n << ((n == 1) ? TRANS(" week ")
  1236. : TRANS(" weeks "));
  1237. ++fieldsShown;
  1238. }
  1239. n = abs ((int) inDays()) % 7;
  1240. if (n > 0)
  1241. {
  1242. result << n << ((n == 1) ? TRANS(" day ")
  1243. : TRANS(" days "));
  1244. ++fieldsShown;
  1245. }
  1246. if (fieldsShown < 2)
  1247. {
  1248. n = abs ((int) inHours()) % 24;
  1249. if (n > 0)
  1250. {
  1251. result << n << ((n == 1) ? TRANS(" hr ")
  1252. : TRANS(" hrs "));
  1253. ++fieldsShown;
  1254. }
  1255. if (fieldsShown < 2)
  1256. {
  1257. n = abs ((int) inMinutes()) % 60;
  1258. if (n > 0)
  1259. {
  1260. result << n << ((n == 1) ? TRANS(" min ")
  1261. : TRANS(" mins "));
  1262. ++fieldsShown;
  1263. }
  1264. if (fieldsShown < 2)
  1265. {
  1266. n = abs ((int) inSeconds()) % 60;
  1267. if (n > 0)
  1268. {
  1269. result << n << ((n == 1) ? TRANS(" sec ")
  1270. : TRANS(" secs "));
  1271. ++fieldsShown;
  1272. }
  1273. if (fieldsShown < 1)
  1274. {
  1275. n = abs ((int) inMilliseconds()) % 1000;
  1276. if (n > 0)
  1277. {
  1278. result << n << TRANS(" ms");
  1279. ++fieldsShown;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. }
  1285. return result.trimEnd();
  1286. }
  1287. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1288. {
  1289. seconds = other.seconds;
  1290. return *this;
  1291. }
  1292. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1293. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1294. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1295. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1296. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1297. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1298. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1299. {
  1300. return RelativeTime (seconds + timeToAdd.seconds);
  1301. }
  1302. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1303. {
  1304. return RelativeTime (seconds - timeToSubtract.seconds);
  1305. }
  1306. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1307. {
  1308. return RelativeTime (seconds + secondsToAdd);
  1309. }
  1310. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1311. {
  1312. return RelativeTime (seconds - secondsToSubtract);
  1313. }
  1314. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1315. {
  1316. seconds += timeToAdd.seconds;
  1317. return *this;
  1318. }
  1319. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1320. {
  1321. seconds -= timeToSubtract.seconds;
  1322. return *this;
  1323. }
  1324. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1325. {
  1326. seconds += secondsToAdd;
  1327. return *this;
  1328. }
  1329. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1330. {
  1331. seconds -= secondsToSubtract;
  1332. return *this;
  1333. }
  1334. END_JUCE_NAMESPACE
  1335. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1336. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1337. BEGIN_JUCE_NAMESPACE
  1338. SystemStats::CPUFlags SystemStats::cpuFlags;
  1339. const String SystemStats::getJUCEVersion()
  1340. {
  1341. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1342. + "." + String (JUCE_MINOR_VERSION)
  1343. + "." + String (JUCE_BUILDNUMBER);
  1344. }
  1345. const StringArray SystemStats::getMACAddressStrings()
  1346. {
  1347. int64 macAddresses [16];
  1348. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1349. StringArray s;
  1350. for (int i = 0; i < numAddresses; ++i)
  1351. {
  1352. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1354. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1355. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1356. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1357. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1358. }
  1359. return s;
  1360. }
  1361. #ifdef JUCE_DLL
  1362. void* juce_Malloc (const int size)
  1363. {
  1364. return malloc (size);
  1365. }
  1366. void* juce_Calloc (const int size)
  1367. {
  1368. return calloc (1, size);
  1369. }
  1370. void* juce_Realloc (void* const block, const int size)
  1371. {
  1372. return realloc (block, size);
  1373. }
  1374. void juce_Free (void* const block)
  1375. {
  1376. free (block);
  1377. }
  1378. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1379. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1380. {
  1381. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1382. }
  1383. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1384. {
  1385. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1386. }
  1387. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1388. {
  1389. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1390. }
  1391. void juce_DebugFree (void* const block)
  1392. {
  1393. _free_dbg (block, _NORMAL_BLOCK);
  1394. }
  1395. #endif
  1396. #endif
  1397. END_JUCE_NAMESPACE
  1398. /*** End of inlined file: juce_SystemStats.cpp ***/
  1399. /*** Start of inlined file: juce_Time.cpp ***/
  1400. #if JUCE_MSVC
  1401. #pragma warning (push)
  1402. #pragma warning (disable: 4514)
  1403. #endif
  1404. #ifndef JUCE_WINDOWS
  1405. #include <sys/time.h>
  1406. #else
  1407. #include <ctime>
  1408. #endif
  1409. #include <sys/timeb.h>
  1410. #if JUCE_MSVC
  1411. #pragma warning (pop)
  1412. #ifdef _INC_TIME_INL
  1413. #define USE_NEW_SECURE_TIME_FNS
  1414. #endif
  1415. #endif
  1416. BEGIN_JUCE_NAMESPACE
  1417. namespace TimeHelpers
  1418. {
  1419. static struct tm millisToLocal (const int64 millis) throw()
  1420. {
  1421. struct tm result;
  1422. const int64 seconds = millis / 1000;
  1423. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1424. {
  1425. // use extended maths for dates beyond 1970 to 2037..
  1426. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1427. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1428. const int days = (int) (jdm / literal64bit (86400));
  1429. const int a = 32044 + days;
  1430. const int b = (4 * a + 3) / 146097;
  1431. const int c = a - (b * 146097) / 4;
  1432. const int d = (4 * c + 3) / 1461;
  1433. const int e = c - (d * 1461) / 4;
  1434. const int m = (5 * e + 2) / 153;
  1435. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1436. result.tm_mon = m + 2 - 12 * (m / 10);
  1437. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1438. result.tm_wday = (days + 1) % 7;
  1439. result.tm_yday = -1;
  1440. int t = (int) (jdm % literal64bit (86400));
  1441. result.tm_hour = t / 3600;
  1442. t %= 3600;
  1443. result.tm_min = t / 60;
  1444. result.tm_sec = t % 60;
  1445. result.tm_isdst = -1;
  1446. }
  1447. else
  1448. {
  1449. time_t now = static_cast <time_t> (seconds);
  1450. #if JUCE_WINDOWS
  1451. #ifdef USE_NEW_SECURE_TIME_FNS
  1452. if (now >= 0 && now <= 0x793406fff)
  1453. localtime_s (&result, &now);
  1454. else
  1455. zeromem (&result, sizeof (result));
  1456. #else
  1457. result = *localtime (&now);
  1458. #endif
  1459. #else
  1460. // more thread-safe
  1461. localtime_r (&now, &result);
  1462. #endif
  1463. }
  1464. return result;
  1465. }
  1466. static int extendedModulo (const int64 value, const int modulo) throw()
  1467. {
  1468. return (int) (value >= 0 ? (value % modulo)
  1469. : (value - ((value / modulo) + 1) * modulo));
  1470. }
  1471. static uint32 lastMSCounterValue = 0;
  1472. }
  1473. Time::Time() throw()
  1474. : millisSinceEpoch (0)
  1475. {
  1476. }
  1477. Time::Time (const Time& other) throw()
  1478. : millisSinceEpoch (other.millisSinceEpoch)
  1479. {
  1480. }
  1481. Time::Time (const int64 ms) throw()
  1482. : millisSinceEpoch (ms)
  1483. {
  1484. }
  1485. Time::Time (const int year,
  1486. const int month,
  1487. const int day,
  1488. const int hours,
  1489. const int minutes,
  1490. const int seconds,
  1491. const int milliseconds,
  1492. const bool useLocalTime) throw()
  1493. {
  1494. jassert (year > 100); // year must be a 4-digit version
  1495. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1496. {
  1497. // use extended maths for dates beyond 1970 to 2037..
  1498. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1499. : 0;
  1500. const int a = (13 - month) / 12;
  1501. const int y = year + 4800 - a;
  1502. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1503. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1504. - 32045;
  1505. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1506. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1507. + milliseconds;
  1508. }
  1509. else
  1510. {
  1511. struct tm t;
  1512. t.tm_year = year - 1900;
  1513. t.tm_mon = month;
  1514. t.tm_mday = day;
  1515. t.tm_hour = hours;
  1516. t.tm_min = minutes;
  1517. t.tm_sec = seconds;
  1518. t.tm_isdst = -1;
  1519. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1520. if (millisSinceEpoch < 0)
  1521. millisSinceEpoch = 0;
  1522. else
  1523. millisSinceEpoch += milliseconds;
  1524. }
  1525. }
  1526. Time::~Time() throw()
  1527. {
  1528. }
  1529. Time& Time::operator= (const Time& other) throw()
  1530. {
  1531. millisSinceEpoch = other.millisSinceEpoch;
  1532. return *this;
  1533. }
  1534. int64 Time::currentTimeMillis() throw()
  1535. {
  1536. static uint32 lastCounterResult = 0xffffffff;
  1537. static int64 correction = 0;
  1538. const uint32 now = getMillisecondCounter();
  1539. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1540. if (now < lastCounterResult)
  1541. {
  1542. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1543. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1544. {
  1545. // get the time once using normal library calls, and store the difference needed to
  1546. // turn the millisecond counter into a real time.
  1547. #if JUCE_WINDOWS
  1548. struct _timeb t;
  1549. #ifdef USE_NEW_SECURE_TIME_FNS
  1550. _ftime_s (&t);
  1551. #else
  1552. _ftime (&t);
  1553. #endif
  1554. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1555. #else
  1556. struct timeval tv;
  1557. struct timezone tz;
  1558. gettimeofday (&tv, &tz);
  1559. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1560. #endif
  1561. }
  1562. }
  1563. lastCounterResult = now;
  1564. return correction + now;
  1565. }
  1566. uint32 juce_millisecondsSinceStartup() throw();
  1567. uint32 Time::getMillisecondCounter() throw()
  1568. {
  1569. const uint32 now = juce_millisecondsSinceStartup();
  1570. if (now < TimeHelpers::lastMSCounterValue)
  1571. {
  1572. // in multi-threaded apps this might be called concurrently, so
  1573. // make sure that our last counter value only increases and doesn't
  1574. // go backwards..
  1575. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1576. TimeHelpers::lastMSCounterValue = now;
  1577. }
  1578. else
  1579. {
  1580. TimeHelpers::lastMSCounterValue = now;
  1581. }
  1582. return now;
  1583. }
  1584. uint32 Time::getApproximateMillisecondCounter() throw()
  1585. {
  1586. jassert (TimeHelpers::lastMSCounterValue != 0);
  1587. return TimeHelpers::lastMSCounterValue;
  1588. }
  1589. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1590. {
  1591. for (;;)
  1592. {
  1593. const uint32 now = getMillisecondCounter();
  1594. if (now >= targetTime)
  1595. break;
  1596. const int toWait = targetTime - now;
  1597. if (toWait > 2)
  1598. {
  1599. Thread::sleep (jmin (20, toWait >> 1));
  1600. }
  1601. else
  1602. {
  1603. // xxx should consider using mutex_pause on the mac as it apparently
  1604. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1605. for (int i = 10; --i >= 0;)
  1606. Thread::yield();
  1607. }
  1608. }
  1609. }
  1610. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1611. {
  1612. return ticks / (double) getHighResolutionTicksPerSecond();
  1613. }
  1614. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1615. {
  1616. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1617. }
  1618. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1619. {
  1620. return Time (currentTimeMillis());
  1621. }
  1622. const String Time::toString (const bool includeDate,
  1623. const bool includeTime,
  1624. const bool includeSeconds,
  1625. const bool use24HourClock) const throw()
  1626. {
  1627. String result;
  1628. if (includeDate)
  1629. {
  1630. result << getDayOfMonth() << ' '
  1631. << getMonthName (true) << ' '
  1632. << getYear();
  1633. if (includeTime)
  1634. result << ' ';
  1635. }
  1636. if (includeTime)
  1637. {
  1638. const int mins = getMinutes();
  1639. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1640. << (mins < 10 ? ":0" : ":") << mins;
  1641. if (includeSeconds)
  1642. {
  1643. const int secs = getSeconds();
  1644. result << (secs < 10 ? ":0" : ":") << secs;
  1645. }
  1646. if (! use24HourClock)
  1647. result << (isAfternoon() ? "pm" : "am");
  1648. }
  1649. return result.trimEnd();
  1650. }
  1651. const String Time::formatted (const String& format) const
  1652. {
  1653. String buffer;
  1654. int bufferSize = 128;
  1655. buffer.preallocateStorage (bufferSize);
  1656. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1657. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1658. {
  1659. bufferSize += 128;
  1660. buffer.preallocateStorage (bufferSize);
  1661. }
  1662. return buffer;
  1663. }
  1664. int Time::getYear() const throw()
  1665. {
  1666. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1667. }
  1668. int Time::getMonth() const throw()
  1669. {
  1670. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1671. }
  1672. int Time::getDayOfMonth() const throw()
  1673. {
  1674. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1675. }
  1676. int Time::getDayOfWeek() const throw()
  1677. {
  1678. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1679. }
  1680. int Time::getHours() const throw()
  1681. {
  1682. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1683. }
  1684. int Time::getHoursInAmPmFormat() const throw()
  1685. {
  1686. const int hours = getHours();
  1687. if (hours == 0)
  1688. return 12;
  1689. else if (hours <= 12)
  1690. return hours;
  1691. else
  1692. return hours - 12;
  1693. }
  1694. bool Time::isAfternoon() const throw()
  1695. {
  1696. return getHours() >= 12;
  1697. }
  1698. int Time::getMinutes() const throw()
  1699. {
  1700. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1701. }
  1702. int Time::getSeconds() const throw()
  1703. {
  1704. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1705. }
  1706. int Time::getMilliseconds() const throw()
  1707. {
  1708. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1709. }
  1710. bool Time::isDaylightSavingTime() const throw()
  1711. {
  1712. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1713. }
  1714. const String Time::getTimeZone() const throw()
  1715. {
  1716. String zone[2];
  1717. #if JUCE_WINDOWS
  1718. _tzset();
  1719. #ifdef USE_NEW_SECURE_TIME_FNS
  1720. {
  1721. char name [128];
  1722. size_t length;
  1723. for (int i = 0; i < 2; ++i)
  1724. {
  1725. zeromem (name, sizeof (name));
  1726. _get_tzname (&length, name, 127, i);
  1727. zone[i] = name;
  1728. }
  1729. }
  1730. #else
  1731. const char** const zonePtr = (const char**) _tzname;
  1732. zone[0] = zonePtr[0];
  1733. zone[1] = zonePtr[1];
  1734. #endif
  1735. #else
  1736. tzset();
  1737. const char** const zonePtr = (const char**) tzname;
  1738. zone[0] = zonePtr[0];
  1739. zone[1] = zonePtr[1];
  1740. #endif
  1741. if (isDaylightSavingTime())
  1742. {
  1743. zone[0] = zone[1];
  1744. if (zone[0].length() > 3
  1745. && zone[0].containsIgnoreCase ("daylight")
  1746. && zone[0].contains ("GMT"))
  1747. zone[0] = "BST";
  1748. }
  1749. return zone[0].substring (0, 3);
  1750. }
  1751. const String Time::getMonthName (const bool threeLetterVersion) const
  1752. {
  1753. return getMonthName (getMonth(), threeLetterVersion);
  1754. }
  1755. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1756. {
  1757. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1758. }
  1759. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1760. {
  1761. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1762. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1763. monthNumber %= 12;
  1764. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1765. : longMonthNames [monthNumber]);
  1766. }
  1767. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1768. {
  1769. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1770. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1771. day %= 7;
  1772. return TRANS (threeLetterVersion ? shortDayNames [day]
  1773. : longDayNames [day]);
  1774. }
  1775. END_JUCE_NAMESPACE
  1776. /*** End of inlined file: juce_Time.cpp ***/
  1777. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1778. BEGIN_JUCE_NAMESPACE
  1779. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1780. #endif
  1781. #if JUCE_WINDOWS
  1782. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1783. #endif
  1784. #if JUCE_DEBUG
  1785. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1786. #endif
  1787. static bool juceInitialisedNonGUI = false;
  1788. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1789. {
  1790. if (! juceInitialisedNonGUI)
  1791. {
  1792. juceInitialisedNonGUI = true;
  1793. JUCE_AUTORELEASEPOOL
  1794. DBG (SystemStats::getJUCEVersion());
  1795. SystemStats::initialiseStats();
  1796. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1797. }
  1798. // Some basic tests, to keep an eye on things and make sure these types work ok
  1799. // on all platforms. Let me know if any of these assertions fail on your system!
  1800. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1801. static_jassert (sizeof (int8) == 1);
  1802. static_jassert (sizeof (uint8) == 1);
  1803. static_jassert (sizeof (int16) == 2);
  1804. static_jassert (sizeof (uint16) == 2);
  1805. static_jassert (sizeof (int32) == 4);
  1806. static_jassert (sizeof (uint32) == 4);
  1807. static_jassert (sizeof (int64) == 8);
  1808. static_jassert (sizeof (uint64) == 8);
  1809. }
  1810. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1811. {
  1812. if (juceInitialisedNonGUI)
  1813. {
  1814. juceInitialisedNonGUI = false;
  1815. JUCE_AUTORELEASEPOOL
  1816. LocalisedStrings::setCurrentMappings (0);
  1817. Thread::stopAllThreads (3000);
  1818. #if JUCE_WINDOWS
  1819. juce_shutdownWin32Sockets();
  1820. #endif
  1821. #if JUCE_DEBUG
  1822. juce_CheckForDanglingStreams();
  1823. #endif
  1824. }
  1825. }
  1826. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1827. void juce_setCurrentThreadName (const String& name);
  1828. static bool juceInitialisedGUI = false;
  1829. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1830. {
  1831. if (! juceInitialisedGUI)
  1832. {
  1833. juceInitialisedGUI = true;
  1834. JUCE_AUTORELEASEPOOL
  1835. initialiseJuce_NonGUI();
  1836. MessageManager::getInstance();
  1837. LookAndFeel::setDefaultLookAndFeel (0);
  1838. juce_setCurrentThreadName ("Juce Message Thread");
  1839. #if JUCE_DEBUG
  1840. // This section is just for catching people who mess up their project settings and
  1841. // turn RTTI off..
  1842. try
  1843. {
  1844. TextButton tb (String::empty);
  1845. Component* c = &tb;
  1846. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1847. c = dynamic_cast <Button*> (c);
  1848. }
  1849. catch (...)
  1850. {
  1851. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1852. jassertfalse;
  1853. }
  1854. #endif
  1855. }
  1856. }
  1857. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1858. {
  1859. if (juceInitialisedGUI)
  1860. {
  1861. juceInitialisedGUI = false;
  1862. JUCE_AUTORELEASEPOOL
  1863. DeletedAtShutdown::deleteAll();
  1864. LookAndFeel::clearDefaultLookAndFeel();
  1865. delete MessageManager::getInstance();
  1866. shutdownJuce_NonGUI();
  1867. }
  1868. }
  1869. #endif
  1870. #if JUCE_UNIT_TESTS
  1871. class AtomicTests : public UnitTest
  1872. {
  1873. public:
  1874. AtomicTests() : UnitTest ("Atomics") {}
  1875. void runTest()
  1876. {
  1877. beginTest ("Misc");
  1878. char a1[7];
  1879. expect (numElementsInArray(a1) == 7);
  1880. int a2[3];
  1881. expect (numElementsInArray(a2) == 3);
  1882. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1883. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1884. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1885. beginTest ("Atomic types");
  1886. AtomicTester <int>::testInteger (*this);
  1887. AtomicTester <unsigned int>::testInteger (*this);
  1888. AtomicTester <int32>::testInteger (*this);
  1889. AtomicTester <uint32>::testInteger (*this);
  1890. AtomicTester <long>::testInteger (*this);
  1891. AtomicTester <void*>::testInteger (*this);
  1892. AtomicTester <int*>::testInteger (*this);
  1893. AtomicTester <float>::testFloat (*this);
  1894. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1895. AtomicTester <int64>::testInteger (*this);
  1896. AtomicTester <uint64>::testInteger (*this);
  1897. AtomicTester <double>::testFloat (*this);
  1898. #endif
  1899. }
  1900. template <typename Type>
  1901. class AtomicTester
  1902. {
  1903. public:
  1904. AtomicTester() {}
  1905. static void testInteger (UnitTest& test)
  1906. {
  1907. Atomic<Type> a, b;
  1908. a.set ((Type) 10);
  1909. a += (Type) 15;
  1910. a.memoryBarrier();
  1911. a -= (Type) 5;
  1912. ++a; ++a; --a;
  1913. a.memoryBarrier();
  1914. testFloat (test);
  1915. }
  1916. static void testFloat (UnitTest& test)
  1917. {
  1918. Atomic<Type> a, b;
  1919. a = (Type) 21;
  1920. a.memoryBarrier();
  1921. /* These are some simple test cases to check the atomics - let me know
  1922. if any of these assertions fail on your system!
  1923. */
  1924. test.expect (a.get() == (Type) 21);
  1925. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1926. test.expect (a.get() == (Type) 21);
  1927. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1928. test.expect (a.get() == (Type) 101);
  1929. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1930. test.expect (a.get() == (Type) 101);
  1931. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1932. test.expect (a.get() == (Type) 200);
  1933. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1934. test.expect (a.get() == (Type) 300);
  1935. b = a;
  1936. test.expect (b.get() == a.get());
  1937. }
  1938. };
  1939. };
  1940. static AtomicTests atomicUnitTests;
  1941. #endif
  1942. END_JUCE_NAMESPACE
  1943. /*** End of inlined file: juce_Initialisation.cpp ***/
  1944. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1945. BEGIN_JUCE_NAMESPACE
  1946. AbstractFifo::AbstractFifo (const int capacity) throw()
  1947. : bufferSize (capacity)
  1948. {
  1949. jassert (bufferSize > 0);
  1950. }
  1951. AbstractFifo::~AbstractFifo() {}
  1952. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1953. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1954. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1955. void AbstractFifo::reset() throw()
  1956. {
  1957. validEnd = 0;
  1958. validStart = 0;
  1959. }
  1960. void AbstractFifo::setTotalSize (int newSize) throw()
  1961. {
  1962. jassert (newSize > 0);
  1963. reset();
  1964. bufferSize = newSize;
  1965. }
  1966. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1967. {
  1968. const int vs = validStart.get();
  1969. const int ve = validEnd.get();
  1970. const int freeSpace = bufferSize - (ve - vs);
  1971. numToWrite = jmin (numToWrite, freeSpace);
  1972. if (numToWrite <= 0)
  1973. {
  1974. startIndex1 = 0;
  1975. startIndex2 = 0;
  1976. blockSize1 = 0;
  1977. blockSize2 = 0;
  1978. }
  1979. else
  1980. {
  1981. startIndex1 = (int) (ve % bufferSize);
  1982. startIndex2 = 0;
  1983. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1984. numToWrite -= blockSize1;
  1985. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1986. }
  1987. }
  1988. void AbstractFifo::finishedWrite (int numWritten) throw()
  1989. {
  1990. jassert (numWritten >= 0 && numWritten < bufferSize);
  1991. validEnd += numWritten;
  1992. }
  1993. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1994. {
  1995. const int vs = validStart.get();
  1996. const int ve = validEnd.get();
  1997. const int numReady = ve - vs;
  1998. numWanted = jmin (numWanted, numReady);
  1999. if (numWanted <= 0)
  2000. {
  2001. startIndex1 = 0;
  2002. startIndex2 = 0;
  2003. blockSize1 = 0;
  2004. blockSize2 = 0;
  2005. }
  2006. else
  2007. {
  2008. startIndex1 = (int) (vs % bufferSize);
  2009. startIndex2 = 0;
  2010. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2011. numWanted -= blockSize1;
  2012. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2013. }
  2014. }
  2015. void AbstractFifo::finishedRead (int numRead) throw()
  2016. {
  2017. jassert (numRead >= 0 && numRead < bufferSize);
  2018. validStart += numRead;
  2019. }
  2020. END_JUCE_NAMESPACE
  2021. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2022. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2023. BEGIN_JUCE_NAMESPACE
  2024. BigInteger::BigInteger()
  2025. : numValues (4),
  2026. highestBit (-1),
  2027. negative (false)
  2028. {
  2029. values.calloc (numValues + 1);
  2030. }
  2031. BigInteger::BigInteger (const int value)
  2032. : numValues (4),
  2033. highestBit (31),
  2034. negative (value < 0)
  2035. {
  2036. values.calloc (numValues + 1);
  2037. values[0] = abs (value);
  2038. highestBit = getHighestBit();
  2039. }
  2040. BigInteger::BigInteger (int64 value)
  2041. : numValues (4),
  2042. highestBit (63),
  2043. negative (value < 0)
  2044. {
  2045. values.calloc (numValues + 1);
  2046. if (value < 0)
  2047. value = -value;
  2048. values[0] = (unsigned int) value;
  2049. values[1] = (unsigned int) (value >> 32);
  2050. highestBit = getHighestBit();
  2051. }
  2052. BigInteger::BigInteger (const unsigned int value)
  2053. : numValues (4),
  2054. highestBit (31),
  2055. negative (false)
  2056. {
  2057. values.calloc (numValues + 1);
  2058. values[0] = value;
  2059. highestBit = getHighestBit();
  2060. }
  2061. BigInteger::BigInteger (const BigInteger& other)
  2062. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2063. highestBit (other.getHighestBit()),
  2064. negative (other.negative)
  2065. {
  2066. values.malloc (numValues + 1);
  2067. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2068. }
  2069. BigInteger::~BigInteger()
  2070. {
  2071. }
  2072. void BigInteger::swapWith (BigInteger& other) throw()
  2073. {
  2074. values.swapWith (other.values);
  2075. swapVariables (numValues, other.numValues);
  2076. swapVariables (highestBit, other.highestBit);
  2077. swapVariables (negative, other.negative);
  2078. }
  2079. BigInteger& BigInteger::operator= (const BigInteger& other)
  2080. {
  2081. if (this != &other)
  2082. {
  2083. highestBit = other.getHighestBit();
  2084. numValues = jmax (4, (highestBit >> 5) + 1);
  2085. negative = other.negative;
  2086. values.malloc (numValues + 1);
  2087. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2088. }
  2089. return *this;
  2090. }
  2091. void BigInteger::ensureSize (const int numVals)
  2092. {
  2093. if (numVals + 2 >= numValues)
  2094. {
  2095. int oldSize = numValues;
  2096. numValues = ((numVals + 2) * 3) / 2;
  2097. values.realloc (numValues + 1);
  2098. while (oldSize < numValues)
  2099. values [oldSize++] = 0;
  2100. }
  2101. }
  2102. bool BigInteger::operator[] (const int bit) const throw()
  2103. {
  2104. return bit <= highestBit && bit >= 0
  2105. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2106. }
  2107. int BigInteger::toInteger() const throw()
  2108. {
  2109. const int n = (int) (values[0] & 0x7fffffff);
  2110. return negative ? -n : n;
  2111. }
  2112. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2113. {
  2114. BigInteger r;
  2115. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2116. r.ensureSize (numBits >> 5);
  2117. r.highestBit = numBits;
  2118. int i = 0;
  2119. while (numBits > 0)
  2120. {
  2121. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2122. numBits -= 32;
  2123. startBit += 32;
  2124. }
  2125. r.highestBit = r.getHighestBit();
  2126. return r;
  2127. }
  2128. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2129. {
  2130. if (numBits > 32)
  2131. {
  2132. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2133. numBits = 32;
  2134. }
  2135. numBits = jmin (numBits, highestBit + 1 - startBit);
  2136. if (numBits <= 0)
  2137. return 0;
  2138. const int pos = startBit >> 5;
  2139. const int offset = startBit & 31;
  2140. const int endSpace = 32 - numBits;
  2141. uint32 n = ((uint32) values [pos]) >> offset;
  2142. if (offset > endSpace)
  2143. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2144. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2145. }
  2146. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2147. {
  2148. if (numBits > 32)
  2149. {
  2150. jassertfalse;
  2151. numBits = 32;
  2152. }
  2153. for (int i = 0; i < numBits; ++i)
  2154. {
  2155. setBit (startBit + i, (valueToSet & 1) != 0);
  2156. valueToSet >>= 1;
  2157. }
  2158. }
  2159. void BigInteger::clear()
  2160. {
  2161. if (numValues > 16)
  2162. {
  2163. numValues = 4;
  2164. values.calloc (numValues + 1);
  2165. }
  2166. else
  2167. {
  2168. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2169. }
  2170. highestBit = -1;
  2171. negative = false;
  2172. }
  2173. void BigInteger::setBit (const int bit)
  2174. {
  2175. if (bit >= 0)
  2176. {
  2177. if (bit > highestBit)
  2178. {
  2179. ensureSize (bit >> 5);
  2180. highestBit = bit;
  2181. }
  2182. values [bit >> 5] |= (1 << (bit & 31));
  2183. }
  2184. }
  2185. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2186. {
  2187. if (shouldBeSet)
  2188. setBit (bit);
  2189. else
  2190. clearBit (bit);
  2191. }
  2192. void BigInteger::clearBit (const int bit) throw()
  2193. {
  2194. if (bit >= 0 && bit <= highestBit)
  2195. values [bit >> 5] &= ~(1 << (bit & 31));
  2196. }
  2197. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2198. {
  2199. while (--numBits >= 0)
  2200. setBit (startBit++, shouldBeSet);
  2201. }
  2202. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2203. {
  2204. if (bit >= 0)
  2205. shiftBits (1, bit);
  2206. setBit (bit, shouldBeSet);
  2207. }
  2208. bool BigInteger::isZero() const throw()
  2209. {
  2210. return getHighestBit() < 0;
  2211. }
  2212. bool BigInteger::isOne() const throw()
  2213. {
  2214. return getHighestBit() == 0 && ! negative;
  2215. }
  2216. bool BigInteger::isNegative() const throw()
  2217. {
  2218. return negative && ! isZero();
  2219. }
  2220. void BigInteger::setNegative (const bool neg) throw()
  2221. {
  2222. negative = neg;
  2223. }
  2224. void BigInteger::negate() throw()
  2225. {
  2226. negative = (! negative) && ! isZero();
  2227. }
  2228. int BigInteger::countNumberOfSetBits() const throw()
  2229. {
  2230. int total = 0;
  2231. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2232. {
  2233. unsigned int n = values[i];
  2234. if (n == 0xffffffff)
  2235. {
  2236. total += 32;
  2237. }
  2238. else
  2239. {
  2240. while (n != 0)
  2241. {
  2242. total += (n & 1);
  2243. n >>= 1;
  2244. }
  2245. }
  2246. }
  2247. return total;
  2248. }
  2249. int BigInteger::getHighestBit() const throw()
  2250. {
  2251. for (int i = highestBit + 1; --i >= 0;)
  2252. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2253. return i;
  2254. return -1;
  2255. }
  2256. int BigInteger::findNextSetBit (int i) const throw()
  2257. {
  2258. for (; i <= highestBit; ++i)
  2259. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2260. return i;
  2261. return -1;
  2262. }
  2263. int BigInteger::findNextClearBit (int i) const throw()
  2264. {
  2265. for (; i <= highestBit; ++i)
  2266. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2267. break;
  2268. return i;
  2269. }
  2270. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2271. {
  2272. if (other.isNegative())
  2273. return operator-= (-other);
  2274. if (isNegative())
  2275. {
  2276. if (compareAbsolute (other) < 0)
  2277. {
  2278. BigInteger temp (*this);
  2279. temp.negate();
  2280. *this = other;
  2281. operator-= (temp);
  2282. }
  2283. else
  2284. {
  2285. negate();
  2286. operator-= (other);
  2287. negate();
  2288. }
  2289. }
  2290. else
  2291. {
  2292. if (other.highestBit > highestBit)
  2293. highestBit = other.highestBit;
  2294. ++highestBit;
  2295. const int numInts = (highestBit >> 5) + 1;
  2296. ensureSize (numInts);
  2297. int64 remainder = 0;
  2298. for (int i = 0; i <= numInts; ++i)
  2299. {
  2300. if (i < numValues)
  2301. remainder += values[i];
  2302. if (i < other.numValues)
  2303. remainder += other.values[i];
  2304. values[i] = (unsigned int) remainder;
  2305. remainder >>= 32;
  2306. }
  2307. jassert (remainder == 0);
  2308. highestBit = getHighestBit();
  2309. }
  2310. return *this;
  2311. }
  2312. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2313. {
  2314. if (other.isNegative())
  2315. return operator+= (-other);
  2316. if (! isNegative())
  2317. {
  2318. if (compareAbsolute (other) < 0)
  2319. {
  2320. BigInteger temp (other);
  2321. swapWith (temp);
  2322. operator-= (temp);
  2323. negate();
  2324. return *this;
  2325. }
  2326. }
  2327. else
  2328. {
  2329. negate();
  2330. operator+= (other);
  2331. negate();
  2332. return *this;
  2333. }
  2334. const int numInts = (highestBit >> 5) + 1;
  2335. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2336. int64 amountToSubtract = 0;
  2337. for (int i = 0; i <= numInts; ++i)
  2338. {
  2339. if (i <= maxOtherInts)
  2340. amountToSubtract += (int64) other.values[i];
  2341. if (values[i] >= amountToSubtract)
  2342. {
  2343. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2344. amountToSubtract = 0;
  2345. }
  2346. else
  2347. {
  2348. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2349. values[i] = (unsigned int) n;
  2350. amountToSubtract = 1;
  2351. }
  2352. }
  2353. return *this;
  2354. }
  2355. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2356. {
  2357. BigInteger total;
  2358. highestBit = getHighestBit();
  2359. const bool wasNegative = isNegative();
  2360. setNegative (false);
  2361. for (int i = 0; i <= highestBit; ++i)
  2362. {
  2363. if (operator[](i))
  2364. {
  2365. BigInteger n (other);
  2366. n.setNegative (false);
  2367. n <<= i;
  2368. total += n;
  2369. }
  2370. }
  2371. total.setNegative (wasNegative ^ other.isNegative());
  2372. swapWith (total);
  2373. return *this;
  2374. }
  2375. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2376. {
  2377. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2378. const int divHB = divisor.getHighestBit();
  2379. const int ourHB = getHighestBit();
  2380. if (divHB < 0 || ourHB < 0)
  2381. {
  2382. // division by zero
  2383. remainder.clear();
  2384. clear();
  2385. }
  2386. else
  2387. {
  2388. const bool wasNegative = isNegative();
  2389. swapWith (remainder);
  2390. remainder.setNegative (false);
  2391. clear();
  2392. BigInteger temp (divisor);
  2393. temp.setNegative (false);
  2394. int leftShift = ourHB - divHB;
  2395. temp <<= leftShift;
  2396. while (leftShift >= 0)
  2397. {
  2398. if (remainder.compareAbsolute (temp) >= 0)
  2399. {
  2400. remainder -= temp;
  2401. setBit (leftShift);
  2402. }
  2403. if (--leftShift >= 0)
  2404. temp >>= 1;
  2405. }
  2406. negative = wasNegative ^ divisor.isNegative();
  2407. remainder.setNegative (wasNegative);
  2408. }
  2409. }
  2410. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2411. {
  2412. BigInteger remainder;
  2413. divideBy (other, remainder);
  2414. return *this;
  2415. }
  2416. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2417. {
  2418. // this operation doesn't take into account negative values..
  2419. jassert (isNegative() == other.isNegative());
  2420. if (other.highestBit >= 0)
  2421. {
  2422. ensureSize (other.highestBit >> 5);
  2423. int n = (other.highestBit >> 5) + 1;
  2424. while (--n >= 0)
  2425. values[n] |= other.values[n];
  2426. if (other.highestBit > highestBit)
  2427. highestBit = other.highestBit;
  2428. highestBit = getHighestBit();
  2429. }
  2430. return *this;
  2431. }
  2432. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2433. {
  2434. // this operation doesn't take into account negative values..
  2435. jassert (isNegative() == other.isNegative());
  2436. int n = numValues;
  2437. while (n > other.numValues)
  2438. values[--n] = 0;
  2439. while (--n >= 0)
  2440. values[n] &= other.values[n];
  2441. if (other.highestBit < highestBit)
  2442. highestBit = other.highestBit;
  2443. highestBit = getHighestBit();
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2447. {
  2448. // this operation will only work with the absolute values
  2449. jassert (isNegative() == other.isNegative());
  2450. if (other.highestBit >= 0)
  2451. {
  2452. ensureSize (other.highestBit >> 5);
  2453. int n = (other.highestBit >> 5) + 1;
  2454. while (--n >= 0)
  2455. values[n] ^= other.values[n];
  2456. if (other.highestBit > highestBit)
  2457. highestBit = other.highestBit;
  2458. highestBit = getHighestBit();
  2459. }
  2460. return *this;
  2461. }
  2462. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2463. {
  2464. BigInteger remainder;
  2465. divideBy (divisor, remainder);
  2466. swapWith (remainder);
  2467. return *this;
  2468. }
  2469. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2470. {
  2471. shiftBits (numBitsToShift, 0);
  2472. return *this;
  2473. }
  2474. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2475. {
  2476. return operator<<= (-numBitsToShift);
  2477. }
  2478. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2479. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2480. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2481. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2482. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2483. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2484. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2485. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2486. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2487. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2488. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2489. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2490. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2491. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2492. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2493. int BigInteger::compare (const BigInteger& other) const throw()
  2494. {
  2495. if (isNegative() == other.isNegative())
  2496. {
  2497. const int absComp = compareAbsolute (other);
  2498. return isNegative() ? -absComp : absComp;
  2499. }
  2500. else
  2501. {
  2502. return isNegative() ? -1 : 1;
  2503. }
  2504. }
  2505. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2506. {
  2507. const int h1 = getHighestBit();
  2508. const int h2 = other.getHighestBit();
  2509. if (h1 > h2)
  2510. return 1;
  2511. else if (h1 < h2)
  2512. return -1;
  2513. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2514. if (values[i] != other.values[i])
  2515. return (values[i] > other.values[i]) ? 1 : -1;
  2516. return 0;
  2517. }
  2518. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2519. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2520. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2521. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2522. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2523. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2524. void BigInteger::shiftBits (int bits, const int startBit)
  2525. {
  2526. if (highestBit < 0)
  2527. return;
  2528. if (startBit > 0)
  2529. {
  2530. if (bits < 0)
  2531. {
  2532. // right shift
  2533. for (int i = startBit; i <= highestBit; ++i)
  2534. setBit (i, operator[] (i - bits));
  2535. highestBit = getHighestBit();
  2536. }
  2537. else if (bits > 0)
  2538. {
  2539. // left shift
  2540. for (int i = highestBit + 1; --i >= startBit;)
  2541. setBit (i + bits, operator[] (i));
  2542. while (--bits >= 0)
  2543. clearBit (bits + startBit);
  2544. }
  2545. }
  2546. else
  2547. {
  2548. if (bits < 0)
  2549. {
  2550. // right shift
  2551. bits = -bits;
  2552. if (bits > highestBit)
  2553. {
  2554. clear();
  2555. }
  2556. else
  2557. {
  2558. const int wordsToMove = bits >> 5;
  2559. int top = 1 + (highestBit >> 5) - wordsToMove;
  2560. highestBit -= bits;
  2561. if (wordsToMove > 0)
  2562. {
  2563. int i;
  2564. for (i = 0; i < top; ++i)
  2565. values [i] = values [i + wordsToMove];
  2566. for (i = 0; i < wordsToMove; ++i)
  2567. values [top + i] = 0;
  2568. bits &= 31;
  2569. }
  2570. if (bits != 0)
  2571. {
  2572. const int invBits = 32 - bits;
  2573. --top;
  2574. for (int i = 0; i < top; ++i)
  2575. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2576. values[top] = (values[top] >> bits);
  2577. }
  2578. highestBit = getHighestBit();
  2579. }
  2580. }
  2581. else if (bits > 0)
  2582. {
  2583. // left shift
  2584. ensureSize (((highestBit + bits) >> 5) + 1);
  2585. const int wordsToMove = bits >> 5;
  2586. int top = 1 + (highestBit >> 5);
  2587. highestBit += bits;
  2588. if (wordsToMove > 0)
  2589. {
  2590. int i;
  2591. for (i = top; --i >= 0;)
  2592. values [i + wordsToMove] = values [i];
  2593. for (i = 0; i < wordsToMove; ++i)
  2594. values [i] = 0;
  2595. bits &= 31;
  2596. }
  2597. if (bits != 0)
  2598. {
  2599. const int invBits = 32 - bits;
  2600. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2601. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2602. values [wordsToMove] = values [wordsToMove] << bits;
  2603. }
  2604. highestBit = getHighestBit();
  2605. }
  2606. }
  2607. }
  2608. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2609. {
  2610. while (! m->isZero())
  2611. {
  2612. if (n->compareAbsolute (*m) > 0)
  2613. swapVariables (m, n);
  2614. *m -= *n;
  2615. }
  2616. return *n;
  2617. }
  2618. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2619. {
  2620. BigInteger m (*this);
  2621. while (! n.isZero())
  2622. {
  2623. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2624. return simpleGCD (&m, &n);
  2625. BigInteger temp1 (m), temp2;
  2626. temp1.divideBy (n, temp2);
  2627. m = n;
  2628. n = temp2;
  2629. }
  2630. return m;
  2631. }
  2632. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2633. {
  2634. BigInteger exp (exponent);
  2635. exp %= modulus;
  2636. BigInteger value (1);
  2637. swapWith (value);
  2638. value %= modulus;
  2639. while (! exp.isZero())
  2640. {
  2641. if (exp [0])
  2642. {
  2643. operator*= (value);
  2644. operator%= (modulus);
  2645. }
  2646. value *= value;
  2647. value %= modulus;
  2648. exp >>= 1;
  2649. }
  2650. }
  2651. void BigInteger::inverseModulo (const BigInteger& modulus)
  2652. {
  2653. if (modulus.isOne() || modulus.isNegative())
  2654. {
  2655. clear();
  2656. return;
  2657. }
  2658. if (isNegative() || compareAbsolute (modulus) >= 0)
  2659. operator%= (modulus);
  2660. if (isOne())
  2661. return;
  2662. if (! (*this)[0])
  2663. {
  2664. // not invertible
  2665. clear();
  2666. return;
  2667. }
  2668. BigInteger a1 (modulus);
  2669. BigInteger a2 (*this);
  2670. BigInteger b1 (modulus);
  2671. BigInteger b2 (1);
  2672. while (! a2.isOne())
  2673. {
  2674. BigInteger temp1, temp2, multiplier (a1);
  2675. multiplier.divideBy (a2, temp1);
  2676. temp1 = a2;
  2677. temp1 *= multiplier;
  2678. temp2 = a1;
  2679. temp2 -= temp1;
  2680. a1 = a2;
  2681. a2 = temp2;
  2682. temp1 = b2;
  2683. temp1 *= multiplier;
  2684. temp2 = b1;
  2685. temp2 -= temp1;
  2686. b1 = b2;
  2687. b2 = temp2;
  2688. }
  2689. while (b2.isNegative())
  2690. b2 += modulus;
  2691. b2 %= modulus;
  2692. swapWith (b2);
  2693. }
  2694. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2695. {
  2696. return stream << value.toString (10);
  2697. }
  2698. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2699. {
  2700. String s;
  2701. BigInteger v (*this);
  2702. if (base == 2 || base == 8 || base == 16)
  2703. {
  2704. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2705. static const char* const hexDigits = "0123456789abcdef";
  2706. for (;;)
  2707. {
  2708. const int remainder = v.getBitRangeAsInt (0, bits);
  2709. v >>= bits;
  2710. if (remainder == 0 && v.isZero())
  2711. break;
  2712. s = String::charToString (hexDigits [remainder]) + s;
  2713. }
  2714. }
  2715. else if (base == 10)
  2716. {
  2717. const BigInteger ten (10);
  2718. BigInteger remainder;
  2719. for (;;)
  2720. {
  2721. v.divideBy (ten, remainder);
  2722. if (remainder.isZero() && v.isZero())
  2723. break;
  2724. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2725. }
  2726. }
  2727. else
  2728. {
  2729. jassertfalse; // can't do the specified base!
  2730. return String::empty;
  2731. }
  2732. s = s.paddedLeft ('0', minimumNumCharacters);
  2733. return isNegative() ? "-" + s : s;
  2734. }
  2735. void BigInteger::parseString (const String& text, const int base)
  2736. {
  2737. clear();
  2738. const juce_wchar* t = text;
  2739. if (base == 2 || base == 8 || base == 16)
  2740. {
  2741. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2742. for (;;)
  2743. {
  2744. const juce_wchar c = *t++;
  2745. const int digit = CharacterFunctions::getHexDigitValue (c);
  2746. if (((unsigned int) digit) < (unsigned int) base)
  2747. {
  2748. operator<<= (bits);
  2749. operator+= (digit);
  2750. }
  2751. else if (c == 0)
  2752. {
  2753. break;
  2754. }
  2755. }
  2756. }
  2757. else if (base == 10)
  2758. {
  2759. const BigInteger ten ((unsigned int) 10);
  2760. for (;;)
  2761. {
  2762. const juce_wchar c = *t++;
  2763. if (c >= '0' && c <= '9')
  2764. {
  2765. operator*= (ten);
  2766. operator+= ((int) (c - '0'));
  2767. }
  2768. else if (c == 0)
  2769. {
  2770. break;
  2771. }
  2772. }
  2773. }
  2774. setNegative (text.trimStart().startsWithChar ('-'));
  2775. }
  2776. const MemoryBlock BigInteger::toMemoryBlock() const
  2777. {
  2778. const int numBytes = (getHighestBit() + 8) >> 3;
  2779. MemoryBlock mb ((size_t) numBytes);
  2780. for (int i = 0; i < numBytes; ++i)
  2781. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2782. return mb;
  2783. }
  2784. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2785. {
  2786. clear();
  2787. for (int i = (int) data.getSize(); --i >= 0;)
  2788. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2789. }
  2790. END_JUCE_NAMESPACE
  2791. /*** End of inlined file: juce_BigInteger.cpp ***/
  2792. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2793. BEGIN_JUCE_NAMESPACE
  2794. MemoryBlock::MemoryBlock() throw()
  2795. : size (0)
  2796. {
  2797. }
  2798. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2799. {
  2800. if (initialSize > 0)
  2801. {
  2802. size = initialSize;
  2803. data.allocate (initialSize, initialiseToZero);
  2804. }
  2805. else
  2806. {
  2807. size = 0;
  2808. }
  2809. }
  2810. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2811. : size (other.size)
  2812. {
  2813. if (size > 0)
  2814. {
  2815. jassert (other.data != 0);
  2816. data.malloc (size);
  2817. memcpy (data, other.data, size);
  2818. }
  2819. }
  2820. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2821. : size (jmax ((size_t) 0, sizeInBytes))
  2822. {
  2823. jassert (sizeInBytes >= 0);
  2824. if (size > 0)
  2825. {
  2826. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2827. data.malloc (size);
  2828. if (dataToInitialiseFrom != 0)
  2829. memcpy (data, dataToInitialiseFrom, size);
  2830. }
  2831. }
  2832. MemoryBlock::~MemoryBlock() throw()
  2833. {
  2834. jassert (size >= 0); // should never happen
  2835. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2836. }
  2837. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2838. {
  2839. if (this != &other)
  2840. {
  2841. setSize (other.size, false);
  2842. memcpy (data, other.data, size);
  2843. }
  2844. return *this;
  2845. }
  2846. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2847. {
  2848. return matches (other.data, other.size);
  2849. }
  2850. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2851. {
  2852. return ! operator== (other);
  2853. }
  2854. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2855. {
  2856. return size == dataSize
  2857. && memcmp (data, dataToCompare, size) == 0;
  2858. }
  2859. // this will resize the block to this size
  2860. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2861. {
  2862. if (size != newSize)
  2863. {
  2864. if (newSize <= 0)
  2865. {
  2866. data.free();
  2867. size = 0;
  2868. }
  2869. else
  2870. {
  2871. if (data != 0)
  2872. {
  2873. data.realloc (newSize);
  2874. if (initialiseToZero && (newSize > size))
  2875. zeromem (data + size, newSize - size);
  2876. }
  2877. else
  2878. {
  2879. data.allocate (newSize, initialiseToZero);
  2880. }
  2881. size = newSize;
  2882. }
  2883. }
  2884. }
  2885. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2886. {
  2887. if (size < minimumSize)
  2888. setSize (minimumSize, initialiseToZero);
  2889. }
  2890. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2891. {
  2892. swapVariables (size, other.size);
  2893. data.swapWith (other.data);
  2894. }
  2895. void MemoryBlock::fillWith (const uint8 value) throw()
  2896. {
  2897. memset (data, (int) value, size);
  2898. }
  2899. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2900. {
  2901. if (numBytes > 0)
  2902. {
  2903. const size_t oldSize = size;
  2904. setSize (size + numBytes);
  2905. memcpy (data + oldSize, srcData, numBytes);
  2906. }
  2907. }
  2908. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2909. {
  2910. const char* d = static_cast<const char*> (src);
  2911. if (offset < 0)
  2912. {
  2913. d -= offset;
  2914. num -= offset;
  2915. offset = 0;
  2916. }
  2917. if (offset + num > size)
  2918. num = size - offset;
  2919. if (num > 0)
  2920. memcpy (data + offset, d, num);
  2921. }
  2922. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2923. {
  2924. char* d = static_cast<char*> (dst);
  2925. if (offset < 0)
  2926. {
  2927. zeromem (d, -offset);
  2928. d -= offset;
  2929. num += offset;
  2930. offset = 0;
  2931. }
  2932. if (offset + num > size)
  2933. {
  2934. const size_t newNum = size - offset;
  2935. zeromem (d + newNum, num - newNum);
  2936. num = newNum;
  2937. }
  2938. if (num > 0)
  2939. memcpy (d, data + offset, num);
  2940. }
  2941. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2942. {
  2943. if (startByte < 0)
  2944. {
  2945. numBytesToRemove += startByte;
  2946. startByte = 0;
  2947. }
  2948. if (startByte + numBytesToRemove >= size)
  2949. {
  2950. setSize (startByte);
  2951. }
  2952. else if (numBytesToRemove > 0)
  2953. {
  2954. memmove (data + startByte,
  2955. data + startByte + numBytesToRemove,
  2956. size - (startByte + numBytesToRemove));
  2957. setSize (size - numBytesToRemove);
  2958. }
  2959. }
  2960. const String MemoryBlock::toString() const
  2961. {
  2962. return String (static_cast <const char*> (getData()), size);
  2963. }
  2964. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2965. {
  2966. int res = 0;
  2967. size_t byte = bitRangeStart >> 3;
  2968. int offsetInByte = (int) bitRangeStart & 7;
  2969. size_t bitsSoFar = 0;
  2970. while (numBits > 0 && (size_t) byte < size)
  2971. {
  2972. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2973. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2974. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2975. bitsSoFar += bitsThisTime;
  2976. numBits -= bitsThisTime;
  2977. ++byte;
  2978. offsetInByte = 0;
  2979. }
  2980. return res;
  2981. }
  2982. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2983. {
  2984. size_t byte = bitRangeStart >> 3;
  2985. int offsetInByte = (int) bitRangeStart & 7;
  2986. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2987. while (numBits > 0 && (size_t) byte < size)
  2988. {
  2989. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2990. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2991. const unsigned int tempBits = bitsToSet << offsetInByte;
  2992. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2993. ++byte;
  2994. numBits -= bitsThisTime;
  2995. bitsToSet >>= bitsThisTime;
  2996. mask >>= bitsThisTime;
  2997. offsetInByte = 0;
  2998. }
  2999. }
  3000. void MemoryBlock::loadFromHexString (const String& hex)
  3001. {
  3002. ensureSize (hex.length() >> 1);
  3003. char* dest = data;
  3004. int i = 0;
  3005. for (;;)
  3006. {
  3007. int byte = 0;
  3008. for (int loop = 2; --loop >= 0;)
  3009. {
  3010. byte <<= 4;
  3011. for (;;)
  3012. {
  3013. const juce_wchar c = hex [i++];
  3014. if (c >= '0' && c <= '9')
  3015. {
  3016. byte |= c - '0';
  3017. break;
  3018. }
  3019. else if (c >= 'a' && c <= 'z')
  3020. {
  3021. byte |= c - ('a' - 10);
  3022. break;
  3023. }
  3024. else if (c >= 'A' && c <= 'Z')
  3025. {
  3026. byte |= c - ('A' - 10);
  3027. break;
  3028. }
  3029. else if (c == 0)
  3030. {
  3031. setSize (static_cast <size_t> (dest - data));
  3032. return;
  3033. }
  3034. }
  3035. }
  3036. *dest++ = (char) byte;
  3037. }
  3038. }
  3039. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3040. const String MemoryBlock::toBase64Encoding() const
  3041. {
  3042. const size_t numChars = ((size << 3) + 5) / 6;
  3043. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3044. const int initialLen = destString.length();
  3045. destString.preallocateStorage (initialLen + 2 + numChars);
  3046. juce_wchar* d = destString;
  3047. d += initialLen;
  3048. *d++ = '.';
  3049. for (size_t i = 0; i < numChars; ++i)
  3050. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3051. *d++ = 0;
  3052. return destString;
  3053. }
  3054. bool MemoryBlock::fromBase64Encoding (const String& s)
  3055. {
  3056. const int startPos = s.indexOfChar ('.') + 1;
  3057. if (startPos <= 0)
  3058. return false;
  3059. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3060. setSize (numBytesNeeded, true);
  3061. const int numChars = s.length() - startPos;
  3062. const juce_wchar* srcChars = s;
  3063. srcChars += startPos;
  3064. int pos = 0;
  3065. for (int i = 0; i < numChars; ++i)
  3066. {
  3067. const char c = (char) srcChars[i];
  3068. for (int j = 0; j < 64; ++j)
  3069. {
  3070. if (encodingTable[j] == c)
  3071. {
  3072. setBitRange (pos, 6, j);
  3073. pos += 6;
  3074. break;
  3075. }
  3076. }
  3077. }
  3078. return true;
  3079. }
  3080. END_JUCE_NAMESPACE
  3081. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3082. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3083. BEGIN_JUCE_NAMESPACE
  3084. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3085. : properties (ignoreCaseOfKeyNames),
  3086. fallbackProperties (0),
  3087. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3088. {
  3089. }
  3090. PropertySet::PropertySet (const PropertySet& other)
  3091. : properties (other.properties),
  3092. fallbackProperties (other.fallbackProperties),
  3093. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3094. {
  3095. }
  3096. PropertySet& PropertySet::operator= (const PropertySet& other)
  3097. {
  3098. properties = other.properties;
  3099. fallbackProperties = other.fallbackProperties;
  3100. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3101. propertyChanged();
  3102. return *this;
  3103. }
  3104. PropertySet::~PropertySet()
  3105. {
  3106. }
  3107. void PropertySet::clear()
  3108. {
  3109. const ScopedLock sl (lock);
  3110. if (properties.size() > 0)
  3111. {
  3112. properties.clear();
  3113. propertyChanged();
  3114. }
  3115. }
  3116. const String PropertySet::getValue (const String& keyName,
  3117. const String& defaultValue) const throw()
  3118. {
  3119. const ScopedLock sl (lock);
  3120. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3121. if (index >= 0)
  3122. return properties.getAllValues() [index];
  3123. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3124. : defaultValue;
  3125. }
  3126. int PropertySet::getIntValue (const String& keyName,
  3127. const int defaultValue) const throw()
  3128. {
  3129. const ScopedLock sl (lock);
  3130. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3131. if (index >= 0)
  3132. return properties.getAllValues() [index].getIntValue();
  3133. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3134. : defaultValue;
  3135. }
  3136. double PropertySet::getDoubleValue (const String& keyName,
  3137. const double defaultValue) const throw()
  3138. {
  3139. const ScopedLock sl (lock);
  3140. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3141. if (index >= 0)
  3142. return properties.getAllValues()[index].getDoubleValue();
  3143. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3144. : defaultValue;
  3145. }
  3146. bool PropertySet::getBoolValue (const String& keyName,
  3147. const bool defaultValue) const throw()
  3148. {
  3149. const ScopedLock sl (lock);
  3150. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3151. if (index >= 0)
  3152. return properties.getAllValues() [index].getIntValue() != 0;
  3153. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3154. : defaultValue;
  3155. }
  3156. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3157. {
  3158. XmlDocument doc (getValue (keyName));
  3159. return doc.getDocumentElement();
  3160. }
  3161. void PropertySet::setValue (const String& keyName, const var& v)
  3162. {
  3163. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3164. if (keyName.isNotEmpty())
  3165. {
  3166. const String value (v.toString());
  3167. const ScopedLock sl (lock);
  3168. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3169. if (index < 0 || properties.getAllValues() [index] != value)
  3170. {
  3171. properties.set (keyName, value);
  3172. propertyChanged();
  3173. }
  3174. }
  3175. }
  3176. void PropertySet::removeValue (const String& keyName)
  3177. {
  3178. if (keyName.isNotEmpty())
  3179. {
  3180. const ScopedLock sl (lock);
  3181. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3182. if (index >= 0)
  3183. {
  3184. properties.remove (keyName);
  3185. propertyChanged();
  3186. }
  3187. }
  3188. }
  3189. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3190. {
  3191. setValue (keyName, xml == 0 ? var::null
  3192. : var (xml->createDocument (String::empty, true)));
  3193. }
  3194. bool PropertySet::containsKey (const String& keyName) const throw()
  3195. {
  3196. const ScopedLock sl (lock);
  3197. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3198. }
  3199. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3200. {
  3201. const ScopedLock sl (lock);
  3202. fallbackProperties = fallbackProperties_;
  3203. }
  3204. XmlElement* PropertySet::createXml (const String& nodeName) const
  3205. {
  3206. const ScopedLock sl (lock);
  3207. XmlElement* const xml = new XmlElement (nodeName);
  3208. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3209. {
  3210. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3211. e->setAttribute ("name", properties.getAllKeys()[i]);
  3212. e->setAttribute ("val", properties.getAllValues()[i]);
  3213. }
  3214. return xml;
  3215. }
  3216. void PropertySet::restoreFromXml (const XmlElement& xml)
  3217. {
  3218. const ScopedLock sl (lock);
  3219. clear();
  3220. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3221. {
  3222. if (e->hasAttribute ("name")
  3223. && e->hasAttribute ("val"))
  3224. {
  3225. properties.set (e->getStringAttribute ("name"),
  3226. e->getStringAttribute ("val"));
  3227. }
  3228. }
  3229. if (properties.size() > 0)
  3230. propertyChanged();
  3231. }
  3232. void PropertySet::propertyChanged()
  3233. {
  3234. }
  3235. END_JUCE_NAMESPACE
  3236. /*** End of inlined file: juce_PropertySet.cpp ***/
  3237. /*** Start of inlined file: juce_Identifier.cpp ***/
  3238. BEGIN_JUCE_NAMESPACE
  3239. StringPool& Identifier::getPool()
  3240. {
  3241. static StringPool pool;
  3242. return pool;
  3243. }
  3244. Identifier::Identifier() throw()
  3245. : name (0)
  3246. {
  3247. }
  3248. Identifier::Identifier (const Identifier& other) throw()
  3249. : name (other.name)
  3250. {
  3251. }
  3252. Identifier& Identifier::operator= (const Identifier& other) throw()
  3253. {
  3254. name = other.name;
  3255. return *this;
  3256. }
  3257. Identifier::Identifier (const String& name_)
  3258. : name (Identifier::getPool().getPooledString (name_))
  3259. {
  3260. /* An Identifier string must be suitable for use as a script variable or XML
  3261. attribute, so it can only contain this limited set of characters.. */
  3262. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3263. }
  3264. Identifier::Identifier (const char* const name_)
  3265. : name (Identifier::getPool().getPooledString (name_))
  3266. {
  3267. /* An Identifier string must be suitable for use as a script variable or XML
  3268. attribute, so it can only contain this limited set of characters.. */
  3269. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3270. }
  3271. Identifier::~Identifier()
  3272. {
  3273. }
  3274. END_JUCE_NAMESPACE
  3275. /*** End of inlined file: juce_Identifier.cpp ***/
  3276. /*** Start of inlined file: juce_Variant.cpp ***/
  3277. BEGIN_JUCE_NAMESPACE
  3278. class var::VariantType
  3279. {
  3280. public:
  3281. VariantType() {}
  3282. virtual ~VariantType() {}
  3283. virtual int toInt (const ValueUnion&) const { return 0; }
  3284. virtual double toDouble (const ValueUnion&) const { return 0; }
  3285. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3286. virtual bool toBool (const ValueUnion&) const { return false; }
  3287. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3288. virtual bool isVoid() const throw() { return false; }
  3289. virtual bool isInt() const throw() { return false; }
  3290. virtual bool isBool() const throw() { return false; }
  3291. virtual bool isDouble() const throw() { return false; }
  3292. virtual bool isString() const throw() { return false; }
  3293. virtual bool isObject() const throw() { return false; }
  3294. virtual bool isMethod() const throw() { return false; }
  3295. virtual void cleanUp (ValueUnion&) const throw() {}
  3296. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3297. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3298. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3299. };
  3300. class var::VariantType_Void : public var::VariantType
  3301. {
  3302. public:
  3303. VariantType_Void() {}
  3304. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3305. bool isVoid() const throw() { return true; }
  3306. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3307. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3308. };
  3309. class var::VariantType_Int : public var::VariantType
  3310. {
  3311. public:
  3312. VariantType_Int() {}
  3313. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3314. int toInt (const ValueUnion& data) const { return data.intValue; };
  3315. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3316. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3317. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3318. bool isInt() const throw() { return true; }
  3319. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3320. {
  3321. return otherType.toInt (otherData) == data.intValue;
  3322. }
  3323. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3324. {
  3325. output.writeCompressedInt (5);
  3326. output.writeByte (1);
  3327. output.writeInt (data.intValue);
  3328. }
  3329. };
  3330. class var::VariantType_Double : public var::VariantType
  3331. {
  3332. public:
  3333. VariantType_Double() {}
  3334. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3335. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3336. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3337. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3338. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3339. bool isDouble() const throw() { return true; }
  3340. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3341. {
  3342. return otherType.toDouble (otherData) == data.doubleValue;
  3343. }
  3344. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3345. {
  3346. output.writeCompressedInt (9);
  3347. output.writeByte (4);
  3348. output.writeDouble (data.doubleValue);
  3349. }
  3350. };
  3351. class var::VariantType_Bool : public var::VariantType
  3352. {
  3353. public:
  3354. VariantType_Bool() {}
  3355. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3356. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3357. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3358. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3359. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3360. bool isBool() const throw() { return true; }
  3361. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3362. {
  3363. return otherType.toBool (otherData) == data.boolValue;
  3364. }
  3365. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3366. {
  3367. output.writeCompressedInt (1);
  3368. output.writeByte (data.boolValue ? 2 : 3);
  3369. }
  3370. };
  3371. class var::VariantType_String : public var::VariantType
  3372. {
  3373. public:
  3374. VariantType_String() {}
  3375. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3376. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3377. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3378. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3379. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3380. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3381. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3382. || data.stringValue->trim().equalsIgnoreCase ("true")
  3383. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3384. bool isString() const throw() { return true; }
  3385. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3386. {
  3387. return otherType.toString (otherData) == *data.stringValue;
  3388. }
  3389. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3390. {
  3391. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3392. output.writeCompressedInt (len + 1);
  3393. output.writeByte (5);
  3394. HeapBlock<char> temp (len);
  3395. data.stringValue->copyToUTF8 (temp, len);
  3396. output.write (temp, len);
  3397. }
  3398. };
  3399. class var::VariantType_Object : public var::VariantType
  3400. {
  3401. public:
  3402. VariantType_Object() {}
  3403. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3404. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3405. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3406. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3407. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3408. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3409. bool isObject() const throw() { return true; }
  3410. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3411. {
  3412. return otherType.toObject (otherData) == data.objectValue;
  3413. }
  3414. void writeToStream (const ValueUnion&, OutputStream& output) const
  3415. {
  3416. jassertfalse; // Can't write an object to a stream!
  3417. output.writeCompressedInt (0);
  3418. }
  3419. };
  3420. class var::VariantType_Method : public var::VariantType
  3421. {
  3422. public:
  3423. VariantType_Method() {}
  3424. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3425. const String toString (const ValueUnion&) const { return "Method"; }
  3426. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3427. bool isMethod() const throw() { return true; }
  3428. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3429. {
  3430. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3431. }
  3432. void writeToStream (const ValueUnion&, OutputStream& output) const
  3433. {
  3434. jassertfalse; // Can't write a method to a stream!
  3435. output.writeCompressedInt (0);
  3436. }
  3437. };
  3438. var::var() throw()
  3439. : type (VariantType_Void::getInstance())
  3440. {
  3441. }
  3442. var::~var() throw()
  3443. {
  3444. type->cleanUp (value);
  3445. }
  3446. const var var::null;
  3447. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3448. {
  3449. type->createCopy (value, valueToCopy.value);
  3450. }
  3451. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3452. {
  3453. value.intValue = value_;
  3454. }
  3455. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3456. {
  3457. value.boolValue = value_;
  3458. }
  3459. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3460. {
  3461. value.doubleValue = value_;
  3462. }
  3463. var::var (const String& value_) : type (VariantType_String::getInstance())
  3464. {
  3465. value.stringValue = new String (value_);
  3466. }
  3467. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3468. {
  3469. value.stringValue = new String (value_);
  3470. }
  3471. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3472. {
  3473. value.stringValue = new String (value_);
  3474. }
  3475. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3476. {
  3477. value.objectValue = object;
  3478. if (object != 0)
  3479. object->incReferenceCount();
  3480. }
  3481. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3482. {
  3483. value.methodValue = method_;
  3484. }
  3485. bool var::isVoid() const throw() { return type->isVoid(); }
  3486. bool var::isInt() const throw() { return type->isInt(); }
  3487. bool var::isBool() const throw() { return type->isBool(); }
  3488. bool var::isDouble() const throw() { return type->isDouble(); }
  3489. bool var::isString() const throw() { return type->isString(); }
  3490. bool var::isObject() const throw() { return type->isObject(); }
  3491. bool var::isMethod() const throw() { return type->isMethod(); }
  3492. var::operator int() const { return type->toInt (value); }
  3493. var::operator bool() const { return type->toBool (value); }
  3494. var::operator float() const { return (float) type->toDouble (value); }
  3495. var::operator double() const { return type->toDouble (value); }
  3496. const String var::toString() const { return type->toString (value); }
  3497. var::operator const String() const { return type->toString (value); }
  3498. DynamicObject* var::getObject() const { return type->toObject (value); }
  3499. void var::swapWith (var& other) throw()
  3500. {
  3501. swapVariables (type, other.type);
  3502. swapVariables (value, other.value);
  3503. }
  3504. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3505. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3506. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3507. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3508. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3509. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3510. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3511. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3512. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3513. bool var::equals (const var& other) const throw()
  3514. {
  3515. return type->equals (value, other.value, *other.type);
  3516. }
  3517. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3518. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3519. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3520. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3521. void var::writeToStream (OutputStream& output) const
  3522. {
  3523. type->writeToStream (value, output);
  3524. }
  3525. const var var::readFromStream (InputStream& input)
  3526. {
  3527. const int numBytes = input.readCompressedInt();
  3528. if (numBytes > 0)
  3529. {
  3530. switch (input.readByte())
  3531. {
  3532. case 1: return var (input.readInt());
  3533. case 2: return var (true);
  3534. case 3: return var (false);
  3535. case 4: return var (input.readDouble());
  3536. case 5:
  3537. {
  3538. MemoryOutputStream mo;
  3539. mo.writeFromInputStream (input, numBytes - 1);
  3540. return var (mo.toUTF8());
  3541. }
  3542. default: input.skipNextBytes (numBytes - 1); break;
  3543. }
  3544. }
  3545. return var::null;
  3546. }
  3547. const var var::operator[] (const Identifier& propertyName) const
  3548. {
  3549. DynamicObject* const o = getObject();
  3550. return o != 0 ? o->getProperty (propertyName) : var::null;
  3551. }
  3552. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3553. {
  3554. DynamicObject* const o = getObject();
  3555. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3556. }
  3557. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3558. {
  3559. if (isMethod())
  3560. {
  3561. DynamicObject* const target = targetObject.getObject();
  3562. if (target != 0)
  3563. return (target->*(value.methodValue)) (arguments, numArguments);
  3564. }
  3565. return var::null;
  3566. }
  3567. const var var::call (const Identifier& method) const
  3568. {
  3569. return invoke (method, 0, 0);
  3570. }
  3571. const var var::call (const Identifier& method, const var& arg1) const
  3572. {
  3573. return invoke (method, &arg1, 1);
  3574. }
  3575. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3576. {
  3577. var args[] = { arg1, arg2 };
  3578. return invoke (method, args, 2);
  3579. }
  3580. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3581. {
  3582. var args[] = { arg1, arg2, arg3 };
  3583. return invoke (method, args, 3);
  3584. }
  3585. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3586. {
  3587. var args[] = { arg1, arg2, arg3, arg4 };
  3588. return invoke (method, args, 4);
  3589. }
  3590. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3591. {
  3592. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3593. return invoke (method, args, 5);
  3594. }
  3595. END_JUCE_NAMESPACE
  3596. /*** End of inlined file: juce_Variant.cpp ***/
  3597. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3598. BEGIN_JUCE_NAMESPACE
  3599. NamedValueSet::NamedValue::NamedValue() throw()
  3600. {
  3601. }
  3602. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3603. : name (name_), value (value_)
  3604. {
  3605. }
  3606. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3607. {
  3608. return name == other.name && value == other.value;
  3609. }
  3610. NamedValueSet::NamedValueSet() throw()
  3611. {
  3612. }
  3613. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3614. : values (other.values)
  3615. {
  3616. }
  3617. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3618. {
  3619. values = other.values;
  3620. return *this;
  3621. }
  3622. NamedValueSet::~NamedValueSet()
  3623. {
  3624. }
  3625. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3626. {
  3627. return values == other.values;
  3628. }
  3629. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3630. {
  3631. return ! operator== (other);
  3632. }
  3633. int NamedValueSet::size() const throw()
  3634. {
  3635. return values.size();
  3636. }
  3637. const var& NamedValueSet::operator[] (const Identifier& name) const
  3638. {
  3639. for (int i = values.size(); --i >= 0;)
  3640. {
  3641. const NamedValue& v = values.getReference(i);
  3642. if (v.name == name)
  3643. return v.value;
  3644. }
  3645. return var::null;
  3646. }
  3647. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3648. {
  3649. const var* v = getItem (name);
  3650. return v != 0 ? *v : defaultReturnValue;
  3651. }
  3652. var* NamedValueSet::getItem (const Identifier& name) const
  3653. {
  3654. for (int i = values.size(); --i >= 0;)
  3655. {
  3656. NamedValue& v = values.getReference(i);
  3657. if (v.name == name)
  3658. return &(v.value);
  3659. }
  3660. return 0;
  3661. }
  3662. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3663. {
  3664. for (int i = values.size(); --i >= 0;)
  3665. {
  3666. NamedValue& v = values.getReference(i);
  3667. if (v.name == name)
  3668. {
  3669. if (v.value == newValue)
  3670. return false;
  3671. v.value = newValue;
  3672. return true;
  3673. }
  3674. }
  3675. values.add (NamedValue (name, newValue));
  3676. return true;
  3677. }
  3678. bool NamedValueSet::contains (const Identifier& name) const
  3679. {
  3680. return getItem (name) != 0;
  3681. }
  3682. bool NamedValueSet::remove (const Identifier& name)
  3683. {
  3684. for (int i = values.size(); --i >= 0;)
  3685. {
  3686. if (values.getReference(i).name == name)
  3687. {
  3688. values.remove (i);
  3689. return true;
  3690. }
  3691. }
  3692. return false;
  3693. }
  3694. const Identifier NamedValueSet::getName (const int index) const
  3695. {
  3696. jassert (((unsigned int) index) < (unsigned int) values.size());
  3697. return values [index].name;
  3698. }
  3699. const var NamedValueSet::getValueAt (const int index) const
  3700. {
  3701. jassert (((unsigned int) index) < (unsigned int) values.size());
  3702. return values [index].value;
  3703. }
  3704. void NamedValueSet::clear()
  3705. {
  3706. values.clear();
  3707. }
  3708. END_JUCE_NAMESPACE
  3709. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3710. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3711. BEGIN_JUCE_NAMESPACE
  3712. DynamicObject::DynamicObject()
  3713. {
  3714. }
  3715. DynamicObject::~DynamicObject()
  3716. {
  3717. }
  3718. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3719. {
  3720. var* const v = properties.getItem (propertyName);
  3721. return v != 0 && ! v->isMethod();
  3722. }
  3723. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3724. {
  3725. return properties [propertyName];
  3726. }
  3727. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3728. {
  3729. properties.set (propertyName, newValue);
  3730. }
  3731. void DynamicObject::removeProperty (const Identifier& propertyName)
  3732. {
  3733. properties.remove (propertyName);
  3734. }
  3735. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3736. {
  3737. return getProperty (methodName).isMethod();
  3738. }
  3739. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3740. const var* parameters,
  3741. int numParameters)
  3742. {
  3743. return properties [methodName].invoke (var (this), parameters, numParameters);
  3744. }
  3745. void DynamicObject::setMethod (const Identifier& name,
  3746. var::MethodFunction methodFunction)
  3747. {
  3748. properties.set (name, var (methodFunction));
  3749. }
  3750. void DynamicObject::clear()
  3751. {
  3752. properties.clear();
  3753. }
  3754. END_JUCE_NAMESPACE
  3755. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3756. /*** Start of inlined file: juce_Expression.cpp ***/
  3757. BEGIN_JUCE_NAMESPACE
  3758. class Expression::Helpers
  3759. {
  3760. public:
  3761. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3762. class Constant : public Term
  3763. {
  3764. public:
  3765. Constant (const double value_, bool isResolutionTarget_)
  3766. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3767. Type getType() const throw() { return constantType; }
  3768. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3769. double evaluate (const EvaluationContext&, int) const { return value; }
  3770. int getNumInputs() const { return 0; }
  3771. Term* getInput (int) const { return 0; }
  3772. const TermPtr negated()
  3773. {
  3774. return new Constant (-value, isResolutionTarget);
  3775. }
  3776. const String toString() const
  3777. {
  3778. if (isResolutionTarget)
  3779. return "@" + String (value);
  3780. return String (value);
  3781. }
  3782. double value;
  3783. bool isResolutionTarget;
  3784. };
  3785. class Symbol : public Term
  3786. {
  3787. public:
  3788. explicit Symbol (const String& symbol_)
  3789. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3790. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3791. {}
  3792. Symbol (const String& symbol_, const String& member_)
  3793. : mainSymbol (symbol_),
  3794. member (member_)
  3795. {}
  3796. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3797. {
  3798. if (++recursionDepth > 256)
  3799. throw EvaluationError ("Recursive symbol references");
  3800. try
  3801. {
  3802. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3803. }
  3804. catch (...)
  3805. {}
  3806. return 0;
  3807. }
  3808. Type getType() const throw() { return symbolType; }
  3809. Term* clone() const { return new Symbol (mainSymbol, member); }
  3810. int getNumInputs() const { return 0; }
  3811. Term* getInput (int) const { return 0; }
  3812. const String getSymbolName() const { return toString(); }
  3813. const String toString() const
  3814. {
  3815. return member.isEmpty() ? mainSymbol
  3816. : mainSymbol + "." + member;
  3817. }
  3818. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3819. {
  3820. if (s == mainSymbol)
  3821. return true;
  3822. if (++recursionDepth > 256)
  3823. throw EvaluationError ("Recursive symbol references");
  3824. try
  3825. {
  3826. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3827. }
  3828. catch (EvaluationError&)
  3829. {
  3830. return false;
  3831. }
  3832. }
  3833. String mainSymbol, member;
  3834. };
  3835. class Function : public Term
  3836. {
  3837. public:
  3838. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3839. : functionName (functionName_), parameters (parameters_)
  3840. {}
  3841. Term* clone() const { return new Function (functionName, parameters); }
  3842. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3843. {
  3844. HeapBlock <double> params (parameters.size());
  3845. for (int i = 0; i < parameters.size(); ++i)
  3846. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3847. return c.evaluateFunction (functionName, params, parameters.size());
  3848. }
  3849. Type getType() const throw() { return functionType; }
  3850. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3851. int getNumInputs() const { return parameters.size(); }
  3852. Term* getInput (int i) const { return parameters [i]; }
  3853. const String getFunctionName() const { return functionName; }
  3854. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3855. {
  3856. for (int i = 0; i < parameters.size(); ++i)
  3857. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3858. return true;
  3859. return false;
  3860. }
  3861. const String toString() const
  3862. {
  3863. if (parameters.size() == 0)
  3864. return functionName + "()";
  3865. String s (functionName + " (");
  3866. for (int i = 0; i < parameters.size(); ++i)
  3867. {
  3868. s << parameters.getUnchecked(i)->toString();
  3869. if (i < parameters.size() - 1)
  3870. s << ", ";
  3871. }
  3872. s << ')';
  3873. return s;
  3874. }
  3875. const String functionName;
  3876. ReferenceCountedArray<Term> parameters;
  3877. };
  3878. class Negate : public Term
  3879. {
  3880. public:
  3881. Negate (const TermPtr& input_) : input (input_)
  3882. {
  3883. jassert (input_ != 0);
  3884. }
  3885. Type getType() const throw() { return operatorType; }
  3886. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3887. int getNumInputs() const { return 1; }
  3888. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3889. Term* clone() const { return new Negate (input->clone()); }
  3890. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3891. const String getFunctionName() const { return "-"; }
  3892. const TermPtr negated()
  3893. {
  3894. return input;
  3895. }
  3896. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3897. {
  3898. (void) input_;
  3899. jassert (input_ == input);
  3900. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3901. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3902. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3903. }
  3904. const String toString() const
  3905. {
  3906. if (input->getOperatorPrecedence() > 0)
  3907. return "-(" + input->toString() + ")";
  3908. else
  3909. return "-" + input->toString();
  3910. }
  3911. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3912. {
  3913. return input->referencesSymbol (s, c, recursionDepth);
  3914. }
  3915. private:
  3916. const TermPtr input;
  3917. };
  3918. class BinaryTerm : public Term
  3919. {
  3920. public:
  3921. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3922. {
  3923. jassert (left_ != 0 && right_ != 0);
  3924. }
  3925. int getInputIndexFor (const Term* possibleInput) const
  3926. {
  3927. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3928. }
  3929. Type getType() const throw() { return operatorType; }
  3930. int getNumInputs() const { return 2; }
  3931. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3932. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3933. {
  3934. return left->referencesSymbol (s, c, recursionDepth)
  3935. || right->referencesSymbol (s, c, recursionDepth);
  3936. }
  3937. const String toString() const
  3938. {
  3939. String s;
  3940. const int ourPrecendence = getOperatorPrecedence();
  3941. if (left->getOperatorPrecedence() > ourPrecendence)
  3942. s << '(' << left->toString() << ')';
  3943. else
  3944. s = left->toString();
  3945. s << ' ' << getFunctionName() << ' ';
  3946. if (right->getOperatorPrecedence() >= ourPrecendence)
  3947. s << '(' << right->toString() << ')';
  3948. else
  3949. s << right->toString();
  3950. return s;
  3951. }
  3952. protected:
  3953. const TermPtr left, right;
  3954. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3955. {
  3956. jassert (input == left || input == right);
  3957. if (input != left && input != right)
  3958. return 0;
  3959. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3960. if (dest == 0)
  3961. return new Constant (overallTarget, false);
  3962. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3963. }
  3964. };
  3965. class Add : public BinaryTerm
  3966. {
  3967. public:
  3968. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3969. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3970. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3971. int getOperatorPrecedence() const { return 2; }
  3972. const String getFunctionName() const { return "+"; }
  3973. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3974. {
  3975. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3976. if (newDest == 0)
  3977. return 0;
  3978. return new Subtract (newDest, (input == left ? right : left)->clone());
  3979. }
  3980. private:
  3981. Add (const Add&);
  3982. Add& operator= (const Add&);
  3983. };
  3984. class Subtract : public BinaryTerm
  3985. {
  3986. public:
  3987. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3988. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3989. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3990. int getOperatorPrecedence() const { return 2; }
  3991. const String getFunctionName() const { return "-"; }
  3992. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3993. {
  3994. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3995. if (newDest == 0)
  3996. return 0;
  3997. if (input == left)
  3998. return new Add (newDest, right->clone());
  3999. else
  4000. return new Subtract (left->clone(), newDest);
  4001. }
  4002. private:
  4003. Subtract (const Subtract&);
  4004. Subtract& operator= (const Subtract&);
  4005. };
  4006. class Multiply : public BinaryTerm
  4007. {
  4008. public:
  4009. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4010. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4011. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4012. const String getFunctionName() const { return "*"; }
  4013. int getOperatorPrecedence() const { return 1; }
  4014. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4015. {
  4016. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4017. if (newDest == 0)
  4018. return 0;
  4019. return new Divide (newDest, (input == left ? right : left)->clone());
  4020. }
  4021. private:
  4022. Multiply (const Multiply&);
  4023. Multiply& operator= (const Multiply&);
  4024. };
  4025. class Divide : public BinaryTerm
  4026. {
  4027. public:
  4028. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4029. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4030. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4031. const String getFunctionName() const { return "/"; }
  4032. int getOperatorPrecedence() const { return 1; }
  4033. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4034. {
  4035. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4036. if (newDest == 0)
  4037. return 0;
  4038. if (input == left)
  4039. return new Multiply (newDest, right->clone());
  4040. else
  4041. return new Divide (left->clone(), newDest);
  4042. }
  4043. private:
  4044. Divide (const Divide&);
  4045. Divide& operator= (const Divide&);
  4046. };
  4047. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4048. {
  4049. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4050. if (inputIndex >= 0)
  4051. return topLevel;
  4052. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4053. {
  4054. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4055. if (t != 0)
  4056. return t;
  4057. }
  4058. return 0;
  4059. }
  4060. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4061. {
  4062. Constant* c = dynamic_cast<Constant*> (term);
  4063. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4064. return c;
  4065. if (dynamic_cast<Function*> (term) != 0)
  4066. return 0;
  4067. int i;
  4068. const int numIns = term->getNumInputs();
  4069. for (i = 0; i < numIns; ++i)
  4070. {
  4071. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4072. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4073. return c;
  4074. }
  4075. for (i = 0; i < numIns; ++i)
  4076. {
  4077. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4078. if (c != 0)
  4079. return c;
  4080. }
  4081. return 0;
  4082. }
  4083. static bool containsAnySymbols (const Term* const t)
  4084. {
  4085. if (dynamic_cast <const Symbol*> (t) != 0)
  4086. return true;
  4087. for (int i = t->getNumInputs(); --i >= 0;)
  4088. if (containsAnySymbols (t->getInput (i)))
  4089. return true;
  4090. return false;
  4091. }
  4092. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4093. {
  4094. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4095. if (sym != 0 && sym->mainSymbol == oldName)
  4096. {
  4097. sym->mainSymbol = newName;
  4098. return true;
  4099. }
  4100. bool anyChanged = false;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (renameSymbol (t->getInput (i), oldName, newName))
  4103. anyChanged = true;
  4104. return anyChanged;
  4105. }
  4106. class Parser
  4107. {
  4108. public:
  4109. Parser (const String& stringToParse, int& textIndex_)
  4110. : textString (stringToParse), textIndex (textIndex_)
  4111. {
  4112. text = textString;
  4113. }
  4114. const TermPtr readExpression()
  4115. {
  4116. TermPtr lhs (readMultiplyOrDivideExpression());
  4117. char opType;
  4118. while (lhs != 0 && readOperator ("+-", &opType))
  4119. {
  4120. TermPtr rhs (readMultiplyOrDivideExpression());
  4121. if (rhs == 0)
  4122. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4123. if (opType == '+')
  4124. lhs = new Add (lhs, rhs);
  4125. else
  4126. lhs = new Subtract (lhs, rhs);
  4127. }
  4128. return lhs;
  4129. }
  4130. private:
  4131. const String textString;
  4132. const juce_wchar* text;
  4133. int& textIndex;
  4134. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4135. {
  4136. return c >= '0' && c <= '9';
  4137. }
  4138. void skipWhitespace (int& i)
  4139. {
  4140. while (CharacterFunctions::isWhitespace (text [i]))
  4141. ++i;
  4142. }
  4143. bool readChar (const juce_wchar required)
  4144. {
  4145. if (text[textIndex] == required)
  4146. {
  4147. ++textIndex;
  4148. return true;
  4149. }
  4150. return false;
  4151. }
  4152. bool readOperator (const char* ops, char* const opType = 0)
  4153. {
  4154. skipWhitespace (textIndex);
  4155. while (*ops != 0)
  4156. {
  4157. if (readChar (*ops))
  4158. {
  4159. if (opType != 0)
  4160. *opType = *ops;
  4161. return true;
  4162. }
  4163. ++ops;
  4164. }
  4165. return false;
  4166. }
  4167. bool readIdentifier (String& identifier)
  4168. {
  4169. skipWhitespace (textIndex);
  4170. int i = textIndex;
  4171. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4172. {
  4173. ++i;
  4174. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4175. ++i;
  4176. }
  4177. if (i > textIndex)
  4178. {
  4179. identifier = String (text + textIndex, i - textIndex);
  4180. textIndex = i;
  4181. return true;
  4182. }
  4183. return false;
  4184. }
  4185. Term* readNumber()
  4186. {
  4187. skipWhitespace (textIndex);
  4188. int i = textIndex;
  4189. const bool isResolutionTarget = (text[i] == '@');
  4190. if (isResolutionTarget)
  4191. {
  4192. ++i;
  4193. skipWhitespace (i);
  4194. textIndex = i;
  4195. }
  4196. if (text[i] == '-')
  4197. {
  4198. ++i;
  4199. skipWhitespace (i);
  4200. }
  4201. int numDigits = 0;
  4202. while (isDecimalDigit (text[i]))
  4203. {
  4204. ++i;
  4205. ++numDigits;
  4206. }
  4207. const bool hasPoint = (text[i] == '.');
  4208. if (hasPoint)
  4209. {
  4210. ++i;
  4211. while (isDecimalDigit (text[i]))
  4212. {
  4213. ++i;
  4214. ++numDigits;
  4215. }
  4216. }
  4217. if (numDigits == 0)
  4218. return 0;
  4219. juce_wchar c = text[i];
  4220. const bool hasExponent = (c == 'e' || c == 'E');
  4221. if (hasExponent)
  4222. {
  4223. ++i;
  4224. c = text[i];
  4225. if (c == '+' || c == '-')
  4226. ++i;
  4227. int numExpDigits = 0;
  4228. while (isDecimalDigit (text[i]))
  4229. {
  4230. ++i;
  4231. ++numExpDigits;
  4232. }
  4233. if (numExpDigits == 0)
  4234. return 0;
  4235. }
  4236. const int start = textIndex;
  4237. textIndex = i;
  4238. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4239. }
  4240. const TermPtr readMultiplyOrDivideExpression()
  4241. {
  4242. TermPtr lhs (readUnaryExpression());
  4243. char opType;
  4244. while (lhs != 0 && readOperator ("*/", &opType))
  4245. {
  4246. TermPtr rhs (readUnaryExpression());
  4247. if (rhs == 0)
  4248. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4249. if (opType == '*')
  4250. lhs = new Multiply (lhs, rhs);
  4251. else
  4252. lhs = new Divide (lhs, rhs);
  4253. }
  4254. return lhs;
  4255. }
  4256. const TermPtr readUnaryExpression()
  4257. {
  4258. char opType;
  4259. if (readOperator ("+-", &opType))
  4260. {
  4261. TermPtr term (readUnaryExpression());
  4262. if (term == 0)
  4263. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4264. if (opType == '-')
  4265. term = term->negated();
  4266. return term;
  4267. }
  4268. return readPrimaryExpression();
  4269. }
  4270. const TermPtr readPrimaryExpression()
  4271. {
  4272. TermPtr e (readParenthesisedExpression());
  4273. if (e != 0)
  4274. return e;
  4275. e = readNumber();
  4276. if (e != 0)
  4277. return e;
  4278. String identifier;
  4279. if (readIdentifier (identifier))
  4280. {
  4281. if (readOperator ("(")) // method call...
  4282. {
  4283. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4284. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4285. TermPtr param (readExpression());
  4286. if (param == 0)
  4287. {
  4288. if (readOperator (")"))
  4289. return func.release();
  4290. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4291. }
  4292. f->parameters.add (param);
  4293. while (readOperator (","))
  4294. {
  4295. param = readExpression();
  4296. if (param == 0)
  4297. throw ParseError ("Expected expression after \",\"");
  4298. f->parameters.add (param);
  4299. }
  4300. if (readOperator (")"))
  4301. return func.release();
  4302. throw ParseError ("Expected \")\"");
  4303. }
  4304. else // just a symbol..
  4305. {
  4306. return new Symbol (identifier);
  4307. }
  4308. }
  4309. return 0;
  4310. }
  4311. const TermPtr readParenthesisedExpression()
  4312. {
  4313. if (! readOperator ("("))
  4314. return 0;
  4315. const TermPtr e (readExpression());
  4316. if (e == 0 || ! readOperator (")"))
  4317. return 0;
  4318. return e;
  4319. }
  4320. Parser (const Parser&);
  4321. Parser& operator= (const Parser&);
  4322. };
  4323. };
  4324. Expression::Expression()
  4325. : term (new Expression::Helpers::Constant (0, false))
  4326. {
  4327. }
  4328. Expression::~Expression()
  4329. {
  4330. }
  4331. Expression::Expression (Term* const term_)
  4332. : term (term_)
  4333. {
  4334. jassert (term != 0);
  4335. }
  4336. Expression::Expression (const double constant)
  4337. : term (new Expression::Helpers::Constant (constant, false))
  4338. {
  4339. }
  4340. Expression::Expression (const Expression& other)
  4341. : term (other.term)
  4342. {
  4343. }
  4344. Expression& Expression::operator= (const Expression& other)
  4345. {
  4346. term = other.term;
  4347. return *this;
  4348. }
  4349. Expression::Expression (const String& stringToParse)
  4350. {
  4351. int i = 0;
  4352. Helpers::Parser parser (stringToParse, i);
  4353. term = parser.readExpression();
  4354. if (term == 0)
  4355. term = new Helpers::Constant (0, false);
  4356. }
  4357. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4358. {
  4359. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4360. const Helpers::TermPtr term (parser.readExpression());
  4361. if (term != 0)
  4362. return Expression (term);
  4363. return Expression();
  4364. }
  4365. double Expression::evaluate() const
  4366. {
  4367. return evaluate (Expression::EvaluationContext());
  4368. }
  4369. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4370. {
  4371. return term->evaluate (context, 0);
  4372. }
  4373. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4374. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4375. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4376. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4377. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4378. const String Expression::toString() const
  4379. {
  4380. return term->toString();
  4381. }
  4382. const Expression Expression::symbol (const String& symbol)
  4383. {
  4384. return Expression (new Helpers::Symbol (symbol));
  4385. }
  4386. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4387. {
  4388. ReferenceCountedArray<Term> params;
  4389. for (int i = 0; i < parameters.size(); ++i)
  4390. params.add (parameters.getReference(i).term);
  4391. return Expression (new Helpers::Function (functionName, params));
  4392. }
  4393. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4394. const Expression::EvaluationContext& context) const
  4395. {
  4396. ScopedPointer<Term> newTerm (term->clone());
  4397. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4398. if (termToAdjust == 0)
  4399. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4400. if (termToAdjust == 0)
  4401. {
  4402. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4403. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4404. }
  4405. jassert (termToAdjust != 0);
  4406. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4407. if (parent == 0)
  4408. {
  4409. termToAdjust->value = targetValue;
  4410. }
  4411. else
  4412. {
  4413. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4414. if (reverseTerm == 0)
  4415. return Expression (targetValue);
  4416. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4417. }
  4418. return Expression (newTerm.release());
  4419. }
  4420. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4421. {
  4422. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4423. Expression newExpression (term->clone());
  4424. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4425. return newExpression;
  4426. }
  4427. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4428. {
  4429. return term->referencesSymbol (symbol, context, 0);
  4430. }
  4431. bool Expression::usesAnySymbols() const
  4432. {
  4433. return Helpers::containsAnySymbols (term);
  4434. }
  4435. Expression::Type Expression::getType() const throw()
  4436. {
  4437. return term->getType();
  4438. }
  4439. const String Expression::getSymbol() const
  4440. {
  4441. return term->getSymbolName();
  4442. }
  4443. const String Expression::getFunction() const
  4444. {
  4445. return term->getFunctionName();
  4446. }
  4447. const String Expression::getOperator() const
  4448. {
  4449. return term->getFunctionName();
  4450. }
  4451. int Expression::getNumInputs() const
  4452. {
  4453. return term->getNumInputs();
  4454. }
  4455. const Expression Expression::getInput (int index) const
  4456. {
  4457. return Expression (term->getInput (index));
  4458. }
  4459. int Expression::Term::getOperatorPrecedence() const
  4460. {
  4461. return 0;
  4462. }
  4463. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4464. {
  4465. return false;
  4466. }
  4467. int Expression::Term::getInputIndexFor (const Term*) const
  4468. {
  4469. return -1;
  4470. }
  4471. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4472. {
  4473. jassertfalse;
  4474. return 0;
  4475. }
  4476. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4477. {
  4478. return new Helpers::Negate (this);
  4479. }
  4480. const String Expression::Term::getSymbolName() const
  4481. {
  4482. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4483. return String::empty;
  4484. }
  4485. const String Expression::Term::getFunctionName() const
  4486. {
  4487. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4488. return String::empty;
  4489. }
  4490. Expression::ParseError::ParseError (const String& message)
  4491. : description (message)
  4492. {
  4493. DBG ("Expression::ParseError: " + message);
  4494. }
  4495. Expression::EvaluationError::EvaluationError (const String& message)
  4496. : description (message)
  4497. {
  4498. DBG ("Expression::EvaluationError: " + description);
  4499. }
  4500. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4501. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4502. {
  4503. DBG ("Expression::EvaluationError: " + description);
  4504. }
  4505. Expression::EvaluationContext::EvaluationContext() {}
  4506. Expression::EvaluationContext::~EvaluationContext() {}
  4507. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4508. {
  4509. throw EvaluationError (symbol, member);
  4510. }
  4511. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4512. {
  4513. if (numParams > 0)
  4514. {
  4515. if (functionName == "min")
  4516. {
  4517. double v = parameters[0];
  4518. for (int i = 1; i < numParams; ++i)
  4519. v = jmin (v, parameters[i]);
  4520. return v;
  4521. }
  4522. else if (functionName == "max")
  4523. {
  4524. double v = parameters[0];
  4525. for (int i = 1; i < numParams; ++i)
  4526. v = jmax (v, parameters[i]);
  4527. return v;
  4528. }
  4529. else if (numParams == 1)
  4530. {
  4531. if (functionName == "sin") return sin (parameters[0]);
  4532. else if (functionName == "cos") return cos (parameters[0]);
  4533. else if (functionName == "tan") return tan (parameters[0]);
  4534. else if (functionName == "abs") return std::abs (parameters[0]);
  4535. }
  4536. }
  4537. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4538. }
  4539. END_JUCE_NAMESPACE
  4540. /*** End of inlined file: juce_Expression.cpp ***/
  4541. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4542. BEGIN_JUCE_NAMESPACE
  4543. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4544. {
  4545. jassert (keyData != 0);
  4546. jassert (keyBytes > 0);
  4547. static const uint32 initialPValues [18] =
  4548. {
  4549. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4550. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4551. 0x9216d5d9, 0x8979fb1b
  4552. };
  4553. static const uint32 initialSValues [4 * 256] =
  4554. {
  4555. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4556. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4557. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4558. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4559. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4560. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4561. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4562. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4563. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4564. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4565. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4566. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4567. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4568. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4569. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4570. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4571. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4572. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4573. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4574. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4575. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4576. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4577. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4578. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4579. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4580. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4581. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4582. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4583. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4584. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4585. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4586. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4587. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4588. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4589. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4590. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4591. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4592. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4593. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4594. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4595. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4596. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4597. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4598. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4599. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4600. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4601. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4602. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4603. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4604. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4605. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4606. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4607. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4608. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4609. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4610. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4611. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4612. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4613. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4614. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4615. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4616. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4617. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4618. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4619. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4620. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4621. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4622. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4623. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4624. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4625. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4626. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4627. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4628. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4629. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4630. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4631. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4632. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4633. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4634. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4635. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4636. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4637. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4638. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4639. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4640. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4641. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4642. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4643. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4644. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4645. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4646. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4647. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4648. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4649. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4650. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4651. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4652. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4653. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4654. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4655. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4656. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4657. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4658. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4659. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4660. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4661. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4662. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4663. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4664. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4665. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4666. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4667. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4668. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4669. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4670. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4671. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4672. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4673. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4674. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4675. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4676. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4677. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4678. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4679. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4680. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4681. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4682. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4683. };
  4684. memcpy (p, initialPValues, sizeof (p));
  4685. int i, j = 0;
  4686. for (i = 4; --i >= 0;)
  4687. {
  4688. s[i].malloc (256);
  4689. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4690. }
  4691. for (i = 0; i < 18; ++i)
  4692. {
  4693. uint32 d = 0;
  4694. for (int k = 0; k < 4; ++k)
  4695. {
  4696. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4697. if (++j >= keyBytes)
  4698. j = 0;
  4699. }
  4700. p[i] = initialPValues[i] ^ d;
  4701. }
  4702. uint32 l = 0, r = 0;
  4703. for (i = 0; i < 18; i += 2)
  4704. {
  4705. encrypt (l, r);
  4706. p[i] = l;
  4707. p[i + 1] = r;
  4708. }
  4709. for (i = 0; i < 4; ++i)
  4710. {
  4711. for (j = 0; j < 256; j += 2)
  4712. {
  4713. encrypt (l, r);
  4714. s[i][j] = l;
  4715. s[i][j + 1] = r;
  4716. }
  4717. }
  4718. }
  4719. BlowFish::BlowFish (const BlowFish& other)
  4720. {
  4721. for (int i = 4; --i >= 0;)
  4722. s[i].malloc (256);
  4723. operator= (other);
  4724. }
  4725. BlowFish& BlowFish::operator= (const BlowFish& other)
  4726. {
  4727. memcpy (p, other.p, sizeof (p));
  4728. for (int i = 4; --i >= 0;)
  4729. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4730. return *this;
  4731. }
  4732. BlowFish::~BlowFish()
  4733. {
  4734. }
  4735. uint32 BlowFish::F (const uint32 x) const throw()
  4736. {
  4737. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4738. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4739. }
  4740. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4741. {
  4742. uint32 l = data1;
  4743. uint32 r = data2;
  4744. for (int i = 0; i < 16; ++i)
  4745. {
  4746. l ^= p[i];
  4747. r ^= F(l);
  4748. swapVariables (l, r);
  4749. }
  4750. data1 = r ^ p[17];
  4751. data2 = l ^ p[16];
  4752. }
  4753. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4754. {
  4755. uint32 l = data1;
  4756. uint32 r = data2;
  4757. for (int i = 17; i > 1; --i)
  4758. {
  4759. l ^= p[i];
  4760. r ^= F(l);
  4761. swapVariables (l, r);
  4762. }
  4763. data1 = r ^ p[0];
  4764. data2 = l ^ p[1];
  4765. }
  4766. END_JUCE_NAMESPACE
  4767. /*** End of inlined file: juce_BlowFish.cpp ***/
  4768. /*** Start of inlined file: juce_MD5.cpp ***/
  4769. BEGIN_JUCE_NAMESPACE
  4770. MD5::MD5()
  4771. {
  4772. zerostruct (result);
  4773. }
  4774. MD5::MD5 (const MD5& other)
  4775. {
  4776. memcpy (result, other.result, sizeof (result));
  4777. }
  4778. MD5& MD5::operator= (const MD5& other)
  4779. {
  4780. memcpy (result, other.result, sizeof (result));
  4781. return *this;
  4782. }
  4783. MD5::MD5 (const MemoryBlock& data)
  4784. {
  4785. ProcessContext context;
  4786. context.processBlock (data.getData(), data.getSize());
  4787. context.finish (result);
  4788. }
  4789. MD5::MD5 (const void* data, const size_t numBytes)
  4790. {
  4791. ProcessContext context;
  4792. context.processBlock (data, numBytes);
  4793. context.finish (result);
  4794. }
  4795. MD5::MD5 (const String& text)
  4796. {
  4797. ProcessContext context;
  4798. const int len = text.length();
  4799. const juce_wchar* const t = text;
  4800. for (int i = 0; i < len; ++i)
  4801. {
  4802. // force the string into integer-sized unicode characters, to try to make it
  4803. // get the same results on all platforms + compilers.
  4804. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4805. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4806. }
  4807. context.finish (result);
  4808. }
  4809. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4810. {
  4811. ProcessContext context;
  4812. if (numBytesToRead < 0)
  4813. numBytesToRead = std::numeric_limits<int64>::max();
  4814. while (numBytesToRead > 0)
  4815. {
  4816. uint8 tempBuffer [512];
  4817. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4818. if (bytesRead <= 0)
  4819. break;
  4820. numBytesToRead -= bytesRead;
  4821. context.processBlock (tempBuffer, bytesRead);
  4822. }
  4823. context.finish (result);
  4824. }
  4825. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4826. {
  4827. processStream (input, numBytesToRead);
  4828. }
  4829. MD5::MD5 (const File& file)
  4830. {
  4831. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4832. if (fin != 0)
  4833. processStream (*fin, -1);
  4834. else
  4835. zerostruct (result);
  4836. }
  4837. MD5::~MD5()
  4838. {
  4839. }
  4840. namespace MD5Functions
  4841. {
  4842. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4843. {
  4844. for (int i = 0; i < (numBytes >> 2); ++i)
  4845. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4846. }
  4847. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4848. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4849. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4850. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4851. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4852. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4853. {
  4854. a += F (b, c, d) + x + ac;
  4855. a = rotateLeft (a, s) + b;
  4856. }
  4857. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4858. {
  4859. a += G (b, c, d) + x + ac;
  4860. a = rotateLeft (a, s) + b;
  4861. }
  4862. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4863. {
  4864. a += H (b, c, d) + x + ac;
  4865. a = rotateLeft (a, s) + b;
  4866. }
  4867. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += I (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. }
  4873. MD5::ProcessContext::ProcessContext()
  4874. {
  4875. state[0] = 0x67452301;
  4876. state[1] = 0xefcdab89;
  4877. state[2] = 0x98badcfe;
  4878. state[3] = 0x10325476;
  4879. count[0] = 0;
  4880. count[1] = 0;
  4881. }
  4882. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4883. {
  4884. int bufferPos = ((count[0] >> 3) & 0x3F);
  4885. count[0] += (uint32) (dataSize << 3);
  4886. if (count[0] < ((uint32) dataSize << 3))
  4887. count[1]++;
  4888. count[1] += (uint32) (dataSize >> 29);
  4889. const size_t spaceLeft = 64 - bufferPos;
  4890. size_t i = 0;
  4891. if (dataSize >= spaceLeft)
  4892. {
  4893. memcpy (buffer + bufferPos, data, spaceLeft);
  4894. transform (buffer);
  4895. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4896. transform (static_cast <const char*> (data) + i);
  4897. bufferPos = 0;
  4898. }
  4899. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4900. }
  4901. void MD5::ProcessContext::finish (void* const result)
  4902. {
  4903. unsigned char encodedLength[8];
  4904. MD5Functions::encode (encodedLength, count, 8);
  4905. // Pad out to 56 mod 64.
  4906. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4907. const int paddingLength = (index < 56) ? (56 - index)
  4908. : (120 - index);
  4909. uint8 paddingBuffer [64];
  4910. zeromem (paddingBuffer, paddingLength);
  4911. paddingBuffer [0] = 0x80;
  4912. processBlock (paddingBuffer, paddingLength);
  4913. processBlock (encodedLength, 8);
  4914. MD5Functions::encode (result, state, 16);
  4915. zerostruct (buffer);
  4916. }
  4917. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4918. {
  4919. using namespace MD5Functions;
  4920. uint32 a = state[0];
  4921. uint32 b = state[1];
  4922. uint32 c = state[2];
  4923. uint32 d = state[3];
  4924. uint32 x[16];
  4925. encode (x, bufferToTransform, 64);
  4926. enum Constants
  4927. {
  4928. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4929. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4930. };
  4931. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4932. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4933. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4934. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4935. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4936. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4937. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4938. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4939. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4940. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4941. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4942. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4943. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4944. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4945. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4946. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4947. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4948. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4949. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4950. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4951. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4952. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4953. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4954. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4955. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4956. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4957. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4958. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4959. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4960. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4961. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4962. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4963. state[0] += a;
  4964. state[1] += b;
  4965. state[2] += c;
  4966. state[3] += d;
  4967. zerostruct (x);
  4968. }
  4969. const MemoryBlock MD5::getRawChecksumData() const
  4970. {
  4971. return MemoryBlock (result, sizeof (result));
  4972. }
  4973. const String MD5::toHexString() const
  4974. {
  4975. return String::toHexString (result, sizeof (result), 0);
  4976. }
  4977. bool MD5::operator== (const MD5& other) const
  4978. {
  4979. return memcmp (result, other.result, sizeof (result)) == 0;
  4980. }
  4981. bool MD5::operator!= (const MD5& other) const
  4982. {
  4983. return ! operator== (other);
  4984. }
  4985. END_JUCE_NAMESPACE
  4986. /*** End of inlined file: juce_MD5.cpp ***/
  4987. /*** Start of inlined file: juce_Primes.cpp ***/
  4988. BEGIN_JUCE_NAMESPACE
  4989. namespace PrimesHelpers
  4990. {
  4991. static void createSmallSieve (const int numBits, BigInteger& result)
  4992. {
  4993. result.setBit (numBits);
  4994. result.clearBit (numBits); // to enlarge the array
  4995. result.setBit (0);
  4996. int n = 2;
  4997. do
  4998. {
  4999. for (int i = n + n; i < numBits; i += n)
  5000. result.setBit (i);
  5001. n = result.findNextClearBit (n + 1);
  5002. }
  5003. while (n <= (numBits >> 1));
  5004. }
  5005. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5006. const BigInteger& smallSieve, const int smallSieveSize)
  5007. {
  5008. jassert (! base[0]); // must be even!
  5009. result.setBit (numBits);
  5010. result.clearBit (numBits); // to enlarge the array
  5011. int index = smallSieve.findNextClearBit (0);
  5012. do
  5013. {
  5014. const int prime = (index << 1) + 1;
  5015. BigInteger r (base), remainder;
  5016. r.divideBy (prime, remainder);
  5017. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5018. if (r.isZero())
  5019. i += prime;
  5020. if ((i & 1) == 0)
  5021. i += prime;
  5022. i = (i - 1) >> 1;
  5023. while (i < numBits)
  5024. {
  5025. result.setBit (i);
  5026. i += prime;
  5027. }
  5028. index = smallSieve.findNextClearBit (index + 1);
  5029. }
  5030. while (index < smallSieveSize);
  5031. }
  5032. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5033. const int numBits, BigInteger& result, const int certainty)
  5034. {
  5035. for (int i = 0; i < numBits; ++i)
  5036. {
  5037. if (! sieve[i])
  5038. {
  5039. result = base + (unsigned int) ((i << 1) + 1);
  5040. if (Primes::isProbablyPrime (result, certainty))
  5041. return true;
  5042. }
  5043. }
  5044. return false;
  5045. }
  5046. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5047. {
  5048. const BigInteger one (1), two (2);
  5049. const BigInteger nMinusOne (n - one);
  5050. BigInteger d (nMinusOne);
  5051. const int s = d.findNextSetBit (0);
  5052. d >>= s;
  5053. BigInteger smallPrimes;
  5054. int numBitsInSmallPrimes = 0;
  5055. for (;;)
  5056. {
  5057. numBitsInSmallPrimes += 256;
  5058. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5059. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5060. if (numPrimesFound > iterations + 1)
  5061. break;
  5062. }
  5063. int smallPrime = 2;
  5064. while (--iterations >= 0)
  5065. {
  5066. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5067. BigInteger r (smallPrime);
  5068. r.exponentModulo (d, n);
  5069. if (r != one && r != nMinusOne)
  5070. {
  5071. for (int j = 0; j < s; ++j)
  5072. {
  5073. r.exponentModulo (two, n);
  5074. if (r == nMinusOne)
  5075. break;
  5076. }
  5077. if (r != nMinusOne)
  5078. return false;
  5079. }
  5080. }
  5081. return true;
  5082. }
  5083. }
  5084. const BigInteger Primes::createProbablePrime (const int bitLength,
  5085. const int certainty,
  5086. const int* randomSeeds,
  5087. int numRandomSeeds)
  5088. {
  5089. using namespace PrimesHelpers;
  5090. int defaultSeeds [16];
  5091. if (numRandomSeeds <= 0)
  5092. {
  5093. randomSeeds = defaultSeeds;
  5094. numRandomSeeds = numElementsInArray (defaultSeeds);
  5095. Random r (0);
  5096. for (int j = 10; --j >= 0;)
  5097. {
  5098. r.setSeedRandomly();
  5099. for (int i = numRandomSeeds; --i >= 0;)
  5100. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5101. }
  5102. }
  5103. BigInteger smallSieve;
  5104. const int smallSieveSize = 15000;
  5105. createSmallSieve (smallSieveSize, smallSieve);
  5106. BigInteger p;
  5107. for (int i = numRandomSeeds; --i >= 0;)
  5108. {
  5109. BigInteger p2;
  5110. Random r (randomSeeds[i]);
  5111. r.fillBitsRandomly (p2, 0, bitLength);
  5112. p ^= p2;
  5113. }
  5114. p.setBit (bitLength - 1);
  5115. p.clearBit (0);
  5116. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5117. while (p.getHighestBit() < bitLength)
  5118. {
  5119. p += 2 * searchLen;
  5120. BigInteger sieve;
  5121. bigSieve (p, searchLen, sieve,
  5122. smallSieve, smallSieveSize);
  5123. BigInteger candidate;
  5124. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5125. return candidate;
  5126. }
  5127. jassertfalse;
  5128. return BigInteger();
  5129. }
  5130. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5131. {
  5132. using namespace PrimesHelpers;
  5133. if (! number[0])
  5134. return false;
  5135. if (number.getHighestBit() <= 10)
  5136. {
  5137. const int num = number.getBitRangeAsInt (0, 10);
  5138. for (int i = num / 2; --i > 1;)
  5139. if (num % i == 0)
  5140. return false;
  5141. return true;
  5142. }
  5143. else
  5144. {
  5145. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5146. return false;
  5147. return passesMillerRabin (number, certainty);
  5148. }
  5149. }
  5150. END_JUCE_NAMESPACE
  5151. /*** End of inlined file: juce_Primes.cpp ***/
  5152. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5153. BEGIN_JUCE_NAMESPACE
  5154. RSAKey::RSAKey()
  5155. {
  5156. }
  5157. RSAKey::RSAKey (const String& s)
  5158. {
  5159. if (s.containsChar (','))
  5160. {
  5161. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5162. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5163. }
  5164. else
  5165. {
  5166. // the string needs to be two hex numbers, comma-separated..
  5167. jassertfalse;
  5168. }
  5169. }
  5170. RSAKey::~RSAKey()
  5171. {
  5172. }
  5173. bool RSAKey::operator== (const RSAKey& other) const throw()
  5174. {
  5175. return part1 == other.part1 && part2 == other.part2;
  5176. }
  5177. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5178. {
  5179. return ! operator== (other);
  5180. }
  5181. const String RSAKey::toString() const
  5182. {
  5183. return part1.toString (16) + "," + part2.toString (16);
  5184. }
  5185. bool RSAKey::applyToValue (BigInteger& value) const
  5186. {
  5187. if (part1.isZero() || part2.isZero() || value <= 0)
  5188. {
  5189. jassertfalse; // using an uninitialised key
  5190. value.clear();
  5191. return false;
  5192. }
  5193. BigInteger result;
  5194. while (! value.isZero())
  5195. {
  5196. result *= part2;
  5197. BigInteger remainder;
  5198. value.divideBy (part2, remainder);
  5199. remainder.exponentModulo (part1, part2);
  5200. result += remainder;
  5201. }
  5202. value.swapWith (result);
  5203. return true;
  5204. }
  5205. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5206. {
  5207. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5208. // are fast to divide + multiply
  5209. for (int i = 2; i <= 65536; i *= 2)
  5210. {
  5211. const BigInteger e (1 + i);
  5212. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5213. return e;
  5214. }
  5215. BigInteger e (4);
  5216. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5217. ++e;
  5218. return e;
  5219. }
  5220. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5221. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5222. {
  5223. jassert (numBits > 16); // not much point using less than this..
  5224. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5225. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5226. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5227. const BigInteger n (p * q);
  5228. const BigInteger m (--p * --q);
  5229. const BigInteger e (findBestCommonDivisor (p, q));
  5230. BigInteger d (e);
  5231. d.inverseModulo (m);
  5232. publicKey.part1 = e;
  5233. publicKey.part2 = n;
  5234. privateKey.part1 = d;
  5235. privateKey.part2 = n;
  5236. }
  5237. END_JUCE_NAMESPACE
  5238. /*** End of inlined file: juce_RSAKey.cpp ***/
  5239. /*** Start of inlined file: juce_InputStream.cpp ***/
  5240. BEGIN_JUCE_NAMESPACE
  5241. char InputStream::readByte()
  5242. {
  5243. char temp = 0;
  5244. read (&temp, 1);
  5245. return temp;
  5246. }
  5247. bool InputStream::readBool()
  5248. {
  5249. return readByte() != 0;
  5250. }
  5251. short InputStream::readShort()
  5252. {
  5253. char temp[2];
  5254. if (read (temp, 2) == 2)
  5255. return (short) ByteOrder::littleEndianShort (temp);
  5256. return 0;
  5257. }
  5258. short InputStream::readShortBigEndian()
  5259. {
  5260. char temp[2];
  5261. if (read (temp, 2) == 2)
  5262. return (short) ByteOrder::bigEndianShort (temp);
  5263. return 0;
  5264. }
  5265. int InputStream::readInt()
  5266. {
  5267. char temp[4];
  5268. if (read (temp, 4) == 4)
  5269. return (int) ByteOrder::littleEndianInt (temp);
  5270. return 0;
  5271. }
  5272. int InputStream::readIntBigEndian()
  5273. {
  5274. char temp[4];
  5275. if (read (temp, 4) == 4)
  5276. return (int) ByteOrder::bigEndianInt (temp);
  5277. return 0;
  5278. }
  5279. int InputStream::readCompressedInt()
  5280. {
  5281. const unsigned char sizeByte = readByte();
  5282. if (sizeByte == 0)
  5283. return 0;
  5284. const int numBytes = (sizeByte & 0x7f);
  5285. if (numBytes > 4)
  5286. {
  5287. jassertfalse; // trying to read corrupt data - this method must only be used
  5288. // to read data that was written by OutputStream::writeCompressedInt()
  5289. return 0;
  5290. }
  5291. char bytes[4] = { 0, 0, 0, 0 };
  5292. if (read (bytes, numBytes) != numBytes)
  5293. return 0;
  5294. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5295. return (sizeByte >> 7) ? -num : num;
  5296. }
  5297. int64 InputStream::readInt64()
  5298. {
  5299. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5300. if (read (n.asBytes, 8) == 8)
  5301. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5302. return 0;
  5303. }
  5304. int64 InputStream::readInt64BigEndian()
  5305. {
  5306. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5307. if (read (n.asBytes, 8) == 8)
  5308. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5309. return 0;
  5310. }
  5311. float InputStream::readFloat()
  5312. {
  5313. // the union below relies on these types being the same size...
  5314. static_jassert (sizeof (int32) == sizeof (float));
  5315. union { int32 asInt; float asFloat; } n;
  5316. n.asInt = (int32) readInt();
  5317. return n.asFloat;
  5318. }
  5319. float InputStream::readFloatBigEndian()
  5320. {
  5321. union { int32 asInt; float asFloat; } n;
  5322. n.asInt = (int32) readIntBigEndian();
  5323. return n.asFloat;
  5324. }
  5325. double InputStream::readDouble()
  5326. {
  5327. union { int64 asInt; double asDouble; } n;
  5328. n.asInt = readInt64();
  5329. return n.asDouble;
  5330. }
  5331. double InputStream::readDoubleBigEndian()
  5332. {
  5333. union { int64 asInt; double asDouble; } n;
  5334. n.asInt = readInt64BigEndian();
  5335. return n.asDouble;
  5336. }
  5337. const String InputStream::readString()
  5338. {
  5339. MemoryBlock buffer (256);
  5340. char* data = static_cast<char*> (buffer.getData());
  5341. size_t i = 0;
  5342. while ((data[i] = readByte()) != 0)
  5343. {
  5344. if (++i >= buffer.getSize())
  5345. {
  5346. buffer.setSize (buffer.getSize() + 512);
  5347. data = static_cast<char*> (buffer.getData());
  5348. }
  5349. }
  5350. return String::fromUTF8 (data, (int) i);
  5351. }
  5352. const String InputStream::readNextLine()
  5353. {
  5354. MemoryBlock buffer (256);
  5355. char* data = static_cast<char*> (buffer.getData());
  5356. size_t i = 0;
  5357. while ((data[i] = readByte()) != 0)
  5358. {
  5359. if (data[i] == '\n')
  5360. break;
  5361. if (data[i] == '\r')
  5362. {
  5363. const int64 lastPos = getPosition();
  5364. if (readByte() != '\n')
  5365. setPosition (lastPos);
  5366. break;
  5367. }
  5368. if (++i >= buffer.getSize())
  5369. {
  5370. buffer.setSize (buffer.getSize() + 512);
  5371. data = static_cast<char*> (buffer.getData());
  5372. }
  5373. }
  5374. return String::fromUTF8 (data, (int) i);
  5375. }
  5376. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5377. {
  5378. MemoryOutputStream mo (block, true);
  5379. return mo.writeFromInputStream (*this, numBytes);
  5380. }
  5381. const String InputStream::readEntireStreamAsString()
  5382. {
  5383. MemoryOutputStream mo;
  5384. mo.writeFromInputStream (*this, -1);
  5385. return mo.toString();
  5386. }
  5387. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5388. {
  5389. if (numBytesToSkip > 0)
  5390. {
  5391. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5392. HeapBlock<char> temp (skipBufferSize);
  5393. while (numBytesToSkip > 0 && ! isExhausted())
  5394. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5395. }
  5396. }
  5397. END_JUCE_NAMESPACE
  5398. /*** End of inlined file: juce_InputStream.cpp ***/
  5399. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5400. BEGIN_JUCE_NAMESPACE
  5401. #if JUCE_DEBUG
  5402. static Array<void*, CriticalSection> activeStreams;
  5403. void juce_CheckForDanglingStreams()
  5404. {
  5405. /*
  5406. It's always a bad idea to leak any object, but if you're leaking output
  5407. streams, then there's a good chance that you're failing to flush a file
  5408. to disk properly, which could result in corrupted data and other similar
  5409. nastiness..
  5410. */
  5411. jassert (activeStreams.size() == 0);
  5412. };
  5413. #endif
  5414. OutputStream::OutputStream()
  5415. {
  5416. #if JUCE_DEBUG
  5417. activeStreams.add (this);
  5418. #endif
  5419. }
  5420. OutputStream::~OutputStream()
  5421. {
  5422. #if JUCE_DEBUG
  5423. activeStreams.removeValue (this);
  5424. #endif
  5425. }
  5426. void OutputStream::writeBool (const bool b)
  5427. {
  5428. writeByte (b ? (char) 1
  5429. : (char) 0);
  5430. }
  5431. void OutputStream::writeByte (char byte)
  5432. {
  5433. write (&byte, 1);
  5434. }
  5435. void OutputStream::writeShort (short value)
  5436. {
  5437. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5438. write (&v, 2);
  5439. }
  5440. void OutputStream::writeShortBigEndian (short value)
  5441. {
  5442. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5443. write (&v, 2);
  5444. }
  5445. void OutputStream::writeInt (int value)
  5446. {
  5447. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5448. write (&v, 4);
  5449. }
  5450. void OutputStream::writeIntBigEndian (int value)
  5451. {
  5452. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5453. write (&v, 4);
  5454. }
  5455. void OutputStream::writeCompressedInt (int value)
  5456. {
  5457. unsigned int un = (value < 0) ? (unsigned int) -value
  5458. : (unsigned int) value;
  5459. uint8 data[5];
  5460. int num = 0;
  5461. while (un > 0)
  5462. {
  5463. data[++num] = (uint8) un;
  5464. un >>= 8;
  5465. }
  5466. data[0] = (uint8) num;
  5467. if (value < 0)
  5468. data[0] |= 0x80;
  5469. write (data, num + 1);
  5470. }
  5471. void OutputStream::writeInt64 (int64 value)
  5472. {
  5473. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5474. write (&v, 8);
  5475. }
  5476. void OutputStream::writeInt64BigEndian (int64 value)
  5477. {
  5478. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5479. write (&v, 8);
  5480. }
  5481. void OutputStream::writeFloat (float value)
  5482. {
  5483. union { int asInt; float asFloat; } n;
  5484. n.asFloat = value;
  5485. writeInt (n.asInt);
  5486. }
  5487. void OutputStream::writeFloatBigEndian (float value)
  5488. {
  5489. union { int asInt; float asFloat; } n;
  5490. n.asFloat = value;
  5491. writeIntBigEndian (n.asInt);
  5492. }
  5493. void OutputStream::writeDouble (double value)
  5494. {
  5495. union { int64 asInt; double asDouble; } n;
  5496. n.asDouble = value;
  5497. writeInt64 (n.asInt);
  5498. }
  5499. void OutputStream::writeDoubleBigEndian (double value)
  5500. {
  5501. union { int64 asInt; double asDouble; } n;
  5502. n.asDouble = value;
  5503. writeInt64BigEndian (n.asInt);
  5504. }
  5505. void OutputStream::writeString (const String& text)
  5506. {
  5507. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5508. // if lots of large, persistent strings were to be written to streams).
  5509. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5510. HeapBlock<char> temp (numBytes);
  5511. text.copyToUTF8 (temp, numBytes);
  5512. write (temp, numBytes);
  5513. }
  5514. void OutputStream::writeText (const String& text, const bool asUnicode,
  5515. const bool writeUnicodeHeaderBytes)
  5516. {
  5517. if (asUnicode)
  5518. {
  5519. if (writeUnicodeHeaderBytes)
  5520. write ("\x0ff\x0fe", 2);
  5521. const juce_wchar* src = text;
  5522. bool lastCharWasReturn = false;
  5523. while (*src != 0)
  5524. {
  5525. if (*src == L'\n' && ! lastCharWasReturn)
  5526. writeShort ((short) L'\r');
  5527. lastCharWasReturn = (*src == L'\r');
  5528. writeShort ((short) *src++);
  5529. }
  5530. }
  5531. else
  5532. {
  5533. const char* src = text.toUTF8();
  5534. const char* t = src;
  5535. for (;;)
  5536. {
  5537. if (*t == '\n')
  5538. {
  5539. if (t > src)
  5540. write (src, (int) (t - src));
  5541. write ("\r\n", 2);
  5542. src = t + 1;
  5543. }
  5544. else if (*t == '\r')
  5545. {
  5546. if (t[1] == '\n')
  5547. ++t;
  5548. }
  5549. else if (*t == 0)
  5550. {
  5551. if (t > src)
  5552. write (src, (int) (t - src));
  5553. break;
  5554. }
  5555. ++t;
  5556. }
  5557. }
  5558. }
  5559. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5560. {
  5561. if (numBytesToWrite < 0)
  5562. numBytesToWrite = std::numeric_limits<int64>::max();
  5563. int numWritten = 0;
  5564. while (numBytesToWrite > 0 && ! source.isExhausted())
  5565. {
  5566. char buffer [8192];
  5567. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5568. if (num <= 0)
  5569. break;
  5570. write (buffer, num);
  5571. numBytesToWrite -= num;
  5572. numWritten += num;
  5573. }
  5574. return numWritten;
  5575. }
  5576. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5577. {
  5578. return stream << String (number);
  5579. }
  5580. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5581. {
  5582. return stream << String (number);
  5583. }
  5584. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5585. {
  5586. stream.writeByte (character);
  5587. return stream;
  5588. }
  5589. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5590. {
  5591. stream.write (text, (int) strlen (text));
  5592. return stream;
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5595. {
  5596. stream.write (data.getData(), (int) data.getSize());
  5597. return stream;
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5600. {
  5601. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5602. if (in != 0)
  5603. stream.writeFromInputStream (*in, -1);
  5604. return stream;
  5605. }
  5606. END_JUCE_NAMESPACE
  5607. /*** End of inlined file: juce_OutputStream.cpp ***/
  5608. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5609. BEGIN_JUCE_NAMESPACE
  5610. DirectoryIterator::DirectoryIterator (const File& directory,
  5611. bool isRecursive_,
  5612. const String& wildCard_,
  5613. const int whatToLookFor_)
  5614. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5615. wildCard (wildCard_),
  5616. path (File::addTrailingSeparator (directory.getFullPathName())),
  5617. index (-1),
  5618. totalNumFiles (-1),
  5619. whatToLookFor (whatToLookFor_),
  5620. isRecursive (isRecursive_),
  5621. hasBeenAdvanced (false)
  5622. {
  5623. // you have to specify the type of files you're looking for!
  5624. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5625. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5626. }
  5627. DirectoryIterator::~DirectoryIterator()
  5628. {
  5629. }
  5630. bool DirectoryIterator::next()
  5631. {
  5632. return next (0, 0, 0, 0, 0, 0);
  5633. }
  5634. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5635. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5636. {
  5637. hasBeenAdvanced = true;
  5638. if (subIterator != 0)
  5639. {
  5640. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5641. return true;
  5642. subIterator = 0;
  5643. }
  5644. String filename;
  5645. bool isDirectory, isHidden;
  5646. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5647. {
  5648. ++index;
  5649. if (! filename.containsOnly ("."))
  5650. {
  5651. const File fileFound (path + filename, 0);
  5652. bool matches = false;
  5653. if (isDirectory)
  5654. {
  5655. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5656. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5657. matches = (whatToLookFor & File::findDirectories) != 0;
  5658. }
  5659. else
  5660. {
  5661. matches = (whatToLookFor & File::findFiles) != 0;
  5662. }
  5663. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5664. if (matches && isRecursive)
  5665. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5666. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5667. matches = ! isHidden;
  5668. if (matches)
  5669. {
  5670. currentFile = fileFound;
  5671. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5672. if (isDirResult != 0) *isDirResult = isDirectory;
  5673. return true;
  5674. }
  5675. else if (subIterator != 0)
  5676. {
  5677. return next();
  5678. }
  5679. }
  5680. }
  5681. return false;
  5682. }
  5683. const File DirectoryIterator::getFile() const
  5684. {
  5685. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5686. return subIterator->getFile();
  5687. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5688. jassert (hasBeenAdvanced);
  5689. return currentFile;
  5690. }
  5691. float DirectoryIterator::getEstimatedProgress() const
  5692. {
  5693. if (totalNumFiles < 0)
  5694. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5695. if (totalNumFiles <= 0)
  5696. return 0.0f;
  5697. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5698. : (float) index;
  5699. return detailedIndex / totalNumFiles;
  5700. }
  5701. END_JUCE_NAMESPACE
  5702. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5703. /*** Start of inlined file: juce_File.cpp ***/
  5704. #if ! JUCE_WINDOWS
  5705. #include <pwd.h>
  5706. #endif
  5707. BEGIN_JUCE_NAMESPACE
  5708. File::File (const String& fullPathName)
  5709. : fullPath (parseAbsolutePath (fullPathName))
  5710. {
  5711. }
  5712. File::File (const String& path, int)
  5713. : fullPath (path)
  5714. {
  5715. }
  5716. const File File::createFileWithoutCheckingPath (const String& path)
  5717. {
  5718. return File (path, 0);
  5719. }
  5720. File::File (const File& other)
  5721. : fullPath (other.fullPath)
  5722. {
  5723. }
  5724. File& File::operator= (const String& newPath)
  5725. {
  5726. fullPath = parseAbsolutePath (newPath);
  5727. return *this;
  5728. }
  5729. File& File::operator= (const File& other)
  5730. {
  5731. fullPath = other.fullPath;
  5732. return *this;
  5733. }
  5734. const File File::nonexistent;
  5735. const String File::parseAbsolutePath (const String& p)
  5736. {
  5737. if (p.isEmpty())
  5738. return String::empty;
  5739. #if JUCE_WINDOWS
  5740. // Windows..
  5741. String path (p.replaceCharacter ('/', '\\'));
  5742. if (path.startsWithChar (File::separator))
  5743. {
  5744. if (path[1] != File::separator)
  5745. {
  5746. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5747. If you're trying to parse a string that may be either a relative path or an absolute path,
  5748. you MUST provide a context against which the partial path can be evaluated - you can do
  5749. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5750. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5751. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5752. */
  5753. jassertfalse;
  5754. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5755. }
  5756. }
  5757. else if (! path.containsChar (':'))
  5758. {
  5759. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5760. If you're trying to parse a string that may be either a relative path or an absolute path,
  5761. you MUST provide a context against which the partial path can be evaluated - you can do
  5762. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5763. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5764. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5765. */
  5766. jassertfalse;
  5767. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5768. }
  5769. #else
  5770. // Mac or Linux..
  5771. String path (p.replaceCharacter ('\\', '/'));
  5772. if (path.startsWithChar ('~'))
  5773. {
  5774. if (path[1] == File::separator || path[1] == 0)
  5775. {
  5776. // expand a name of the form "~/abc"
  5777. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5778. + path.substring (1);
  5779. }
  5780. else
  5781. {
  5782. // expand a name of type "~dave/abc"
  5783. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5784. struct passwd* const pw = getpwnam (userName.toUTF8());
  5785. if (pw != 0)
  5786. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5787. }
  5788. }
  5789. else if (! path.startsWithChar (File::separator))
  5790. {
  5791. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5792. If you're trying to parse a string that may be either a relative path or an absolute path,
  5793. you MUST provide a context against which the partial path can be evaluated - you can do
  5794. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5795. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5796. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5797. */
  5798. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5799. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5800. }
  5801. #endif
  5802. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5803. path = path.dropLastCharacters (1);
  5804. return path;
  5805. }
  5806. const String File::addTrailingSeparator (const String& path)
  5807. {
  5808. return path.endsWithChar (File::separator) ? path
  5809. : path + File::separator;
  5810. }
  5811. #if JUCE_LINUX
  5812. #define NAMES_ARE_CASE_SENSITIVE 1
  5813. #endif
  5814. bool File::areFileNamesCaseSensitive()
  5815. {
  5816. #if NAMES_ARE_CASE_SENSITIVE
  5817. return true;
  5818. #else
  5819. return false;
  5820. #endif
  5821. }
  5822. bool File::operator== (const File& other) const
  5823. {
  5824. #if NAMES_ARE_CASE_SENSITIVE
  5825. return fullPath == other.fullPath;
  5826. #else
  5827. return fullPath.equalsIgnoreCase (other.fullPath);
  5828. #endif
  5829. }
  5830. bool File::operator!= (const File& other) const
  5831. {
  5832. return ! operator== (other);
  5833. }
  5834. bool File::operator< (const File& other) const
  5835. {
  5836. #if NAMES_ARE_CASE_SENSITIVE
  5837. return fullPath < other.fullPath;
  5838. #else
  5839. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5840. #endif
  5841. }
  5842. bool File::operator> (const File& other) const
  5843. {
  5844. #if NAMES_ARE_CASE_SENSITIVE
  5845. return fullPath > other.fullPath;
  5846. #else
  5847. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5848. #endif
  5849. }
  5850. bool File::setReadOnly (const bool shouldBeReadOnly,
  5851. const bool applyRecursively) const
  5852. {
  5853. bool worked = true;
  5854. if (applyRecursively && isDirectory())
  5855. {
  5856. Array <File> subFiles;
  5857. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5858. for (int i = subFiles.size(); --i >= 0;)
  5859. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5860. }
  5861. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5862. }
  5863. bool File::deleteRecursively() const
  5864. {
  5865. bool worked = true;
  5866. if (isDirectory())
  5867. {
  5868. Array<File> subFiles;
  5869. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5870. for (int i = subFiles.size(); --i >= 0;)
  5871. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5872. }
  5873. return deleteFile() && worked;
  5874. }
  5875. bool File::moveFileTo (const File& newFile) const
  5876. {
  5877. if (newFile.fullPath == fullPath)
  5878. return true;
  5879. #if ! NAMES_ARE_CASE_SENSITIVE
  5880. if (*this != newFile)
  5881. #endif
  5882. if (! newFile.deleteFile())
  5883. return false;
  5884. return moveInternal (newFile);
  5885. }
  5886. bool File::copyFileTo (const File& newFile) const
  5887. {
  5888. return (*this == newFile)
  5889. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5890. }
  5891. bool File::copyDirectoryTo (const File& newDirectory) const
  5892. {
  5893. if (isDirectory() && newDirectory.createDirectory())
  5894. {
  5895. Array<File> subFiles;
  5896. findChildFiles (subFiles, File::findFiles, false);
  5897. int i;
  5898. for (i = 0; i < subFiles.size(); ++i)
  5899. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5900. return false;
  5901. subFiles.clear();
  5902. findChildFiles (subFiles, File::findDirectories, false);
  5903. for (i = 0; i < subFiles.size(); ++i)
  5904. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5905. return false;
  5906. return true;
  5907. }
  5908. return false;
  5909. }
  5910. const String File::getPathUpToLastSlash() const
  5911. {
  5912. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5913. if (lastSlash > 0)
  5914. return fullPath.substring (0, lastSlash);
  5915. else if (lastSlash == 0)
  5916. return separatorString;
  5917. else
  5918. return fullPath;
  5919. }
  5920. const File File::getParentDirectory() const
  5921. {
  5922. return File (getPathUpToLastSlash(), (int) 0);
  5923. }
  5924. const String File::getFileName() const
  5925. {
  5926. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5927. }
  5928. int File::hashCode() const
  5929. {
  5930. return fullPath.hashCode();
  5931. }
  5932. int64 File::hashCode64() const
  5933. {
  5934. return fullPath.hashCode64();
  5935. }
  5936. const String File::getFileNameWithoutExtension() const
  5937. {
  5938. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5939. const int lastDot = fullPath.lastIndexOfChar ('.');
  5940. if (lastDot > lastSlash)
  5941. return fullPath.substring (lastSlash, lastDot);
  5942. else
  5943. return fullPath.substring (lastSlash);
  5944. }
  5945. bool File::isAChildOf (const File& potentialParent) const
  5946. {
  5947. if (potentialParent == File::nonexistent)
  5948. return false;
  5949. const String ourPath (getPathUpToLastSlash());
  5950. #if NAMES_ARE_CASE_SENSITIVE
  5951. if (potentialParent.fullPath == ourPath)
  5952. #else
  5953. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5954. #endif
  5955. {
  5956. return true;
  5957. }
  5958. else if (potentialParent.fullPath.length() >= ourPath.length())
  5959. {
  5960. return false;
  5961. }
  5962. else
  5963. {
  5964. return getParentDirectory().isAChildOf (potentialParent);
  5965. }
  5966. }
  5967. bool File::isAbsolutePath (const String& path)
  5968. {
  5969. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5970. #if JUCE_WINDOWS
  5971. || (path.isNotEmpty() && path[1] == ':');
  5972. #else
  5973. || path.startsWithChar ('~');
  5974. #endif
  5975. }
  5976. const File File::getChildFile (String relativePath) const
  5977. {
  5978. if (isAbsolutePath (relativePath))
  5979. {
  5980. // the path is really absolute..
  5981. return File (relativePath);
  5982. }
  5983. else
  5984. {
  5985. // it's relative, so remove any ../ or ./ bits at the start.
  5986. String path (fullPath);
  5987. if (relativePath[0] == '.')
  5988. {
  5989. #if JUCE_WINDOWS
  5990. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5991. #else
  5992. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5993. #endif
  5994. while (relativePath[0] == '.')
  5995. {
  5996. if (relativePath[1] == '.')
  5997. {
  5998. if (relativePath [2] == 0 || relativePath[2] == separator)
  5999. {
  6000. const int lastSlash = path.lastIndexOfChar (separator);
  6001. if (lastSlash >= 0)
  6002. path = path.substring (0, lastSlash);
  6003. relativePath = relativePath.substring (3);
  6004. }
  6005. else
  6006. {
  6007. break;
  6008. }
  6009. }
  6010. else if (relativePath[1] == separator)
  6011. {
  6012. relativePath = relativePath.substring (2);
  6013. }
  6014. else
  6015. {
  6016. break;
  6017. }
  6018. }
  6019. }
  6020. return File (addTrailingSeparator (path) + relativePath);
  6021. }
  6022. }
  6023. const File File::getSiblingFile (const String& fileName) const
  6024. {
  6025. return getParentDirectory().getChildFile (fileName);
  6026. }
  6027. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6028. {
  6029. if (bytes == 1)
  6030. {
  6031. return "1 byte";
  6032. }
  6033. else if (bytes < 1024)
  6034. {
  6035. return String ((int) bytes) + " bytes";
  6036. }
  6037. else if (bytes < 1024 * 1024)
  6038. {
  6039. return String (bytes / 1024.0, 1) + " KB";
  6040. }
  6041. else if (bytes < 1024 * 1024 * 1024)
  6042. {
  6043. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6044. }
  6045. else
  6046. {
  6047. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6048. }
  6049. }
  6050. bool File::create() const
  6051. {
  6052. if (exists())
  6053. return true;
  6054. {
  6055. const File parentDir (getParentDirectory());
  6056. if (parentDir == *this || ! parentDir.createDirectory())
  6057. return false;
  6058. FileOutputStream fo (*this, 8);
  6059. }
  6060. return exists();
  6061. }
  6062. bool File::createDirectory() const
  6063. {
  6064. if (! isDirectory())
  6065. {
  6066. const File parentDir (getParentDirectory());
  6067. if (parentDir == *this || ! parentDir.createDirectory())
  6068. return false;
  6069. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6070. return isDirectory();
  6071. }
  6072. return true;
  6073. }
  6074. const Time File::getCreationTime() const
  6075. {
  6076. int64 m, a, c;
  6077. getFileTimesInternal (m, a, c);
  6078. return Time (c);
  6079. }
  6080. const Time File::getLastModificationTime() const
  6081. {
  6082. int64 m, a, c;
  6083. getFileTimesInternal (m, a, c);
  6084. return Time (m);
  6085. }
  6086. const Time File::getLastAccessTime() const
  6087. {
  6088. int64 m, a, c;
  6089. getFileTimesInternal (m, a, c);
  6090. return Time (a);
  6091. }
  6092. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6093. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6094. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6095. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6096. {
  6097. if (! existsAsFile())
  6098. return false;
  6099. FileInputStream in (*this);
  6100. return getSize() == in.readIntoMemoryBlock (destBlock);
  6101. }
  6102. const String File::loadFileAsString() const
  6103. {
  6104. if (! existsAsFile())
  6105. return String::empty;
  6106. FileInputStream in (*this);
  6107. return in.readEntireStreamAsString();
  6108. }
  6109. int File::findChildFiles (Array<File>& results,
  6110. const int whatToLookFor,
  6111. const bool searchRecursively,
  6112. const String& wildCardPattern) const
  6113. {
  6114. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6115. int total = 0;
  6116. while (di.next())
  6117. {
  6118. results.add (di.getFile());
  6119. ++total;
  6120. }
  6121. return total;
  6122. }
  6123. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6124. {
  6125. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6126. int total = 0;
  6127. while (di.next())
  6128. ++total;
  6129. return total;
  6130. }
  6131. bool File::containsSubDirectories() const
  6132. {
  6133. if (isDirectory())
  6134. {
  6135. DirectoryIterator di (*this, false, "*", findDirectories);
  6136. return di.next();
  6137. }
  6138. return false;
  6139. }
  6140. const File File::getNonexistentChildFile (const String& prefix_,
  6141. const String& suffix,
  6142. bool putNumbersInBrackets) const
  6143. {
  6144. File f (getChildFile (prefix_ + suffix));
  6145. if (f.exists())
  6146. {
  6147. int num = 2;
  6148. String prefix (prefix_);
  6149. // remove any bracketed numbers that may already be on the end..
  6150. if (prefix.trim().endsWithChar (')'))
  6151. {
  6152. putNumbersInBrackets = true;
  6153. const int openBracks = prefix.lastIndexOfChar ('(');
  6154. const int closeBracks = prefix.lastIndexOfChar (')');
  6155. if (openBracks > 0
  6156. && closeBracks > openBracks
  6157. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6158. {
  6159. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6160. prefix = prefix.substring (0, openBracks);
  6161. }
  6162. }
  6163. // also use brackets if it ends in a digit.
  6164. putNumbersInBrackets = putNumbersInBrackets
  6165. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6166. do
  6167. {
  6168. if (putNumbersInBrackets)
  6169. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6170. else
  6171. f = getChildFile (prefix + String (num++) + suffix);
  6172. } while (f.exists());
  6173. }
  6174. return f;
  6175. }
  6176. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6177. {
  6178. if (exists())
  6179. {
  6180. return getParentDirectory()
  6181. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6182. getFileExtension(),
  6183. putNumbersInBrackets);
  6184. }
  6185. else
  6186. {
  6187. return *this;
  6188. }
  6189. }
  6190. const String File::getFileExtension() const
  6191. {
  6192. String ext;
  6193. if (! isDirectory())
  6194. {
  6195. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6196. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6197. ext = fullPath.substring (indexOfDot);
  6198. }
  6199. return ext;
  6200. }
  6201. bool File::hasFileExtension (const String& possibleSuffix) const
  6202. {
  6203. if (possibleSuffix.isEmpty())
  6204. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6205. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6206. if (semicolon >= 0)
  6207. {
  6208. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6209. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6210. }
  6211. else
  6212. {
  6213. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6214. {
  6215. if (possibleSuffix.startsWithChar ('.'))
  6216. return true;
  6217. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6218. if (dotPos >= 0)
  6219. return fullPath [dotPos] == '.';
  6220. }
  6221. }
  6222. return false;
  6223. }
  6224. const File File::withFileExtension (const String& newExtension) const
  6225. {
  6226. if (fullPath.isEmpty())
  6227. return File::nonexistent;
  6228. String filePart (getFileName());
  6229. int i = filePart.lastIndexOfChar ('.');
  6230. if (i >= 0)
  6231. filePart = filePart.substring (0, i);
  6232. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6233. filePart << '.';
  6234. return getSiblingFile (filePart + newExtension);
  6235. }
  6236. bool File::startAsProcess (const String& parameters) const
  6237. {
  6238. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6239. }
  6240. FileInputStream* File::createInputStream() const
  6241. {
  6242. if (existsAsFile())
  6243. return new FileInputStream (*this);
  6244. return 0;
  6245. }
  6246. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6247. {
  6248. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6249. if (out->failedToOpen())
  6250. return 0;
  6251. return out.release();
  6252. }
  6253. bool File::appendData (const void* const dataToAppend,
  6254. const int numberOfBytes) const
  6255. {
  6256. if (numberOfBytes > 0)
  6257. {
  6258. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6259. if (out == 0)
  6260. return false;
  6261. out->write (dataToAppend, numberOfBytes);
  6262. }
  6263. return true;
  6264. }
  6265. bool File::replaceWithData (const void* const dataToWrite,
  6266. const int numberOfBytes) const
  6267. {
  6268. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6269. if (numberOfBytes <= 0)
  6270. return deleteFile();
  6271. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6272. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6273. return tempFile.overwriteTargetFileWithTemporary();
  6274. }
  6275. bool File::appendText (const String& text,
  6276. const bool asUnicode,
  6277. const bool writeUnicodeHeaderBytes) const
  6278. {
  6279. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6280. if (out != 0)
  6281. {
  6282. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6283. return true;
  6284. }
  6285. return false;
  6286. }
  6287. bool File::replaceWithText (const String& textToWrite,
  6288. const bool asUnicode,
  6289. const bool writeUnicodeHeaderBytes) const
  6290. {
  6291. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6292. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6293. return tempFile.overwriteTargetFileWithTemporary();
  6294. }
  6295. bool File::hasIdenticalContentTo (const File& other) const
  6296. {
  6297. if (other == *this)
  6298. return true;
  6299. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6300. {
  6301. FileInputStream in1 (*this), in2 (other);
  6302. const int bufferSize = 4096;
  6303. HeapBlock <char> buffer1, buffer2;
  6304. buffer1.malloc (bufferSize);
  6305. buffer2.malloc (bufferSize);
  6306. for (;;)
  6307. {
  6308. const int num1 = in1.read (buffer1, bufferSize);
  6309. const int num2 = in2.read (buffer2, bufferSize);
  6310. if (num1 != num2)
  6311. break;
  6312. if (num1 <= 0)
  6313. return true;
  6314. if (memcmp (buffer1, buffer2, num1) != 0)
  6315. break;
  6316. }
  6317. }
  6318. return false;
  6319. }
  6320. const String File::createLegalPathName (const String& original)
  6321. {
  6322. String s (original);
  6323. String start;
  6324. if (s[1] == ':')
  6325. {
  6326. start = s.substring (0, 2);
  6327. s = s.substring (2);
  6328. }
  6329. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6330. .substring (0, 1024);
  6331. }
  6332. const String File::createLegalFileName (const String& original)
  6333. {
  6334. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6335. const int maxLength = 128; // only the length of the filename, not the whole path
  6336. const int len = s.length();
  6337. if (len > maxLength)
  6338. {
  6339. const int lastDot = s.lastIndexOfChar ('.');
  6340. if (lastDot > jmax (0, len - 12))
  6341. {
  6342. s = s.substring (0, maxLength - (len - lastDot))
  6343. + s.substring (lastDot);
  6344. }
  6345. else
  6346. {
  6347. s = s.substring (0, maxLength);
  6348. }
  6349. }
  6350. return s;
  6351. }
  6352. const String File::getRelativePathFrom (const File& dir) const
  6353. {
  6354. String thisPath (fullPath);
  6355. {
  6356. int len = thisPath.length();
  6357. while (--len >= 0 && thisPath [len] == File::separator)
  6358. thisPath [len] = 0;
  6359. }
  6360. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6361. : dir.fullPath));
  6362. const int len = jmin (thisPath.length(), dirPath.length());
  6363. int commonBitLength = 0;
  6364. for (int i = 0; i < len; ++i)
  6365. {
  6366. #if NAMES_ARE_CASE_SENSITIVE
  6367. if (thisPath[i] != dirPath[i])
  6368. #else
  6369. if (CharacterFunctions::toLowerCase (thisPath[i])
  6370. != CharacterFunctions::toLowerCase (dirPath[i]))
  6371. #endif
  6372. {
  6373. break;
  6374. }
  6375. ++commonBitLength;
  6376. }
  6377. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6378. --commonBitLength;
  6379. // if the only common bit is the root, then just return the full path..
  6380. if (commonBitLength <= 0
  6381. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6382. return fullPath;
  6383. thisPath = thisPath.substring (commonBitLength);
  6384. dirPath = dirPath.substring (commonBitLength);
  6385. while (dirPath.isNotEmpty())
  6386. {
  6387. #if JUCE_WINDOWS
  6388. thisPath = "..\\" + thisPath;
  6389. #else
  6390. thisPath = "../" + thisPath;
  6391. #endif
  6392. const int sep = dirPath.indexOfChar (separator);
  6393. if (sep >= 0)
  6394. dirPath = dirPath.substring (sep + 1);
  6395. else
  6396. dirPath = String::empty;
  6397. }
  6398. return thisPath;
  6399. }
  6400. const File File::createTempFile (const String& fileNameEnding)
  6401. {
  6402. const File tempFile (getSpecialLocation (tempDirectory)
  6403. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6404. .withFileExtension (fileNameEnding));
  6405. if (tempFile.exists())
  6406. return createTempFile (fileNameEnding);
  6407. else
  6408. return tempFile;
  6409. }
  6410. #if JUCE_UNIT_TESTS
  6411. class FileTests : public UnitTest
  6412. {
  6413. public:
  6414. FileTests() : UnitTest ("Files") {}
  6415. void runTest()
  6416. {
  6417. beginTest ("Reading");
  6418. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6419. const File temp (File::getSpecialLocation (File::tempDirectory));
  6420. expect (! File::nonexistent.exists());
  6421. expect (home.isDirectory());
  6422. expect (home.exists());
  6423. expect (! home.existsAsFile());
  6424. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6425. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6426. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6427. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6428. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6429. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6430. expect (home.getBytesFreeOnVolume() > 0);
  6431. expect (! home.isHidden());
  6432. expect (home.isOnHardDisk());
  6433. expect (! home.isOnCDRomDrive());
  6434. expect (File::getCurrentWorkingDirectory().exists());
  6435. expect (home.setAsCurrentWorkingDirectory());
  6436. expect (File::getCurrentWorkingDirectory() == home);
  6437. {
  6438. Array<File> roots;
  6439. File::findFileSystemRoots (roots);
  6440. expect (roots.size() > 0);
  6441. int numRootsExisting = 0;
  6442. for (int i = 0; i < roots.size(); ++i)
  6443. if (roots[i].exists())
  6444. ++numRootsExisting;
  6445. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6446. expect (numRootsExisting > 0);
  6447. }
  6448. beginTest ("Writing");
  6449. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6450. expect (demoFolder.deleteRecursively());
  6451. expect (demoFolder.createDirectory());
  6452. expect (demoFolder.isDirectory());
  6453. expect (demoFolder.getParentDirectory() == temp);
  6454. expect (temp.isDirectory());
  6455. {
  6456. Array<File> files;
  6457. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6458. expect (files.contains (demoFolder));
  6459. }
  6460. {
  6461. Array<File> files;
  6462. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6463. expect (files.contains (demoFolder));
  6464. }
  6465. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6466. expect (tempFile.getFileExtension() == ".txt");
  6467. expect (tempFile.hasFileExtension (".txt"));
  6468. expect (tempFile.hasFileExtension ("txt"));
  6469. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6470. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6471. expect (tempFile.hasWriteAccess());
  6472. {
  6473. FileOutputStream fo (tempFile);
  6474. fo.write ("0123456789", 10);
  6475. }
  6476. expect (tempFile.exists());
  6477. expect (tempFile.getSize() == 10);
  6478. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6479. expect (tempFile.loadFileAsString() == "0123456789");
  6480. expect (! demoFolder.containsSubDirectories());
  6481. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6482. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6483. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6484. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6485. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6486. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6487. expect (demoFolder.containsSubDirectories());
  6488. expect (tempFile.hasWriteAccess());
  6489. tempFile.setReadOnly (true);
  6490. expect (! tempFile.hasWriteAccess());
  6491. tempFile.setReadOnly (false);
  6492. expect (tempFile.hasWriteAccess());
  6493. Time t (Time::getCurrentTime());
  6494. tempFile.setLastModificationTime (t);
  6495. Time t2 = tempFile.getLastModificationTime();
  6496. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6497. {
  6498. MemoryBlock mb;
  6499. tempFile.loadFileAsData (mb);
  6500. expect (mb.getSize() == 10);
  6501. expect (mb[0] == '0');
  6502. }
  6503. expect (tempFile.appendData ("abcdefghij", 10));
  6504. expect (tempFile.getSize() == 20);
  6505. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6506. expect (tempFile.getSize() == 10);
  6507. File tempFile2 (tempFile.getNonexistentSibling (false));
  6508. expect (tempFile.copyFileTo (tempFile2));
  6509. expect (tempFile2.exists());
  6510. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6511. expect (tempFile.deleteFile());
  6512. expect (! tempFile.exists());
  6513. expect (tempFile2.moveFileTo (tempFile));
  6514. expect (tempFile.exists());
  6515. expect (! tempFile2.exists());
  6516. expect (demoFolder.deleteRecursively());
  6517. expect (! demoFolder.exists());
  6518. }
  6519. };
  6520. static FileTests fileUnitTests;
  6521. #endif
  6522. END_JUCE_NAMESPACE
  6523. /*** End of inlined file: juce_File.cpp ***/
  6524. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6525. BEGIN_JUCE_NAMESPACE
  6526. int64 juce_fileSetPosition (void* handle, int64 pos);
  6527. FileInputStream::FileInputStream (const File& f)
  6528. : file (f),
  6529. fileHandle (0),
  6530. currentPosition (0),
  6531. totalSize (0),
  6532. needToSeek (true)
  6533. {
  6534. openHandle();
  6535. }
  6536. FileInputStream::~FileInputStream()
  6537. {
  6538. closeHandle();
  6539. }
  6540. int64 FileInputStream::getTotalLength()
  6541. {
  6542. return totalSize;
  6543. }
  6544. int FileInputStream::read (void* buffer, int bytesToRead)
  6545. {
  6546. int num = 0;
  6547. if (needToSeek)
  6548. {
  6549. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6550. return 0;
  6551. needToSeek = false;
  6552. }
  6553. num = readInternal (buffer, bytesToRead);
  6554. currentPosition += num;
  6555. return num;
  6556. }
  6557. bool FileInputStream::isExhausted()
  6558. {
  6559. return currentPosition >= totalSize;
  6560. }
  6561. int64 FileInputStream::getPosition()
  6562. {
  6563. return currentPosition;
  6564. }
  6565. bool FileInputStream::setPosition (int64 pos)
  6566. {
  6567. pos = jlimit ((int64) 0, totalSize, pos);
  6568. needToSeek |= (currentPosition != pos);
  6569. currentPosition = pos;
  6570. return true;
  6571. }
  6572. END_JUCE_NAMESPACE
  6573. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6574. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6575. BEGIN_JUCE_NAMESPACE
  6576. int64 juce_fileSetPosition (void* handle, int64 pos);
  6577. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6578. : file (f),
  6579. fileHandle (0),
  6580. currentPosition (0),
  6581. bufferSize (bufferSize_),
  6582. bytesInBuffer (0),
  6583. buffer (jmax (bufferSize_, 16))
  6584. {
  6585. openHandle();
  6586. }
  6587. FileOutputStream::~FileOutputStream()
  6588. {
  6589. flush();
  6590. closeHandle();
  6591. }
  6592. int64 FileOutputStream::getPosition()
  6593. {
  6594. return currentPosition;
  6595. }
  6596. bool FileOutputStream::setPosition (int64 newPosition)
  6597. {
  6598. if (newPosition != currentPosition)
  6599. {
  6600. flush();
  6601. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6602. }
  6603. return newPosition == currentPosition;
  6604. }
  6605. void FileOutputStream::flush()
  6606. {
  6607. if (bytesInBuffer > 0)
  6608. {
  6609. writeInternal (buffer, bytesInBuffer);
  6610. bytesInBuffer = 0;
  6611. }
  6612. flushInternal();
  6613. }
  6614. bool FileOutputStream::write (const void* const src, const int numBytes)
  6615. {
  6616. if (bytesInBuffer + numBytes < bufferSize)
  6617. {
  6618. memcpy (buffer + bytesInBuffer, src, numBytes);
  6619. bytesInBuffer += numBytes;
  6620. currentPosition += numBytes;
  6621. }
  6622. else
  6623. {
  6624. if (bytesInBuffer > 0)
  6625. {
  6626. // flush the reservoir
  6627. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6628. bytesInBuffer = 0;
  6629. if (! wroteOk)
  6630. return false;
  6631. }
  6632. if (numBytes < bufferSize)
  6633. {
  6634. memcpy (buffer + bytesInBuffer, src, numBytes);
  6635. bytesInBuffer += numBytes;
  6636. currentPosition += numBytes;
  6637. }
  6638. else
  6639. {
  6640. const int bytesWritten = writeInternal (src, numBytes);
  6641. if (bytesWritten < 0)
  6642. return false;
  6643. currentPosition += bytesWritten;
  6644. return bytesWritten == numBytes;
  6645. }
  6646. }
  6647. return true;
  6648. }
  6649. END_JUCE_NAMESPACE
  6650. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6651. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6652. BEGIN_JUCE_NAMESPACE
  6653. FileSearchPath::FileSearchPath()
  6654. {
  6655. }
  6656. FileSearchPath::FileSearchPath (const String& path)
  6657. {
  6658. init (path);
  6659. }
  6660. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6661. : directories (other.directories)
  6662. {
  6663. }
  6664. FileSearchPath::~FileSearchPath()
  6665. {
  6666. }
  6667. FileSearchPath& FileSearchPath::operator= (const String& path)
  6668. {
  6669. init (path);
  6670. return *this;
  6671. }
  6672. void FileSearchPath::init (const String& path)
  6673. {
  6674. directories.clear();
  6675. directories.addTokens (path, ";", "\"");
  6676. directories.trim();
  6677. directories.removeEmptyStrings();
  6678. for (int i = directories.size(); --i >= 0;)
  6679. directories.set (i, directories[i].unquoted());
  6680. }
  6681. int FileSearchPath::getNumPaths() const
  6682. {
  6683. return directories.size();
  6684. }
  6685. const File FileSearchPath::operator[] (const int index) const
  6686. {
  6687. return File (directories [index]);
  6688. }
  6689. const String FileSearchPath::toString() const
  6690. {
  6691. StringArray directories2 (directories);
  6692. for (int i = directories2.size(); --i >= 0;)
  6693. if (directories2[i].containsChar (';'))
  6694. directories2.set (i, directories2[i].quoted());
  6695. return directories2.joinIntoString (";");
  6696. }
  6697. void FileSearchPath::add (const File& dir, const int insertIndex)
  6698. {
  6699. directories.insert (insertIndex, dir.getFullPathName());
  6700. }
  6701. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6702. {
  6703. for (int i = 0; i < directories.size(); ++i)
  6704. if (File (directories[i]) == dir)
  6705. return;
  6706. add (dir);
  6707. }
  6708. void FileSearchPath::remove (const int index)
  6709. {
  6710. directories.remove (index);
  6711. }
  6712. void FileSearchPath::addPath (const FileSearchPath& other)
  6713. {
  6714. for (int i = 0; i < other.getNumPaths(); ++i)
  6715. addIfNotAlreadyThere (other[i]);
  6716. }
  6717. void FileSearchPath::removeRedundantPaths()
  6718. {
  6719. for (int i = directories.size(); --i >= 0;)
  6720. {
  6721. const File d1 (directories[i]);
  6722. for (int j = directories.size(); --j >= 0;)
  6723. {
  6724. const File d2 (directories[j]);
  6725. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6726. {
  6727. directories.remove (i);
  6728. break;
  6729. }
  6730. }
  6731. }
  6732. }
  6733. void FileSearchPath::removeNonExistentPaths()
  6734. {
  6735. for (int i = directories.size(); --i >= 0;)
  6736. if (! File (directories[i]).isDirectory())
  6737. directories.remove (i);
  6738. }
  6739. int FileSearchPath::findChildFiles (Array<File>& results,
  6740. const int whatToLookFor,
  6741. const bool searchRecursively,
  6742. const String& wildCardPattern) const
  6743. {
  6744. int total = 0;
  6745. for (int i = 0; i < directories.size(); ++i)
  6746. total += operator[] (i).findChildFiles (results,
  6747. whatToLookFor,
  6748. searchRecursively,
  6749. wildCardPattern);
  6750. return total;
  6751. }
  6752. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6753. const bool checkRecursively) const
  6754. {
  6755. for (int i = directories.size(); --i >= 0;)
  6756. {
  6757. const File d (directories[i]);
  6758. if (checkRecursively)
  6759. {
  6760. if (fileToCheck.isAChildOf (d))
  6761. return true;
  6762. }
  6763. else
  6764. {
  6765. if (fileToCheck.getParentDirectory() == d)
  6766. return true;
  6767. }
  6768. }
  6769. return false;
  6770. }
  6771. END_JUCE_NAMESPACE
  6772. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6773. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6774. BEGIN_JUCE_NAMESPACE
  6775. NamedPipe::NamedPipe()
  6776. : internal (0)
  6777. {
  6778. }
  6779. NamedPipe::~NamedPipe()
  6780. {
  6781. close();
  6782. }
  6783. bool NamedPipe::openExisting (const String& pipeName)
  6784. {
  6785. currentPipeName = pipeName;
  6786. return openInternal (pipeName, false);
  6787. }
  6788. bool NamedPipe::createNewPipe (const String& pipeName)
  6789. {
  6790. currentPipeName = pipeName;
  6791. return openInternal (pipeName, true);
  6792. }
  6793. bool NamedPipe::isOpen() const
  6794. {
  6795. return internal != 0;
  6796. }
  6797. const String NamedPipe::getName() const
  6798. {
  6799. return currentPipeName;
  6800. }
  6801. // other methods for this class are implemented in the platform-specific files
  6802. END_JUCE_NAMESPACE
  6803. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6804. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6805. BEGIN_JUCE_NAMESPACE
  6806. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6807. {
  6808. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6809. "temp_" + String (Random::getSystemRandom().nextInt()),
  6810. suffix,
  6811. optionFlags);
  6812. }
  6813. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6814. : targetFile (targetFile_)
  6815. {
  6816. // If you use this constructor, you need to give it a valid target file!
  6817. jassert (targetFile != File::nonexistent);
  6818. createTempFile (targetFile.getParentDirectory(),
  6819. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6820. targetFile.getFileExtension(),
  6821. optionFlags);
  6822. }
  6823. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6824. const String& suffix, const int optionFlags)
  6825. {
  6826. if ((optionFlags & useHiddenFile) != 0)
  6827. name = "." + name;
  6828. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6829. }
  6830. TemporaryFile::~TemporaryFile()
  6831. {
  6832. if (! deleteTemporaryFile())
  6833. {
  6834. /* Failed to delete our temporary file! The most likely reason for this would be
  6835. that you've not closed an output stream that was being used to write to file.
  6836. If you find that something beyond your control is changing permissions on
  6837. your temporary files and preventing them from being deleted, you may want to
  6838. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6839. handle them appropriately.
  6840. */
  6841. jassertfalse;
  6842. }
  6843. }
  6844. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6845. {
  6846. // This method only works if you created this object with the constructor
  6847. // that takes a target file!
  6848. jassert (targetFile != File::nonexistent);
  6849. if (temporaryFile.exists())
  6850. {
  6851. // Have a few attempts at overwriting the file before giving up..
  6852. for (int i = 5; --i >= 0;)
  6853. {
  6854. if (temporaryFile.moveFileTo (targetFile))
  6855. return true;
  6856. Thread::sleep (100);
  6857. }
  6858. }
  6859. else
  6860. {
  6861. // There's no temporary file to use. If your write failed, you should
  6862. // probably check, and not bother calling this method.
  6863. jassertfalse;
  6864. }
  6865. return false;
  6866. }
  6867. bool TemporaryFile::deleteTemporaryFile() const
  6868. {
  6869. // Have a few attempts at deleting the file before giving up..
  6870. for (int i = 5; --i >= 0;)
  6871. {
  6872. if (temporaryFile.deleteFile())
  6873. return true;
  6874. Thread::sleep (50);
  6875. }
  6876. return false;
  6877. }
  6878. END_JUCE_NAMESPACE
  6879. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6880. /*** Start of inlined file: juce_Socket.cpp ***/
  6881. #if JUCE_WINDOWS
  6882. #include <winsock2.h>
  6883. #if JUCE_MSVC
  6884. #pragma warning (push)
  6885. #pragma warning (disable : 4127 4389 4018)
  6886. #endif
  6887. #else
  6888. #if JUCE_LINUX
  6889. #include <sys/types.h>
  6890. #include <sys/socket.h>
  6891. #include <sys/errno.h>
  6892. #include <unistd.h>
  6893. #include <netinet/in.h>
  6894. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6895. #include <CoreServices/CoreServices.h>
  6896. #endif
  6897. #include <fcntl.h>
  6898. #include <netdb.h>
  6899. #include <arpa/inet.h>
  6900. #include <netinet/tcp.h>
  6901. #endif
  6902. BEGIN_JUCE_NAMESPACE
  6903. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6904. typedef socklen_t juce_socklen_t;
  6905. #else
  6906. typedef int juce_socklen_t;
  6907. #endif
  6908. #if JUCE_WINDOWS
  6909. namespace SocketHelpers
  6910. {
  6911. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6912. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6913. }
  6914. static void initWin32Sockets()
  6915. {
  6916. static CriticalSection lock;
  6917. const ScopedLock sl (lock);
  6918. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6919. {
  6920. WSADATA wsaData;
  6921. const WORD wVersionRequested = MAKEWORD (1, 1);
  6922. WSAStartup (wVersionRequested, &wsaData);
  6923. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6924. }
  6925. }
  6926. void juce_shutdownWin32Sockets()
  6927. {
  6928. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6929. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6930. }
  6931. #endif
  6932. namespace SocketHelpers
  6933. {
  6934. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6935. {
  6936. const int sndBufSize = 65536;
  6937. const int rcvBufSize = 65536;
  6938. const int one = 1;
  6939. return handle > 0
  6940. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6941. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6942. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6943. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6944. }
  6945. static bool bindSocketToPort (const int handle, const int port) throw()
  6946. {
  6947. if (handle <= 0 || port <= 0)
  6948. return false;
  6949. struct sockaddr_in servTmpAddr;
  6950. zerostruct (servTmpAddr);
  6951. servTmpAddr.sin_family = PF_INET;
  6952. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6953. servTmpAddr.sin_port = htons ((uint16) port);
  6954. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6955. }
  6956. static int readSocket (const int handle,
  6957. void* const destBuffer, const int maxBytesToRead,
  6958. bool volatile& connected,
  6959. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6960. {
  6961. int bytesRead = 0;
  6962. while (bytesRead < maxBytesToRead)
  6963. {
  6964. int bytesThisTime;
  6965. #if JUCE_WINDOWS
  6966. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6967. #else
  6968. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6969. && errno == EINTR
  6970. && connected)
  6971. {
  6972. }
  6973. #endif
  6974. if (bytesThisTime <= 0 || ! connected)
  6975. {
  6976. if (bytesRead == 0)
  6977. bytesRead = -1;
  6978. break;
  6979. }
  6980. bytesRead += bytesThisTime;
  6981. if (! blockUntilSpecifiedAmountHasArrived)
  6982. break;
  6983. }
  6984. return bytesRead;
  6985. }
  6986. static int waitForReadiness (const int handle, const bool forReading,
  6987. const int timeoutMsecs) throw()
  6988. {
  6989. struct timeval timeout;
  6990. struct timeval* timeoutp;
  6991. if (timeoutMsecs >= 0)
  6992. {
  6993. timeout.tv_sec = timeoutMsecs / 1000;
  6994. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6995. timeoutp = &timeout;
  6996. }
  6997. else
  6998. {
  6999. timeoutp = 0;
  7000. }
  7001. fd_set rset, wset;
  7002. FD_ZERO (&rset);
  7003. FD_SET (handle, &rset);
  7004. FD_ZERO (&wset);
  7005. FD_SET (handle, &wset);
  7006. fd_set* const prset = forReading ? &rset : 0;
  7007. fd_set* const pwset = forReading ? 0 : &wset;
  7008. #if JUCE_WINDOWS
  7009. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7010. return -1;
  7011. #else
  7012. {
  7013. int result;
  7014. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7015. && errno == EINTR)
  7016. {
  7017. }
  7018. if (result < 0)
  7019. return -1;
  7020. }
  7021. #endif
  7022. {
  7023. int opt;
  7024. juce_socklen_t len = sizeof (opt);
  7025. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7026. || opt != 0)
  7027. return -1;
  7028. }
  7029. if ((forReading && FD_ISSET (handle, &rset))
  7030. || ((! forReading) && FD_ISSET (handle, &wset)))
  7031. return 1;
  7032. return 0;
  7033. }
  7034. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7035. {
  7036. #if JUCE_WINDOWS
  7037. u_long nonBlocking = shouldBlock ? 0 : 1;
  7038. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7039. return false;
  7040. #else
  7041. int socketFlags = fcntl (handle, F_GETFL, 0);
  7042. if (socketFlags == -1)
  7043. return false;
  7044. if (shouldBlock)
  7045. socketFlags &= ~O_NONBLOCK;
  7046. else
  7047. socketFlags |= O_NONBLOCK;
  7048. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7049. return false;
  7050. #endif
  7051. return true;
  7052. }
  7053. static bool connectSocket (int volatile& handle,
  7054. const bool isDatagram,
  7055. void** serverAddress,
  7056. const String& hostName,
  7057. const int portNumber,
  7058. const int timeOutMillisecs) throw()
  7059. {
  7060. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7061. if (hostEnt == 0)
  7062. return false;
  7063. struct in_addr targetAddress;
  7064. memcpy (&targetAddress.s_addr,
  7065. *(hostEnt->h_addr_list),
  7066. sizeof (targetAddress.s_addr));
  7067. struct sockaddr_in servTmpAddr;
  7068. zerostruct (servTmpAddr);
  7069. servTmpAddr.sin_family = PF_INET;
  7070. servTmpAddr.sin_addr = targetAddress;
  7071. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7072. if (handle < 0)
  7073. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7074. if (handle < 0)
  7075. return false;
  7076. if (isDatagram)
  7077. {
  7078. *serverAddress = new struct sockaddr_in();
  7079. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7080. return true;
  7081. }
  7082. setSocketBlockingState (handle, false);
  7083. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7084. if (result < 0)
  7085. {
  7086. #if JUCE_WINDOWS
  7087. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7088. #else
  7089. if (errno == EINPROGRESS)
  7090. #endif
  7091. {
  7092. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7093. {
  7094. setSocketBlockingState (handle, true);
  7095. return false;
  7096. }
  7097. }
  7098. }
  7099. setSocketBlockingState (handle, true);
  7100. resetSocketOptions (handle, false, false);
  7101. return true;
  7102. }
  7103. }
  7104. StreamingSocket::StreamingSocket()
  7105. : portNumber (0),
  7106. handle (-1),
  7107. connected (false),
  7108. isListener (false)
  7109. {
  7110. #if JUCE_WINDOWS
  7111. initWin32Sockets();
  7112. #endif
  7113. }
  7114. StreamingSocket::StreamingSocket (const String& hostName_,
  7115. const int portNumber_,
  7116. const int handle_)
  7117. : hostName (hostName_),
  7118. portNumber (portNumber_),
  7119. handle (handle_),
  7120. connected (true),
  7121. isListener (false)
  7122. {
  7123. #if JUCE_WINDOWS
  7124. initWin32Sockets();
  7125. #endif
  7126. SocketHelpers::resetSocketOptions (handle_, false, false);
  7127. }
  7128. StreamingSocket::~StreamingSocket()
  7129. {
  7130. close();
  7131. }
  7132. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7133. {
  7134. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7135. : -1;
  7136. }
  7137. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7138. {
  7139. if (isListener || ! connected)
  7140. return -1;
  7141. #if JUCE_WINDOWS
  7142. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7143. #else
  7144. int result;
  7145. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7146. && errno == EINTR)
  7147. {
  7148. }
  7149. return result;
  7150. #endif
  7151. }
  7152. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7153. const int timeoutMsecs) const
  7154. {
  7155. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7156. : -1;
  7157. }
  7158. bool StreamingSocket::bindToPort (const int port)
  7159. {
  7160. return SocketHelpers::bindSocketToPort (handle, port);
  7161. }
  7162. bool StreamingSocket::connect (const String& remoteHostName,
  7163. const int remotePortNumber,
  7164. const int timeOutMillisecs)
  7165. {
  7166. if (isListener)
  7167. {
  7168. jassertfalse; // a listener socket can't connect to another one!
  7169. return false;
  7170. }
  7171. if (connected)
  7172. close();
  7173. hostName = remoteHostName;
  7174. portNumber = remotePortNumber;
  7175. isListener = false;
  7176. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7177. remotePortNumber, timeOutMillisecs);
  7178. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7179. {
  7180. close();
  7181. return false;
  7182. }
  7183. return true;
  7184. }
  7185. void StreamingSocket::close()
  7186. {
  7187. #if JUCE_WINDOWS
  7188. if (handle != SOCKET_ERROR || connected)
  7189. closesocket (handle);
  7190. connected = false;
  7191. #else
  7192. if (connected)
  7193. {
  7194. connected = false;
  7195. if (isListener)
  7196. {
  7197. // need to do this to interrupt the accept() function..
  7198. StreamingSocket temp;
  7199. temp.connect ("localhost", portNumber, 1000);
  7200. }
  7201. }
  7202. if (handle != -1)
  7203. ::close (handle);
  7204. #endif
  7205. hostName = String::empty;
  7206. portNumber = 0;
  7207. handle = -1;
  7208. isListener = false;
  7209. }
  7210. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7211. {
  7212. if (connected)
  7213. close();
  7214. hostName = "listener";
  7215. portNumber = newPortNumber;
  7216. isListener = true;
  7217. struct sockaddr_in servTmpAddr;
  7218. zerostruct (servTmpAddr);
  7219. servTmpAddr.sin_family = PF_INET;
  7220. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7221. if (localHostName.isNotEmpty())
  7222. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7223. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7224. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7225. if (handle < 0)
  7226. return false;
  7227. const int reuse = 1;
  7228. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7229. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7230. || listen (handle, SOMAXCONN) < 0)
  7231. {
  7232. close();
  7233. return false;
  7234. }
  7235. connected = true;
  7236. return true;
  7237. }
  7238. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7239. {
  7240. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7241. // prepare this socket as a listener.
  7242. if (connected && isListener)
  7243. {
  7244. struct sockaddr address;
  7245. juce_socklen_t len = sizeof (sockaddr);
  7246. const int newSocket = (int) accept (handle, &address, &len);
  7247. if (newSocket >= 0 && connected)
  7248. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7249. portNumber, newSocket);
  7250. }
  7251. return 0;
  7252. }
  7253. bool StreamingSocket::isLocal() const throw()
  7254. {
  7255. return hostName == "127.0.0.1";
  7256. }
  7257. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7258. : portNumber (0),
  7259. handle (-1),
  7260. connected (true),
  7261. allowBroadcast (allowBroadcast_),
  7262. serverAddress (0)
  7263. {
  7264. #if JUCE_WINDOWS
  7265. initWin32Sockets();
  7266. #endif
  7267. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7268. bindToPort (localPortNumber);
  7269. }
  7270. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7271. const int handle_, const int localPortNumber)
  7272. : hostName (hostName_),
  7273. portNumber (portNumber_),
  7274. handle (handle_),
  7275. connected (true),
  7276. allowBroadcast (false),
  7277. serverAddress (0)
  7278. {
  7279. #if JUCE_WINDOWS
  7280. initWin32Sockets();
  7281. #endif
  7282. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7283. bindToPort (localPortNumber);
  7284. }
  7285. DatagramSocket::~DatagramSocket()
  7286. {
  7287. close();
  7288. delete static_cast <struct sockaddr_in*> (serverAddress);
  7289. serverAddress = 0;
  7290. }
  7291. void DatagramSocket::close()
  7292. {
  7293. #if JUCE_WINDOWS
  7294. closesocket (handle);
  7295. connected = false;
  7296. #else
  7297. connected = false;
  7298. ::close (handle);
  7299. #endif
  7300. hostName = String::empty;
  7301. portNumber = 0;
  7302. handle = -1;
  7303. }
  7304. bool DatagramSocket::bindToPort (const int port)
  7305. {
  7306. return SocketHelpers::bindSocketToPort (handle, port);
  7307. }
  7308. bool DatagramSocket::connect (const String& remoteHostName,
  7309. const int remotePortNumber,
  7310. const int timeOutMillisecs)
  7311. {
  7312. if (connected)
  7313. close();
  7314. hostName = remoteHostName;
  7315. portNumber = remotePortNumber;
  7316. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7317. remoteHostName, remotePortNumber,
  7318. timeOutMillisecs);
  7319. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7320. {
  7321. close();
  7322. return false;
  7323. }
  7324. return true;
  7325. }
  7326. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7327. {
  7328. struct sockaddr address;
  7329. juce_socklen_t len = sizeof (sockaddr);
  7330. while (waitUntilReady (true, -1) == 1)
  7331. {
  7332. char buf[1];
  7333. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7334. {
  7335. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7336. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7337. -1, -1);
  7338. }
  7339. }
  7340. return 0;
  7341. }
  7342. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7343. const int timeoutMsecs) const
  7344. {
  7345. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7346. : -1;
  7347. }
  7348. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7349. {
  7350. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7351. : -1;
  7352. }
  7353. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7354. {
  7355. // You need to call connect() first to set the server address..
  7356. jassert (serverAddress != 0 && connected);
  7357. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7358. numBytesToWrite, 0,
  7359. (const struct sockaddr*) serverAddress,
  7360. sizeof (struct sockaddr_in))
  7361. : -1;
  7362. }
  7363. bool DatagramSocket::isLocal() const throw()
  7364. {
  7365. return hostName == "127.0.0.1";
  7366. }
  7367. #if JUCE_MSVC
  7368. #pragma warning (pop)
  7369. #endif
  7370. END_JUCE_NAMESPACE
  7371. /*** End of inlined file: juce_Socket.cpp ***/
  7372. /*** Start of inlined file: juce_URL.cpp ***/
  7373. BEGIN_JUCE_NAMESPACE
  7374. URL::URL()
  7375. {
  7376. }
  7377. URL::URL (const String& url_)
  7378. : url (url_)
  7379. {
  7380. int i = url.indexOfChar ('?');
  7381. if (i >= 0)
  7382. {
  7383. do
  7384. {
  7385. const int nextAmp = url.indexOfChar (i + 1, '&');
  7386. const int equalsPos = url.indexOfChar (i + 1, '=');
  7387. if (equalsPos > i + 1)
  7388. {
  7389. if (nextAmp < 0)
  7390. {
  7391. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7392. removeEscapeChars (url.substring (equalsPos + 1)));
  7393. }
  7394. else if (nextAmp > 0 && equalsPos < nextAmp)
  7395. {
  7396. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7397. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7398. }
  7399. }
  7400. i = nextAmp;
  7401. }
  7402. while (i >= 0);
  7403. url = url.upToFirstOccurrenceOf ("?", false, false);
  7404. }
  7405. }
  7406. URL::URL (const URL& other)
  7407. : url (other.url),
  7408. postData (other.postData),
  7409. parameters (other.parameters),
  7410. filesToUpload (other.filesToUpload),
  7411. mimeTypes (other.mimeTypes)
  7412. {
  7413. }
  7414. URL& URL::operator= (const URL& other)
  7415. {
  7416. url = other.url;
  7417. postData = other.postData;
  7418. parameters = other.parameters;
  7419. filesToUpload = other.filesToUpload;
  7420. mimeTypes = other.mimeTypes;
  7421. return *this;
  7422. }
  7423. URL::~URL()
  7424. {
  7425. }
  7426. static const String getMangledParameters (const StringPairArray& parameters)
  7427. {
  7428. String p;
  7429. for (int i = 0; i < parameters.size(); ++i)
  7430. {
  7431. if (i > 0)
  7432. p << '&';
  7433. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7434. << '='
  7435. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7436. }
  7437. return p;
  7438. }
  7439. const String URL::toString (const bool includeGetParameters) const
  7440. {
  7441. if (includeGetParameters && parameters.size() > 0)
  7442. return url + "?" + getMangledParameters (parameters);
  7443. else
  7444. return url;
  7445. }
  7446. bool URL::isWellFormed() const
  7447. {
  7448. //xxx TODO
  7449. return url.isNotEmpty();
  7450. }
  7451. static int findStartOfDomain (const String& url)
  7452. {
  7453. int i = 0;
  7454. while (CharacterFunctions::isLetterOrDigit (url[i])
  7455. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7456. ++i;
  7457. return url[i] == ':' ? i + 1 : 0;
  7458. }
  7459. const String URL::getDomain() const
  7460. {
  7461. int start = findStartOfDomain (url);
  7462. while (url[start] == '/')
  7463. ++start;
  7464. const int end1 = url.indexOfChar (start, '/');
  7465. const int end2 = url.indexOfChar (start, ':');
  7466. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7467. : jmin (end1, end2);
  7468. return url.substring (start, end);
  7469. }
  7470. const String URL::getSubPath() const
  7471. {
  7472. int start = findStartOfDomain (url);
  7473. while (url[start] == '/')
  7474. ++start;
  7475. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7476. return startOfPath <= 0 ? String::empty
  7477. : url.substring (startOfPath);
  7478. }
  7479. const String URL::getScheme() const
  7480. {
  7481. return url.substring (0, findStartOfDomain (url) - 1);
  7482. }
  7483. const URL URL::withNewSubPath (const String& newPath) const
  7484. {
  7485. int start = findStartOfDomain (url);
  7486. while (url[start] == '/')
  7487. ++start;
  7488. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7489. URL u (*this);
  7490. if (startOfPath > 0)
  7491. u.url = url.substring (0, startOfPath);
  7492. if (! u.url.endsWithChar ('/'))
  7493. u.url << '/';
  7494. if (newPath.startsWithChar ('/'))
  7495. u.url << newPath.substring (1);
  7496. else
  7497. u.url << newPath;
  7498. return u;
  7499. }
  7500. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7501. {
  7502. if (possibleURL.startsWithIgnoreCase ("http:")
  7503. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7504. return true;
  7505. if (possibleURL.startsWithIgnoreCase ("file:")
  7506. || possibleURL.containsChar ('@')
  7507. || possibleURL.endsWithChar ('.')
  7508. || (! possibleURL.containsChar ('.')))
  7509. return false;
  7510. if (possibleURL.startsWithIgnoreCase ("www.")
  7511. && possibleURL.substring (5).containsChar ('.'))
  7512. return true;
  7513. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7514. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7515. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7516. return true;
  7517. return false;
  7518. }
  7519. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7520. {
  7521. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7522. return atSign > 0
  7523. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7524. && (! possibleEmailAddress.endsWithChar ('.'));
  7525. }
  7526. void* juce_openInternetFile (const String& url,
  7527. const String& headers,
  7528. const MemoryBlock& optionalPostData,
  7529. const bool isPost,
  7530. URL::OpenStreamProgressCallback* callback,
  7531. void* callbackContext,
  7532. int timeOutMs);
  7533. void juce_closeInternetFile (void* handle);
  7534. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7535. int juce_seekInInternetFile (void* handle, int newPosition);
  7536. int64 juce_getInternetFileContentLength (void* handle);
  7537. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7538. class WebInputStream : public InputStream
  7539. {
  7540. public:
  7541. WebInputStream (const URL& url,
  7542. const bool isPost_,
  7543. URL::OpenStreamProgressCallback* const progressCallback_,
  7544. void* const progressCallbackContext_,
  7545. const String& extraHeaders,
  7546. const int timeOutMs_,
  7547. StringPairArray* const responseHeaders)
  7548. : position (0),
  7549. finished (false),
  7550. isPost (isPost_),
  7551. progressCallback (progressCallback_),
  7552. progressCallbackContext (progressCallbackContext_),
  7553. timeOutMs (timeOutMs_)
  7554. {
  7555. server = url.toString (! isPost);
  7556. if (isPost_)
  7557. createHeadersAndPostData (url);
  7558. headers += extraHeaders;
  7559. if (! headers.endsWithChar ('\n'))
  7560. headers << "\r\n";
  7561. handle = juce_openInternetFile (server, headers, postData, isPost,
  7562. progressCallback_, progressCallbackContext_,
  7563. timeOutMs);
  7564. if (responseHeaders != 0)
  7565. juce_getInternetFileHeaders (handle, *responseHeaders);
  7566. }
  7567. ~WebInputStream()
  7568. {
  7569. juce_closeInternetFile (handle);
  7570. }
  7571. bool isError() const { return handle == 0; }
  7572. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7573. bool isExhausted() { return finished; }
  7574. int64 getPosition() { return position; }
  7575. int read (void* dest, int bytes)
  7576. {
  7577. if (finished || isError())
  7578. {
  7579. return 0;
  7580. }
  7581. else
  7582. {
  7583. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7584. position += bytesRead;
  7585. if (bytesRead == 0)
  7586. finished = true;
  7587. return bytesRead;
  7588. }
  7589. }
  7590. bool setPosition (int64 wantedPos)
  7591. {
  7592. if (wantedPos != position)
  7593. {
  7594. finished = false;
  7595. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7596. if (actualPos == wantedPos)
  7597. {
  7598. position = wantedPos;
  7599. }
  7600. else
  7601. {
  7602. if (wantedPos < position)
  7603. {
  7604. juce_closeInternetFile (handle);
  7605. position = 0;
  7606. finished = false;
  7607. handle = juce_openInternetFile (server, headers, postData, isPost,
  7608. progressCallback, progressCallbackContext,
  7609. timeOutMs);
  7610. }
  7611. skipNextBytes (wantedPos - position);
  7612. }
  7613. }
  7614. return true;
  7615. }
  7616. juce_UseDebuggingNewOperator
  7617. private:
  7618. String server, headers;
  7619. MemoryBlock postData;
  7620. int64 position;
  7621. bool finished;
  7622. const bool isPost;
  7623. void* handle;
  7624. URL::OpenStreamProgressCallback* const progressCallback;
  7625. void* const progressCallbackContext;
  7626. const int timeOutMs;
  7627. void createHeadersAndPostData (const URL& url)
  7628. {
  7629. MemoryOutputStream data (postData, false);
  7630. if (url.getFilesToUpload().size() > 0)
  7631. {
  7632. // need to upload some files, so do it as multi-part...
  7633. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7634. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7635. data << "--" << boundary;
  7636. int i;
  7637. for (i = 0; i < url.getParameters().size(); ++i)
  7638. {
  7639. data << "\r\nContent-Disposition: form-data; name=\""
  7640. << url.getParameters().getAllKeys() [i]
  7641. << "\"\r\n\r\n"
  7642. << url.getParameters().getAllValues() [i]
  7643. << "\r\n--"
  7644. << boundary;
  7645. }
  7646. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7647. {
  7648. const File file (url.getFilesToUpload().getAllValues() [i]);
  7649. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7650. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7651. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7652. const String mimeType (url.getMimeTypesOfUploadFiles()
  7653. .getValue (paramName, String::empty));
  7654. if (mimeType.isNotEmpty())
  7655. data << "Content-Type: " << mimeType << "\r\n";
  7656. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7657. << file << "\r\n--" << boundary;
  7658. }
  7659. data << "--\r\n";
  7660. data.flush();
  7661. }
  7662. else
  7663. {
  7664. data << getMangledParameters (url.getParameters())
  7665. << url.getPostData();
  7666. data.flush();
  7667. // just a short text attachment, so use simple url encoding..
  7668. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7669. + String ((unsigned int) postData.getSize())
  7670. + "\r\n";
  7671. }
  7672. }
  7673. WebInputStream (const WebInputStream&);
  7674. WebInputStream& operator= (const WebInputStream&);
  7675. };
  7676. InputStream* URL::createInputStream (const bool usePostCommand,
  7677. OpenStreamProgressCallback* const progressCallback,
  7678. void* const progressCallbackContext,
  7679. const String& extraHeaders,
  7680. const int timeOutMs,
  7681. StringPairArray* const responseHeaders) const
  7682. {
  7683. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7684. progressCallback, progressCallbackContext,
  7685. extraHeaders, timeOutMs, responseHeaders));
  7686. return wi->isError() ? 0 : wi.release();
  7687. }
  7688. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7689. const bool usePostCommand) const
  7690. {
  7691. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7692. if (in != 0)
  7693. {
  7694. in->readIntoMemoryBlock (destData);
  7695. return true;
  7696. }
  7697. return false;
  7698. }
  7699. const String URL::readEntireTextStream (const bool usePostCommand) const
  7700. {
  7701. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7702. if (in != 0)
  7703. return in->readEntireStreamAsString();
  7704. return String::empty;
  7705. }
  7706. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7707. {
  7708. XmlDocument doc (readEntireTextStream (usePostCommand));
  7709. return doc.getDocumentElement();
  7710. }
  7711. const URL URL::withParameter (const String& parameterName,
  7712. const String& parameterValue) const
  7713. {
  7714. URL u (*this);
  7715. u.parameters.set (parameterName, parameterValue);
  7716. return u;
  7717. }
  7718. const URL URL::withFileToUpload (const String& parameterName,
  7719. const File& fileToUpload,
  7720. const String& mimeType) const
  7721. {
  7722. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7723. URL u (*this);
  7724. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7725. u.mimeTypes.set (parameterName, mimeType);
  7726. return u;
  7727. }
  7728. const URL URL::withPOSTData (const String& postData_) const
  7729. {
  7730. URL u (*this);
  7731. u.postData = postData_;
  7732. return u;
  7733. }
  7734. const StringPairArray& URL::getParameters() const
  7735. {
  7736. return parameters;
  7737. }
  7738. const StringPairArray& URL::getFilesToUpload() const
  7739. {
  7740. return filesToUpload;
  7741. }
  7742. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7743. {
  7744. return mimeTypes;
  7745. }
  7746. const String URL::removeEscapeChars (const String& s)
  7747. {
  7748. String result (s.replaceCharacter ('+', ' '));
  7749. if (! result.containsChar ('%'))
  7750. return result;
  7751. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7752. // after all the replacements have been made, so that multi-byte chars are handled.
  7753. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7754. for (int i = 0; i < utf8.size(); ++i)
  7755. {
  7756. if (utf8.getUnchecked(i) == '%')
  7757. {
  7758. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7759. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7760. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7761. {
  7762. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7763. utf8.removeRange (i + 1, 2);
  7764. }
  7765. }
  7766. }
  7767. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7768. }
  7769. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7770. {
  7771. const char* const legalChars = isParameter ? "_-.*!'()"
  7772. : ",$_-.*!'()";
  7773. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7774. for (int i = 0; i < utf8.size(); ++i)
  7775. {
  7776. const char c = utf8.getUnchecked(i);
  7777. if (! (CharacterFunctions::isLetterOrDigit (c)
  7778. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7779. {
  7780. if (c == ' ')
  7781. {
  7782. utf8.set (i, '+');
  7783. }
  7784. else
  7785. {
  7786. static const char* const hexDigits = "0123456789abcdef";
  7787. utf8.set (i, '%');
  7788. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7789. utf8.insert (++i, hexDigits [c & 15]);
  7790. }
  7791. }
  7792. }
  7793. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7794. }
  7795. bool URL::launchInDefaultBrowser() const
  7796. {
  7797. String u (toString (true));
  7798. if (u.containsChar ('@') && ! u.containsChar (':'))
  7799. u = "mailto:" + u;
  7800. return PlatformUtilities::openDocument (u, String::empty);
  7801. }
  7802. END_JUCE_NAMESPACE
  7803. /*** End of inlined file: juce_URL.cpp ***/
  7804. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7805. BEGIN_JUCE_NAMESPACE
  7806. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7807. const int bufferSize_,
  7808. const bool deleteSourceWhenDestroyed)
  7809. : source (source_),
  7810. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7811. bufferSize (jmax (256, bufferSize_)),
  7812. position (source_->getPosition()),
  7813. lastReadPos (0),
  7814. bufferOverlap (128)
  7815. {
  7816. const int sourceSize = (int) source_->getTotalLength();
  7817. if (sourceSize >= 0)
  7818. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7819. bufferStart = position;
  7820. buffer.malloc (bufferSize);
  7821. }
  7822. BufferedInputStream::~BufferedInputStream()
  7823. {
  7824. }
  7825. int64 BufferedInputStream::getTotalLength()
  7826. {
  7827. return source->getTotalLength();
  7828. }
  7829. int64 BufferedInputStream::getPosition()
  7830. {
  7831. return position;
  7832. }
  7833. bool BufferedInputStream::setPosition (int64 newPosition)
  7834. {
  7835. position = jmax ((int64) 0, newPosition);
  7836. return true;
  7837. }
  7838. bool BufferedInputStream::isExhausted()
  7839. {
  7840. return (position >= lastReadPos)
  7841. && source->isExhausted();
  7842. }
  7843. void BufferedInputStream::ensureBuffered()
  7844. {
  7845. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7846. if (position < bufferStart || position >= bufferEndOverlap)
  7847. {
  7848. int bytesRead;
  7849. if (position < lastReadPos
  7850. && position >= bufferEndOverlap
  7851. && position >= bufferStart)
  7852. {
  7853. const int bytesToKeep = (int) (lastReadPos - position);
  7854. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7855. bufferStart = position;
  7856. bytesRead = source->read (buffer + bytesToKeep,
  7857. bufferSize - bytesToKeep);
  7858. lastReadPos += bytesRead;
  7859. bytesRead += bytesToKeep;
  7860. }
  7861. else
  7862. {
  7863. bufferStart = position;
  7864. source->setPosition (bufferStart);
  7865. bytesRead = source->read (buffer, bufferSize);
  7866. lastReadPos = bufferStart + bytesRead;
  7867. }
  7868. while (bytesRead < bufferSize)
  7869. buffer [bytesRead++] = 0;
  7870. }
  7871. }
  7872. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7873. {
  7874. if (position >= bufferStart
  7875. && position + maxBytesToRead <= lastReadPos)
  7876. {
  7877. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7878. position += maxBytesToRead;
  7879. return maxBytesToRead;
  7880. }
  7881. else
  7882. {
  7883. if (position < bufferStart || position >= lastReadPos)
  7884. ensureBuffered();
  7885. int bytesRead = 0;
  7886. while (maxBytesToRead > 0)
  7887. {
  7888. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7889. if (bytesAvailable > 0)
  7890. {
  7891. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7892. maxBytesToRead -= bytesAvailable;
  7893. bytesRead += bytesAvailable;
  7894. position += bytesAvailable;
  7895. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7896. }
  7897. const int64 oldLastReadPos = lastReadPos;
  7898. ensureBuffered();
  7899. if (oldLastReadPos == lastReadPos)
  7900. break; // if ensureBuffered() failed to read any more data, bail out
  7901. if (isExhausted())
  7902. break;
  7903. }
  7904. return bytesRead;
  7905. }
  7906. }
  7907. const String BufferedInputStream::readString()
  7908. {
  7909. if (position >= bufferStart
  7910. && position < lastReadPos)
  7911. {
  7912. const int maxChars = (int) (lastReadPos - position);
  7913. const char* const src = buffer + (int) (position - bufferStart);
  7914. for (int i = 0; i < maxChars; ++i)
  7915. {
  7916. if (src[i] == 0)
  7917. {
  7918. position += i + 1;
  7919. return String::fromUTF8 (src, i);
  7920. }
  7921. }
  7922. }
  7923. return InputStream::readString();
  7924. }
  7925. END_JUCE_NAMESPACE
  7926. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7927. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7928. BEGIN_JUCE_NAMESPACE
  7929. FileInputSource::FileInputSource (const File& file_)
  7930. : file (file_)
  7931. {
  7932. }
  7933. FileInputSource::~FileInputSource()
  7934. {
  7935. }
  7936. InputStream* FileInputSource::createInputStream()
  7937. {
  7938. return file.createInputStream();
  7939. }
  7940. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7941. {
  7942. return file.getSiblingFile (relatedItemPath).createInputStream();
  7943. }
  7944. int64 FileInputSource::hashCode() const
  7945. {
  7946. return file.hashCode();
  7947. }
  7948. END_JUCE_NAMESPACE
  7949. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7950. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7951. BEGIN_JUCE_NAMESPACE
  7952. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7953. const size_t sourceDataSize,
  7954. const bool keepInternalCopy)
  7955. : data (static_cast <const char*> (sourceData)),
  7956. dataSize (sourceDataSize),
  7957. position (0)
  7958. {
  7959. if (keepInternalCopy)
  7960. {
  7961. internalCopy.append (data, sourceDataSize);
  7962. data = static_cast <const char*> (internalCopy.getData());
  7963. }
  7964. }
  7965. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7966. const bool keepInternalCopy)
  7967. : data (static_cast <const char*> (sourceData.getData())),
  7968. dataSize (sourceData.getSize()),
  7969. position (0)
  7970. {
  7971. if (keepInternalCopy)
  7972. {
  7973. internalCopy = sourceData;
  7974. data = static_cast <const char*> (internalCopy.getData());
  7975. }
  7976. }
  7977. MemoryInputStream::~MemoryInputStream()
  7978. {
  7979. }
  7980. int64 MemoryInputStream::getTotalLength()
  7981. {
  7982. return dataSize;
  7983. }
  7984. int MemoryInputStream::read (void* const buffer, const int howMany)
  7985. {
  7986. jassert (howMany >= 0);
  7987. const int num = jmin (howMany, (int) (dataSize - position));
  7988. memcpy (buffer, data + position, num);
  7989. position += num;
  7990. return (int) num;
  7991. }
  7992. bool MemoryInputStream::isExhausted()
  7993. {
  7994. return (position >= dataSize);
  7995. }
  7996. bool MemoryInputStream::setPosition (const int64 pos)
  7997. {
  7998. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7999. return true;
  8000. }
  8001. int64 MemoryInputStream::getPosition()
  8002. {
  8003. return position;
  8004. }
  8005. #if JUCE_UNIT_TESTS
  8006. class MemoryStreamTests : public UnitTest
  8007. {
  8008. public:
  8009. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8010. void runTest()
  8011. {
  8012. beginTest ("Basics");
  8013. int randomInt = Random::getSystemRandom().nextInt();
  8014. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8015. double randomDouble = Random::getSystemRandom().nextDouble();
  8016. String randomString;
  8017. for (int i = 50; --i >= 0;)
  8018. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8019. MemoryOutputStream mo;
  8020. mo.writeInt (randomInt);
  8021. mo.writeIntBigEndian (randomInt);
  8022. mo.writeCompressedInt (randomInt);
  8023. mo.writeString (randomString);
  8024. mo.writeInt64 (randomInt64);
  8025. mo.writeInt64BigEndian (randomInt64);
  8026. mo.writeDouble (randomDouble);
  8027. mo.writeDoubleBigEndian (randomDouble);
  8028. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8029. expect (mi.readInt() == randomInt);
  8030. expect (mi.readIntBigEndian() == randomInt);
  8031. expect (mi.readCompressedInt() == randomInt);
  8032. expect (mi.readString() == randomString);
  8033. expect (mi.readInt64() == randomInt64);
  8034. expect (mi.readInt64BigEndian() == randomInt64);
  8035. expect (mi.readDouble() == randomDouble);
  8036. expect (mi.readDoubleBigEndian() == randomDouble);
  8037. }
  8038. };
  8039. static MemoryStreamTests memoryInputStreamUnitTests;
  8040. #endif
  8041. END_JUCE_NAMESPACE
  8042. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8043. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8044. BEGIN_JUCE_NAMESPACE
  8045. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8046. : data (internalBlock),
  8047. position (0),
  8048. size (0)
  8049. {
  8050. internalBlock.setSize (initialSize, false);
  8051. }
  8052. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8053. const bool appendToExistingBlockContent)
  8054. : data (memoryBlockToWriteTo),
  8055. position (0),
  8056. size (0)
  8057. {
  8058. if (appendToExistingBlockContent)
  8059. position = size = memoryBlockToWriteTo.getSize();
  8060. }
  8061. MemoryOutputStream::~MemoryOutputStream()
  8062. {
  8063. flush();
  8064. }
  8065. void MemoryOutputStream::flush()
  8066. {
  8067. if (&data != &internalBlock)
  8068. data.setSize (size, false);
  8069. }
  8070. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8071. {
  8072. data.ensureSize (bytesToPreallocate + 1);
  8073. }
  8074. void MemoryOutputStream::reset() throw()
  8075. {
  8076. position = 0;
  8077. size = 0;
  8078. }
  8079. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8080. {
  8081. if (howMany > 0)
  8082. {
  8083. const size_t storageNeeded = position + howMany;
  8084. if (storageNeeded >= data.getSize())
  8085. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8086. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8087. position += howMany;
  8088. size = jmax (size, position);
  8089. }
  8090. return true;
  8091. }
  8092. const void* MemoryOutputStream::getData() const throw()
  8093. {
  8094. void* const d = data.getData();
  8095. if (data.getSize() > size)
  8096. static_cast <char*> (d) [size] = 0;
  8097. return d;
  8098. }
  8099. bool MemoryOutputStream::setPosition (int64 newPosition)
  8100. {
  8101. if (newPosition <= (int64) size)
  8102. {
  8103. // ok to seek backwards
  8104. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8105. return true;
  8106. }
  8107. else
  8108. {
  8109. // trying to make it bigger isn't a good thing to do..
  8110. return false;
  8111. }
  8112. }
  8113. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8114. {
  8115. // before writing from an input, see if we can preallocate to make it more efficient..
  8116. int64 availableData = source.getTotalLength() - source.getPosition();
  8117. if (availableData > 0)
  8118. {
  8119. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8120. availableData = maxNumBytesToWrite;
  8121. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8122. }
  8123. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8124. }
  8125. const String MemoryOutputStream::toUTF8() const
  8126. {
  8127. return String (static_cast <const char*> (getData()), getDataSize());
  8128. }
  8129. const String MemoryOutputStream::toString() const
  8130. {
  8131. return String::createStringFromData (getData(), getDataSize());
  8132. }
  8133. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8134. {
  8135. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8136. return stream;
  8137. }
  8138. END_JUCE_NAMESPACE
  8139. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8140. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8141. BEGIN_JUCE_NAMESPACE
  8142. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8143. const int64 startPositionInSourceStream_,
  8144. const int64 lengthOfSourceStream_,
  8145. const bool deleteSourceWhenDestroyed)
  8146. : source (sourceStream),
  8147. startPositionInSourceStream (startPositionInSourceStream_),
  8148. lengthOfSourceStream (lengthOfSourceStream_)
  8149. {
  8150. if (deleteSourceWhenDestroyed)
  8151. sourceToDelete = source;
  8152. setPosition (0);
  8153. }
  8154. SubregionStream::~SubregionStream()
  8155. {
  8156. }
  8157. int64 SubregionStream::getTotalLength()
  8158. {
  8159. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8160. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8161. : srcLen;
  8162. }
  8163. int64 SubregionStream::getPosition()
  8164. {
  8165. return source->getPosition() - startPositionInSourceStream;
  8166. }
  8167. bool SubregionStream::setPosition (int64 newPosition)
  8168. {
  8169. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8170. }
  8171. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8172. {
  8173. if (lengthOfSourceStream < 0)
  8174. {
  8175. return source->read (destBuffer, maxBytesToRead);
  8176. }
  8177. else
  8178. {
  8179. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8180. if (maxBytesToRead <= 0)
  8181. return 0;
  8182. return source->read (destBuffer, maxBytesToRead);
  8183. }
  8184. }
  8185. bool SubregionStream::isExhausted()
  8186. {
  8187. if (lengthOfSourceStream >= 0)
  8188. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8189. else
  8190. return source->isExhausted();
  8191. }
  8192. END_JUCE_NAMESPACE
  8193. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8194. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8195. BEGIN_JUCE_NAMESPACE
  8196. PerformanceCounter::PerformanceCounter (const String& name_,
  8197. int runsPerPrintout,
  8198. const File& loggingFile)
  8199. : name (name_),
  8200. numRuns (0),
  8201. runsPerPrint (runsPerPrintout),
  8202. totalTime (0),
  8203. outputFile (loggingFile)
  8204. {
  8205. if (outputFile != File::nonexistent)
  8206. {
  8207. String s ("**** Counter for \"");
  8208. s << name_ << "\" started at: "
  8209. << Time::getCurrentTime().toString (true, true)
  8210. << "\r\n";
  8211. outputFile.appendText (s, false, false);
  8212. }
  8213. }
  8214. PerformanceCounter::~PerformanceCounter()
  8215. {
  8216. printStatistics();
  8217. }
  8218. void PerformanceCounter::start()
  8219. {
  8220. started = Time::getHighResolutionTicks();
  8221. }
  8222. void PerformanceCounter::stop()
  8223. {
  8224. const int64 now = Time::getHighResolutionTicks();
  8225. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8226. if (++numRuns == runsPerPrint)
  8227. printStatistics();
  8228. }
  8229. void PerformanceCounter::printStatistics()
  8230. {
  8231. if (numRuns > 0)
  8232. {
  8233. String s ("Performance count for \"");
  8234. s << name << "\" - average over " << numRuns << " run(s) = ";
  8235. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8236. if (micros > 10000)
  8237. s << (micros/1000) << " millisecs";
  8238. else
  8239. s << micros << " microsecs";
  8240. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8241. Logger::outputDebugString (s);
  8242. s << "\r\n";
  8243. if (outputFile != File::nonexistent)
  8244. outputFile.appendText (s, false, false);
  8245. numRuns = 0;
  8246. totalTime = 0;
  8247. }
  8248. }
  8249. END_JUCE_NAMESPACE
  8250. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8251. /*** Start of inlined file: juce_Uuid.cpp ***/
  8252. BEGIN_JUCE_NAMESPACE
  8253. Uuid::Uuid()
  8254. {
  8255. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8256. // to make it very very unlikely that two UUIDs will ever be the same..
  8257. static int64 macAddresses[2];
  8258. static bool hasCheckedMacAddresses = false;
  8259. if (! hasCheckedMacAddresses)
  8260. {
  8261. hasCheckedMacAddresses = true;
  8262. SystemStats::getMACAddresses (macAddresses, 2);
  8263. }
  8264. value.asInt64[0] = macAddresses[0];
  8265. value.asInt64[1] = macAddresses[1];
  8266. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8267. // whose seed will carry over between calls to this method.
  8268. Random r (macAddresses[0] ^ macAddresses[1]
  8269. ^ Random::getSystemRandom().nextInt64());
  8270. for (int i = 4; --i >= 0;)
  8271. {
  8272. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8273. value.asInt[i] ^= r.nextInt();
  8274. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8275. }
  8276. }
  8277. Uuid::~Uuid() throw()
  8278. {
  8279. }
  8280. Uuid::Uuid (const Uuid& other)
  8281. : value (other.value)
  8282. {
  8283. }
  8284. Uuid& Uuid::operator= (const Uuid& other)
  8285. {
  8286. value = other.value;
  8287. return *this;
  8288. }
  8289. bool Uuid::operator== (const Uuid& other) const
  8290. {
  8291. return value.asInt64[0] == other.value.asInt64[0]
  8292. && value.asInt64[1] == other.value.asInt64[1];
  8293. }
  8294. bool Uuid::operator!= (const Uuid& other) const
  8295. {
  8296. return ! operator== (other);
  8297. }
  8298. bool Uuid::isNull() const throw()
  8299. {
  8300. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8301. }
  8302. const String Uuid::toString() const
  8303. {
  8304. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8305. }
  8306. Uuid::Uuid (const String& uuidString)
  8307. {
  8308. operator= (uuidString);
  8309. }
  8310. Uuid& Uuid::operator= (const String& uuidString)
  8311. {
  8312. MemoryBlock mb;
  8313. mb.loadFromHexString (uuidString);
  8314. mb.ensureSize (sizeof (value.asBytes), true);
  8315. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8316. return *this;
  8317. }
  8318. Uuid::Uuid (const uint8* const rawData)
  8319. {
  8320. operator= (rawData);
  8321. }
  8322. Uuid& Uuid::operator= (const uint8* const rawData)
  8323. {
  8324. if (rawData != 0)
  8325. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8326. else
  8327. zeromem (value.asBytes, sizeof (value.asBytes));
  8328. return *this;
  8329. }
  8330. END_JUCE_NAMESPACE
  8331. /*** End of inlined file: juce_Uuid.cpp ***/
  8332. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8333. BEGIN_JUCE_NAMESPACE
  8334. class ZipFile::ZipEntryInfo
  8335. {
  8336. public:
  8337. ZipFile::ZipEntry entry;
  8338. int streamOffset;
  8339. int compressedSize;
  8340. bool compressed;
  8341. };
  8342. class ZipFile::ZipInputStream : public InputStream
  8343. {
  8344. public:
  8345. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8346. : file (file_),
  8347. zipEntryInfo (zei),
  8348. pos (0),
  8349. headerSize (0),
  8350. inputStream (0)
  8351. {
  8352. inputStream = file_.inputStream;
  8353. if (file_.inputSource != 0)
  8354. {
  8355. inputStream = file.inputSource->createInputStream();
  8356. }
  8357. else
  8358. {
  8359. #if JUCE_DEBUG
  8360. file_.numOpenStreams++;
  8361. #endif
  8362. }
  8363. char buffer [30];
  8364. if (inputStream != 0
  8365. && inputStream->setPosition (zei.streamOffset)
  8366. && inputStream->read (buffer, 30) == 30
  8367. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8368. {
  8369. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8370. + ByteOrder::littleEndianShort (buffer + 28);
  8371. }
  8372. }
  8373. ~ZipInputStream()
  8374. {
  8375. #if JUCE_DEBUG
  8376. if (inputStream != 0 && inputStream == file.inputStream)
  8377. file.numOpenStreams--;
  8378. #endif
  8379. if (inputStream != file.inputStream)
  8380. delete inputStream;
  8381. }
  8382. int64 getTotalLength()
  8383. {
  8384. return zipEntryInfo.compressedSize;
  8385. }
  8386. int read (void* buffer, int howMany)
  8387. {
  8388. if (headerSize <= 0)
  8389. return 0;
  8390. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8391. if (inputStream == 0)
  8392. return 0;
  8393. int num;
  8394. if (inputStream == file.inputStream)
  8395. {
  8396. const ScopedLock sl (file.lock);
  8397. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8398. num = inputStream->read (buffer, howMany);
  8399. }
  8400. else
  8401. {
  8402. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8403. num = inputStream->read (buffer, howMany);
  8404. }
  8405. pos += num;
  8406. return num;
  8407. }
  8408. bool isExhausted()
  8409. {
  8410. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8411. }
  8412. int64 getPosition()
  8413. {
  8414. return pos;
  8415. }
  8416. bool setPosition (int64 newPos)
  8417. {
  8418. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8419. return true;
  8420. }
  8421. private:
  8422. ZipFile& file;
  8423. ZipEntryInfo zipEntryInfo;
  8424. int64 pos;
  8425. int headerSize;
  8426. InputStream* inputStream;
  8427. ZipInputStream (const ZipInputStream&);
  8428. ZipInputStream& operator= (const ZipInputStream&);
  8429. };
  8430. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8431. : inputStream (source_)
  8432. #if JUCE_DEBUG
  8433. , numOpenStreams (0)
  8434. #endif
  8435. {
  8436. if (deleteStreamWhenDestroyed)
  8437. streamToDelete = inputStream;
  8438. init();
  8439. }
  8440. ZipFile::ZipFile (const File& file)
  8441. : inputStream (0)
  8442. #if JUCE_DEBUG
  8443. , numOpenStreams (0)
  8444. #endif
  8445. {
  8446. inputSource = new FileInputSource (file);
  8447. init();
  8448. }
  8449. ZipFile::ZipFile (InputSource* const inputSource_)
  8450. : inputStream (0),
  8451. inputSource (inputSource_)
  8452. #if JUCE_DEBUG
  8453. , numOpenStreams (0)
  8454. #endif
  8455. {
  8456. init();
  8457. }
  8458. ZipFile::~ZipFile()
  8459. {
  8460. #if JUCE_DEBUG
  8461. entries.clear();
  8462. // If you hit this assertion, it means you've created a stream to read
  8463. // one of the items in the zipfile, but you've forgotten to delete that
  8464. // stream object before deleting the file.. Streams can't be kept open
  8465. // after the file is deleted because they need to share the input
  8466. // stream that the file uses to read itself.
  8467. jassert (numOpenStreams == 0);
  8468. #endif
  8469. }
  8470. int ZipFile::getNumEntries() const throw()
  8471. {
  8472. return entries.size();
  8473. }
  8474. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8475. {
  8476. ZipEntryInfo* const zei = entries [index];
  8477. return zei != 0 ? &(zei->entry) : 0;
  8478. }
  8479. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8480. {
  8481. for (int i = 0; i < entries.size(); ++i)
  8482. if (entries.getUnchecked (i)->entry.filename == fileName)
  8483. return i;
  8484. return -1;
  8485. }
  8486. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8487. {
  8488. return getEntry (getIndexOfFileName (fileName));
  8489. }
  8490. InputStream* ZipFile::createStreamForEntry (const int index)
  8491. {
  8492. ZipEntryInfo* const zei = entries[index];
  8493. InputStream* stream = 0;
  8494. if (zei != 0)
  8495. {
  8496. stream = new ZipInputStream (*this, *zei);
  8497. if (zei->compressed)
  8498. {
  8499. stream = new GZIPDecompressorInputStream (stream, true, true,
  8500. zei->entry.uncompressedSize);
  8501. // (much faster to unzip in big blocks using a buffer..)
  8502. stream = new BufferedInputStream (stream, 32768, true);
  8503. }
  8504. }
  8505. return stream;
  8506. }
  8507. class ZipFile::ZipFilenameComparator
  8508. {
  8509. public:
  8510. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8511. {
  8512. return first->entry.filename.compare (second->entry.filename);
  8513. }
  8514. };
  8515. void ZipFile::sortEntriesByFilename()
  8516. {
  8517. ZipFilenameComparator sorter;
  8518. entries.sort (sorter);
  8519. }
  8520. void ZipFile::init()
  8521. {
  8522. ScopedPointer <InputStream> toDelete;
  8523. InputStream* in = inputStream;
  8524. if (inputSource != 0)
  8525. {
  8526. in = inputSource->createInputStream();
  8527. toDelete = in;
  8528. }
  8529. if (in != 0)
  8530. {
  8531. int numEntries = 0;
  8532. int pos = findEndOfZipEntryTable (in, numEntries);
  8533. if (pos >= 0 && pos < in->getTotalLength())
  8534. {
  8535. const int size = (int) (in->getTotalLength() - pos);
  8536. in->setPosition (pos);
  8537. MemoryBlock headerData;
  8538. if (in->readIntoMemoryBlock (headerData, size) == size)
  8539. {
  8540. pos = 0;
  8541. for (int i = 0; i < numEntries; ++i)
  8542. {
  8543. if (pos + 46 > size)
  8544. break;
  8545. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8546. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8547. if (pos + 46 + fileNameLen > size)
  8548. break;
  8549. ZipEntryInfo* const zei = new ZipEntryInfo();
  8550. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8551. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8552. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8553. const int year = 1980 + (date >> 9);
  8554. const int month = ((date >> 5) & 15) - 1;
  8555. const int day = date & 31;
  8556. const int hours = time >> 11;
  8557. const int minutes = (time >> 5) & 63;
  8558. const int seconds = (time & 31) << 1;
  8559. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8560. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8561. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8562. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8563. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8564. entries.add (zei);
  8565. pos += 46 + fileNameLen
  8566. + ByteOrder::littleEndianShort (buffer + 30)
  8567. + ByteOrder::littleEndianShort (buffer + 32);
  8568. }
  8569. }
  8570. }
  8571. }
  8572. }
  8573. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8574. {
  8575. BufferedInputStream in (input, 8192, false);
  8576. in.setPosition (in.getTotalLength());
  8577. int64 pos = in.getPosition();
  8578. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8579. char buffer [32];
  8580. zeromem (buffer, sizeof (buffer));
  8581. while (pos > lowestPos)
  8582. {
  8583. in.setPosition (pos - 22);
  8584. pos = in.getPosition();
  8585. memcpy (buffer + 22, buffer, 4);
  8586. if (in.read (buffer, 22) != 22)
  8587. return 0;
  8588. for (int i = 0; i < 22; ++i)
  8589. {
  8590. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8591. {
  8592. in.setPosition (pos + i);
  8593. in.read (buffer, 22);
  8594. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8595. return ByteOrder::littleEndianInt (buffer + 16);
  8596. }
  8597. }
  8598. }
  8599. return 0;
  8600. }
  8601. bool ZipFile::uncompressTo (const File& targetDirectory,
  8602. const bool shouldOverwriteFiles)
  8603. {
  8604. for (int i = 0; i < entries.size(); ++i)
  8605. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8606. return false;
  8607. return true;
  8608. }
  8609. bool ZipFile::uncompressEntry (const int index,
  8610. const File& targetDirectory,
  8611. bool shouldOverwriteFiles)
  8612. {
  8613. const ZipEntryInfo* zei = entries [index];
  8614. if (zei != 0)
  8615. {
  8616. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8617. if (zei->entry.filename.endsWithChar ('/'))
  8618. {
  8619. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8620. }
  8621. else
  8622. {
  8623. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8624. if (in != 0)
  8625. {
  8626. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8627. return false;
  8628. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8629. {
  8630. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8631. if (out != 0)
  8632. {
  8633. out->writeFromInputStream (*in, -1);
  8634. out = 0;
  8635. targetFile.setCreationTime (zei->entry.fileTime);
  8636. targetFile.setLastModificationTime (zei->entry.fileTime);
  8637. targetFile.setLastAccessTime (zei->entry.fileTime);
  8638. return true;
  8639. }
  8640. }
  8641. }
  8642. }
  8643. }
  8644. return false;
  8645. }
  8646. END_JUCE_NAMESPACE
  8647. /*** End of inlined file: juce_ZipFile.cpp ***/
  8648. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8649. #if JUCE_MSVC
  8650. #pragma warning (push)
  8651. #pragma warning (disable: 4514 4996)
  8652. #endif
  8653. #include <cwctype>
  8654. #include <cctype>
  8655. #include <ctime>
  8656. BEGIN_JUCE_NAMESPACE
  8657. int CharacterFunctions::length (const char* const s) throw()
  8658. {
  8659. return (int) strlen (s);
  8660. }
  8661. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8662. {
  8663. return (int) wcslen (s);
  8664. }
  8665. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8666. {
  8667. strncpy (dest, src, maxChars);
  8668. }
  8669. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8670. {
  8671. wcsncpy (dest, src, maxChars);
  8672. }
  8673. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8674. {
  8675. mbstowcs (dest, src, maxChars);
  8676. }
  8677. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8678. {
  8679. wcstombs (dest, src, maxChars);
  8680. }
  8681. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8682. {
  8683. return (int) wcstombs (0, src, 0);
  8684. }
  8685. void CharacterFunctions::append (char* dest, const char* src) throw()
  8686. {
  8687. strcat (dest, src);
  8688. }
  8689. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8690. {
  8691. wcscat (dest, src);
  8692. }
  8693. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8694. {
  8695. return strcmp (s1, s2);
  8696. }
  8697. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8698. {
  8699. jassert (s1 != 0 && s2 != 0);
  8700. return wcscmp (s1, s2);
  8701. }
  8702. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8703. {
  8704. jassert (s1 != 0 && s2 != 0);
  8705. return strncmp (s1, s2, maxChars);
  8706. }
  8707. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8708. {
  8709. jassert (s1 != 0 && s2 != 0);
  8710. return wcsncmp (s1, s2, maxChars);
  8711. }
  8712. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8713. {
  8714. jassert (s1 != 0 && s2 != 0);
  8715. for (;;)
  8716. {
  8717. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8718. if (diff != 0)
  8719. return diff;
  8720. else if (*s1 == 0)
  8721. break;
  8722. ++s1;
  8723. ++s2;
  8724. }
  8725. return 0;
  8726. }
  8727. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8728. {
  8729. return -compare (s2, s1);
  8730. }
  8731. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8732. {
  8733. jassert (s1 != 0 && s2 != 0);
  8734. #if JUCE_WINDOWS
  8735. return stricmp (s1, s2);
  8736. #else
  8737. return strcasecmp (s1, s2);
  8738. #endif
  8739. }
  8740. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8741. {
  8742. jassert (s1 != 0 && s2 != 0);
  8743. #if JUCE_WINDOWS
  8744. return _wcsicmp (s1, s2);
  8745. #else
  8746. for (;;)
  8747. {
  8748. if (*s1 != *s2)
  8749. {
  8750. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8751. if (diff != 0)
  8752. return diff < 0 ? -1 : 1;
  8753. }
  8754. else if (*s1 == 0)
  8755. break;
  8756. ++s1;
  8757. ++s2;
  8758. }
  8759. return 0;
  8760. #endif
  8761. }
  8762. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8763. {
  8764. jassert (s1 != 0 && s2 != 0);
  8765. for (;;)
  8766. {
  8767. if (*s1 != *s2)
  8768. {
  8769. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8770. if (diff != 0)
  8771. return diff < 0 ? -1 : 1;
  8772. }
  8773. else if (*s1 == 0)
  8774. break;
  8775. ++s1;
  8776. ++s2;
  8777. }
  8778. return 0;
  8779. }
  8780. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8781. {
  8782. jassert (s1 != 0 && s2 != 0);
  8783. #if JUCE_WINDOWS
  8784. return strnicmp (s1, s2, maxChars);
  8785. #else
  8786. return strncasecmp (s1, s2, maxChars);
  8787. #endif
  8788. }
  8789. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8790. {
  8791. jassert (s1 != 0 && s2 != 0);
  8792. #if JUCE_WINDOWS
  8793. return _wcsnicmp (s1, s2, maxChars);
  8794. #else
  8795. while (--maxChars >= 0)
  8796. {
  8797. if (*s1 != *s2)
  8798. {
  8799. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8800. if (diff != 0)
  8801. return diff < 0 ? -1 : 1;
  8802. }
  8803. else if (*s1 == 0)
  8804. break;
  8805. ++s1;
  8806. ++s2;
  8807. }
  8808. return 0;
  8809. #endif
  8810. }
  8811. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8812. {
  8813. return strstr (haystack, needle);
  8814. }
  8815. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8816. {
  8817. return wcsstr (haystack, needle);
  8818. }
  8819. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8820. {
  8821. if (haystack != 0)
  8822. {
  8823. int i = 0;
  8824. if (ignoreCase)
  8825. {
  8826. const char n1 = toLowerCase (needle);
  8827. const char n2 = toUpperCase (needle);
  8828. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8829. {
  8830. while (haystack[i] != 0)
  8831. {
  8832. if (haystack[i] == n1 || haystack[i] == n2)
  8833. return i;
  8834. ++i;
  8835. }
  8836. return -1;
  8837. }
  8838. jassert (n1 == needle);
  8839. }
  8840. while (haystack[i] != 0)
  8841. {
  8842. if (haystack[i] == needle)
  8843. return i;
  8844. ++i;
  8845. }
  8846. }
  8847. return -1;
  8848. }
  8849. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8850. {
  8851. if (haystack != 0)
  8852. {
  8853. int i = 0;
  8854. if (ignoreCase)
  8855. {
  8856. const juce_wchar n1 = toLowerCase (needle);
  8857. const juce_wchar n2 = toUpperCase (needle);
  8858. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8859. {
  8860. while (haystack[i] != 0)
  8861. {
  8862. if (haystack[i] == n1 || haystack[i] == n2)
  8863. return i;
  8864. ++i;
  8865. }
  8866. return -1;
  8867. }
  8868. jassert (n1 == needle);
  8869. }
  8870. while (haystack[i] != 0)
  8871. {
  8872. if (haystack[i] == needle)
  8873. return i;
  8874. ++i;
  8875. }
  8876. }
  8877. return -1;
  8878. }
  8879. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8880. {
  8881. jassert (haystack != 0);
  8882. int i = 0;
  8883. while (haystack[i] != 0)
  8884. {
  8885. if (haystack[i] == needle)
  8886. return i;
  8887. ++i;
  8888. }
  8889. return -1;
  8890. }
  8891. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8892. {
  8893. jassert (haystack != 0);
  8894. int i = 0;
  8895. while (haystack[i] != 0)
  8896. {
  8897. if (haystack[i] == needle)
  8898. return i;
  8899. ++i;
  8900. }
  8901. return -1;
  8902. }
  8903. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8904. {
  8905. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8906. }
  8907. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8908. {
  8909. if (allowedChars == 0)
  8910. return 0;
  8911. int i = 0;
  8912. for (;;)
  8913. {
  8914. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8915. break;
  8916. ++i;
  8917. }
  8918. return i;
  8919. }
  8920. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8921. {
  8922. return (int) strftime (dest, maxChars, format, tm);
  8923. }
  8924. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8925. {
  8926. return (int) wcsftime (dest, maxChars, format, tm);
  8927. }
  8928. int CharacterFunctions::getIntValue (const char* const s) throw()
  8929. {
  8930. return atoi (s);
  8931. }
  8932. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8933. {
  8934. #if JUCE_WINDOWS
  8935. return _wtoi (s);
  8936. #else
  8937. int v = 0;
  8938. while (isWhitespace (*s))
  8939. ++s;
  8940. const bool isNeg = *s == '-';
  8941. if (isNeg)
  8942. ++s;
  8943. for (;;)
  8944. {
  8945. const wchar_t c = *s++;
  8946. if (c >= '0' && c <= '9')
  8947. v = v * 10 + (int) (c - '0');
  8948. else
  8949. break;
  8950. }
  8951. return isNeg ? -v : v;
  8952. #endif
  8953. }
  8954. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8955. {
  8956. #if JUCE_LINUX
  8957. return atoll (s);
  8958. #elif JUCE_WINDOWS
  8959. return _atoi64 (s);
  8960. #else
  8961. int64 v = 0;
  8962. while (isWhitespace (*s))
  8963. ++s;
  8964. const bool isNeg = *s == '-';
  8965. if (isNeg)
  8966. ++s;
  8967. for (;;)
  8968. {
  8969. const char c = *s++;
  8970. if (c >= '0' && c <= '9')
  8971. v = v * 10 + (int64) (c - '0');
  8972. else
  8973. break;
  8974. }
  8975. return isNeg ? -v : v;
  8976. #endif
  8977. }
  8978. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8979. {
  8980. #if JUCE_WINDOWS
  8981. return _wtoi64 (s);
  8982. #else
  8983. int64 v = 0;
  8984. while (isWhitespace (*s))
  8985. ++s;
  8986. const bool isNeg = *s == '-';
  8987. if (isNeg)
  8988. ++s;
  8989. for (;;)
  8990. {
  8991. const juce_wchar c = *s++;
  8992. if (c >= '0' && c <= '9')
  8993. v = v * 10 + (int64) (c - '0');
  8994. else
  8995. break;
  8996. }
  8997. return isNeg ? -v : v;
  8998. #endif
  8999. }
  9000. static double juce_mulexp10 (const double value, int exponent) throw()
  9001. {
  9002. if (exponent == 0)
  9003. return value;
  9004. if (value == 0)
  9005. return 0;
  9006. const bool negative = (exponent < 0);
  9007. if (negative)
  9008. exponent = -exponent;
  9009. double result = 1.0, power = 10.0;
  9010. for (int bit = 1; exponent != 0; bit <<= 1)
  9011. {
  9012. if ((exponent & bit) != 0)
  9013. {
  9014. exponent ^= bit;
  9015. result *= power;
  9016. if (exponent == 0)
  9017. break;
  9018. }
  9019. power *= power;
  9020. }
  9021. return negative ? (value / result) : (value * result);
  9022. }
  9023. template <class CharType>
  9024. double juce_atof (const CharType* const original) throw()
  9025. {
  9026. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9027. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9028. int exponent = 0, decPointIndex = 0, digit = 0;
  9029. int lastDigit = 0, numSignificantDigits = 0;
  9030. bool isNegative = false, digitsFound = false;
  9031. const int maxSignificantDigits = 15 + 2;
  9032. const CharType* s = original;
  9033. while (CharacterFunctions::isWhitespace (*s))
  9034. ++s;
  9035. switch (*s)
  9036. {
  9037. case '-': isNegative = true; // fall-through..
  9038. case '+': ++s;
  9039. }
  9040. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9041. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9042. for (;;)
  9043. {
  9044. if (CharacterFunctions::isDigit (*s))
  9045. {
  9046. lastDigit = digit;
  9047. digit = *s++ - '0';
  9048. digitsFound = true;
  9049. if (decPointIndex != 0)
  9050. exponentAdjustment[1]++;
  9051. if (numSignificantDigits == 0 && digit == 0)
  9052. continue;
  9053. if (++numSignificantDigits > maxSignificantDigits)
  9054. {
  9055. if (digit > 5)
  9056. ++accumulator [decPointIndex];
  9057. else if (digit == 5 && (lastDigit & 1) != 0)
  9058. ++accumulator [decPointIndex];
  9059. if (decPointIndex > 0)
  9060. exponentAdjustment[1]--;
  9061. else
  9062. exponentAdjustment[0]++;
  9063. while (CharacterFunctions::isDigit (*s))
  9064. {
  9065. ++s;
  9066. if (decPointIndex == 0)
  9067. exponentAdjustment[0]++;
  9068. }
  9069. }
  9070. else
  9071. {
  9072. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9073. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9074. {
  9075. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9076. + accumulator [decPointIndex];
  9077. accumulator [decPointIndex] = 0;
  9078. exponentAccumulator [decPointIndex] = 0;
  9079. }
  9080. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9081. exponentAccumulator [decPointIndex]++;
  9082. }
  9083. }
  9084. else if (decPointIndex == 0 && *s == '.')
  9085. {
  9086. ++s;
  9087. decPointIndex = 1;
  9088. if (numSignificantDigits > maxSignificantDigits)
  9089. {
  9090. while (CharacterFunctions::isDigit (*s))
  9091. ++s;
  9092. break;
  9093. }
  9094. }
  9095. else
  9096. {
  9097. break;
  9098. }
  9099. }
  9100. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9101. if (decPointIndex != 0)
  9102. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9103. if ((*s == 'e' || *s == 'E') && digitsFound)
  9104. {
  9105. bool negativeExponent = false;
  9106. switch (*++s)
  9107. {
  9108. case '-': negativeExponent = true; // fall-through..
  9109. case '+': ++s;
  9110. }
  9111. while (CharacterFunctions::isDigit (*s))
  9112. exponent = (exponent * 10) + (*s++ - '0');
  9113. if (negativeExponent)
  9114. exponent = -exponent;
  9115. }
  9116. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9117. if (decPointIndex != 0)
  9118. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9119. return isNegative ? -r : r;
  9120. }
  9121. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9122. {
  9123. return juce_atof <char> (s);
  9124. }
  9125. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9126. {
  9127. return juce_atof <juce_wchar> (s);
  9128. }
  9129. char CharacterFunctions::toUpperCase (const char character) throw()
  9130. {
  9131. return (char) toupper (character);
  9132. }
  9133. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9134. {
  9135. return towupper (character);
  9136. }
  9137. void CharacterFunctions::toUpperCase (char* s) throw()
  9138. {
  9139. #if JUCE_WINDOWS
  9140. strupr (s);
  9141. #else
  9142. while (*s != 0)
  9143. {
  9144. *s = toUpperCase (*s);
  9145. ++s;
  9146. }
  9147. #endif
  9148. }
  9149. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9150. {
  9151. #if JUCE_WINDOWS
  9152. _wcsupr (s);
  9153. #else
  9154. while (*s != 0)
  9155. {
  9156. *s = toUpperCase (*s);
  9157. ++s;
  9158. }
  9159. #endif
  9160. }
  9161. bool CharacterFunctions::isUpperCase (const char character) throw()
  9162. {
  9163. return isupper (character) != 0;
  9164. }
  9165. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9166. {
  9167. #if JUCE_WINDOWS
  9168. return iswupper (character) != 0;
  9169. #else
  9170. return toLowerCase (character) != character;
  9171. #endif
  9172. }
  9173. char CharacterFunctions::toLowerCase (const char character) throw()
  9174. {
  9175. return (char) tolower (character);
  9176. }
  9177. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9178. {
  9179. return towlower (character);
  9180. }
  9181. void CharacterFunctions::toLowerCase (char* s) throw()
  9182. {
  9183. #if JUCE_WINDOWS
  9184. strlwr (s);
  9185. #else
  9186. while (*s != 0)
  9187. {
  9188. *s = toLowerCase (*s);
  9189. ++s;
  9190. }
  9191. #endif
  9192. }
  9193. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9194. {
  9195. #if JUCE_WINDOWS
  9196. _wcslwr (s);
  9197. #else
  9198. while (*s != 0)
  9199. {
  9200. *s = toLowerCase (*s);
  9201. ++s;
  9202. }
  9203. #endif
  9204. }
  9205. bool CharacterFunctions::isLowerCase (const char character) throw()
  9206. {
  9207. return islower (character) != 0;
  9208. }
  9209. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9210. {
  9211. #if JUCE_WINDOWS
  9212. return iswlower (character) != 0;
  9213. #else
  9214. return toUpperCase (character) != character;
  9215. #endif
  9216. }
  9217. bool CharacterFunctions::isWhitespace (const char character) throw()
  9218. {
  9219. return character == ' ' || (character <= 13 && character >= 9);
  9220. }
  9221. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9222. {
  9223. return iswspace (character) != 0;
  9224. }
  9225. bool CharacterFunctions::isDigit (const char character) throw()
  9226. {
  9227. return (character >= '0' && character <= '9');
  9228. }
  9229. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9230. {
  9231. return iswdigit (character) != 0;
  9232. }
  9233. bool CharacterFunctions::isLetter (const char character) throw()
  9234. {
  9235. return (character >= 'a' && character <= 'z')
  9236. || (character >= 'A' && character <= 'Z');
  9237. }
  9238. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9239. {
  9240. return iswalpha (character) != 0;
  9241. }
  9242. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9243. {
  9244. return (character >= 'a' && character <= 'z')
  9245. || (character >= 'A' && character <= 'Z')
  9246. || (character >= '0' && character <= '9');
  9247. }
  9248. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9249. {
  9250. return iswalnum (character) != 0;
  9251. }
  9252. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9253. {
  9254. unsigned int d = digit - '0';
  9255. if (d < (unsigned int) 10)
  9256. return (int) d;
  9257. d += (unsigned int) ('0' - 'a');
  9258. if (d < (unsigned int) 6)
  9259. return (int) d + 10;
  9260. d += (unsigned int) ('a' - 'A');
  9261. if (d < (unsigned int) 6)
  9262. return (int) d + 10;
  9263. return -1;
  9264. }
  9265. #if JUCE_MSVC
  9266. #pragma warning (pop)
  9267. #endif
  9268. END_JUCE_NAMESPACE
  9269. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9270. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9271. BEGIN_JUCE_NAMESPACE
  9272. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9273. {
  9274. loadFromText (fileContents);
  9275. }
  9276. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9277. {
  9278. loadFromText (fileToLoad.loadFileAsString());
  9279. }
  9280. LocalisedStrings::~LocalisedStrings()
  9281. {
  9282. }
  9283. const String LocalisedStrings::translate (const String& text) const
  9284. {
  9285. return translations.getValue (text, text);
  9286. }
  9287. static int findCloseQuote (const String& text, int startPos)
  9288. {
  9289. juce_wchar lastChar = 0;
  9290. for (;;)
  9291. {
  9292. const juce_wchar c = text [startPos];
  9293. if (c == 0 || (c == '"' && lastChar != '\\'))
  9294. break;
  9295. lastChar = c;
  9296. ++startPos;
  9297. }
  9298. return startPos;
  9299. }
  9300. static const String unescapeString (const String& s)
  9301. {
  9302. return s.replace ("\\\"", "\"")
  9303. .replace ("\\\'", "\'")
  9304. .replace ("\\t", "\t")
  9305. .replace ("\\r", "\r")
  9306. .replace ("\\n", "\n");
  9307. }
  9308. void LocalisedStrings::loadFromText (const String& fileContents)
  9309. {
  9310. StringArray lines;
  9311. lines.addLines (fileContents);
  9312. for (int i = 0; i < lines.size(); ++i)
  9313. {
  9314. String line (lines[i].trim());
  9315. if (line.startsWithChar ('"'))
  9316. {
  9317. int closeQuote = findCloseQuote (line, 1);
  9318. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9319. if (originalText.isNotEmpty())
  9320. {
  9321. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9322. closeQuote = findCloseQuote (line, openingQuote + 1);
  9323. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9324. if (newText.isNotEmpty())
  9325. translations.set (originalText, newText);
  9326. }
  9327. }
  9328. else if (line.startsWithIgnoreCase ("language:"))
  9329. {
  9330. languageName = line.substring (9).trim();
  9331. }
  9332. else if (line.startsWithIgnoreCase ("countries:"))
  9333. {
  9334. countryCodes.addTokens (line.substring (10).trim(), true);
  9335. countryCodes.trim();
  9336. countryCodes.removeEmptyStrings();
  9337. }
  9338. }
  9339. }
  9340. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9341. {
  9342. translations.setIgnoresCase (shouldIgnoreCase);
  9343. }
  9344. static CriticalSection currentMappingsLock;
  9345. static LocalisedStrings* currentMappings = 0;
  9346. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9347. {
  9348. const ScopedLock sl (currentMappingsLock);
  9349. delete currentMappings;
  9350. currentMappings = newTranslations;
  9351. }
  9352. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9353. {
  9354. return currentMappings;
  9355. }
  9356. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9357. {
  9358. const ScopedLock sl (currentMappingsLock);
  9359. if (currentMappings != 0)
  9360. return currentMappings->translate (text);
  9361. return text;
  9362. }
  9363. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9364. {
  9365. return translateWithCurrentMappings (String (text));
  9366. }
  9367. END_JUCE_NAMESPACE
  9368. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9369. /*** Start of inlined file: juce_String.cpp ***/
  9370. #if JUCE_MSVC
  9371. #pragma warning (push)
  9372. #pragma warning (disable: 4514)
  9373. #endif
  9374. #include <locale>
  9375. BEGIN_JUCE_NAMESPACE
  9376. #if JUCE_MSVC
  9377. #pragma warning (pop)
  9378. #endif
  9379. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9380. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9381. #endif
  9382. class StringHolder
  9383. {
  9384. public:
  9385. StringHolder()
  9386. : refCount (0x3fffffff), allocatedNumChars (0)
  9387. {
  9388. text[0] = 0;
  9389. }
  9390. static juce_wchar* createUninitialised (const size_t numChars)
  9391. {
  9392. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9393. s->refCount.value = 0;
  9394. s->allocatedNumChars = numChars;
  9395. return &(s->text[0]);
  9396. }
  9397. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9398. {
  9399. juce_wchar* const dest = createUninitialised (numChars);
  9400. copyChars (dest, src, numChars);
  9401. return dest;
  9402. }
  9403. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9404. {
  9405. juce_wchar* const dest = createUninitialised (numChars);
  9406. CharacterFunctions::copy (dest, src, (int) numChars);
  9407. dest [numChars] = 0;
  9408. return dest;
  9409. }
  9410. static inline juce_wchar* getEmpty() throw()
  9411. {
  9412. return &(empty.text[0]);
  9413. }
  9414. static void retain (juce_wchar* const text) throw()
  9415. {
  9416. ++(bufferFromText (text)->refCount);
  9417. }
  9418. static inline void release (StringHolder* const b) throw()
  9419. {
  9420. if (--(b->refCount) == -1 && b != &empty)
  9421. delete[] reinterpret_cast <char*> (b);
  9422. }
  9423. static void release (juce_wchar* const text) throw()
  9424. {
  9425. release (bufferFromText (text));
  9426. }
  9427. static juce_wchar* makeUnique (juce_wchar* const text)
  9428. {
  9429. StringHolder* const b = bufferFromText (text);
  9430. if (b->refCount.get() <= 0)
  9431. return text;
  9432. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9433. release (b);
  9434. return newText;
  9435. }
  9436. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9437. {
  9438. StringHolder* const b = bufferFromText (text);
  9439. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9440. return text;
  9441. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9442. copyChars (newText, text, b->allocatedNumChars);
  9443. release (b);
  9444. return newText;
  9445. }
  9446. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9447. {
  9448. return bufferFromText (text)->allocatedNumChars;
  9449. }
  9450. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9451. {
  9452. jassert (src != 0 && dest != 0);
  9453. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9454. dest [numChars] = 0;
  9455. }
  9456. Atomic<int> refCount;
  9457. size_t allocatedNumChars;
  9458. juce_wchar text[1];
  9459. static StringHolder empty;
  9460. private:
  9461. static inline StringHolder* bufferFromText (void* const text) throw()
  9462. {
  9463. // (Can't use offsetof() here because of warnings about this not being a POD)
  9464. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9465. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9466. }
  9467. };
  9468. StringHolder StringHolder::empty;
  9469. const String String::empty;
  9470. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9471. {
  9472. jassert (t[numChars] == 0); // must have a null terminator
  9473. text = StringHolder::createCopy (t, numChars);
  9474. }
  9475. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9476. {
  9477. if (numExtraChars > 0)
  9478. {
  9479. const int oldLen = length();
  9480. const int newTotalLen = oldLen + numExtraChars;
  9481. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9482. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9483. }
  9484. }
  9485. void String::preallocateStorage (const size_t numChars)
  9486. {
  9487. text = StringHolder::makeUniqueWithSize (text, numChars);
  9488. }
  9489. String::String() throw()
  9490. : text (StringHolder::getEmpty())
  9491. {
  9492. }
  9493. String::~String() throw()
  9494. {
  9495. StringHolder::release (text);
  9496. }
  9497. String::String (const String& other) throw()
  9498. : text (other.text)
  9499. {
  9500. StringHolder::retain (text);
  9501. }
  9502. void String::swapWith (String& other) throw()
  9503. {
  9504. swapVariables (text, other.text);
  9505. }
  9506. String& String::operator= (const String& other) throw()
  9507. {
  9508. juce_wchar* const newText = other.text;
  9509. StringHolder::retain (newText);
  9510. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9511. return *this;
  9512. }
  9513. String::String (const size_t numChars, const int /*dummyVariable*/)
  9514. : text (StringHolder::createUninitialised (numChars))
  9515. {
  9516. }
  9517. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9518. {
  9519. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9520. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9521. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9522. }
  9523. String::String (const char* const t)
  9524. {
  9525. if (t != 0 && *t != 0)
  9526. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9527. else
  9528. text = StringHolder::getEmpty();
  9529. }
  9530. String::String (const juce_wchar* const t)
  9531. {
  9532. if (t != 0 && *t != 0)
  9533. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9534. else
  9535. text = StringHolder::getEmpty();
  9536. }
  9537. String::String (const char* const t, const size_t maxChars)
  9538. {
  9539. int i;
  9540. for (i = 0; (size_t) i < maxChars; ++i)
  9541. if (t[i] == 0)
  9542. break;
  9543. if (i > 0)
  9544. text = StringHolder::createCopy (t, i);
  9545. else
  9546. text = StringHolder::getEmpty();
  9547. }
  9548. String::String (const juce_wchar* const t, const size_t maxChars)
  9549. {
  9550. int i;
  9551. for (i = 0; (size_t) i < maxChars; ++i)
  9552. if (t[i] == 0)
  9553. break;
  9554. if (i > 0)
  9555. text = StringHolder::createCopy (t, i);
  9556. else
  9557. text = StringHolder::getEmpty();
  9558. }
  9559. const String String::charToString (const juce_wchar character)
  9560. {
  9561. String result ((size_t) 1, (int) 0);
  9562. result.text[0] = character;
  9563. result.text[1] = 0;
  9564. return result;
  9565. }
  9566. namespace NumberToStringConverters
  9567. {
  9568. // pass in a pointer to the END of a buffer..
  9569. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9570. {
  9571. *--t = 0;
  9572. int64 v = (n >= 0) ? n : -n;
  9573. do
  9574. {
  9575. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9576. v /= 10;
  9577. } while (v > 0);
  9578. if (n < 0)
  9579. *--t = '-';
  9580. return t;
  9581. }
  9582. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9583. {
  9584. *--t = 0;
  9585. do
  9586. {
  9587. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9588. v /= 10;
  9589. } while (v > 0);
  9590. return t;
  9591. }
  9592. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9593. {
  9594. if (n == (int) 0x80000000) // (would cause an overflow)
  9595. return int64ToString (t, n);
  9596. *--t = 0;
  9597. int v = abs (n);
  9598. do
  9599. {
  9600. *--t = (juce_wchar) ('0' + (v % 10));
  9601. v /= 10;
  9602. } while (v > 0);
  9603. if (n < 0)
  9604. *--t = '-';
  9605. return t;
  9606. }
  9607. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9608. {
  9609. *--t = 0;
  9610. do
  9611. {
  9612. *--t = (juce_wchar) ('0' + (v % 10));
  9613. v /= 10;
  9614. } while (v > 0);
  9615. return t;
  9616. }
  9617. static juce_wchar getDecimalPoint()
  9618. {
  9619. #if JUCE_MSVC && _MSC_VER < 1400
  9620. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9621. #else
  9622. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9623. #endif
  9624. return dp;
  9625. }
  9626. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9627. {
  9628. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9629. {
  9630. juce_wchar* const end = buffer + numChars;
  9631. juce_wchar* t = end;
  9632. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9633. *--t = (juce_wchar) 0;
  9634. while (numDecPlaces >= 0 || v > 0)
  9635. {
  9636. if (numDecPlaces == 0)
  9637. *--t = getDecimalPoint();
  9638. *--t = (juce_wchar) ('0' + (v % 10));
  9639. v /= 10;
  9640. --numDecPlaces;
  9641. }
  9642. if (n < 0)
  9643. *--t = '-';
  9644. len = end - t - 1;
  9645. return t;
  9646. }
  9647. else
  9648. {
  9649. #if JUCE_WINDOWS
  9650. #if JUCE_MSVC && _MSC_VER <= 1400
  9651. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9652. #else
  9653. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9654. #endif
  9655. #else
  9656. len = swprintf (buffer, numChars, L"%.9g", n);
  9657. #endif
  9658. return buffer;
  9659. }
  9660. }
  9661. }
  9662. String::String (const int number)
  9663. {
  9664. juce_wchar buffer [16];
  9665. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9666. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9667. createInternal (start, end - start - 1);
  9668. }
  9669. String::String (const unsigned int number)
  9670. {
  9671. juce_wchar buffer [16];
  9672. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9673. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9674. createInternal (start, end - start - 1);
  9675. }
  9676. String::String (const short number)
  9677. {
  9678. juce_wchar buffer [16];
  9679. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9680. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9681. createInternal (start, end - start - 1);
  9682. }
  9683. String::String (const unsigned short number)
  9684. {
  9685. juce_wchar buffer [16];
  9686. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9687. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9688. createInternal (start, end - start - 1);
  9689. }
  9690. String::String (const int64 number)
  9691. {
  9692. juce_wchar buffer [32];
  9693. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9694. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9695. createInternal (start, end - start - 1);
  9696. }
  9697. String::String (const uint64 number)
  9698. {
  9699. juce_wchar buffer [32];
  9700. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9701. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9702. createInternal (start, end - start - 1);
  9703. }
  9704. String::String (const float number, const int numberOfDecimalPlaces)
  9705. {
  9706. juce_wchar buffer [48];
  9707. size_t len;
  9708. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9709. createInternal (start, len);
  9710. }
  9711. String::String (const double number, const int numberOfDecimalPlaces)
  9712. {
  9713. juce_wchar buffer [48];
  9714. size_t len;
  9715. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9716. createInternal (start, len);
  9717. }
  9718. int String::length() const throw()
  9719. {
  9720. return CharacterFunctions::length (text);
  9721. }
  9722. int String::hashCode() const throw()
  9723. {
  9724. const juce_wchar* t = text;
  9725. int result = 0;
  9726. while (*t != (juce_wchar) 0)
  9727. result = 31 * result + *t++;
  9728. return result;
  9729. }
  9730. int64 String::hashCode64() const throw()
  9731. {
  9732. const juce_wchar* t = text;
  9733. int64 result = 0;
  9734. while (*t != (juce_wchar) 0)
  9735. result = 101 * result + *t++;
  9736. return result;
  9737. }
  9738. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9739. {
  9740. return string1.compare (string2) == 0;
  9741. }
  9742. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9743. {
  9744. return string1.compare (string2) == 0;
  9745. }
  9746. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9747. {
  9748. return string1.compare (string2) == 0;
  9749. }
  9750. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9751. {
  9752. return string1.compare (string2) != 0;
  9753. }
  9754. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9755. {
  9756. return string1.compare (string2) != 0;
  9757. }
  9758. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9759. {
  9760. return string1.compare (string2) != 0;
  9761. }
  9762. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9763. {
  9764. return string1.compare (string2) > 0;
  9765. }
  9766. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9767. {
  9768. return string1.compare (string2) < 0;
  9769. }
  9770. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9771. {
  9772. return string1.compare (string2) >= 0;
  9773. }
  9774. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9775. {
  9776. return string1.compare (string2) <= 0;
  9777. }
  9778. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9779. {
  9780. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9781. : isEmpty();
  9782. }
  9783. bool String::equalsIgnoreCase (const char* t) const throw()
  9784. {
  9785. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9786. : isEmpty();
  9787. }
  9788. bool String::equalsIgnoreCase (const String& other) const throw()
  9789. {
  9790. return text == other.text
  9791. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9792. }
  9793. int String::compare (const String& other) const throw()
  9794. {
  9795. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9796. }
  9797. int String::compare (const char* other) const throw()
  9798. {
  9799. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9800. }
  9801. int String::compare (const juce_wchar* other) const throw()
  9802. {
  9803. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9804. }
  9805. int String::compareIgnoreCase (const String& other) const throw()
  9806. {
  9807. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9808. }
  9809. int String::compareLexicographically (const String& other) const throw()
  9810. {
  9811. const juce_wchar* s1 = text;
  9812. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9813. ++s1;
  9814. const juce_wchar* s2 = other.text;
  9815. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9816. ++s2;
  9817. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9818. }
  9819. String& String::operator+= (const juce_wchar* const t)
  9820. {
  9821. if (t != 0)
  9822. appendInternal (t, CharacterFunctions::length (t));
  9823. return *this;
  9824. }
  9825. String& String::operator+= (const String& other)
  9826. {
  9827. if (isEmpty())
  9828. operator= (other);
  9829. else
  9830. appendInternal (other.text, other.length());
  9831. return *this;
  9832. }
  9833. String& String::operator+= (const char ch)
  9834. {
  9835. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9836. return operator+= (static_cast <const juce_wchar*> (asString));
  9837. }
  9838. String& String::operator+= (const juce_wchar ch)
  9839. {
  9840. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9841. return operator+= (static_cast <const juce_wchar*> (asString));
  9842. }
  9843. String& String::operator+= (const int number)
  9844. {
  9845. juce_wchar buffer [16];
  9846. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9847. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9848. appendInternal (start, (int) (end - start));
  9849. return *this;
  9850. }
  9851. String& String::operator+= (const unsigned int number)
  9852. {
  9853. juce_wchar buffer [16];
  9854. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9855. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9856. appendInternal (start, (int) (end - start));
  9857. return *this;
  9858. }
  9859. void String::append (const juce_wchar* const other, const int howMany)
  9860. {
  9861. if (howMany > 0)
  9862. {
  9863. int i;
  9864. for (i = 0; i < howMany; ++i)
  9865. if (other[i] == 0)
  9866. break;
  9867. appendInternal (other, i);
  9868. }
  9869. }
  9870. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9871. {
  9872. String s (string1);
  9873. return s += string2;
  9874. }
  9875. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9876. {
  9877. String s (string1);
  9878. return s += string2;
  9879. }
  9880. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9881. {
  9882. return String::charToString (string1) + string2;
  9883. }
  9884. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9885. {
  9886. return String::charToString (string1) + string2;
  9887. }
  9888. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9889. {
  9890. return string1 += string2;
  9891. }
  9892. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9893. {
  9894. return string1 += string2;
  9895. }
  9896. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9897. {
  9898. return string1 += string2;
  9899. }
  9900. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9901. {
  9902. return string1 += string2;
  9903. }
  9904. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9905. {
  9906. return string1 += string2;
  9907. }
  9908. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9909. {
  9910. return string1 += characterToAppend;
  9911. }
  9912. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9913. {
  9914. return string1 += characterToAppend;
  9915. }
  9916. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9917. {
  9918. return string1 += string2;
  9919. }
  9920. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9921. {
  9922. return string1 += string2;
  9923. }
  9924. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9925. {
  9926. return string1 += string2;
  9927. }
  9928. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9929. {
  9930. return string1 += (int) number;
  9931. }
  9932. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9933. {
  9934. return string1 += number;
  9935. }
  9936. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9937. {
  9938. return string1 += number;
  9939. }
  9940. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9941. {
  9942. return string1 += (int) number;
  9943. }
  9944. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9945. {
  9946. return string1 += (unsigned int) number;
  9947. }
  9948. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9949. {
  9950. return string1 += String (number);
  9951. }
  9952. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9953. {
  9954. return string1 += String (number);
  9955. }
  9956. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9957. {
  9958. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9959. // if lots of large, persistent strings were to be written to streams).
  9960. const int numBytes = text.getNumBytesAsUTF8();
  9961. HeapBlock<char> temp (numBytes + 1);
  9962. text.copyToUTF8 (temp, numBytes + 1);
  9963. stream.write (temp, numBytes);
  9964. return stream;
  9965. }
  9966. int String::indexOfChar (const juce_wchar character) const throw()
  9967. {
  9968. const juce_wchar* t = text;
  9969. for (;;)
  9970. {
  9971. if (*t == character)
  9972. return (int) (t - text);
  9973. if (*t++ == 0)
  9974. return -1;
  9975. }
  9976. }
  9977. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9978. {
  9979. for (int i = length(); --i >= 0;)
  9980. if (text[i] == character)
  9981. return i;
  9982. return -1;
  9983. }
  9984. int String::indexOf (const String& t) const throw()
  9985. {
  9986. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9987. return r == 0 ? -1 : (int) (r - text);
  9988. }
  9989. int String::indexOfChar (const int startIndex,
  9990. const juce_wchar character) const throw()
  9991. {
  9992. if (startIndex > 0 && startIndex >= length())
  9993. return -1;
  9994. const juce_wchar* t = text + jmax (0, startIndex);
  9995. for (;;)
  9996. {
  9997. if (*t == character)
  9998. return (int) (t - text);
  9999. if (*t == 0)
  10000. return -1;
  10001. ++t;
  10002. }
  10003. }
  10004. int String::indexOfAnyOf (const String& charactersToLookFor,
  10005. const int startIndex,
  10006. const bool ignoreCase) const throw()
  10007. {
  10008. if (startIndex > 0 && startIndex >= length())
  10009. return -1;
  10010. const juce_wchar* t = text + jmax (0, startIndex);
  10011. while (*t != 0)
  10012. {
  10013. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10014. return (int) (t - text);
  10015. ++t;
  10016. }
  10017. return -1;
  10018. }
  10019. int String::indexOf (const int startIndex, const String& other) const throw()
  10020. {
  10021. if (startIndex > 0 && startIndex >= length())
  10022. return -1;
  10023. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10024. return found == 0 ? -1 : (int) (found - text);
  10025. }
  10026. int String::indexOfIgnoreCase (const String& other) const throw()
  10027. {
  10028. if (other.isNotEmpty())
  10029. {
  10030. const int len = other.length();
  10031. const int end = length() - len;
  10032. for (int i = 0; i <= end; ++i)
  10033. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10034. return i;
  10035. }
  10036. return -1;
  10037. }
  10038. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10039. {
  10040. if (other.isNotEmpty())
  10041. {
  10042. const int len = other.length();
  10043. const int end = length() - len;
  10044. for (int i = jmax (0, startIndex); i <= end; ++i)
  10045. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10046. return i;
  10047. }
  10048. return -1;
  10049. }
  10050. int String::lastIndexOf (const String& other) const throw()
  10051. {
  10052. if (other.isNotEmpty())
  10053. {
  10054. const int len = other.length();
  10055. int i = length() - len;
  10056. if (i >= 0)
  10057. {
  10058. const juce_wchar* n = text + i;
  10059. while (i >= 0)
  10060. {
  10061. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10062. return i;
  10063. --i;
  10064. }
  10065. }
  10066. }
  10067. return -1;
  10068. }
  10069. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10070. {
  10071. if (other.isNotEmpty())
  10072. {
  10073. const int len = other.length();
  10074. int i = length() - len;
  10075. if (i >= 0)
  10076. {
  10077. const juce_wchar* n = text + i;
  10078. while (i >= 0)
  10079. {
  10080. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10081. return i;
  10082. --i;
  10083. }
  10084. }
  10085. }
  10086. return -1;
  10087. }
  10088. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10089. {
  10090. for (int i = length(); --i >= 0;)
  10091. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10092. return i;
  10093. return -1;
  10094. }
  10095. bool String::contains (const String& other) const throw()
  10096. {
  10097. return indexOf (other) >= 0;
  10098. }
  10099. bool String::containsChar (const juce_wchar character) const throw()
  10100. {
  10101. const juce_wchar* t = text;
  10102. for (;;)
  10103. {
  10104. if (*t == 0)
  10105. return false;
  10106. if (*t == character)
  10107. return true;
  10108. ++t;
  10109. }
  10110. }
  10111. bool String::containsIgnoreCase (const String& t) const throw()
  10112. {
  10113. return indexOfIgnoreCase (t) >= 0;
  10114. }
  10115. int String::indexOfWholeWord (const String& word) const throw()
  10116. {
  10117. if (word.isNotEmpty())
  10118. {
  10119. const int wordLen = word.length();
  10120. const int end = length() - wordLen;
  10121. const juce_wchar* t = text;
  10122. for (int i = 0; i <= end; ++i)
  10123. {
  10124. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10125. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10126. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10127. {
  10128. return i;
  10129. }
  10130. ++t;
  10131. }
  10132. }
  10133. return -1;
  10134. }
  10135. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10136. {
  10137. if (word.isNotEmpty())
  10138. {
  10139. const int wordLen = word.length();
  10140. const int end = length() - wordLen;
  10141. const juce_wchar* t = text;
  10142. for (int i = 0; i <= end; ++i)
  10143. {
  10144. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10145. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10146. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10147. {
  10148. return i;
  10149. }
  10150. ++t;
  10151. }
  10152. }
  10153. return -1;
  10154. }
  10155. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10156. {
  10157. return indexOfWholeWord (wordToLookFor) >= 0;
  10158. }
  10159. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10160. {
  10161. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10162. }
  10163. static int indexOfMatch (const juce_wchar* const wildcard,
  10164. const juce_wchar* const test,
  10165. const bool ignoreCase) throw()
  10166. {
  10167. int start = 0;
  10168. while (test [start] != 0)
  10169. {
  10170. int i = 0;
  10171. for (;;)
  10172. {
  10173. const juce_wchar wc = wildcard [i];
  10174. const juce_wchar c = test [i + start];
  10175. if (wc == c
  10176. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10177. || (wc == '?' && c != 0))
  10178. {
  10179. if (wc == 0)
  10180. return start;
  10181. ++i;
  10182. }
  10183. else
  10184. {
  10185. if (wc == '*' && (wildcard [i + 1] == 0
  10186. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10187. {
  10188. return start;
  10189. }
  10190. break;
  10191. }
  10192. }
  10193. ++start;
  10194. }
  10195. return -1;
  10196. }
  10197. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10198. {
  10199. int i = 0;
  10200. for (;;)
  10201. {
  10202. const juce_wchar wc = wildcard.text [i];
  10203. const juce_wchar c = text [i];
  10204. if (wc == c
  10205. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10206. || (wc == '?' && c != 0))
  10207. {
  10208. if (wc == 0)
  10209. return true;
  10210. ++i;
  10211. }
  10212. else
  10213. {
  10214. return wc == '*' && (wildcard [i + 1] == 0
  10215. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10216. }
  10217. }
  10218. }
  10219. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10220. {
  10221. const int len = stringToRepeat.length();
  10222. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10223. juce_wchar* n = result.text;
  10224. *n = 0;
  10225. while (--numberOfTimesToRepeat >= 0)
  10226. {
  10227. StringHolder::copyChars (n, stringToRepeat.text, len);
  10228. n += len;
  10229. }
  10230. return result;
  10231. }
  10232. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10233. {
  10234. jassert (padCharacter != 0);
  10235. const int len = length();
  10236. if (len >= minimumLength || padCharacter == 0)
  10237. return *this;
  10238. String result ((size_t) minimumLength + 1, (int) 0);
  10239. juce_wchar* n = result.text;
  10240. minimumLength -= len;
  10241. while (--minimumLength >= 0)
  10242. *n++ = padCharacter;
  10243. StringHolder::copyChars (n, text, len);
  10244. return result;
  10245. }
  10246. const String String::paddedRight (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 (*this, (size_t) minimumLength);
  10253. juce_wchar* n = result.text + len;
  10254. minimumLength -= len;
  10255. while (--minimumLength >= 0)
  10256. *n++ = padCharacter;
  10257. *n = 0;
  10258. return result;
  10259. }
  10260. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10261. {
  10262. if (index < 0)
  10263. {
  10264. // a negative index to replace from?
  10265. jassertfalse;
  10266. index = 0;
  10267. }
  10268. if (numCharsToReplace < 0)
  10269. {
  10270. // replacing a negative number of characters?
  10271. numCharsToReplace = 0;
  10272. jassertfalse;
  10273. }
  10274. const int len = length();
  10275. if (index + numCharsToReplace > len)
  10276. {
  10277. if (index > len)
  10278. {
  10279. // replacing beyond the end of the string?
  10280. index = len;
  10281. jassertfalse;
  10282. }
  10283. numCharsToReplace = len - index;
  10284. }
  10285. const int newStringLen = stringToInsert.length();
  10286. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10287. if (newTotalLen <= 0)
  10288. return String::empty;
  10289. String result ((size_t) newTotalLen, (int) 0);
  10290. StringHolder::copyChars (result.text, text, index);
  10291. if (newStringLen > 0)
  10292. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10293. const int endStringLen = newTotalLen - (index + newStringLen);
  10294. if (endStringLen > 0)
  10295. StringHolder::copyChars (result.text + (index + newStringLen),
  10296. text + (index + numCharsToReplace),
  10297. endStringLen);
  10298. return result;
  10299. }
  10300. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10301. {
  10302. const int stringToReplaceLen = stringToReplace.length();
  10303. const int stringToInsertLen = stringToInsert.length();
  10304. int i = 0;
  10305. String result (*this);
  10306. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10307. : result.indexOf (i, stringToReplace))) >= 0)
  10308. {
  10309. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10310. i += stringToInsertLen;
  10311. }
  10312. return result;
  10313. }
  10314. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10315. {
  10316. const int index = indexOfChar (charToReplace);
  10317. if (index < 0)
  10318. return *this;
  10319. String result (*this, size_t());
  10320. juce_wchar* t = result.text + index;
  10321. while (*t != 0)
  10322. {
  10323. if (*t == charToReplace)
  10324. *t = charToInsert;
  10325. ++t;
  10326. }
  10327. return result;
  10328. }
  10329. const String String::replaceCharacters (const String& charactersToReplace,
  10330. const String& charactersToInsertInstead) const
  10331. {
  10332. String result (*this, size_t());
  10333. juce_wchar* t = result.text;
  10334. const int len2 = charactersToInsertInstead.length();
  10335. // the two strings passed in are supposed to be the same length!
  10336. jassert (len2 == charactersToReplace.length());
  10337. while (*t != 0)
  10338. {
  10339. const int index = charactersToReplace.indexOfChar (*t);
  10340. if (((unsigned int) index) < (unsigned int) len2)
  10341. *t = charactersToInsertInstead [index];
  10342. ++t;
  10343. }
  10344. return result;
  10345. }
  10346. bool String::startsWith (const String& other) const throw()
  10347. {
  10348. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10349. }
  10350. bool String::startsWithIgnoreCase (const String& other) const throw()
  10351. {
  10352. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10353. }
  10354. bool String::startsWithChar (const juce_wchar character) const throw()
  10355. {
  10356. jassert (character != 0); // strings can't contain a null character!
  10357. return text[0] == character;
  10358. }
  10359. bool String::endsWithChar (const juce_wchar character) const throw()
  10360. {
  10361. jassert (character != 0); // strings can't contain a null character!
  10362. return text[0] != 0
  10363. && text [length() - 1] == character;
  10364. }
  10365. bool String::endsWith (const String& other) const throw()
  10366. {
  10367. const int thisLen = length();
  10368. const int otherLen = other.length();
  10369. return thisLen >= otherLen
  10370. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10371. }
  10372. bool String::endsWithIgnoreCase (const String& other) const throw()
  10373. {
  10374. const int thisLen = length();
  10375. const int otherLen = other.length();
  10376. return thisLen >= otherLen
  10377. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10378. }
  10379. const String String::toUpperCase() const
  10380. {
  10381. String result (*this, size_t());
  10382. CharacterFunctions::toUpperCase (result.text);
  10383. return result;
  10384. }
  10385. const String String::toLowerCase() const
  10386. {
  10387. String result (*this, size_t());
  10388. CharacterFunctions::toLowerCase (result.text);
  10389. return result;
  10390. }
  10391. juce_wchar& String::operator[] (const int index)
  10392. {
  10393. jassert (((unsigned int) index) <= (unsigned int) length());
  10394. text = StringHolder::makeUnique (text);
  10395. return text [index];
  10396. }
  10397. juce_wchar String::getLastCharacter() const throw()
  10398. {
  10399. return isEmpty() ? juce_wchar() : text [length() - 1];
  10400. }
  10401. const String String::substring (int start, int end) const
  10402. {
  10403. if (start < 0)
  10404. start = 0;
  10405. else if (end <= start)
  10406. return empty;
  10407. int len = 0;
  10408. while (len <= end && text [len] != 0)
  10409. ++len;
  10410. if (end >= len)
  10411. {
  10412. if (start == 0)
  10413. return *this;
  10414. end = len;
  10415. }
  10416. return String (text + start, end - start);
  10417. }
  10418. const String String::substring (const int start) const
  10419. {
  10420. if (start <= 0)
  10421. return *this;
  10422. const int len = length();
  10423. if (start >= len)
  10424. return empty;
  10425. return String (text + start, len - start);
  10426. }
  10427. const String String::dropLastCharacters (const int numberToDrop) const
  10428. {
  10429. return String (text, jmax (0, length() - numberToDrop));
  10430. }
  10431. const String String::getLastCharacters (const int numCharacters) const
  10432. {
  10433. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10434. }
  10435. const String String::fromFirstOccurrenceOf (const String& sub,
  10436. const bool includeSubString,
  10437. const bool ignoreCase) const
  10438. {
  10439. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10440. : indexOf (sub);
  10441. if (i < 0)
  10442. return empty;
  10443. return substring (includeSubString ? i : i + sub.length());
  10444. }
  10445. const String String::fromLastOccurrenceOf (const String& sub,
  10446. const bool includeSubString,
  10447. const bool ignoreCase) const
  10448. {
  10449. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10450. : lastIndexOf (sub);
  10451. if (i < 0)
  10452. return *this;
  10453. return substring (includeSubString ? i : i + sub.length());
  10454. }
  10455. const String String::upToFirstOccurrenceOf (const String& sub,
  10456. const bool includeSubString,
  10457. const bool ignoreCase) const
  10458. {
  10459. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10460. : indexOf (sub);
  10461. if (i < 0)
  10462. return *this;
  10463. return substring (0, includeSubString ? i + sub.length() : i);
  10464. }
  10465. const String String::upToLastOccurrenceOf (const String& sub,
  10466. const bool includeSubString,
  10467. const bool ignoreCase) const
  10468. {
  10469. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10470. : lastIndexOf (sub);
  10471. if (i < 0)
  10472. return *this;
  10473. return substring (0, includeSubString ? i + sub.length() : i);
  10474. }
  10475. bool String::isQuotedString() const
  10476. {
  10477. const String trimmed (trimStart());
  10478. return trimmed[0] == '"'
  10479. || trimmed[0] == '\'';
  10480. }
  10481. const String String::unquoted() const
  10482. {
  10483. String s (*this);
  10484. if (s.text[0] == '"' || s.text[0] == '\'')
  10485. s = s.substring (1);
  10486. const int lastCharIndex = s.length() - 1;
  10487. if (lastCharIndex >= 0
  10488. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10489. s [lastCharIndex] = 0;
  10490. return s;
  10491. }
  10492. const String String::quoted (const juce_wchar quoteCharacter) const
  10493. {
  10494. if (isEmpty())
  10495. return charToString (quoteCharacter) + quoteCharacter;
  10496. String t (*this);
  10497. if (! t.startsWithChar (quoteCharacter))
  10498. t = charToString (quoteCharacter) + t;
  10499. if (! t.endsWithChar (quoteCharacter))
  10500. t += quoteCharacter;
  10501. return t;
  10502. }
  10503. const String String::trim() const
  10504. {
  10505. if (isEmpty())
  10506. return empty;
  10507. int start = 0;
  10508. while (CharacterFunctions::isWhitespace (text [start]))
  10509. ++start;
  10510. const int len = length();
  10511. int end = len - 1;
  10512. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10513. --end;
  10514. ++end;
  10515. if (end <= start)
  10516. return empty;
  10517. else if (start > 0 || end < len)
  10518. return String (text + start, end - start);
  10519. return *this;
  10520. }
  10521. const String String::trimStart() const
  10522. {
  10523. if (isEmpty())
  10524. return empty;
  10525. const juce_wchar* t = text;
  10526. while (CharacterFunctions::isWhitespace (*t))
  10527. ++t;
  10528. if (t == text)
  10529. return *this;
  10530. return String (t);
  10531. }
  10532. const String String::trimEnd() const
  10533. {
  10534. if (isEmpty())
  10535. return empty;
  10536. const juce_wchar* endT = text + (length() - 1);
  10537. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10538. --endT;
  10539. return String (text, (int) (++endT - text));
  10540. }
  10541. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10542. {
  10543. const juce_wchar* t = text;
  10544. while (charactersToTrim.containsChar (*t))
  10545. ++t;
  10546. return t == text ? *this : String (t);
  10547. }
  10548. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10549. {
  10550. if (isEmpty())
  10551. return empty;
  10552. const int len = length();
  10553. const juce_wchar* endT = text + (len - 1);
  10554. int numToRemove = 0;
  10555. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10556. {
  10557. ++numToRemove;
  10558. --endT;
  10559. }
  10560. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10561. }
  10562. const String String::retainCharacters (const String& charactersToRetain) const
  10563. {
  10564. if (isEmpty())
  10565. return empty;
  10566. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10567. juce_wchar* dst = result.text;
  10568. const juce_wchar* src = text;
  10569. while (*src != 0)
  10570. {
  10571. if (charactersToRetain.containsChar (*src))
  10572. *dst++ = *src;
  10573. ++src;
  10574. }
  10575. *dst = 0;
  10576. return result;
  10577. }
  10578. const String String::removeCharacters (const String& charactersToRemove) const
  10579. {
  10580. if (isEmpty())
  10581. return empty;
  10582. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10583. juce_wchar* dst = result.text;
  10584. const juce_wchar* src = text;
  10585. while (*src != 0)
  10586. {
  10587. if (! charactersToRemove.containsChar (*src))
  10588. *dst++ = *src;
  10589. ++src;
  10590. }
  10591. *dst = 0;
  10592. return result;
  10593. }
  10594. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10595. {
  10596. int i = 0;
  10597. for (;;)
  10598. {
  10599. if (! permittedCharacters.containsChar (text[i]))
  10600. break;
  10601. ++i;
  10602. }
  10603. return substring (0, i);
  10604. }
  10605. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10606. {
  10607. const juce_wchar* const t = text;
  10608. int i = 0;
  10609. while (t[i] != 0)
  10610. {
  10611. if (charactersToStopAt.containsChar (t[i]))
  10612. return String (text, i);
  10613. ++i;
  10614. }
  10615. return empty;
  10616. }
  10617. bool String::containsOnly (const String& chars) const throw()
  10618. {
  10619. const juce_wchar* t = text;
  10620. while (*t != 0)
  10621. if (! chars.containsChar (*t++))
  10622. return false;
  10623. return true;
  10624. }
  10625. bool String::containsAnyOf (const String& chars) const throw()
  10626. {
  10627. const juce_wchar* t = text;
  10628. while (*t != 0)
  10629. if (chars.containsChar (*t++))
  10630. return true;
  10631. return false;
  10632. }
  10633. bool String::containsNonWhitespaceChars() const throw()
  10634. {
  10635. const juce_wchar* t = text;
  10636. while (*t != 0)
  10637. if (! CharacterFunctions::isWhitespace (*t++))
  10638. return true;
  10639. return false;
  10640. }
  10641. const String String::formatted (const juce_wchar* const pf, ... )
  10642. {
  10643. jassert (pf != 0);
  10644. va_list args;
  10645. va_start (args, pf);
  10646. size_t bufferSize = 256;
  10647. String result (bufferSize, (int) 0);
  10648. result.text[0] = 0;
  10649. for (;;)
  10650. {
  10651. #if JUCE_LINUX && JUCE_64BIT
  10652. va_list tempArgs;
  10653. va_copy (tempArgs, args);
  10654. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10655. va_end (tempArgs);
  10656. #elif JUCE_WINDOWS
  10657. #if JUCE_MSVC
  10658. #pragma warning (push)
  10659. #pragma warning (disable: 4996)
  10660. #endif
  10661. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10662. #if JUCE_MSVC
  10663. #pragma warning (pop)
  10664. #endif
  10665. #else
  10666. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10667. #endif
  10668. if (num > 0)
  10669. return result;
  10670. bufferSize += 256;
  10671. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10672. break; // returns -1 because of an error rather than because it needs more space.
  10673. result.preallocateStorage (bufferSize);
  10674. }
  10675. return empty;
  10676. }
  10677. int String::getIntValue() const throw()
  10678. {
  10679. return CharacterFunctions::getIntValue (text);
  10680. }
  10681. int String::getTrailingIntValue() const throw()
  10682. {
  10683. int n = 0;
  10684. int mult = 1;
  10685. const juce_wchar* t = text + length();
  10686. while (--t >= text)
  10687. {
  10688. const juce_wchar c = *t;
  10689. if (! CharacterFunctions::isDigit (c))
  10690. {
  10691. if (c == '-')
  10692. n = -n;
  10693. break;
  10694. }
  10695. n += mult * (c - '0');
  10696. mult *= 10;
  10697. }
  10698. return n;
  10699. }
  10700. int64 String::getLargeIntValue() const throw()
  10701. {
  10702. return CharacterFunctions::getInt64Value (text);
  10703. }
  10704. float String::getFloatValue() const throw()
  10705. {
  10706. return (float) CharacterFunctions::getDoubleValue (text);
  10707. }
  10708. double String::getDoubleValue() const throw()
  10709. {
  10710. return CharacterFunctions::getDoubleValue (text);
  10711. }
  10712. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10713. const String String::toHexString (const int number)
  10714. {
  10715. juce_wchar buffer[32];
  10716. juce_wchar* const end = buffer + 32;
  10717. juce_wchar* t = end;
  10718. *--t = 0;
  10719. unsigned int v = (unsigned int) number;
  10720. do
  10721. {
  10722. *--t = hexDigits [v & 15];
  10723. v >>= 4;
  10724. } while (v != 0);
  10725. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10726. }
  10727. const String String::toHexString (const int64 number)
  10728. {
  10729. juce_wchar buffer[32];
  10730. juce_wchar* const end = buffer + 32;
  10731. juce_wchar* t = end;
  10732. *--t = 0;
  10733. uint64 v = (uint64) number;
  10734. do
  10735. {
  10736. *--t = hexDigits [(int) (v & 15)];
  10737. v >>= 4;
  10738. } while (v != 0);
  10739. return String (t, (int) (((char*) end) - (char*) t));
  10740. }
  10741. const String String::toHexString (const short number)
  10742. {
  10743. return toHexString ((int) (unsigned short) number);
  10744. }
  10745. const String String::toHexString (const unsigned char* data,
  10746. const int size,
  10747. const int groupSize)
  10748. {
  10749. if (size <= 0)
  10750. return empty;
  10751. int numChars = (size * 2) + 2;
  10752. if (groupSize > 0)
  10753. numChars += size / groupSize;
  10754. String s ((size_t) numChars, (int) 0);
  10755. juce_wchar* d = s.text;
  10756. for (int i = 0; i < size; ++i)
  10757. {
  10758. *d++ = hexDigits [(*data) >> 4];
  10759. *d++ = hexDigits [(*data) & 0xf];
  10760. ++data;
  10761. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10762. *d++ = ' ';
  10763. }
  10764. *d = 0;
  10765. return s;
  10766. }
  10767. int String::getHexValue32() const throw()
  10768. {
  10769. int result = 0;
  10770. const juce_wchar* c = text;
  10771. for (;;)
  10772. {
  10773. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10774. if (hexValue >= 0)
  10775. result = (result << 4) | hexValue;
  10776. else if (*c == 0)
  10777. break;
  10778. ++c;
  10779. }
  10780. return result;
  10781. }
  10782. int64 String::getHexValue64() const throw()
  10783. {
  10784. int64 result = 0;
  10785. const juce_wchar* c = text;
  10786. for (;;)
  10787. {
  10788. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10789. if (hexValue >= 0)
  10790. result = (result << 4) | hexValue;
  10791. else if (*c == 0)
  10792. break;
  10793. ++c;
  10794. }
  10795. return result;
  10796. }
  10797. const String String::createStringFromData (const void* const data_, const int size)
  10798. {
  10799. const char* const data = static_cast <const char*> (data_);
  10800. if (size <= 0 || data == 0)
  10801. {
  10802. return empty;
  10803. }
  10804. else if (size < 2)
  10805. {
  10806. return charToString (data[0]);
  10807. }
  10808. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10809. || (data[0] == (char)-1 && data[1] == (char)-2))
  10810. {
  10811. // assume it's 16-bit unicode
  10812. const bool bigEndian = (data[0] == (char)-2);
  10813. const int numChars = size / 2 - 1;
  10814. String result;
  10815. result.preallocateStorage (numChars + 2);
  10816. const uint16* const src = (const uint16*) (data + 2);
  10817. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10818. if (bigEndian)
  10819. {
  10820. for (int i = 0; i < numChars; ++i)
  10821. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10822. }
  10823. else
  10824. {
  10825. for (int i = 0; i < numChars; ++i)
  10826. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10827. }
  10828. dst [numChars] = 0;
  10829. return result;
  10830. }
  10831. else
  10832. {
  10833. return String::fromUTF8 (data, size);
  10834. }
  10835. }
  10836. const char* String::toUTF8() const
  10837. {
  10838. if (isEmpty())
  10839. {
  10840. return reinterpret_cast <const char*> (text);
  10841. }
  10842. else
  10843. {
  10844. const int currentLen = length() + 1;
  10845. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10846. String* const mutableThis = const_cast <String*> (this);
  10847. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10848. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10849. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10850. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10851. #endif
  10852. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10853. return otherCopy;
  10854. }
  10855. }
  10856. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10857. {
  10858. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10859. int num = 0, index = 0;
  10860. for (;;)
  10861. {
  10862. const uint32 c = (uint32) text [index++];
  10863. if (c >= 0x80)
  10864. {
  10865. int numExtraBytes = 1;
  10866. if (c >= 0x800)
  10867. {
  10868. ++numExtraBytes;
  10869. if (c >= 0x10000)
  10870. {
  10871. ++numExtraBytes;
  10872. if (c >= 0x200000)
  10873. {
  10874. ++numExtraBytes;
  10875. if (c >= 0x4000000)
  10876. ++numExtraBytes;
  10877. }
  10878. }
  10879. }
  10880. if (buffer != 0)
  10881. {
  10882. if (num + numExtraBytes >= maxBufferSizeBytes)
  10883. {
  10884. buffer [num++] = 0;
  10885. break;
  10886. }
  10887. else
  10888. {
  10889. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10890. while (--numExtraBytes >= 0)
  10891. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10892. }
  10893. }
  10894. else
  10895. {
  10896. num += numExtraBytes + 1;
  10897. }
  10898. }
  10899. else
  10900. {
  10901. if (buffer != 0)
  10902. {
  10903. if (num + 1 >= maxBufferSizeBytes)
  10904. {
  10905. buffer [num++] = 0;
  10906. break;
  10907. }
  10908. buffer [num] = (uint8) c;
  10909. }
  10910. ++num;
  10911. }
  10912. if (c == 0)
  10913. break;
  10914. }
  10915. return num;
  10916. }
  10917. int String::getNumBytesAsUTF8() const throw()
  10918. {
  10919. int num = 0;
  10920. const juce_wchar* t = text;
  10921. for (;;)
  10922. {
  10923. const uint32 c = (uint32) *t;
  10924. if (c >= 0x80)
  10925. {
  10926. ++num;
  10927. if (c >= 0x800)
  10928. {
  10929. ++num;
  10930. if (c >= 0x10000)
  10931. {
  10932. ++num;
  10933. if (c >= 0x200000)
  10934. {
  10935. ++num;
  10936. if (c >= 0x4000000)
  10937. ++num;
  10938. }
  10939. }
  10940. }
  10941. }
  10942. else if (c == 0)
  10943. break;
  10944. ++num;
  10945. ++t;
  10946. }
  10947. return num;
  10948. }
  10949. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10950. {
  10951. if (buffer == 0)
  10952. return empty;
  10953. if (bufferSizeBytes < 0)
  10954. bufferSizeBytes = std::numeric_limits<int>::max();
  10955. size_t numBytes;
  10956. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10957. if (buffer [numBytes] == 0)
  10958. break;
  10959. String result ((size_t) numBytes + 1, (int) 0);
  10960. juce_wchar* dest = result.text;
  10961. size_t i = 0;
  10962. while (i < numBytes)
  10963. {
  10964. const char c = buffer [i++];
  10965. if (c < 0)
  10966. {
  10967. unsigned int mask = 0x7f;
  10968. int bit = 0x40;
  10969. int numExtraValues = 0;
  10970. while (bit != 0 && (c & bit) != 0)
  10971. {
  10972. bit >>= 1;
  10973. mask >>= 1;
  10974. ++numExtraValues;
  10975. }
  10976. int n = (mask & (unsigned char) c);
  10977. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10978. {
  10979. const char nextByte = buffer[i];
  10980. if ((nextByte & 0xc0) != 0x80)
  10981. break;
  10982. n <<= 6;
  10983. n |= (nextByte & 0x3f);
  10984. ++i;
  10985. }
  10986. *dest++ = (juce_wchar) n;
  10987. }
  10988. else
  10989. {
  10990. *dest++ = (juce_wchar) c;
  10991. }
  10992. }
  10993. *dest = 0;
  10994. return result;
  10995. }
  10996. const char* String::toCString() const
  10997. {
  10998. if (isEmpty())
  10999. {
  11000. return reinterpret_cast <const char*> (text);
  11001. }
  11002. else
  11003. {
  11004. const int len = length();
  11005. String* const mutableThis = const_cast <String*> (this);
  11006. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11007. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11008. CharacterFunctions::copy (otherCopy, text, len);
  11009. otherCopy [len] = 0;
  11010. return otherCopy;
  11011. }
  11012. }
  11013. #if JUCE_MSVC
  11014. #pragma warning (push)
  11015. #pragma warning (disable: 4514 4996)
  11016. #endif
  11017. int String::getNumBytesAsCString() const throw()
  11018. {
  11019. return (int) wcstombs (0, text, 0);
  11020. }
  11021. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11022. {
  11023. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11024. if (destBuffer != 0 && numBytes >= 0)
  11025. destBuffer [numBytes] = 0;
  11026. return numBytes;
  11027. }
  11028. #if JUCE_MSVC
  11029. #pragma warning (pop)
  11030. #endif
  11031. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11032. {
  11033. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11034. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11035. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11036. }
  11037. String::Concatenator::Concatenator (String& stringToAppendTo)
  11038. : result (stringToAppendTo),
  11039. nextIndex (stringToAppendTo.length())
  11040. {
  11041. }
  11042. String::Concatenator::~Concatenator()
  11043. {
  11044. }
  11045. void String::Concatenator::append (const String& s)
  11046. {
  11047. const int len = s.length();
  11048. if (len > 0)
  11049. {
  11050. result.preallocateStorage (nextIndex + len);
  11051. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11052. nextIndex += len;
  11053. }
  11054. }
  11055. #if JUCE_UNIT_TESTS
  11056. class StringTests : public UnitTest
  11057. {
  11058. public:
  11059. StringTests() : UnitTest ("String class") {}
  11060. void runTest()
  11061. {
  11062. {
  11063. beginTest ("Basics");
  11064. expect (String().length() == 0);
  11065. expect (String() == String::empty);
  11066. String s1, s2 ("abcd");
  11067. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11068. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11069. expect (s2.length() == 4);
  11070. s1 = "abcd";
  11071. expect (s2 == s1 && s1 == s2);
  11072. expect (s1 == "abcd" && s1 == L"abcd");
  11073. expect (String ("abcd") == String (L"abcd"));
  11074. expect (String ("abcdefg", 4) == L"abcd");
  11075. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11076. expect (String::charToString ('x') == "x");
  11077. expect (String::charToString (0) == String::empty);
  11078. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11079. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11080. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11081. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11082. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11083. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11084. expect (s1.indexOf (String::empty) == 0);
  11085. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11086. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11087. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11088. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11089. }
  11090. {
  11091. beginTest ("Operations");
  11092. String s ("012345678");
  11093. expect (s.hashCode() != 0);
  11094. expect (s.hashCode64() != 0);
  11095. expect (s.hashCode() != (s + s).hashCode());
  11096. expect (s.hashCode64() != (s + s).hashCode64());
  11097. expect (s.compare (String ("012345678")) == 0);
  11098. expect (s.compare (String ("012345679")) < 0);
  11099. expect (s.compare (String ("012345676")) > 0);
  11100. expect (s.substring (2, 3) == String::charToString (s[2]));
  11101. expect (s.substring (0, 1) == String::charToString (s[0]));
  11102. expect (s.getLastCharacter() == s [s.length() - 1]);
  11103. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11104. expect (s.substring (0, 3) == L"012");
  11105. expect (s.substring (0, 100) == s);
  11106. expect (s.substring (-1, 100) == s);
  11107. expect (s.substring (3) == "345678");
  11108. expect (s.indexOf (L"45") == 4);
  11109. expect (String ("444445").indexOf ("45") == 4);
  11110. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11111. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11112. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11113. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11114. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11115. expect (s.indexOfChar (L'4') == 4);
  11116. expect (s + s == "012345678012345678");
  11117. expect (s.startsWith (s));
  11118. expect (s.startsWith (s.substring (0, 4)));
  11119. expect (s.startsWith (s.dropLastCharacters (4)));
  11120. expect (s.endsWith (s.substring (5)));
  11121. expect (s.endsWith (s));
  11122. expect (s.contains (s.substring (3, 6)));
  11123. expect (s.contains (s.substring (3)));
  11124. expect (s.startsWithChar (s[0]));
  11125. expect (s.endsWithChar (s.getLastCharacter()));
  11126. expect (s [s.length()] == 0);
  11127. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11128. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11129. String s2 ("123");
  11130. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11131. s2 += "xyz";
  11132. expect (s2 == "1234567890xyz");
  11133. beginTest ("Numeric conversions");
  11134. expect (String::empty.getIntValue() == 0);
  11135. expect (String::empty.getDoubleValue() == 0.0);
  11136. expect (String::empty.getFloatValue() == 0.0f);
  11137. expect (s.getIntValue() == 12345678);
  11138. expect (s.getLargeIntValue() == (int64) 12345678);
  11139. expect (s.getDoubleValue() == 12345678.0);
  11140. expect (s.getFloatValue() == 12345678.0f);
  11141. expect (String (-1234).getIntValue() == -1234);
  11142. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11143. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11144. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11145. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11146. expect (s.getHexValue32() == 0x12345678);
  11147. expect (s.getHexValue64() == (int64) 0x12345678);
  11148. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11149. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11150. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11151. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11152. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11153. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11154. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11155. beginTest ("Subsections");
  11156. String s3;
  11157. s3 = "abcdeFGHIJ";
  11158. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11159. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11160. expect (s3.containsIgnoreCase (s3.substring (3)));
  11161. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11162. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11163. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11164. expect (s3.containsAnyOf (L"zzzFs"));
  11165. expect (s3.startsWith ("abcd"));
  11166. expect (s3.startsWithIgnoreCase (L"abCD"));
  11167. expect (s3.startsWith (String::empty));
  11168. expect (s3.startsWithChar ('a'));
  11169. expect (s3.endsWith (String ("HIJ")));
  11170. expect (s3.endsWithIgnoreCase (L"Hij"));
  11171. expect (s3.endsWith (String::empty));
  11172. expect (s3.endsWithChar (L'J'));
  11173. expect (s3.indexOf ("HIJ") == 7);
  11174. expect (s3.indexOf (L"HIJK") == -1);
  11175. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11176. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11177. String s4 (s3);
  11178. s4.append (String ("xyz123"), 3);
  11179. expect (s4 == s3 + "xyz");
  11180. expect (String (1234) < String (1235));
  11181. expect (String (1235) > String (1234));
  11182. expect (String (1234) >= String (1234));
  11183. expect (String (1234) <= String (1234));
  11184. expect (String (1235) >= String (1234));
  11185. expect (String (1234) <= String (1235));
  11186. String s5 ("word word2 word3");
  11187. expect (s5.containsWholeWord (String ("word2")));
  11188. expect (s5.indexOfWholeWord ("word2") == 5);
  11189. expect (s5.containsWholeWord (L"word"));
  11190. expect (s5.containsWholeWord ("word3"));
  11191. expect (s5.containsWholeWord (s5));
  11192. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11193. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11194. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11195. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11196. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11197. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11198. expect (s5.containsNonWhitespaceChars());
  11199. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11200. expect (s5.matchesWildcard (L"wor*", false));
  11201. expect (s5.matchesWildcard ("wOr*", true));
  11202. expect (s5.matchesWildcard (L"*word3", true));
  11203. expect (s5.matchesWildcard ("*word?", true));
  11204. expect (s5.matchesWildcard (L"Word*3", true));
  11205. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11206. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11207. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11208. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11209. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11210. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11211. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11212. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11213. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11214. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11215. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11216. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11217. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11218. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11219. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11220. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11221. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11222. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11223. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11224. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11225. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11226. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11227. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11228. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11229. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11230. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11231. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11232. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11233. expect (s5.replace ("Word", "", true) == " 2 3");
  11234. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11235. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11236. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11237. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11238. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11239. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11240. expect (s5.retainCharacters (String::empty).isEmpty());
  11241. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11242. expect (s5.removeCharacters (String::empty) == s5);
  11243. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11244. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11245. expect (! s5.isQuotedString());
  11246. expect (s5.quoted().isQuotedString());
  11247. expect (! s5.quoted().unquoted().isQuotedString());
  11248. expect (! String ("x'").isQuotedString());
  11249. expect (String ("'x").isQuotedString());
  11250. String s6 (" \t xyz \t\r\n");
  11251. expect (s6.trim() == String ("xyz"));
  11252. expect (s6.trim().trim() == "xyz");
  11253. expect (s5.trim() == s5);
  11254. expect (s6.trimStart().trimEnd() == s6.trim());
  11255. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11256. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11257. expect (s6.trimStart() != s6.trimEnd());
  11258. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11259. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11260. }
  11261. {
  11262. beginTest ("UTF8");
  11263. String s ("word word2 word3");
  11264. {
  11265. char buffer [100];
  11266. memset (buffer, 0xff, sizeof (buffer));
  11267. s.copyToUTF8 (buffer, 100);
  11268. expect (String::fromUTF8 (buffer, 100) == s);
  11269. juce_wchar bufferUnicode [100];
  11270. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11271. s.copyToUnicode (bufferUnicode, 100);
  11272. expect (String (bufferUnicode, 100) == s);
  11273. }
  11274. {
  11275. juce_wchar wideBuffer [50];
  11276. zerostruct (wideBuffer);
  11277. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11278. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11279. String wide (wideBuffer);
  11280. expect (wide == (const juce_wchar*) wideBuffer);
  11281. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11282. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11283. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11284. }
  11285. }
  11286. }
  11287. };
  11288. static StringTests stringUnitTests;
  11289. #endif
  11290. END_JUCE_NAMESPACE
  11291. /*** End of inlined file: juce_String.cpp ***/
  11292. /*** Start of inlined file: juce_StringArray.cpp ***/
  11293. BEGIN_JUCE_NAMESPACE
  11294. StringArray::StringArray() throw()
  11295. {
  11296. }
  11297. StringArray::StringArray (const StringArray& other)
  11298. : strings (other.strings)
  11299. {
  11300. }
  11301. StringArray::StringArray (const String& firstValue)
  11302. {
  11303. strings.add (firstValue);
  11304. }
  11305. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11306. const int numberOfStrings)
  11307. {
  11308. for (int i = 0; i < numberOfStrings; ++i)
  11309. strings.add (initialStrings [i]);
  11310. }
  11311. StringArray::StringArray (const char* const* const initialStrings,
  11312. const int numberOfStrings)
  11313. {
  11314. for (int i = 0; i < numberOfStrings; ++i)
  11315. strings.add (initialStrings [i]);
  11316. }
  11317. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11318. {
  11319. int i = 0;
  11320. while (initialStrings[i] != 0)
  11321. strings.add (initialStrings [i++]);
  11322. }
  11323. StringArray::StringArray (const char* const* const initialStrings)
  11324. {
  11325. int i = 0;
  11326. while (initialStrings[i] != 0)
  11327. strings.add (initialStrings [i++]);
  11328. }
  11329. StringArray& StringArray::operator= (const StringArray& other)
  11330. {
  11331. strings = other.strings;
  11332. return *this;
  11333. }
  11334. StringArray::~StringArray()
  11335. {
  11336. }
  11337. bool StringArray::operator== (const StringArray& other) const throw()
  11338. {
  11339. if (other.size() != size())
  11340. return false;
  11341. for (int i = size(); --i >= 0;)
  11342. if (other.strings.getReference(i) != strings.getReference(i))
  11343. return false;
  11344. return true;
  11345. }
  11346. bool StringArray::operator!= (const StringArray& other) const throw()
  11347. {
  11348. return ! operator== (other);
  11349. }
  11350. void StringArray::clear()
  11351. {
  11352. strings.clear();
  11353. }
  11354. const String& StringArray::operator[] (const int index) const throw()
  11355. {
  11356. if (((unsigned int) index) < (unsigned int) strings.size())
  11357. return strings.getReference (index);
  11358. return String::empty;
  11359. }
  11360. String& StringArray::getReference (const int index) throw()
  11361. {
  11362. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11363. return strings.getReference (index);
  11364. }
  11365. void StringArray::add (const String& newString)
  11366. {
  11367. strings.add (newString);
  11368. }
  11369. void StringArray::insert (const int index, const String& newString)
  11370. {
  11371. strings.insert (index, newString);
  11372. }
  11373. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11374. {
  11375. if (! contains (newString, ignoreCase))
  11376. add (newString);
  11377. }
  11378. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11379. {
  11380. if (startIndex < 0)
  11381. {
  11382. jassertfalse;
  11383. startIndex = 0;
  11384. }
  11385. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11386. numElementsToAdd = otherArray.size() - startIndex;
  11387. while (--numElementsToAdd >= 0)
  11388. strings.add (otherArray.strings.getReference (startIndex++));
  11389. }
  11390. void StringArray::set (const int index, const String& newString)
  11391. {
  11392. strings.set (index, newString);
  11393. }
  11394. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11395. {
  11396. if (ignoreCase)
  11397. {
  11398. for (int i = size(); --i >= 0;)
  11399. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11400. return true;
  11401. }
  11402. else
  11403. {
  11404. for (int i = size(); --i >= 0;)
  11405. if (stringToLookFor == strings.getReference(i))
  11406. return true;
  11407. }
  11408. return false;
  11409. }
  11410. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11411. {
  11412. if (i < 0)
  11413. i = 0;
  11414. const int numElements = size();
  11415. if (ignoreCase)
  11416. {
  11417. while (i < numElements)
  11418. {
  11419. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11420. return i;
  11421. ++i;
  11422. }
  11423. }
  11424. else
  11425. {
  11426. while (i < numElements)
  11427. {
  11428. if (stringToLookFor == strings.getReference (i))
  11429. return i;
  11430. ++i;
  11431. }
  11432. }
  11433. return -1;
  11434. }
  11435. void StringArray::remove (const int index)
  11436. {
  11437. strings.remove (index);
  11438. }
  11439. void StringArray::removeString (const String& stringToRemove,
  11440. const bool ignoreCase)
  11441. {
  11442. if (ignoreCase)
  11443. {
  11444. for (int i = size(); --i >= 0;)
  11445. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11446. strings.remove (i);
  11447. }
  11448. else
  11449. {
  11450. for (int i = size(); --i >= 0;)
  11451. if (stringToRemove == strings.getReference (i))
  11452. strings.remove (i);
  11453. }
  11454. }
  11455. void StringArray::removeRange (int startIndex, int numberToRemove)
  11456. {
  11457. strings.removeRange (startIndex, numberToRemove);
  11458. }
  11459. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11460. {
  11461. if (removeWhitespaceStrings)
  11462. {
  11463. for (int i = size(); --i >= 0;)
  11464. if (! strings.getReference(i).containsNonWhitespaceChars())
  11465. strings.remove (i);
  11466. }
  11467. else
  11468. {
  11469. for (int i = size(); --i >= 0;)
  11470. if (strings.getReference(i).isEmpty())
  11471. strings.remove (i);
  11472. }
  11473. }
  11474. void StringArray::trim()
  11475. {
  11476. for (int i = size(); --i >= 0;)
  11477. {
  11478. String& s = strings.getReference(i);
  11479. s = s.trim();
  11480. }
  11481. }
  11482. class InternalStringArrayComparator_CaseSensitive
  11483. {
  11484. public:
  11485. static int compareElements (String& first, String& second) { return first.compare (second); }
  11486. };
  11487. class InternalStringArrayComparator_CaseInsensitive
  11488. {
  11489. public:
  11490. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11491. };
  11492. void StringArray::sort (const bool ignoreCase)
  11493. {
  11494. if (ignoreCase)
  11495. {
  11496. InternalStringArrayComparator_CaseInsensitive comp;
  11497. strings.sort (comp);
  11498. }
  11499. else
  11500. {
  11501. InternalStringArrayComparator_CaseSensitive comp;
  11502. strings.sort (comp);
  11503. }
  11504. }
  11505. void StringArray::move (const int currentIndex, int newIndex) throw()
  11506. {
  11507. strings.move (currentIndex, newIndex);
  11508. }
  11509. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11510. {
  11511. const int last = (numberToJoin < 0) ? size()
  11512. : jmin (size(), start + numberToJoin);
  11513. if (start < 0)
  11514. start = 0;
  11515. if (start >= last)
  11516. return String::empty;
  11517. if (start == last - 1)
  11518. return strings.getReference (start);
  11519. const int separatorLen = separator.length();
  11520. int charsNeeded = separatorLen * (last - start - 1);
  11521. for (int i = start; i < last; ++i)
  11522. charsNeeded += strings.getReference(i).length();
  11523. String result;
  11524. result.preallocateStorage (charsNeeded);
  11525. juce_wchar* dest = result;
  11526. while (start < last)
  11527. {
  11528. const String& s = strings.getReference (start);
  11529. const int len = s.length();
  11530. if (len > 0)
  11531. {
  11532. s.copyToUnicode (dest, len);
  11533. dest += len;
  11534. }
  11535. if (++start < last && separatorLen > 0)
  11536. {
  11537. separator.copyToUnicode (dest, separatorLen);
  11538. dest += separatorLen;
  11539. }
  11540. }
  11541. *dest = 0;
  11542. return result;
  11543. }
  11544. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11545. {
  11546. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11547. }
  11548. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11549. {
  11550. int num = 0;
  11551. if (text.isNotEmpty())
  11552. {
  11553. bool insideQuotes = false;
  11554. juce_wchar currentQuoteChar = 0;
  11555. int i = 0;
  11556. int tokenStart = 0;
  11557. for (;;)
  11558. {
  11559. const juce_wchar c = text[i];
  11560. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11561. if (! isBreak)
  11562. {
  11563. if (quoteCharacters.containsChar (c))
  11564. {
  11565. if (insideQuotes)
  11566. {
  11567. // only break out of quotes-mode if we find a matching quote to the
  11568. // one that we opened with..
  11569. if (currentQuoteChar == c)
  11570. insideQuotes = false;
  11571. }
  11572. else
  11573. {
  11574. insideQuotes = true;
  11575. currentQuoteChar = c;
  11576. }
  11577. }
  11578. }
  11579. else
  11580. {
  11581. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11582. ++num;
  11583. tokenStart = i + 1;
  11584. }
  11585. if (c == 0)
  11586. break;
  11587. ++i;
  11588. }
  11589. }
  11590. return num;
  11591. }
  11592. int StringArray::addLines (const String& sourceText)
  11593. {
  11594. int numLines = 0;
  11595. const juce_wchar* text = sourceText;
  11596. while (*text != 0)
  11597. {
  11598. const juce_wchar* const startOfLine = text;
  11599. while (*text != 0)
  11600. {
  11601. if (*text == '\r')
  11602. {
  11603. ++text;
  11604. if (*text == '\n')
  11605. ++text;
  11606. break;
  11607. }
  11608. if (*text == '\n')
  11609. {
  11610. ++text;
  11611. break;
  11612. }
  11613. ++text;
  11614. }
  11615. const juce_wchar* endOfLine = text;
  11616. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11617. --endOfLine;
  11618. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11619. --endOfLine;
  11620. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11621. ++numLines;
  11622. }
  11623. return numLines;
  11624. }
  11625. void StringArray::removeDuplicates (const bool ignoreCase)
  11626. {
  11627. for (int i = 0; i < size() - 1; ++i)
  11628. {
  11629. const String s (strings.getReference(i));
  11630. int nextIndex = i + 1;
  11631. for (;;)
  11632. {
  11633. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11634. if (nextIndex < 0)
  11635. break;
  11636. strings.remove (nextIndex);
  11637. }
  11638. }
  11639. }
  11640. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11641. const bool appendNumberToFirstInstance,
  11642. const juce_wchar* preNumberString,
  11643. const juce_wchar* postNumberString)
  11644. {
  11645. if (preNumberString == 0)
  11646. preNumberString = L" (";
  11647. if (postNumberString == 0)
  11648. postNumberString = L")";
  11649. for (int i = 0; i < size() - 1; ++i)
  11650. {
  11651. String& s = strings.getReference(i);
  11652. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11653. if (nextIndex >= 0)
  11654. {
  11655. const String original (s);
  11656. int number = 0;
  11657. if (appendNumberToFirstInstance)
  11658. s = original + preNumberString + String (++number) + postNumberString;
  11659. else
  11660. ++number;
  11661. while (nextIndex >= 0)
  11662. {
  11663. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11664. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11665. }
  11666. }
  11667. }
  11668. }
  11669. void StringArray::minimiseStorageOverheads()
  11670. {
  11671. strings.minimiseStorageOverheads();
  11672. }
  11673. END_JUCE_NAMESPACE
  11674. /*** End of inlined file: juce_StringArray.cpp ***/
  11675. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11676. BEGIN_JUCE_NAMESPACE
  11677. StringPairArray::StringPairArray (const bool ignoreCase_)
  11678. : ignoreCase (ignoreCase_)
  11679. {
  11680. }
  11681. StringPairArray::StringPairArray (const StringPairArray& other)
  11682. : keys (other.keys),
  11683. values (other.values),
  11684. ignoreCase (other.ignoreCase)
  11685. {
  11686. }
  11687. StringPairArray::~StringPairArray()
  11688. {
  11689. }
  11690. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11691. {
  11692. keys = other.keys;
  11693. values = other.values;
  11694. return *this;
  11695. }
  11696. bool StringPairArray::operator== (const StringPairArray& other) const
  11697. {
  11698. for (int i = keys.size(); --i >= 0;)
  11699. if (other [keys[i]] != values[i])
  11700. return false;
  11701. return true;
  11702. }
  11703. bool StringPairArray::operator!= (const StringPairArray& other) const
  11704. {
  11705. return ! operator== (other);
  11706. }
  11707. const String& StringPairArray::operator[] (const String& key) const
  11708. {
  11709. return values [keys.indexOf (key, ignoreCase)];
  11710. }
  11711. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11712. {
  11713. const int i = keys.indexOf (key, ignoreCase);
  11714. if (i >= 0)
  11715. return values[i];
  11716. return defaultReturnValue;
  11717. }
  11718. void StringPairArray::set (const String& key, const String& value)
  11719. {
  11720. const int i = keys.indexOf (key, ignoreCase);
  11721. if (i >= 0)
  11722. {
  11723. values.set (i, value);
  11724. }
  11725. else
  11726. {
  11727. keys.add (key);
  11728. values.add (value);
  11729. }
  11730. }
  11731. void StringPairArray::addArray (const StringPairArray& other)
  11732. {
  11733. for (int i = 0; i < other.size(); ++i)
  11734. set (other.keys[i], other.values[i]);
  11735. }
  11736. void StringPairArray::clear()
  11737. {
  11738. keys.clear();
  11739. values.clear();
  11740. }
  11741. void StringPairArray::remove (const String& key)
  11742. {
  11743. remove (keys.indexOf (key, ignoreCase));
  11744. }
  11745. void StringPairArray::remove (const int index)
  11746. {
  11747. keys.remove (index);
  11748. values.remove (index);
  11749. }
  11750. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11751. {
  11752. ignoreCase = shouldIgnoreCase;
  11753. }
  11754. const String StringPairArray::getDescription() const
  11755. {
  11756. String s;
  11757. for (int i = 0; i < keys.size(); ++i)
  11758. {
  11759. s << keys[i] << " = " << values[i];
  11760. if (i < keys.size())
  11761. s << ", ";
  11762. }
  11763. return s;
  11764. }
  11765. void StringPairArray::minimiseStorageOverheads()
  11766. {
  11767. keys.minimiseStorageOverheads();
  11768. values.minimiseStorageOverheads();
  11769. }
  11770. END_JUCE_NAMESPACE
  11771. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11772. /*** Start of inlined file: juce_StringPool.cpp ***/
  11773. BEGIN_JUCE_NAMESPACE
  11774. StringPool::StringPool() throw() {}
  11775. StringPool::~StringPool() {}
  11776. template <class StringType>
  11777. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11778. {
  11779. int start = 0;
  11780. int end = strings.size();
  11781. for (;;)
  11782. {
  11783. if (start >= end)
  11784. {
  11785. jassert (start <= end);
  11786. strings.insert (start, newString);
  11787. return strings.getReference (start);
  11788. }
  11789. else
  11790. {
  11791. const String& startString = strings.getReference (start);
  11792. if (startString == newString)
  11793. return startString;
  11794. const int halfway = (start + end) >> 1;
  11795. if (halfway == start)
  11796. {
  11797. if (startString.compare (newString) < 0)
  11798. ++start;
  11799. strings.insert (start, newString);
  11800. return strings.getReference (start);
  11801. }
  11802. const int comp = strings.getReference (halfway).compare (newString);
  11803. if (comp == 0)
  11804. return strings.getReference (halfway);
  11805. else if (comp < 0)
  11806. start = halfway;
  11807. else
  11808. end = halfway;
  11809. }
  11810. }
  11811. }
  11812. const juce_wchar* StringPool::getPooledString (const String& s)
  11813. {
  11814. if (s.isEmpty())
  11815. return String::empty;
  11816. return getPooledStringFromArray (strings, s);
  11817. }
  11818. const juce_wchar* StringPool::getPooledString (const char* const s)
  11819. {
  11820. if (s == 0 || *s == 0)
  11821. return String::empty;
  11822. return getPooledStringFromArray (strings, s);
  11823. }
  11824. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11825. {
  11826. if (s == 0 || *s == 0)
  11827. return String::empty;
  11828. return getPooledStringFromArray (strings, s);
  11829. }
  11830. int StringPool::size() const throw()
  11831. {
  11832. return strings.size();
  11833. }
  11834. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11835. {
  11836. return strings [index];
  11837. }
  11838. END_JUCE_NAMESPACE
  11839. /*** End of inlined file: juce_StringPool.cpp ***/
  11840. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11841. BEGIN_JUCE_NAMESPACE
  11842. XmlDocument::XmlDocument (const String& documentText)
  11843. : originalText (documentText),
  11844. ignoreEmptyTextElements (true)
  11845. {
  11846. }
  11847. XmlDocument::XmlDocument (const File& file)
  11848. : ignoreEmptyTextElements (true)
  11849. {
  11850. inputSource = new FileInputSource (file);
  11851. }
  11852. XmlDocument::~XmlDocument()
  11853. {
  11854. }
  11855. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11856. {
  11857. inputSource = newSource;
  11858. }
  11859. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11860. {
  11861. ignoreEmptyTextElements = shouldBeIgnored;
  11862. }
  11863. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11864. {
  11865. return CharacterFunctions::isLetterOrDigit (c)
  11866. || c == '_' || c == '-' || c == ':' || c == '.';
  11867. }
  11868. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11869. {
  11870. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11871. : isXmlIdentifierCharSlow (c);
  11872. }
  11873. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11874. {
  11875. String textToParse (originalText);
  11876. if (textToParse.isEmpty() && inputSource != 0)
  11877. {
  11878. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11879. if (in != 0)
  11880. {
  11881. MemoryOutputStream data;
  11882. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11883. textToParse = data.toString();
  11884. if (! onlyReadOuterDocumentElement)
  11885. originalText = textToParse;
  11886. }
  11887. }
  11888. input = textToParse;
  11889. lastError = String::empty;
  11890. errorOccurred = false;
  11891. outOfData = false;
  11892. needToLoadDTD = true;
  11893. for (int i = 0; i < 128; ++i)
  11894. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11895. if (textToParse.isEmpty())
  11896. {
  11897. lastError = "not enough input";
  11898. }
  11899. else
  11900. {
  11901. skipHeader();
  11902. if (input != 0)
  11903. {
  11904. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11905. if (! errorOccurred)
  11906. return result.release();
  11907. }
  11908. else
  11909. {
  11910. lastError = "incorrect xml header";
  11911. }
  11912. }
  11913. return 0;
  11914. }
  11915. const String& XmlDocument::getLastParseError() const throw()
  11916. {
  11917. return lastError;
  11918. }
  11919. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11920. {
  11921. lastError = desc;
  11922. errorOccurred = ! carryOn;
  11923. }
  11924. const String XmlDocument::getFileContents (const String& filename) const
  11925. {
  11926. if (inputSource != 0)
  11927. {
  11928. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11929. if (in != 0)
  11930. return in->readEntireStreamAsString();
  11931. }
  11932. return String::empty;
  11933. }
  11934. juce_wchar XmlDocument::readNextChar() throw()
  11935. {
  11936. if (*input != 0)
  11937. {
  11938. return *input++;
  11939. }
  11940. else
  11941. {
  11942. outOfData = true;
  11943. return 0;
  11944. }
  11945. }
  11946. int XmlDocument::findNextTokenLength() throw()
  11947. {
  11948. int len = 0;
  11949. juce_wchar c = *input;
  11950. while (isXmlIdentifierChar (c))
  11951. c = input [++len];
  11952. return len;
  11953. }
  11954. void XmlDocument::skipHeader()
  11955. {
  11956. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11957. if (found != 0)
  11958. {
  11959. input = found;
  11960. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11961. if (input == 0)
  11962. return;
  11963. input += 2;
  11964. }
  11965. skipNextWhiteSpace();
  11966. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11967. if (docType == 0)
  11968. return;
  11969. input = docType + 9;
  11970. int n = 1;
  11971. while (n > 0)
  11972. {
  11973. const juce_wchar c = readNextChar();
  11974. if (outOfData)
  11975. return;
  11976. if (c == '<')
  11977. ++n;
  11978. else if (c == '>')
  11979. --n;
  11980. }
  11981. docType += 9;
  11982. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11983. }
  11984. void XmlDocument::skipNextWhiteSpace()
  11985. {
  11986. for (;;)
  11987. {
  11988. juce_wchar c = *input;
  11989. while (CharacterFunctions::isWhitespace (c))
  11990. c = *++input;
  11991. if (c == 0)
  11992. {
  11993. outOfData = true;
  11994. break;
  11995. }
  11996. else if (c == '<')
  11997. {
  11998. if (input[1] == '!'
  11999. && input[2] == '-'
  12000. && input[3] == '-')
  12001. {
  12002. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12003. if (closeComment == 0)
  12004. {
  12005. outOfData = true;
  12006. break;
  12007. }
  12008. input = closeComment + 3;
  12009. continue;
  12010. }
  12011. else if (input[1] == '?')
  12012. {
  12013. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12014. if (closeBracket == 0)
  12015. {
  12016. outOfData = true;
  12017. break;
  12018. }
  12019. input = closeBracket + 2;
  12020. continue;
  12021. }
  12022. }
  12023. break;
  12024. }
  12025. }
  12026. void XmlDocument::readQuotedString (String& result)
  12027. {
  12028. const juce_wchar quote = readNextChar();
  12029. while (! outOfData)
  12030. {
  12031. const juce_wchar c = readNextChar();
  12032. if (c == quote)
  12033. break;
  12034. if (c == '&')
  12035. {
  12036. --input;
  12037. readEntity (result);
  12038. }
  12039. else
  12040. {
  12041. --input;
  12042. const juce_wchar* const start = input;
  12043. for (;;)
  12044. {
  12045. const juce_wchar character = *input;
  12046. if (character == quote)
  12047. {
  12048. result.append (start, (int) (input - start));
  12049. ++input;
  12050. return;
  12051. }
  12052. else if (character == '&')
  12053. {
  12054. result.append (start, (int) (input - start));
  12055. break;
  12056. }
  12057. else if (character == 0)
  12058. {
  12059. outOfData = true;
  12060. setLastError ("unmatched quotes", false);
  12061. break;
  12062. }
  12063. ++input;
  12064. }
  12065. }
  12066. }
  12067. }
  12068. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12069. {
  12070. XmlElement* node = 0;
  12071. skipNextWhiteSpace();
  12072. if (outOfData)
  12073. return 0;
  12074. input = CharacterFunctions::find (input, JUCE_T("<"));
  12075. if (input != 0)
  12076. {
  12077. ++input;
  12078. int tagLen = findNextTokenLength();
  12079. if (tagLen == 0)
  12080. {
  12081. // no tag name - but allow for a gap after the '<' before giving an error
  12082. skipNextWhiteSpace();
  12083. tagLen = findNextTokenLength();
  12084. if (tagLen == 0)
  12085. {
  12086. setLastError ("tag name missing", false);
  12087. return node;
  12088. }
  12089. }
  12090. node = new XmlElement (String (input, tagLen));
  12091. input += tagLen;
  12092. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12093. // look for attributes
  12094. for (;;)
  12095. {
  12096. skipNextWhiteSpace();
  12097. const juce_wchar c = *input;
  12098. // empty tag..
  12099. if (c == '/' && input[1] == '>')
  12100. {
  12101. input += 2;
  12102. break;
  12103. }
  12104. // parse the guts of the element..
  12105. if (c == '>')
  12106. {
  12107. ++input;
  12108. if (alsoParseSubElements)
  12109. readChildElements (node);
  12110. break;
  12111. }
  12112. // get an attribute..
  12113. if (isXmlIdentifierChar (c))
  12114. {
  12115. const int attNameLen = findNextTokenLength();
  12116. if (attNameLen > 0)
  12117. {
  12118. const juce_wchar* attNameStart = input;
  12119. input += attNameLen;
  12120. skipNextWhiteSpace();
  12121. if (readNextChar() == '=')
  12122. {
  12123. skipNextWhiteSpace();
  12124. const juce_wchar nextChar = *input;
  12125. if (nextChar == '"' || nextChar == '\'')
  12126. {
  12127. XmlElement::XmlAttributeNode* const newAtt
  12128. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12129. String::empty);
  12130. readQuotedString (newAtt->value);
  12131. if (lastAttribute == 0)
  12132. node->attributes = newAtt;
  12133. else
  12134. lastAttribute->next = newAtt;
  12135. lastAttribute = newAtt;
  12136. continue;
  12137. }
  12138. }
  12139. }
  12140. }
  12141. else
  12142. {
  12143. if (! outOfData)
  12144. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12145. }
  12146. break;
  12147. }
  12148. }
  12149. return node;
  12150. }
  12151. void XmlDocument::readChildElements (XmlElement* parent)
  12152. {
  12153. XmlElement* lastChildNode = 0;
  12154. for (;;)
  12155. {
  12156. const juce_wchar* const preWhitespaceInput = input;
  12157. skipNextWhiteSpace();
  12158. if (outOfData)
  12159. {
  12160. setLastError ("unmatched tags", false);
  12161. break;
  12162. }
  12163. if (*input == '<')
  12164. {
  12165. if (input[1] == '/')
  12166. {
  12167. // our close tag..
  12168. input = CharacterFunctions::find (input, JUCE_T(">"));
  12169. ++input;
  12170. break;
  12171. }
  12172. else if (input[1] == '!'
  12173. && input[2] == '['
  12174. && input[3] == 'C'
  12175. && input[4] == 'D'
  12176. && input[5] == 'A'
  12177. && input[6] == 'T'
  12178. && input[7] == 'A'
  12179. && input[8] == '[')
  12180. {
  12181. input += 9;
  12182. const juce_wchar* const inputStart = input;
  12183. int len = 0;
  12184. for (;;)
  12185. {
  12186. if (*input == 0)
  12187. {
  12188. setLastError ("unterminated CDATA section", false);
  12189. outOfData = true;
  12190. break;
  12191. }
  12192. else if (input[0] == ']'
  12193. && input[1] == ']'
  12194. && input[2] == '>')
  12195. {
  12196. input += 3;
  12197. break;
  12198. }
  12199. ++input;
  12200. ++len;
  12201. }
  12202. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12203. if (lastChildNode != 0)
  12204. lastChildNode->nextElement = e;
  12205. else
  12206. parent->addChildElement (e);
  12207. lastChildNode = e;
  12208. }
  12209. else
  12210. {
  12211. // this is some other element, so parse and add it..
  12212. XmlElement* const n = readNextElement (true);
  12213. if (n != 0)
  12214. {
  12215. if (lastChildNode == 0)
  12216. parent->addChildElement (n);
  12217. else
  12218. lastChildNode->nextElement = n;
  12219. lastChildNode = n;
  12220. }
  12221. else
  12222. {
  12223. return;
  12224. }
  12225. }
  12226. }
  12227. else // must be a character block
  12228. {
  12229. input = preWhitespaceInput; // roll back to include the leading whitespace
  12230. String textElementContent;
  12231. for (;;)
  12232. {
  12233. const juce_wchar c = *input;
  12234. if (c == '<')
  12235. break;
  12236. if (c == 0)
  12237. {
  12238. setLastError ("unmatched tags", false);
  12239. outOfData = true;
  12240. return;
  12241. }
  12242. if (c == '&')
  12243. {
  12244. String entity;
  12245. readEntity (entity);
  12246. if (entity.startsWithChar ('<') && entity [1] != 0)
  12247. {
  12248. const juce_wchar* const oldInput = input;
  12249. const bool oldOutOfData = outOfData;
  12250. input = entity;
  12251. outOfData = false;
  12252. for (;;)
  12253. {
  12254. XmlElement* const n = readNextElement (true);
  12255. if (n == 0)
  12256. break;
  12257. if (lastChildNode == 0)
  12258. parent->addChildElement (n);
  12259. else
  12260. lastChildNode->nextElement = n;
  12261. lastChildNode = n;
  12262. }
  12263. input = oldInput;
  12264. outOfData = oldOutOfData;
  12265. }
  12266. else
  12267. {
  12268. textElementContent += entity;
  12269. }
  12270. }
  12271. else
  12272. {
  12273. const juce_wchar* start = input;
  12274. int len = 0;
  12275. for (;;)
  12276. {
  12277. const juce_wchar nextChar = *input;
  12278. if (nextChar == '<' || nextChar == '&')
  12279. {
  12280. break;
  12281. }
  12282. else if (nextChar == 0)
  12283. {
  12284. setLastError ("unmatched tags", false);
  12285. outOfData = true;
  12286. return;
  12287. }
  12288. ++input;
  12289. ++len;
  12290. }
  12291. textElementContent.append (start, len);
  12292. }
  12293. }
  12294. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12295. {
  12296. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12297. if (lastChildNode != 0)
  12298. lastChildNode->nextElement = textElement;
  12299. else
  12300. parent->addChildElement (textElement);
  12301. lastChildNode = textElement;
  12302. }
  12303. }
  12304. }
  12305. }
  12306. void XmlDocument::readEntity (String& result)
  12307. {
  12308. // skip over the ampersand
  12309. ++input;
  12310. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12311. {
  12312. input += 4;
  12313. result += '&';
  12314. }
  12315. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12316. {
  12317. input += 5;
  12318. result += '"';
  12319. }
  12320. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12321. {
  12322. input += 5;
  12323. result += '\'';
  12324. }
  12325. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12326. {
  12327. input += 3;
  12328. result += '<';
  12329. }
  12330. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12331. {
  12332. input += 3;
  12333. result += '>';
  12334. }
  12335. else if (*input == '#')
  12336. {
  12337. int charCode = 0;
  12338. ++input;
  12339. if (*input == 'x' || *input == 'X')
  12340. {
  12341. ++input;
  12342. int numChars = 0;
  12343. while (input[0] != ';')
  12344. {
  12345. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12346. if (hexValue < 0 || ++numChars > 8)
  12347. {
  12348. setLastError ("illegal escape sequence", true);
  12349. break;
  12350. }
  12351. charCode = (charCode << 4) | hexValue;
  12352. ++input;
  12353. }
  12354. ++input;
  12355. }
  12356. else if (input[0] >= '0' && input[0] <= '9')
  12357. {
  12358. int numChars = 0;
  12359. while (input[0] != ';')
  12360. {
  12361. if (++numChars > 12)
  12362. {
  12363. setLastError ("illegal escape sequence", true);
  12364. break;
  12365. }
  12366. charCode = charCode * 10 + (input[0] - '0');
  12367. ++input;
  12368. }
  12369. ++input;
  12370. }
  12371. else
  12372. {
  12373. setLastError ("illegal escape sequence", true);
  12374. result += '&';
  12375. return;
  12376. }
  12377. result << (juce_wchar) charCode;
  12378. }
  12379. else
  12380. {
  12381. const juce_wchar* const entityNameStart = input;
  12382. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12383. if (closingSemiColon == 0)
  12384. {
  12385. outOfData = true;
  12386. result += '&';
  12387. }
  12388. else
  12389. {
  12390. input = closingSemiColon + 1;
  12391. result += expandExternalEntity (String (entityNameStart,
  12392. (int) (closingSemiColon - entityNameStart)));
  12393. }
  12394. }
  12395. }
  12396. const String XmlDocument::expandEntity (const String& ent)
  12397. {
  12398. if (ent.equalsIgnoreCase ("amp"))
  12399. return String::charToString ('&');
  12400. if (ent.equalsIgnoreCase ("quot"))
  12401. return String::charToString ('"');
  12402. if (ent.equalsIgnoreCase ("apos"))
  12403. return String::charToString ('\'');
  12404. if (ent.equalsIgnoreCase ("lt"))
  12405. return String::charToString ('<');
  12406. if (ent.equalsIgnoreCase ("gt"))
  12407. return String::charToString ('>');
  12408. if (ent[0] == '#')
  12409. {
  12410. if (ent[1] == 'x' || ent[1] == 'X')
  12411. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12412. if (ent[1] >= '0' && ent[1] <= '9')
  12413. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12414. setLastError ("illegal escape sequence", false);
  12415. return String::charToString ('&');
  12416. }
  12417. return expandExternalEntity (ent);
  12418. }
  12419. const String XmlDocument::expandExternalEntity (const String& entity)
  12420. {
  12421. if (needToLoadDTD)
  12422. {
  12423. if (dtdText.isNotEmpty())
  12424. {
  12425. dtdText = dtdText.trimCharactersAtEnd (">");
  12426. tokenisedDTD.addTokens (dtdText, true);
  12427. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12428. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12429. {
  12430. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12431. tokenisedDTD.clear();
  12432. tokenisedDTD.addTokens (getFileContents (fn), true);
  12433. }
  12434. else
  12435. {
  12436. tokenisedDTD.clear();
  12437. const int openBracket = dtdText.indexOfChar ('[');
  12438. if (openBracket > 0)
  12439. {
  12440. const int closeBracket = dtdText.lastIndexOfChar (']');
  12441. if (closeBracket > openBracket)
  12442. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12443. closeBracket), true);
  12444. }
  12445. }
  12446. for (int i = tokenisedDTD.size(); --i >= 0;)
  12447. {
  12448. if (tokenisedDTD[i].startsWithChar ('%')
  12449. && tokenisedDTD[i].endsWithChar (';'))
  12450. {
  12451. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12452. StringArray newToks;
  12453. newToks.addTokens (parsed, true);
  12454. tokenisedDTD.remove (i);
  12455. for (int j = newToks.size(); --j >= 0;)
  12456. tokenisedDTD.insert (i, newToks[j]);
  12457. }
  12458. }
  12459. }
  12460. needToLoadDTD = false;
  12461. }
  12462. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12463. {
  12464. if (tokenisedDTD[i] == entity)
  12465. {
  12466. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12467. {
  12468. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12469. // check for sub-entities..
  12470. int ampersand = ent.indexOfChar ('&');
  12471. while (ampersand >= 0)
  12472. {
  12473. const int semiColon = ent.indexOf (i + 1, ";");
  12474. if (semiColon < 0)
  12475. {
  12476. setLastError ("entity without terminating semi-colon", false);
  12477. break;
  12478. }
  12479. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12480. ent = ent.substring (0, ampersand)
  12481. + resolved
  12482. + ent.substring (semiColon + 1);
  12483. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12484. }
  12485. return ent;
  12486. }
  12487. }
  12488. }
  12489. setLastError ("unknown entity", true);
  12490. return entity;
  12491. }
  12492. const String XmlDocument::getParameterEntity (const String& entity)
  12493. {
  12494. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12495. {
  12496. if (tokenisedDTD[i] == entity)
  12497. {
  12498. if (tokenisedDTD [i - 1] == "%"
  12499. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12500. {
  12501. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12502. if (ent.equalsIgnoreCase ("system"))
  12503. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12504. else
  12505. return ent.trim().unquoted();
  12506. }
  12507. }
  12508. }
  12509. return entity;
  12510. }
  12511. END_JUCE_NAMESPACE
  12512. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12513. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12514. BEGIN_JUCE_NAMESPACE
  12515. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12516. : name (other.name),
  12517. value (other.value),
  12518. next (0)
  12519. {
  12520. }
  12521. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12522. : name (name_),
  12523. value (value_),
  12524. next (0)
  12525. {
  12526. }
  12527. XmlElement::XmlElement (const String& tagName_) throw()
  12528. : tagName (tagName_),
  12529. firstChildElement (0),
  12530. nextElement (0),
  12531. attributes (0)
  12532. {
  12533. // the tag name mustn't be empty, or it'll look like a text element!
  12534. jassert (tagName_.containsNonWhitespaceChars())
  12535. // The tag can't contain spaces or other characters that would create invalid XML!
  12536. jassert (! tagName_.containsAnyOf (" <>/&"));
  12537. }
  12538. XmlElement::XmlElement (int /*dummy*/) throw()
  12539. : firstChildElement (0),
  12540. nextElement (0),
  12541. attributes (0)
  12542. {
  12543. }
  12544. XmlElement::XmlElement (const XmlElement& other)
  12545. : tagName (other.tagName),
  12546. firstChildElement (0),
  12547. nextElement (0),
  12548. attributes (0)
  12549. {
  12550. copyChildrenAndAttributesFrom (other);
  12551. }
  12552. XmlElement& XmlElement::operator= (const XmlElement& other)
  12553. {
  12554. if (this != &other)
  12555. {
  12556. removeAllAttributes();
  12557. deleteAllChildElements();
  12558. tagName = other.tagName;
  12559. copyChildrenAndAttributesFrom (other);
  12560. }
  12561. return *this;
  12562. }
  12563. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12564. {
  12565. XmlElement* child = other.firstChildElement;
  12566. XmlElement* lastChild = 0;
  12567. while (child != 0)
  12568. {
  12569. XmlElement* const copiedChild = new XmlElement (*child);
  12570. if (lastChild != 0)
  12571. lastChild->nextElement = copiedChild;
  12572. else
  12573. firstChildElement = copiedChild;
  12574. lastChild = copiedChild;
  12575. child = child->nextElement;
  12576. }
  12577. const XmlAttributeNode* att = other.attributes;
  12578. XmlAttributeNode* lastAtt = 0;
  12579. while (att != 0)
  12580. {
  12581. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12582. if (lastAtt != 0)
  12583. lastAtt->next = newAtt;
  12584. else
  12585. attributes = newAtt;
  12586. lastAtt = newAtt;
  12587. att = att->next;
  12588. }
  12589. }
  12590. XmlElement::~XmlElement() throw()
  12591. {
  12592. XmlElement* child = firstChildElement;
  12593. while (child != 0)
  12594. {
  12595. XmlElement* const nextChild = child->nextElement;
  12596. delete child;
  12597. child = nextChild;
  12598. }
  12599. XmlAttributeNode* att = attributes;
  12600. while (att != 0)
  12601. {
  12602. XmlAttributeNode* const nextAtt = att->next;
  12603. delete att;
  12604. att = nextAtt;
  12605. }
  12606. }
  12607. namespace XmlOutputFunctions
  12608. {
  12609. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12610. {
  12611. if ((character >= 'a' && character <= 'z')
  12612. || (character >= 'A' && character <= 'Z')
  12613. || (character >= '0' && character <= '9'))
  12614. return true;
  12615. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12616. do
  12617. {
  12618. if (((juce_wchar) (uint8) *t) == character)
  12619. return true;
  12620. }
  12621. while (*++t != 0);
  12622. return false;
  12623. }
  12624. static void generateLegalCharConstants()
  12625. {
  12626. uint8 n[32];
  12627. zerostruct (n);
  12628. for (int i = 0; i < 256; ++i)
  12629. if (isLegalXmlCharSlow (i))
  12630. n[i >> 3] |= (1 << (i & 7));
  12631. String s;
  12632. for (int i = 0; i < 32; ++i)
  12633. s << (int) n[i] << ", ";
  12634. DBG (s);
  12635. }*/
  12636. static bool isLegalXmlChar (const uint32 c) throw()
  12637. {
  12638. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12639. return c < sizeof (legalChars) * 8
  12640. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12641. }
  12642. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12643. {
  12644. const juce_wchar* t = text;
  12645. for (;;)
  12646. {
  12647. const juce_wchar character = *t++;
  12648. if (character == 0)
  12649. break;
  12650. if (isLegalXmlChar ((uint32) character))
  12651. {
  12652. outputStream << (char) character;
  12653. }
  12654. else
  12655. {
  12656. switch (character)
  12657. {
  12658. case '&': outputStream << "&amp;"; break;
  12659. case '"': outputStream << "&quot;"; break;
  12660. case '>': outputStream << "&gt;"; break;
  12661. case '<': outputStream << "&lt;"; break;
  12662. case '\n':
  12663. if (changeNewLines)
  12664. outputStream << "&#10;";
  12665. else
  12666. outputStream << (char) character;
  12667. break;
  12668. case '\r':
  12669. if (changeNewLines)
  12670. outputStream << "&#13;";
  12671. else
  12672. outputStream << (char) character;
  12673. break;
  12674. default:
  12675. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12676. break;
  12677. }
  12678. }
  12679. }
  12680. }
  12681. static void writeSpaces (OutputStream& out, int numSpaces)
  12682. {
  12683. if (numSpaces > 0)
  12684. {
  12685. const char blanks[] = " ";
  12686. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12687. while (numSpaces > blankSize)
  12688. {
  12689. out.write (blanks, blankSize);
  12690. numSpaces -= blankSize;
  12691. }
  12692. out.write (blanks, numSpaces);
  12693. }
  12694. }
  12695. static void writeNewLine (OutputStream& out)
  12696. {
  12697. out.write ("\r\n", 2);
  12698. }
  12699. }
  12700. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12701. const int indentationLevel,
  12702. const int lineWrapLength) const
  12703. {
  12704. using namespace XmlOutputFunctions;
  12705. writeSpaces (outputStream, indentationLevel);
  12706. if (! isTextElement())
  12707. {
  12708. outputStream.writeByte ('<');
  12709. outputStream << tagName;
  12710. {
  12711. const int attIndent = indentationLevel + tagName.length() + 1;
  12712. int lineLen = 0;
  12713. const XmlAttributeNode* att = attributes;
  12714. while (att != 0)
  12715. {
  12716. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12717. {
  12718. writeNewLine (outputStream);
  12719. writeSpaces (outputStream, attIndent);
  12720. lineLen = 0;
  12721. }
  12722. const int64 startPos = outputStream.getPosition();
  12723. outputStream.writeByte (' ');
  12724. outputStream << att->name;
  12725. outputStream.write ("=\"", 2);
  12726. escapeIllegalXmlChars (outputStream, att->value, true);
  12727. outputStream.writeByte ('"');
  12728. lineLen += (int) (outputStream.getPosition() - startPos);
  12729. att = att->next;
  12730. }
  12731. }
  12732. if (firstChildElement != 0)
  12733. {
  12734. outputStream.writeByte ('>');
  12735. XmlElement* child = firstChildElement;
  12736. bool lastWasTextNode = false;
  12737. while (child != 0)
  12738. {
  12739. if (child->isTextElement())
  12740. {
  12741. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12742. lastWasTextNode = true;
  12743. }
  12744. else
  12745. {
  12746. if (indentationLevel >= 0 && ! lastWasTextNode)
  12747. writeNewLine (outputStream);
  12748. child->writeElementAsText (outputStream,
  12749. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12750. lastWasTextNode = false;
  12751. }
  12752. child = child->nextElement;
  12753. }
  12754. if (indentationLevel >= 0 && ! lastWasTextNode)
  12755. {
  12756. writeNewLine (outputStream);
  12757. writeSpaces (outputStream, indentationLevel);
  12758. }
  12759. outputStream.write ("</", 2);
  12760. outputStream << tagName;
  12761. outputStream.writeByte ('>');
  12762. }
  12763. else
  12764. {
  12765. outputStream.write ("/>", 2);
  12766. }
  12767. }
  12768. else
  12769. {
  12770. escapeIllegalXmlChars (outputStream, getText(), false);
  12771. }
  12772. }
  12773. const String XmlElement::createDocument (const String& dtdToUse,
  12774. const bool allOnOneLine,
  12775. const bool includeXmlHeader,
  12776. const String& encodingType,
  12777. const int lineWrapLength) const
  12778. {
  12779. MemoryOutputStream mem (2048);
  12780. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12781. return mem.toUTF8();
  12782. }
  12783. void XmlElement::writeToStream (OutputStream& output,
  12784. const String& dtdToUse,
  12785. const bool allOnOneLine,
  12786. const bool includeXmlHeader,
  12787. const String& encodingType,
  12788. const int lineWrapLength) const
  12789. {
  12790. using namespace XmlOutputFunctions;
  12791. if (includeXmlHeader)
  12792. {
  12793. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12794. if (allOnOneLine)
  12795. {
  12796. output.writeByte (' ');
  12797. }
  12798. else
  12799. {
  12800. writeNewLine (output);
  12801. writeNewLine (output);
  12802. }
  12803. }
  12804. if (dtdToUse.isNotEmpty())
  12805. {
  12806. output << dtdToUse;
  12807. if (allOnOneLine)
  12808. output.writeByte (' ');
  12809. else
  12810. writeNewLine (output);
  12811. }
  12812. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12813. if (! allOnOneLine)
  12814. writeNewLine (output);
  12815. }
  12816. bool XmlElement::writeToFile (const File& file,
  12817. const String& dtdToUse,
  12818. const String& encodingType,
  12819. const int lineWrapLength) const
  12820. {
  12821. if (file.hasWriteAccess())
  12822. {
  12823. TemporaryFile tempFile (file);
  12824. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12825. if (out != 0)
  12826. {
  12827. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12828. out = 0;
  12829. return tempFile.overwriteTargetFileWithTemporary();
  12830. }
  12831. }
  12832. return false;
  12833. }
  12834. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12835. {
  12836. #if JUCE_DEBUG
  12837. // if debugging, check that the case is actually the same, because
  12838. // valid xml is case-sensitive, and although this lets it pass, it's
  12839. // better not to..
  12840. if (tagName.equalsIgnoreCase (tagNameWanted))
  12841. {
  12842. jassert (tagName == tagNameWanted);
  12843. return true;
  12844. }
  12845. else
  12846. {
  12847. return false;
  12848. }
  12849. #else
  12850. return tagName.equalsIgnoreCase (tagNameWanted);
  12851. #endif
  12852. }
  12853. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12854. {
  12855. XmlElement* e = nextElement;
  12856. while (e != 0 && ! e->hasTagName (requiredTagName))
  12857. e = e->nextElement;
  12858. return e;
  12859. }
  12860. int XmlElement::getNumAttributes() const throw()
  12861. {
  12862. const XmlAttributeNode* att = attributes;
  12863. int count = 0;
  12864. while (att != 0)
  12865. {
  12866. att = att->next;
  12867. ++count;
  12868. }
  12869. return count;
  12870. }
  12871. const String& XmlElement::getAttributeName (const int index) const throw()
  12872. {
  12873. const XmlAttributeNode* att = attributes;
  12874. int count = 0;
  12875. while (att != 0)
  12876. {
  12877. if (count == index)
  12878. return att->name;
  12879. att = att->next;
  12880. ++count;
  12881. }
  12882. return String::empty;
  12883. }
  12884. const String& XmlElement::getAttributeValue (const int index) const throw()
  12885. {
  12886. const XmlAttributeNode* att = attributes;
  12887. int count = 0;
  12888. while (att != 0)
  12889. {
  12890. if (count == index)
  12891. return att->value;
  12892. att = att->next;
  12893. ++count;
  12894. }
  12895. return String::empty;
  12896. }
  12897. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12898. {
  12899. const XmlAttributeNode* att = attributes;
  12900. while (att != 0)
  12901. {
  12902. if (att->name.equalsIgnoreCase (attributeName))
  12903. return true;
  12904. att = att->next;
  12905. }
  12906. return false;
  12907. }
  12908. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12909. {
  12910. const XmlAttributeNode* att = attributes;
  12911. while (att != 0)
  12912. {
  12913. if (att->name.equalsIgnoreCase (attributeName))
  12914. return att->value;
  12915. att = att->next;
  12916. }
  12917. return String::empty;
  12918. }
  12919. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12920. {
  12921. const XmlAttributeNode* att = attributes;
  12922. while (att != 0)
  12923. {
  12924. if (att->name.equalsIgnoreCase (attributeName))
  12925. return att->value;
  12926. att = att->next;
  12927. }
  12928. return defaultReturnValue;
  12929. }
  12930. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12931. {
  12932. const XmlAttributeNode* att = attributes;
  12933. while (att != 0)
  12934. {
  12935. if (att->name.equalsIgnoreCase (attributeName))
  12936. return att->value.getIntValue();
  12937. att = att->next;
  12938. }
  12939. return defaultReturnValue;
  12940. }
  12941. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12942. {
  12943. const XmlAttributeNode* att = attributes;
  12944. while (att != 0)
  12945. {
  12946. if (att->name.equalsIgnoreCase (attributeName))
  12947. return att->value.getDoubleValue();
  12948. att = att->next;
  12949. }
  12950. return defaultReturnValue;
  12951. }
  12952. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12953. {
  12954. const XmlAttributeNode* att = attributes;
  12955. while (att != 0)
  12956. {
  12957. if (att->name.equalsIgnoreCase (attributeName))
  12958. {
  12959. juce_wchar firstChar = att->value[0];
  12960. if (CharacterFunctions::isWhitespace (firstChar))
  12961. firstChar = att->value.trimStart() [0];
  12962. return firstChar == '1'
  12963. || firstChar == 't'
  12964. || firstChar == 'y'
  12965. || firstChar == 'T'
  12966. || firstChar == 'Y';
  12967. }
  12968. att = att->next;
  12969. }
  12970. return defaultReturnValue;
  12971. }
  12972. bool XmlElement::compareAttribute (const String& attributeName,
  12973. const String& stringToCompareAgainst,
  12974. const bool ignoreCase) const throw()
  12975. {
  12976. const XmlAttributeNode* att = attributes;
  12977. while (att != 0)
  12978. {
  12979. if (att->name.equalsIgnoreCase (attributeName))
  12980. {
  12981. if (ignoreCase)
  12982. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12983. else
  12984. return att->value == stringToCompareAgainst;
  12985. }
  12986. att = att->next;
  12987. }
  12988. return false;
  12989. }
  12990. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12991. {
  12992. #if JUCE_DEBUG
  12993. // check the identifier being passed in is legal..
  12994. const juce_wchar* t = attributeName;
  12995. while (*t != 0)
  12996. {
  12997. jassert (CharacterFunctions::isLetterOrDigit (*t)
  12998. || *t == '_'
  12999. || *t == '-'
  13000. || *t == ':');
  13001. ++t;
  13002. }
  13003. #endif
  13004. if (attributes == 0)
  13005. {
  13006. attributes = new XmlAttributeNode (attributeName, value);
  13007. }
  13008. else
  13009. {
  13010. XmlAttributeNode* att = attributes;
  13011. for (;;)
  13012. {
  13013. if (att->name.equalsIgnoreCase (attributeName))
  13014. {
  13015. att->value = value;
  13016. break;
  13017. }
  13018. else if (att->next == 0)
  13019. {
  13020. att->next = new XmlAttributeNode (attributeName, value);
  13021. break;
  13022. }
  13023. att = att->next;
  13024. }
  13025. }
  13026. }
  13027. void XmlElement::setAttribute (const String& attributeName, const int number)
  13028. {
  13029. setAttribute (attributeName, String (number));
  13030. }
  13031. void XmlElement::setAttribute (const String& attributeName, const double number)
  13032. {
  13033. setAttribute (attributeName, String (number));
  13034. }
  13035. void XmlElement::removeAttribute (const String& attributeName) throw()
  13036. {
  13037. XmlAttributeNode* att = attributes;
  13038. XmlAttributeNode* lastAtt = 0;
  13039. while (att != 0)
  13040. {
  13041. if (att->name.equalsIgnoreCase (attributeName))
  13042. {
  13043. if (lastAtt == 0)
  13044. attributes = att->next;
  13045. else
  13046. lastAtt->next = att->next;
  13047. delete att;
  13048. break;
  13049. }
  13050. lastAtt = att;
  13051. att = att->next;
  13052. }
  13053. }
  13054. void XmlElement::removeAllAttributes() throw()
  13055. {
  13056. while (attributes != 0)
  13057. {
  13058. XmlAttributeNode* const nextAtt = attributes->next;
  13059. delete attributes;
  13060. attributes = nextAtt;
  13061. }
  13062. }
  13063. int XmlElement::getNumChildElements() const throw()
  13064. {
  13065. int count = 0;
  13066. const XmlElement* child = firstChildElement;
  13067. while (child != 0)
  13068. {
  13069. ++count;
  13070. child = child->nextElement;
  13071. }
  13072. return count;
  13073. }
  13074. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13075. {
  13076. int count = 0;
  13077. XmlElement* child = firstChildElement;
  13078. while (child != 0 && count < index)
  13079. {
  13080. child = child->nextElement;
  13081. ++count;
  13082. }
  13083. return child;
  13084. }
  13085. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13086. {
  13087. XmlElement* child = firstChildElement;
  13088. while (child != 0)
  13089. {
  13090. if (child->hasTagName (childName))
  13091. break;
  13092. child = child->nextElement;
  13093. }
  13094. return child;
  13095. }
  13096. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13097. {
  13098. if (newNode != 0)
  13099. {
  13100. if (firstChildElement == 0)
  13101. {
  13102. firstChildElement = newNode;
  13103. }
  13104. else
  13105. {
  13106. XmlElement* child = firstChildElement;
  13107. while (child->nextElement != 0)
  13108. child = child->nextElement;
  13109. child->nextElement = newNode;
  13110. // if this is non-zero, then something's probably
  13111. // gone wrong..
  13112. jassert (newNode->nextElement == 0);
  13113. }
  13114. }
  13115. }
  13116. void XmlElement::insertChildElement (XmlElement* const newNode,
  13117. int indexToInsertAt) throw()
  13118. {
  13119. if (newNode != 0)
  13120. {
  13121. removeChildElement (newNode, false);
  13122. if (indexToInsertAt == 0)
  13123. {
  13124. newNode->nextElement = firstChildElement;
  13125. firstChildElement = newNode;
  13126. }
  13127. else
  13128. {
  13129. if (firstChildElement == 0)
  13130. {
  13131. firstChildElement = newNode;
  13132. }
  13133. else
  13134. {
  13135. if (indexToInsertAt < 0)
  13136. indexToInsertAt = std::numeric_limits<int>::max();
  13137. XmlElement* child = firstChildElement;
  13138. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13139. child = child->nextElement;
  13140. newNode->nextElement = child->nextElement;
  13141. child->nextElement = newNode;
  13142. }
  13143. }
  13144. }
  13145. }
  13146. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13147. {
  13148. XmlElement* const newElement = new XmlElement (childTagName);
  13149. addChildElement (newElement);
  13150. return newElement;
  13151. }
  13152. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13153. XmlElement* const newNode) throw()
  13154. {
  13155. if (newNode != 0)
  13156. {
  13157. XmlElement* child = firstChildElement;
  13158. XmlElement* previousNode = 0;
  13159. while (child != 0)
  13160. {
  13161. if (child == currentChildElement)
  13162. {
  13163. if (child != newNode)
  13164. {
  13165. if (previousNode == 0)
  13166. firstChildElement = newNode;
  13167. else
  13168. previousNode->nextElement = newNode;
  13169. newNode->nextElement = child->nextElement;
  13170. delete child;
  13171. }
  13172. return true;
  13173. }
  13174. previousNode = child;
  13175. child = child->nextElement;
  13176. }
  13177. }
  13178. return false;
  13179. }
  13180. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13181. const bool shouldDeleteTheChild) throw()
  13182. {
  13183. if (childToRemove != 0)
  13184. {
  13185. if (firstChildElement == childToRemove)
  13186. {
  13187. firstChildElement = childToRemove->nextElement;
  13188. childToRemove->nextElement = 0;
  13189. }
  13190. else
  13191. {
  13192. XmlElement* child = firstChildElement;
  13193. XmlElement* last = 0;
  13194. while (child != 0)
  13195. {
  13196. if (child == childToRemove)
  13197. {
  13198. if (last == 0)
  13199. firstChildElement = child->nextElement;
  13200. else
  13201. last->nextElement = child->nextElement;
  13202. childToRemove->nextElement = 0;
  13203. break;
  13204. }
  13205. last = child;
  13206. child = child->nextElement;
  13207. }
  13208. }
  13209. if (shouldDeleteTheChild)
  13210. delete childToRemove;
  13211. }
  13212. }
  13213. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13214. const bool ignoreOrderOfAttributes) const throw()
  13215. {
  13216. if (this != other)
  13217. {
  13218. if (other == 0 || tagName != other->tagName)
  13219. return false;
  13220. if (ignoreOrderOfAttributes)
  13221. {
  13222. int totalAtts = 0;
  13223. const XmlAttributeNode* att = attributes;
  13224. while (att != 0)
  13225. {
  13226. if (! other->compareAttribute (att->name, att->value))
  13227. return false;
  13228. att = att->next;
  13229. ++totalAtts;
  13230. }
  13231. if (totalAtts != other->getNumAttributes())
  13232. return false;
  13233. }
  13234. else
  13235. {
  13236. const XmlAttributeNode* thisAtt = attributes;
  13237. const XmlAttributeNode* otherAtt = other->attributes;
  13238. for (;;)
  13239. {
  13240. if (thisAtt == 0 || otherAtt == 0)
  13241. {
  13242. if (thisAtt == otherAtt) // both 0, so it's a match
  13243. break;
  13244. return false;
  13245. }
  13246. if (thisAtt->name != otherAtt->name
  13247. || thisAtt->value != otherAtt->value)
  13248. {
  13249. return false;
  13250. }
  13251. thisAtt = thisAtt->next;
  13252. otherAtt = otherAtt->next;
  13253. }
  13254. }
  13255. const XmlElement* thisChild = firstChildElement;
  13256. const XmlElement* otherChild = other->firstChildElement;
  13257. for (;;)
  13258. {
  13259. if (thisChild == 0 || otherChild == 0)
  13260. {
  13261. if (thisChild == otherChild) // both 0, so it's a match
  13262. break;
  13263. return false;
  13264. }
  13265. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13266. return false;
  13267. thisChild = thisChild->nextElement;
  13268. otherChild = otherChild->nextElement;
  13269. }
  13270. }
  13271. return true;
  13272. }
  13273. void XmlElement::deleteAllChildElements() throw()
  13274. {
  13275. while (firstChildElement != 0)
  13276. {
  13277. XmlElement* const nextChild = firstChildElement->nextElement;
  13278. delete firstChildElement;
  13279. firstChildElement = nextChild;
  13280. }
  13281. }
  13282. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13283. {
  13284. XmlElement* child = firstChildElement;
  13285. while (child != 0)
  13286. {
  13287. if (child->hasTagName (name))
  13288. {
  13289. XmlElement* const nextChild = child->nextElement;
  13290. removeChildElement (child, true);
  13291. child = nextChild;
  13292. }
  13293. else
  13294. {
  13295. child = child->nextElement;
  13296. }
  13297. }
  13298. }
  13299. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13300. {
  13301. const XmlElement* child = firstChildElement;
  13302. while (child != 0)
  13303. {
  13304. if (child == possibleChild)
  13305. return true;
  13306. child = child->nextElement;
  13307. }
  13308. return false;
  13309. }
  13310. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13311. {
  13312. if (this == elementToLookFor || elementToLookFor == 0)
  13313. return 0;
  13314. XmlElement* child = firstChildElement;
  13315. while (child != 0)
  13316. {
  13317. if (elementToLookFor == child)
  13318. return this;
  13319. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13320. if (found != 0)
  13321. return found;
  13322. child = child->nextElement;
  13323. }
  13324. return 0;
  13325. }
  13326. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13327. {
  13328. XmlElement* e = firstChildElement;
  13329. while (e != 0)
  13330. {
  13331. *elems++ = e;
  13332. e = e->nextElement;
  13333. }
  13334. }
  13335. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13336. {
  13337. XmlElement* e = firstChildElement = elems[0];
  13338. for (int i = 1; i < num; ++i)
  13339. {
  13340. e->nextElement = elems[i];
  13341. e = e->nextElement;
  13342. }
  13343. e->nextElement = 0;
  13344. }
  13345. bool XmlElement::isTextElement() const throw()
  13346. {
  13347. return tagName.isEmpty();
  13348. }
  13349. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13350. const String& XmlElement::getText() const throw()
  13351. {
  13352. jassert (isTextElement()); // you're trying to get the text from an element that
  13353. // isn't actually a text element.. If this contains text sub-nodes, you
  13354. // probably want to use getAllSubText instead.
  13355. return getStringAttribute (juce_xmltextContentAttributeName);
  13356. }
  13357. void XmlElement::setText (const String& newText)
  13358. {
  13359. if (isTextElement())
  13360. setAttribute (juce_xmltextContentAttributeName, newText);
  13361. else
  13362. jassertfalse; // you can only change the text in a text element, not a normal one.
  13363. }
  13364. const String XmlElement::getAllSubText() const
  13365. {
  13366. if (isTextElement())
  13367. return getText();
  13368. String result;
  13369. String::Concatenator concatenator (result);
  13370. const XmlElement* child = firstChildElement;
  13371. while (child != 0)
  13372. {
  13373. concatenator.append (child->getAllSubText());
  13374. child = child->nextElement;
  13375. }
  13376. return result;
  13377. }
  13378. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13379. const String& defaultReturnValue) const
  13380. {
  13381. const XmlElement* const child = getChildByName (childTagName);
  13382. if (child != 0)
  13383. return child->getAllSubText();
  13384. return defaultReturnValue;
  13385. }
  13386. XmlElement* XmlElement::createTextElement (const String& text)
  13387. {
  13388. XmlElement* const e = new XmlElement ((int) 0);
  13389. e->setAttribute (juce_xmltextContentAttributeName, text);
  13390. return e;
  13391. }
  13392. void XmlElement::addTextElement (const String& text)
  13393. {
  13394. addChildElement (createTextElement (text));
  13395. }
  13396. void XmlElement::deleteAllTextElements() throw()
  13397. {
  13398. XmlElement* child = firstChildElement;
  13399. while (child != 0)
  13400. {
  13401. XmlElement* const next = child->nextElement;
  13402. if (child->isTextElement())
  13403. removeChildElement (child, true);
  13404. child = next;
  13405. }
  13406. }
  13407. END_JUCE_NAMESPACE
  13408. /*** End of inlined file: juce_XmlElement.cpp ***/
  13409. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13410. BEGIN_JUCE_NAMESPACE
  13411. ReadWriteLock::ReadWriteLock() throw()
  13412. : numWaitingWriters (0),
  13413. numWriters (0),
  13414. writerThreadId (0)
  13415. {
  13416. }
  13417. ReadWriteLock::~ReadWriteLock() throw()
  13418. {
  13419. jassert (readerThreads.size() == 0);
  13420. jassert (numWriters == 0);
  13421. }
  13422. void ReadWriteLock::enterRead() const throw()
  13423. {
  13424. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13425. const ScopedLock sl (accessLock);
  13426. for (;;)
  13427. {
  13428. jassert (readerThreads.size() % 2 == 0);
  13429. int i;
  13430. for (i = 0; i < readerThreads.size(); i += 2)
  13431. if (readerThreads.getUnchecked(i) == threadId)
  13432. break;
  13433. if (i < readerThreads.size()
  13434. || numWriters + numWaitingWriters == 0
  13435. || (threadId == writerThreadId && numWriters > 0))
  13436. {
  13437. if (i < readerThreads.size())
  13438. {
  13439. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13440. }
  13441. else
  13442. {
  13443. readerThreads.add (threadId);
  13444. readerThreads.add ((Thread::ThreadID) 1);
  13445. }
  13446. return;
  13447. }
  13448. const ScopedUnlock ul (accessLock);
  13449. waitEvent.wait (100);
  13450. }
  13451. }
  13452. void ReadWriteLock::exitRead() const throw()
  13453. {
  13454. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13455. const ScopedLock sl (accessLock);
  13456. for (int i = 0; i < readerThreads.size(); i += 2)
  13457. {
  13458. if (readerThreads.getUnchecked(i) == threadId)
  13459. {
  13460. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13461. if (newCount == 0)
  13462. {
  13463. readerThreads.removeRange (i, 2);
  13464. waitEvent.signal();
  13465. }
  13466. else
  13467. {
  13468. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13469. }
  13470. return;
  13471. }
  13472. }
  13473. jassertfalse; // unlocking a lock that wasn't locked..
  13474. }
  13475. void ReadWriteLock::enterWrite() const throw()
  13476. {
  13477. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13478. const ScopedLock sl (accessLock);
  13479. for (;;)
  13480. {
  13481. if (readerThreads.size() + numWriters == 0
  13482. || threadId == writerThreadId
  13483. || (readerThreads.size() == 2
  13484. && readerThreads.getUnchecked(0) == threadId))
  13485. {
  13486. writerThreadId = threadId;
  13487. ++numWriters;
  13488. break;
  13489. }
  13490. ++numWaitingWriters;
  13491. accessLock.exit();
  13492. waitEvent.wait (100);
  13493. accessLock.enter();
  13494. --numWaitingWriters;
  13495. }
  13496. }
  13497. bool ReadWriteLock::tryEnterWrite() const throw()
  13498. {
  13499. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13500. const ScopedLock sl (accessLock);
  13501. if (readerThreads.size() + numWriters == 0
  13502. || threadId == writerThreadId
  13503. || (readerThreads.size() == 2
  13504. && readerThreads.getUnchecked(0) == threadId))
  13505. {
  13506. writerThreadId = threadId;
  13507. ++numWriters;
  13508. return true;
  13509. }
  13510. return false;
  13511. }
  13512. void ReadWriteLock::exitWrite() const throw()
  13513. {
  13514. const ScopedLock sl (accessLock);
  13515. // check this thread actually had the lock..
  13516. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13517. if (--numWriters == 0)
  13518. {
  13519. writerThreadId = 0;
  13520. waitEvent.signal();
  13521. }
  13522. }
  13523. END_JUCE_NAMESPACE
  13524. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13525. /*** Start of inlined file: juce_Thread.cpp ***/
  13526. BEGIN_JUCE_NAMESPACE
  13527. // these functions are implemented in the platform-specific code.
  13528. void* juce_createThread (void* userData);
  13529. void juce_killThread (void* handle);
  13530. bool juce_setThreadPriority (void* handle, int priority);
  13531. void juce_setCurrentThreadName (const String& name);
  13532. #if JUCE_WINDOWS
  13533. void juce_CloseThreadHandle (void* handle);
  13534. #endif
  13535. void Thread::threadEntryPoint (Thread* const thread)
  13536. {
  13537. {
  13538. const ScopedLock sl (runningThreadsLock);
  13539. runningThreads.add (thread);
  13540. }
  13541. JUCE_TRY
  13542. {
  13543. thread->threadId_ = Thread::getCurrentThreadId();
  13544. if (thread->threadName_.isNotEmpty())
  13545. juce_setCurrentThreadName (thread->threadName_);
  13546. if (thread->startSuspensionEvent_.wait (10000))
  13547. {
  13548. if (thread->affinityMask_ != 0)
  13549. setCurrentThreadAffinityMask (thread->affinityMask_);
  13550. thread->run();
  13551. }
  13552. }
  13553. JUCE_CATCH_ALL_ASSERT
  13554. {
  13555. const ScopedLock sl (runningThreadsLock);
  13556. jassert (runningThreads.contains (thread));
  13557. runningThreads.removeValue (thread);
  13558. }
  13559. #if JUCE_WINDOWS
  13560. juce_CloseThreadHandle (thread->threadHandle_);
  13561. #endif
  13562. thread->threadHandle_ = 0;
  13563. thread->threadId_ = 0;
  13564. }
  13565. // used to wrap the incoming call from the platform-specific code
  13566. void JUCE_API juce_threadEntryPoint (void* userData)
  13567. {
  13568. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13569. }
  13570. Thread::Thread (const String& threadName)
  13571. : threadName_ (threadName),
  13572. threadHandle_ (0),
  13573. threadPriority_ (5),
  13574. threadId_ (0),
  13575. affinityMask_ (0),
  13576. threadShouldExit_ (false)
  13577. {
  13578. }
  13579. Thread::~Thread()
  13580. {
  13581. stopThread (100);
  13582. }
  13583. void Thread::startThread()
  13584. {
  13585. const ScopedLock sl (startStopLock);
  13586. threadShouldExit_ = false;
  13587. if (threadHandle_ == 0)
  13588. {
  13589. threadHandle_ = juce_createThread (this);
  13590. juce_setThreadPriority (threadHandle_, threadPriority_);
  13591. startSuspensionEvent_.signal();
  13592. }
  13593. }
  13594. void Thread::startThread (const int priority)
  13595. {
  13596. const ScopedLock sl (startStopLock);
  13597. if (threadHandle_ == 0)
  13598. {
  13599. threadPriority_ = priority;
  13600. startThread();
  13601. }
  13602. else
  13603. {
  13604. setPriority (priority);
  13605. }
  13606. }
  13607. bool Thread::isThreadRunning() const
  13608. {
  13609. return threadHandle_ != 0;
  13610. }
  13611. void Thread::signalThreadShouldExit()
  13612. {
  13613. threadShouldExit_ = true;
  13614. }
  13615. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13616. {
  13617. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13618. jassert (getThreadId() != getCurrentThreadId());
  13619. const int sleepMsPerIteration = 5;
  13620. int count = timeOutMilliseconds / sleepMsPerIteration;
  13621. while (isThreadRunning())
  13622. {
  13623. if (timeOutMilliseconds > 0 && --count < 0)
  13624. return false;
  13625. sleep (sleepMsPerIteration);
  13626. }
  13627. return true;
  13628. }
  13629. void Thread::stopThread (const int timeOutMilliseconds)
  13630. {
  13631. // agh! You can't stop the thread that's calling this method! How on earth
  13632. // would that work??
  13633. jassert (getCurrentThreadId() != getThreadId());
  13634. const ScopedLock sl (startStopLock);
  13635. if (isThreadRunning())
  13636. {
  13637. signalThreadShouldExit();
  13638. notify();
  13639. if (timeOutMilliseconds != 0)
  13640. waitForThreadToExit (timeOutMilliseconds);
  13641. if (isThreadRunning())
  13642. {
  13643. // very bad karma if this point is reached, as
  13644. // there are bound to be locks and events left in
  13645. // silly states when a thread is killed by force..
  13646. jassertfalse;
  13647. Logger::writeToLog ("!! killing thread by force !!");
  13648. juce_killThread (threadHandle_);
  13649. threadHandle_ = 0;
  13650. threadId_ = 0;
  13651. const ScopedLock sl2 (runningThreadsLock);
  13652. runningThreads.removeValue (this);
  13653. }
  13654. }
  13655. }
  13656. bool Thread::setPriority (const int priority)
  13657. {
  13658. const ScopedLock sl (startStopLock);
  13659. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13660. if (worked)
  13661. threadPriority_ = priority;
  13662. return worked;
  13663. }
  13664. bool Thread::setCurrentThreadPriority (const int priority)
  13665. {
  13666. return juce_setThreadPriority (0, priority);
  13667. }
  13668. void Thread::setAffinityMask (const uint32 affinityMask)
  13669. {
  13670. affinityMask_ = affinityMask;
  13671. }
  13672. bool Thread::wait (const int timeOutMilliseconds) const
  13673. {
  13674. return defaultEvent_.wait (timeOutMilliseconds);
  13675. }
  13676. void Thread::notify() const
  13677. {
  13678. defaultEvent_.signal();
  13679. }
  13680. int Thread::getNumRunningThreads()
  13681. {
  13682. return runningThreads.size();
  13683. }
  13684. Thread* Thread::getCurrentThread()
  13685. {
  13686. const ThreadID thisId = getCurrentThreadId();
  13687. const ScopedLock sl (runningThreadsLock);
  13688. for (int i = runningThreads.size(); --i >= 0;)
  13689. {
  13690. Thread* const t = runningThreads.getUnchecked(i);
  13691. if (t->threadId_ == thisId)
  13692. return t;
  13693. }
  13694. return 0;
  13695. }
  13696. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13697. {
  13698. {
  13699. const ScopedLock sl (runningThreadsLock);
  13700. for (int i = runningThreads.size(); --i >= 0;)
  13701. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13702. }
  13703. for (;;)
  13704. {
  13705. Thread* firstThread;
  13706. {
  13707. const ScopedLock sl (runningThreadsLock);
  13708. firstThread = runningThreads.getFirst();
  13709. }
  13710. if (firstThread == 0)
  13711. break;
  13712. firstThread->stopThread (timeOutMilliseconds);
  13713. }
  13714. }
  13715. Array<Thread*> Thread::runningThreads;
  13716. CriticalSection Thread::runningThreadsLock;
  13717. END_JUCE_NAMESPACE
  13718. /*** End of inlined file: juce_Thread.cpp ***/
  13719. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13720. BEGIN_JUCE_NAMESPACE
  13721. ThreadPoolJob::ThreadPoolJob (const String& name)
  13722. : jobName (name),
  13723. pool (0),
  13724. shouldStop (false),
  13725. isActive (false),
  13726. shouldBeDeleted (false)
  13727. {
  13728. }
  13729. ThreadPoolJob::~ThreadPoolJob()
  13730. {
  13731. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13732. // to remove it first!
  13733. jassert (pool == 0 || ! pool->contains (this));
  13734. }
  13735. const String ThreadPoolJob::getJobName() const
  13736. {
  13737. return jobName;
  13738. }
  13739. void ThreadPoolJob::setJobName (const String& newName)
  13740. {
  13741. jobName = newName;
  13742. }
  13743. void ThreadPoolJob::signalJobShouldExit()
  13744. {
  13745. shouldStop = true;
  13746. }
  13747. class ThreadPool::ThreadPoolThread : public Thread
  13748. {
  13749. public:
  13750. ThreadPoolThread (ThreadPool& pool_)
  13751. : Thread ("Pool"),
  13752. pool (pool_),
  13753. busy (false)
  13754. {
  13755. }
  13756. ~ThreadPoolThread()
  13757. {
  13758. }
  13759. void run()
  13760. {
  13761. while (! threadShouldExit())
  13762. {
  13763. if (! pool.runNextJob())
  13764. wait (500);
  13765. }
  13766. }
  13767. private:
  13768. ThreadPool& pool;
  13769. bool volatile busy;
  13770. ThreadPoolThread (const ThreadPoolThread&);
  13771. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13772. };
  13773. ThreadPool::ThreadPool (const int numThreads,
  13774. const bool startThreadsOnlyWhenNeeded,
  13775. const int stopThreadsWhenNotUsedTimeoutMs)
  13776. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13777. priority (5)
  13778. {
  13779. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13780. for (int i = jmax (1, numThreads); --i >= 0;)
  13781. threads.add (new ThreadPoolThread (*this));
  13782. if (! startThreadsOnlyWhenNeeded)
  13783. for (int i = threads.size(); --i >= 0;)
  13784. threads.getUnchecked(i)->startThread (priority);
  13785. }
  13786. ThreadPool::~ThreadPool()
  13787. {
  13788. removeAllJobs (true, 4000);
  13789. int i;
  13790. for (i = threads.size(); --i >= 0;)
  13791. threads.getUnchecked(i)->signalThreadShouldExit();
  13792. for (i = threads.size(); --i >= 0;)
  13793. threads.getUnchecked(i)->stopThread (500);
  13794. }
  13795. void ThreadPool::addJob (ThreadPoolJob* const job)
  13796. {
  13797. jassert (job != 0);
  13798. jassert (job->pool == 0);
  13799. if (job->pool == 0)
  13800. {
  13801. job->pool = this;
  13802. job->shouldStop = false;
  13803. job->isActive = false;
  13804. {
  13805. const ScopedLock sl (lock);
  13806. jobs.add (job);
  13807. int numRunning = 0;
  13808. for (int i = threads.size(); --i >= 0;)
  13809. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13810. ++numRunning;
  13811. if (numRunning < threads.size())
  13812. {
  13813. bool startedOne = false;
  13814. int n = 1000;
  13815. while (--n >= 0 && ! startedOne)
  13816. {
  13817. for (int i = threads.size(); --i >= 0;)
  13818. {
  13819. if (! threads.getUnchecked(i)->isThreadRunning())
  13820. {
  13821. threads.getUnchecked(i)->startThread (priority);
  13822. startedOne = true;
  13823. break;
  13824. }
  13825. }
  13826. if (! startedOne)
  13827. Thread::sleep (2);
  13828. }
  13829. }
  13830. }
  13831. for (int i = threads.size(); --i >= 0;)
  13832. threads.getUnchecked(i)->notify();
  13833. }
  13834. }
  13835. int ThreadPool::getNumJobs() const
  13836. {
  13837. return jobs.size();
  13838. }
  13839. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13840. {
  13841. const ScopedLock sl (lock);
  13842. return jobs [index];
  13843. }
  13844. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13845. {
  13846. const ScopedLock sl (lock);
  13847. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13848. }
  13849. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13850. {
  13851. const ScopedLock sl (lock);
  13852. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13853. }
  13854. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13855. const int timeOutMs) const
  13856. {
  13857. if (job != 0)
  13858. {
  13859. const uint32 start = Time::getMillisecondCounter();
  13860. while (contains (job))
  13861. {
  13862. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13863. return false;
  13864. jobFinishedSignal.wait (2);
  13865. }
  13866. }
  13867. return true;
  13868. }
  13869. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13870. const bool interruptIfRunning,
  13871. const int timeOutMs)
  13872. {
  13873. bool dontWait = true;
  13874. if (job != 0)
  13875. {
  13876. const ScopedLock sl (lock);
  13877. if (jobs.contains (job))
  13878. {
  13879. if (job->isActive)
  13880. {
  13881. if (interruptIfRunning)
  13882. job->signalJobShouldExit();
  13883. dontWait = false;
  13884. }
  13885. else
  13886. {
  13887. jobs.removeValue (job);
  13888. job->pool = 0;
  13889. }
  13890. }
  13891. }
  13892. return dontWait || waitForJobToFinish (job, timeOutMs);
  13893. }
  13894. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13895. const int timeOutMs,
  13896. const bool deleteInactiveJobs,
  13897. ThreadPool::JobSelector* selectedJobsToRemove)
  13898. {
  13899. Array <ThreadPoolJob*> jobsToWaitFor;
  13900. {
  13901. const ScopedLock sl (lock);
  13902. for (int i = jobs.size(); --i >= 0;)
  13903. {
  13904. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13905. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13906. {
  13907. if (job->isActive)
  13908. {
  13909. jobsToWaitFor.add (job);
  13910. if (interruptRunningJobs)
  13911. job->signalJobShouldExit();
  13912. }
  13913. else
  13914. {
  13915. jobs.remove (i);
  13916. if (deleteInactiveJobs)
  13917. delete job;
  13918. else
  13919. job->pool = 0;
  13920. }
  13921. }
  13922. }
  13923. }
  13924. const uint32 start = Time::getMillisecondCounter();
  13925. for (;;)
  13926. {
  13927. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13928. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13929. jobsToWaitFor.remove (i);
  13930. if (jobsToWaitFor.size() == 0)
  13931. break;
  13932. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13933. return false;
  13934. jobFinishedSignal.wait (20);
  13935. }
  13936. return true;
  13937. }
  13938. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13939. {
  13940. StringArray s;
  13941. const ScopedLock sl (lock);
  13942. for (int i = 0; i < jobs.size(); ++i)
  13943. {
  13944. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13945. if (job->isActive || ! onlyReturnActiveJobs)
  13946. s.add (job->getJobName());
  13947. }
  13948. return s;
  13949. }
  13950. bool ThreadPool::setThreadPriorities (const int newPriority)
  13951. {
  13952. bool ok = true;
  13953. if (priority != newPriority)
  13954. {
  13955. priority = newPriority;
  13956. for (int i = threads.size(); --i >= 0;)
  13957. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13958. ok = false;
  13959. }
  13960. return ok;
  13961. }
  13962. bool ThreadPool::runNextJob()
  13963. {
  13964. ThreadPoolJob* job = 0;
  13965. {
  13966. const ScopedLock sl (lock);
  13967. for (int i = 0; i < jobs.size(); ++i)
  13968. {
  13969. job = jobs[i];
  13970. if (job != 0 && ! (job->isActive || job->shouldStop))
  13971. break;
  13972. job = 0;
  13973. }
  13974. if (job != 0)
  13975. job->isActive = true;
  13976. }
  13977. if (job != 0)
  13978. {
  13979. JUCE_TRY
  13980. {
  13981. ThreadPoolJob::JobStatus result = job->runJob();
  13982. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13983. const ScopedLock sl (lock);
  13984. if (jobs.contains (job))
  13985. {
  13986. job->isActive = false;
  13987. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13988. {
  13989. job->pool = 0;
  13990. job->shouldStop = true;
  13991. jobs.removeValue (job);
  13992. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13993. delete job;
  13994. jobFinishedSignal.signal();
  13995. }
  13996. else
  13997. {
  13998. // move the job to the end of the queue if it wants another go
  13999. jobs.move (jobs.indexOf (job), -1);
  14000. }
  14001. }
  14002. }
  14003. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14004. catch (...)
  14005. {
  14006. const ScopedLock sl (lock);
  14007. jobs.removeValue (job);
  14008. }
  14009. #endif
  14010. }
  14011. else
  14012. {
  14013. if (threadStopTimeout > 0
  14014. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14015. {
  14016. const ScopedLock sl (lock);
  14017. if (jobs.size() == 0)
  14018. for (int i = threads.size(); --i >= 0;)
  14019. threads.getUnchecked(i)->signalThreadShouldExit();
  14020. }
  14021. else
  14022. {
  14023. return false;
  14024. }
  14025. }
  14026. return true;
  14027. }
  14028. END_JUCE_NAMESPACE
  14029. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14030. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14031. BEGIN_JUCE_NAMESPACE
  14032. TimeSliceThread::TimeSliceThread (const String& threadName)
  14033. : Thread (threadName),
  14034. index (0),
  14035. clientBeingCalled (0),
  14036. clientsChanged (false)
  14037. {
  14038. }
  14039. TimeSliceThread::~TimeSliceThread()
  14040. {
  14041. stopThread (2000);
  14042. }
  14043. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14044. {
  14045. const ScopedLock sl (listLock);
  14046. clients.addIfNotAlreadyThere (client);
  14047. clientsChanged = true;
  14048. notify();
  14049. }
  14050. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14051. {
  14052. const ScopedLock sl1 (listLock);
  14053. clientsChanged = true;
  14054. // if there's a chance we're in the middle of calling this client, we need to
  14055. // also lock the outer lock..
  14056. if (clientBeingCalled == client)
  14057. {
  14058. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14059. const ScopedLock sl2 (callbackLock);
  14060. const ScopedLock sl3 (listLock);
  14061. clients.removeValue (client);
  14062. }
  14063. else
  14064. {
  14065. clients.removeValue (client);
  14066. }
  14067. }
  14068. int TimeSliceThread::getNumClients() const
  14069. {
  14070. return clients.size();
  14071. }
  14072. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14073. {
  14074. const ScopedLock sl (listLock);
  14075. return clients [i];
  14076. }
  14077. void TimeSliceThread::run()
  14078. {
  14079. int numCallsSinceBusy = 0;
  14080. while (! threadShouldExit())
  14081. {
  14082. int timeToWait = 500;
  14083. {
  14084. const ScopedLock sl (callbackLock);
  14085. {
  14086. const ScopedLock sl2 (listLock);
  14087. if (clients.size() > 0)
  14088. {
  14089. index = (index + 1) % clients.size();
  14090. clientBeingCalled = clients [index];
  14091. }
  14092. else
  14093. {
  14094. index = 0;
  14095. clientBeingCalled = 0;
  14096. }
  14097. if (clientsChanged)
  14098. {
  14099. clientsChanged = false;
  14100. numCallsSinceBusy = 0;
  14101. }
  14102. }
  14103. if (clientBeingCalled != 0)
  14104. {
  14105. if (clientBeingCalled->useTimeSlice())
  14106. numCallsSinceBusy = 0;
  14107. else
  14108. ++numCallsSinceBusy;
  14109. if (numCallsSinceBusy >= clients.size())
  14110. timeToWait = 500;
  14111. else if (index == 0)
  14112. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14113. else
  14114. timeToWait = 0;
  14115. }
  14116. }
  14117. if (timeToWait > 0)
  14118. wait (timeToWait);
  14119. }
  14120. }
  14121. END_JUCE_NAMESPACE
  14122. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14123. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14124. BEGIN_JUCE_NAMESPACE
  14125. DeletedAtShutdown::DeletedAtShutdown()
  14126. {
  14127. const ScopedLock sl (getLock());
  14128. getObjects().add (this);
  14129. }
  14130. DeletedAtShutdown::~DeletedAtShutdown()
  14131. {
  14132. const ScopedLock sl (getLock());
  14133. getObjects().removeValue (this);
  14134. }
  14135. void DeletedAtShutdown::deleteAll()
  14136. {
  14137. // make a local copy of the array, so it can't get into a loop if something
  14138. // creates another DeletedAtShutdown object during its destructor.
  14139. Array <DeletedAtShutdown*> localCopy;
  14140. {
  14141. const ScopedLock sl (getLock());
  14142. localCopy = getObjects();
  14143. }
  14144. for (int i = localCopy.size(); --i >= 0;)
  14145. {
  14146. JUCE_TRY
  14147. {
  14148. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14149. // double-check that it's not already been deleted during another object's destructor.
  14150. {
  14151. const ScopedLock sl (getLock());
  14152. if (! getObjects().contains (deletee))
  14153. deletee = 0;
  14154. }
  14155. delete deletee;
  14156. }
  14157. JUCE_CATCH_EXCEPTION
  14158. }
  14159. // if no objects got re-created during shutdown, this should have been emptied by their
  14160. // destructors
  14161. jassert (getObjects().size() == 0);
  14162. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14163. }
  14164. CriticalSection& DeletedAtShutdown::getLock()
  14165. {
  14166. static CriticalSection lock;
  14167. return lock;
  14168. }
  14169. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14170. {
  14171. static Array <DeletedAtShutdown*> objects;
  14172. return objects;
  14173. }
  14174. END_JUCE_NAMESPACE
  14175. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14176. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14177. BEGIN_JUCE_NAMESPACE
  14178. UnitTest::UnitTest (const String& name_)
  14179. : name (name_), runner (0)
  14180. {
  14181. getAllTests().add (this);
  14182. }
  14183. UnitTest::~UnitTest()
  14184. {
  14185. getAllTests().removeValue (this);
  14186. }
  14187. Array<UnitTest*>& UnitTest::getAllTests()
  14188. {
  14189. static Array<UnitTest*> tests;
  14190. return tests;
  14191. }
  14192. void UnitTest::performTest (UnitTestRunner* const runner_)
  14193. {
  14194. jassert (runner_ != 0);
  14195. runner = runner_;
  14196. runTest();
  14197. }
  14198. void UnitTest::logMessage (const String& message)
  14199. {
  14200. runner->logMessage (message);
  14201. }
  14202. void UnitTest::beginTest (const String& testName)
  14203. {
  14204. runner->beginNewTest (this, testName);
  14205. }
  14206. void UnitTest::expect (const bool result, const String& failureMessage)
  14207. {
  14208. if (result)
  14209. runner->addPass();
  14210. else
  14211. runner->addFail (failureMessage);
  14212. }
  14213. UnitTestRunner::UnitTestRunner()
  14214. : currentTest (0), assertOnFailure (false)
  14215. {
  14216. }
  14217. UnitTestRunner::~UnitTestRunner()
  14218. {
  14219. }
  14220. void UnitTestRunner::resultsUpdated()
  14221. {
  14222. }
  14223. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14224. {
  14225. results.clear();
  14226. assertOnFailure = assertOnFailure_;
  14227. resultsUpdated();
  14228. for (int i = 0; i < tests.size(); ++i)
  14229. {
  14230. try
  14231. {
  14232. tests.getUnchecked(i)->performTest (this);
  14233. }
  14234. catch (...)
  14235. {
  14236. addFail ("An unhandled exception was thrown!");
  14237. }
  14238. }
  14239. endTest();
  14240. }
  14241. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14242. {
  14243. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14244. }
  14245. void UnitTestRunner::logMessage (const String& message)
  14246. {
  14247. Logger::writeToLog (message);
  14248. }
  14249. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14250. {
  14251. endTest();
  14252. currentTest = test;
  14253. TestResult* const r = new TestResult();
  14254. r->unitTestName = test->getName();
  14255. r->subcategoryName = subCategory;
  14256. r->passes = 0;
  14257. r->failures = 0;
  14258. results.add (r);
  14259. logMessage ("-----------------------------------------------------------------");
  14260. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14261. resultsUpdated();
  14262. }
  14263. void UnitTestRunner::endTest()
  14264. {
  14265. if (results.size() > 0)
  14266. {
  14267. TestResult* const r = results.getLast();
  14268. if (r->failures > 0)
  14269. {
  14270. String m ("FAILED!!");
  14271. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14272. << " failed, out of a total of " << (r->passes + r->failures);
  14273. logMessage (String::empty);
  14274. logMessage (m);
  14275. logMessage (String::empty);
  14276. }
  14277. else
  14278. {
  14279. logMessage ("All tests completed successfully");
  14280. }
  14281. }
  14282. }
  14283. void UnitTestRunner::addPass()
  14284. {
  14285. {
  14286. const ScopedLock sl (results.getLock());
  14287. TestResult* const r = results.getLast();
  14288. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14289. r->passes++;
  14290. String message ("Test ");
  14291. message << (r->failures + r->passes) << " passed";
  14292. logMessage (message);
  14293. }
  14294. resultsUpdated();
  14295. }
  14296. void UnitTestRunner::addFail (const String& failureMessage)
  14297. {
  14298. {
  14299. const ScopedLock sl (results.getLock());
  14300. TestResult* const r = results.getLast();
  14301. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14302. r->failures++;
  14303. String message ("!!! Test ");
  14304. message << (r->failures + r->passes) << " failed";
  14305. if (failureMessage.isNotEmpty())
  14306. message << ": " << failureMessage;
  14307. r->messages.add (message);
  14308. logMessage (message);
  14309. }
  14310. resultsUpdated();
  14311. if (assertOnFailure) { jassertfalse }
  14312. }
  14313. END_JUCE_NAMESPACE
  14314. /*** End of inlined file: juce_UnitTest.cpp ***/
  14315. #endif
  14316. #if JUCE_BUILD_MISC
  14317. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14318. BEGIN_JUCE_NAMESPACE
  14319. class ValueTree::SetPropertyAction : public UndoableAction
  14320. {
  14321. public:
  14322. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14323. const var& newValue_, const var& oldValue_,
  14324. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14325. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14326. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14327. {
  14328. }
  14329. ~SetPropertyAction() {}
  14330. bool perform()
  14331. {
  14332. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14333. if (isDeletingProperty)
  14334. target->removeProperty (name, 0);
  14335. else
  14336. target->setProperty (name, newValue, 0);
  14337. return true;
  14338. }
  14339. bool undo()
  14340. {
  14341. if (isAddingNewProperty)
  14342. target->removeProperty (name, 0);
  14343. else
  14344. target->setProperty (name, oldValue, 0);
  14345. return true;
  14346. }
  14347. int getSizeInUnits()
  14348. {
  14349. return (int) sizeof (*this); //xxx should be more accurate
  14350. }
  14351. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14352. {
  14353. if (! (isAddingNewProperty || isDeletingProperty))
  14354. {
  14355. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14356. if (next != 0 && next->target == target && next->name == name
  14357. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14358. {
  14359. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14360. }
  14361. }
  14362. return 0;
  14363. }
  14364. private:
  14365. const SharedObjectPtr target;
  14366. const Identifier name;
  14367. const var newValue;
  14368. var oldValue;
  14369. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14370. SetPropertyAction (const SetPropertyAction&);
  14371. SetPropertyAction& operator= (const SetPropertyAction&);
  14372. };
  14373. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14374. {
  14375. public:
  14376. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14377. const SharedObjectPtr& newChild_)
  14378. : target (target_),
  14379. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14380. childIndex (childIndex_),
  14381. isDeleting (newChild_ == 0)
  14382. {
  14383. jassert (child != 0);
  14384. }
  14385. ~AddOrRemoveChildAction() {}
  14386. bool perform()
  14387. {
  14388. if (isDeleting)
  14389. target->removeChild (childIndex, 0);
  14390. else
  14391. target->addChild (child, childIndex, 0);
  14392. return true;
  14393. }
  14394. bool undo()
  14395. {
  14396. if (isDeleting)
  14397. {
  14398. target->addChild (child, childIndex, 0);
  14399. }
  14400. else
  14401. {
  14402. // If you hit this, it seems that your object's state is getting confused - probably
  14403. // because you've interleaved some undoable and non-undoable operations?
  14404. jassert (childIndex < target->children.size());
  14405. target->removeChild (childIndex, 0);
  14406. }
  14407. return true;
  14408. }
  14409. int getSizeInUnits()
  14410. {
  14411. return (int) sizeof (*this); //xxx should be more accurate
  14412. }
  14413. private:
  14414. const SharedObjectPtr target, child;
  14415. const int childIndex;
  14416. const bool isDeleting;
  14417. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14418. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14419. };
  14420. class ValueTree::MoveChildAction : public UndoableAction
  14421. {
  14422. public:
  14423. MoveChildAction (const SharedObjectPtr& parent_,
  14424. const int startIndex_, const int endIndex_)
  14425. : parent (parent_),
  14426. startIndex (startIndex_),
  14427. endIndex (endIndex_)
  14428. {
  14429. }
  14430. ~MoveChildAction() {}
  14431. bool perform()
  14432. {
  14433. parent->moveChild (startIndex, endIndex, 0);
  14434. return true;
  14435. }
  14436. bool undo()
  14437. {
  14438. parent->moveChild (endIndex, startIndex, 0);
  14439. return true;
  14440. }
  14441. int getSizeInUnits()
  14442. {
  14443. return (int) sizeof (*this); //xxx should be more accurate
  14444. }
  14445. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14446. {
  14447. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14448. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14449. return new MoveChildAction (parent, startIndex, next->endIndex);
  14450. return 0;
  14451. }
  14452. private:
  14453. const SharedObjectPtr parent;
  14454. const int startIndex, endIndex;
  14455. MoveChildAction (const MoveChildAction&);
  14456. MoveChildAction& operator= (const MoveChildAction&);
  14457. };
  14458. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14459. : type (type_), parent (0)
  14460. {
  14461. }
  14462. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14463. : type (other.type), properties (other.properties), parent (0)
  14464. {
  14465. for (int i = 0; i < other.children.size(); ++i)
  14466. {
  14467. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14468. child->parent = this;
  14469. children.add (child);
  14470. }
  14471. }
  14472. ValueTree::SharedObject::~SharedObject()
  14473. {
  14474. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14475. for (int i = children.size(); --i >= 0;)
  14476. {
  14477. const SharedObjectPtr c (children.getUnchecked(i));
  14478. c->parent = 0;
  14479. children.remove (i);
  14480. c->sendParentChangeMessage();
  14481. }
  14482. }
  14483. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14484. {
  14485. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14486. {
  14487. ValueTree* const v = valueTreesWithListeners[i];
  14488. if (v != 0)
  14489. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14490. }
  14491. }
  14492. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14493. {
  14494. ValueTree tree (this);
  14495. ValueTree::SharedObject* t = this;
  14496. while (t != 0)
  14497. {
  14498. t->sendPropertyChangeMessage (tree, property);
  14499. t = t->parent;
  14500. }
  14501. }
  14502. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14503. {
  14504. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14505. {
  14506. ValueTree* const v = valueTreesWithListeners[i];
  14507. if (v != 0)
  14508. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14509. }
  14510. }
  14511. void ValueTree::SharedObject::sendChildChangeMessage()
  14512. {
  14513. ValueTree tree (this);
  14514. ValueTree::SharedObject* t = this;
  14515. while (t != 0)
  14516. {
  14517. t->sendChildChangeMessage (tree);
  14518. t = t->parent;
  14519. }
  14520. }
  14521. void ValueTree::SharedObject::sendParentChangeMessage()
  14522. {
  14523. ValueTree tree (this);
  14524. int i;
  14525. for (i = children.size(); --i >= 0;)
  14526. {
  14527. SharedObject* const t = children[i];
  14528. if (t != 0)
  14529. t->sendParentChangeMessage();
  14530. }
  14531. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14532. {
  14533. ValueTree* const v = valueTreesWithListeners[i];
  14534. if (v != 0)
  14535. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14536. }
  14537. }
  14538. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14539. {
  14540. return properties [name];
  14541. }
  14542. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14543. {
  14544. return properties.getWithDefault (name, defaultReturnValue);
  14545. }
  14546. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14547. {
  14548. if (undoManager == 0)
  14549. {
  14550. if (properties.set (name, newValue))
  14551. sendPropertyChangeMessage (name);
  14552. }
  14553. else
  14554. {
  14555. var* const existingValue = properties.getItem (name);
  14556. if (existingValue != 0)
  14557. {
  14558. if (*existingValue != newValue)
  14559. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14560. }
  14561. else
  14562. {
  14563. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14564. }
  14565. }
  14566. }
  14567. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14568. {
  14569. return properties.contains (name);
  14570. }
  14571. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14572. {
  14573. if (undoManager == 0)
  14574. {
  14575. if (properties.remove (name))
  14576. sendPropertyChangeMessage (name);
  14577. }
  14578. else
  14579. {
  14580. if (properties.contains (name))
  14581. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14582. }
  14583. }
  14584. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14585. {
  14586. if (undoManager == 0)
  14587. {
  14588. while (properties.size() > 0)
  14589. {
  14590. const Identifier name (properties.getName (properties.size() - 1));
  14591. properties.remove (name);
  14592. sendPropertyChangeMessage (name);
  14593. }
  14594. }
  14595. else
  14596. {
  14597. for (int i = properties.size(); --i >= 0;)
  14598. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14599. }
  14600. }
  14601. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14602. {
  14603. for (int i = 0; i < children.size(); ++i)
  14604. if (children.getUnchecked(i)->type == typeToMatch)
  14605. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14606. return ValueTree::invalid;
  14607. }
  14608. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14609. {
  14610. for (int i = 0; i < children.size(); ++i)
  14611. if (children.getUnchecked(i)->type == typeToMatch)
  14612. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14613. SharedObject* const newObject = new SharedObject (typeToMatch);
  14614. addChild (newObject, -1, undoManager);
  14615. return ValueTree (newObject);
  14616. }
  14617. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14618. {
  14619. for (int i = 0; i < children.size(); ++i)
  14620. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14621. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14622. return ValueTree::invalid;
  14623. }
  14624. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14625. {
  14626. const SharedObject* p = parent;
  14627. while (p != 0)
  14628. {
  14629. if (p == possibleParent)
  14630. return true;
  14631. p = p->parent;
  14632. }
  14633. return false;
  14634. }
  14635. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14636. {
  14637. return children.indexOf (child.object);
  14638. }
  14639. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14640. {
  14641. if (child != 0 && child->parent != this)
  14642. {
  14643. if (child != this && ! isAChildOf (child))
  14644. {
  14645. // You should always make sure that a child is removed from its previous parent before
  14646. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14647. // undomanager should be used when removing it from its current parent..
  14648. jassert (child->parent == 0);
  14649. if (child->parent != 0)
  14650. {
  14651. jassert (child->parent->children.indexOf (child) >= 0);
  14652. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14653. }
  14654. if (undoManager == 0)
  14655. {
  14656. children.insert (index, child);
  14657. child->parent = this;
  14658. sendChildChangeMessage();
  14659. child->sendParentChangeMessage();
  14660. }
  14661. else
  14662. {
  14663. if (index < 0)
  14664. index = children.size();
  14665. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14666. }
  14667. }
  14668. else
  14669. {
  14670. // You're attempting to create a recursive loop! A node
  14671. // can't be a child of one of its own children!
  14672. jassertfalse;
  14673. }
  14674. }
  14675. }
  14676. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14677. {
  14678. const SharedObjectPtr child (children [childIndex]);
  14679. if (child != 0)
  14680. {
  14681. if (undoManager == 0)
  14682. {
  14683. children.remove (childIndex);
  14684. child->parent = 0;
  14685. sendChildChangeMessage();
  14686. child->sendParentChangeMessage();
  14687. }
  14688. else
  14689. {
  14690. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14691. }
  14692. }
  14693. }
  14694. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14695. {
  14696. while (children.size() > 0)
  14697. removeChild (children.size() - 1, undoManager);
  14698. }
  14699. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14700. {
  14701. // The source index must be a valid index!
  14702. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14703. if (currentIndex != newIndex
  14704. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14705. {
  14706. if (undoManager == 0)
  14707. {
  14708. children.move (currentIndex, newIndex);
  14709. sendChildChangeMessage();
  14710. }
  14711. else
  14712. {
  14713. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14714. newIndex = children.size() - 1;
  14715. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14716. }
  14717. }
  14718. }
  14719. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14720. {
  14721. if (type != other.type
  14722. || properties.size() != other.properties.size()
  14723. || children.size() != other.children.size()
  14724. || properties != other.properties)
  14725. return false;
  14726. for (int i = 0; i < children.size(); ++i)
  14727. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14728. return false;
  14729. return true;
  14730. }
  14731. ValueTree::ValueTree() throw()
  14732. : object (0)
  14733. {
  14734. }
  14735. const ValueTree ValueTree::invalid;
  14736. ValueTree::ValueTree (const Identifier& type_)
  14737. : object (new ValueTree::SharedObject (type_))
  14738. {
  14739. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14740. }
  14741. ValueTree::ValueTree (SharedObject* const object_)
  14742. : object (object_)
  14743. {
  14744. }
  14745. ValueTree::ValueTree (const ValueTree& other)
  14746. : object (other.object)
  14747. {
  14748. }
  14749. ValueTree& ValueTree::operator= (const ValueTree& other)
  14750. {
  14751. if (listeners.size() > 0)
  14752. {
  14753. if (object != 0)
  14754. object->valueTreesWithListeners.removeValue (this);
  14755. if (other.object != 0)
  14756. other.object->valueTreesWithListeners.add (this);
  14757. }
  14758. object = other.object;
  14759. return *this;
  14760. }
  14761. ValueTree::~ValueTree()
  14762. {
  14763. if (listeners.size() > 0 && object != 0)
  14764. object->valueTreesWithListeners.removeValue (this);
  14765. }
  14766. bool ValueTree::operator== (const ValueTree& other) const throw()
  14767. {
  14768. return object == other.object;
  14769. }
  14770. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14771. {
  14772. return object != other.object;
  14773. }
  14774. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14775. {
  14776. return object == other.object
  14777. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14778. }
  14779. ValueTree ValueTree::createCopy() const
  14780. {
  14781. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14782. }
  14783. bool ValueTree::hasType (const Identifier& typeName) const
  14784. {
  14785. return object != 0 && object->type == typeName;
  14786. }
  14787. const Identifier ValueTree::getType() const
  14788. {
  14789. return object != 0 ? object->type : Identifier();
  14790. }
  14791. ValueTree ValueTree::getParent() const
  14792. {
  14793. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14794. }
  14795. ValueTree ValueTree::getSibling (const int delta) const
  14796. {
  14797. if (object == 0 || object->parent == 0)
  14798. return invalid;
  14799. const int index = object->parent->indexOf (*this) + delta;
  14800. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14801. }
  14802. const var& ValueTree::operator[] (const Identifier& name) const
  14803. {
  14804. return object == 0 ? var::null : object->getProperty (name);
  14805. }
  14806. const var& ValueTree::getProperty (const Identifier& name) const
  14807. {
  14808. return object == 0 ? var::null : object->getProperty (name);
  14809. }
  14810. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14811. {
  14812. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14813. }
  14814. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14815. {
  14816. jassert (name.toString().isNotEmpty());
  14817. if (object != 0 && name.toString().isNotEmpty())
  14818. object->setProperty (name, newValue, undoManager);
  14819. }
  14820. bool ValueTree::hasProperty (const Identifier& name) const
  14821. {
  14822. return object != 0 && object->hasProperty (name);
  14823. }
  14824. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14825. {
  14826. if (object != 0)
  14827. object->removeProperty (name, undoManager);
  14828. }
  14829. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14830. {
  14831. if (object != 0)
  14832. object->removeAllProperties (undoManager);
  14833. }
  14834. int ValueTree::getNumProperties() const
  14835. {
  14836. return object == 0 ? 0 : object->properties.size();
  14837. }
  14838. const Identifier ValueTree::getPropertyName (const int index) const
  14839. {
  14840. return object == 0 ? Identifier()
  14841. : object->properties.getName (index);
  14842. }
  14843. class ValueTreePropertyValueSource : public Value::ValueSource,
  14844. public ValueTree::Listener
  14845. {
  14846. public:
  14847. ValueTreePropertyValueSource (const ValueTree& tree_,
  14848. const Identifier& property_,
  14849. UndoManager* const undoManager_)
  14850. : tree (tree_),
  14851. property (property_),
  14852. undoManager (undoManager_)
  14853. {
  14854. tree.addListener (this);
  14855. }
  14856. ~ValueTreePropertyValueSource()
  14857. {
  14858. tree.removeListener (this);
  14859. }
  14860. const var getValue() const
  14861. {
  14862. return tree [property];
  14863. }
  14864. void setValue (const var& newValue)
  14865. {
  14866. tree.setProperty (property, newValue, undoManager);
  14867. }
  14868. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14869. {
  14870. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14871. sendChangeMessage (false);
  14872. }
  14873. void valueTreeChildrenChanged (ValueTree&) {}
  14874. void valueTreeParentChanged (ValueTree&) {}
  14875. private:
  14876. ValueTree tree;
  14877. const Identifier property;
  14878. UndoManager* const undoManager;
  14879. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14880. };
  14881. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14882. {
  14883. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14884. }
  14885. int ValueTree::getNumChildren() const
  14886. {
  14887. return object == 0 ? 0 : object->children.size();
  14888. }
  14889. ValueTree ValueTree::getChild (int index) const
  14890. {
  14891. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14892. }
  14893. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14894. {
  14895. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14896. }
  14897. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14898. {
  14899. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14900. }
  14901. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14902. {
  14903. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14904. }
  14905. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14906. {
  14907. return object != 0 && object->isAChildOf (possibleParent.object);
  14908. }
  14909. int ValueTree::indexOf (const ValueTree& child) const
  14910. {
  14911. return object != 0 ? object->indexOf (child) : -1;
  14912. }
  14913. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14914. {
  14915. if (object != 0)
  14916. object->addChild (child.object, index, undoManager);
  14917. }
  14918. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14919. {
  14920. if (object != 0)
  14921. object->removeChild (childIndex, undoManager);
  14922. }
  14923. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14924. {
  14925. if (object != 0)
  14926. object->removeChild (object->children.indexOf (child.object), undoManager);
  14927. }
  14928. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14929. {
  14930. if (object != 0)
  14931. object->removeAllChildren (undoManager);
  14932. }
  14933. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14934. {
  14935. if (object != 0)
  14936. object->moveChild (currentIndex, newIndex, undoManager);
  14937. }
  14938. void ValueTree::addListener (Listener* listener)
  14939. {
  14940. if (listener != 0)
  14941. {
  14942. if (listeners.size() == 0 && object != 0)
  14943. object->valueTreesWithListeners.add (this);
  14944. listeners.add (listener);
  14945. }
  14946. }
  14947. void ValueTree::removeListener (Listener* listener)
  14948. {
  14949. listeners.remove (listener);
  14950. if (listeners.size() == 0 && object != 0)
  14951. object->valueTreesWithListeners.removeValue (this);
  14952. }
  14953. XmlElement* ValueTree::SharedObject::createXml() const
  14954. {
  14955. XmlElement* xml = new XmlElement (type.toString());
  14956. int i;
  14957. for (i = 0; i < properties.size(); ++i)
  14958. {
  14959. Identifier name (properties.getName(i));
  14960. const var& v = properties [name];
  14961. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14962. xml->setAttribute (name.toString(), v.toString());
  14963. }
  14964. for (i = 0; i < children.size(); ++i)
  14965. xml->addChildElement (children.getUnchecked(i)->createXml());
  14966. return xml;
  14967. }
  14968. XmlElement* ValueTree::createXml() const
  14969. {
  14970. return object != 0 ? object->createXml() : 0;
  14971. }
  14972. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14973. {
  14974. ValueTree v (xml.getTagName());
  14975. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14976. for (int i = 0; i < numAtts; ++i)
  14977. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14978. forEachXmlChildElement (xml, e)
  14979. {
  14980. v.addChild (fromXml (*e), -1, 0);
  14981. }
  14982. return v;
  14983. }
  14984. void ValueTree::writeToStream (OutputStream& output)
  14985. {
  14986. output.writeString (getType().toString());
  14987. const int numProps = getNumProperties();
  14988. output.writeCompressedInt (numProps);
  14989. int i;
  14990. for (i = 0; i < numProps; ++i)
  14991. {
  14992. const Identifier name (getPropertyName(i));
  14993. output.writeString (name.toString());
  14994. getProperty(name).writeToStream (output);
  14995. }
  14996. const int numChildren = getNumChildren();
  14997. output.writeCompressedInt (numChildren);
  14998. for (i = 0; i < numChildren; ++i)
  14999. getChild (i).writeToStream (output);
  15000. }
  15001. ValueTree ValueTree::readFromStream (InputStream& input)
  15002. {
  15003. const String type (input.readString());
  15004. if (type.isEmpty())
  15005. return ValueTree::invalid;
  15006. ValueTree v (type);
  15007. const int numProps = input.readCompressedInt();
  15008. if (numProps < 0)
  15009. {
  15010. jassertfalse; // trying to read corrupted data!
  15011. return v;
  15012. }
  15013. int i;
  15014. for (i = 0; i < numProps; ++i)
  15015. {
  15016. const String name (input.readString());
  15017. jassert (name.isNotEmpty());
  15018. const var value (var::readFromStream (input));
  15019. v.setProperty (name, value, 0);
  15020. }
  15021. const int numChildren = input.readCompressedInt();
  15022. for (i = 0; i < numChildren; ++i)
  15023. v.addChild (readFromStream (input), -1, 0);
  15024. return v;
  15025. }
  15026. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15027. {
  15028. MemoryInputStream in (data, numBytes, false);
  15029. return readFromStream (in);
  15030. }
  15031. END_JUCE_NAMESPACE
  15032. /*** End of inlined file: juce_ValueTree.cpp ***/
  15033. /*** Start of inlined file: juce_Value.cpp ***/
  15034. BEGIN_JUCE_NAMESPACE
  15035. Value::ValueSource::ValueSource()
  15036. {
  15037. }
  15038. Value::ValueSource::~ValueSource()
  15039. {
  15040. }
  15041. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15042. {
  15043. if (synchronous)
  15044. {
  15045. for (int i = valuesWithListeners.size(); --i >= 0;)
  15046. {
  15047. Value* const v = valuesWithListeners[i];
  15048. if (v != 0)
  15049. v->callListeners();
  15050. }
  15051. }
  15052. else
  15053. {
  15054. triggerAsyncUpdate();
  15055. }
  15056. }
  15057. void Value::ValueSource::handleAsyncUpdate()
  15058. {
  15059. sendChangeMessage (true);
  15060. }
  15061. class SimpleValueSource : public Value::ValueSource
  15062. {
  15063. public:
  15064. SimpleValueSource()
  15065. {
  15066. }
  15067. SimpleValueSource (const var& initialValue)
  15068. : value (initialValue)
  15069. {
  15070. }
  15071. ~SimpleValueSource()
  15072. {
  15073. }
  15074. const var getValue() const
  15075. {
  15076. return value;
  15077. }
  15078. void setValue (const var& newValue)
  15079. {
  15080. if (newValue != value)
  15081. {
  15082. value = newValue;
  15083. sendChangeMessage (false);
  15084. }
  15085. }
  15086. private:
  15087. var value;
  15088. SimpleValueSource (const SimpleValueSource&);
  15089. SimpleValueSource& operator= (const SimpleValueSource&);
  15090. };
  15091. Value::Value()
  15092. : value (new SimpleValueSource())
  15093. {
  15094. }
  15095. Value::Value (ValueSource* const value_)
  15096. : value (value_)
  15097. {
  15098. jassert (value_ != 0);
  15099. }
  15100. Value::Value (const var& initialValue)
  15101. : value (new SimpleValueSource (initialValue))
  15102. {
  15103. }
  15104. Value::Value (const Value& other)
  15105. : value (other.value)
  15106. {
  15107. }
  15108. Value& Value::operator= (const Value& other)
  15109. {
  15110. value = other.value;
  15111. return *this;
  15112. }
  15113. Value::~Value()
  15114. {
  15115. if (listeners.size() > 0)
  15116. value->valuesWithListeners.removeValue (this);
  15117. }
  15118. const var Value::getValue() const
  15119. {
  15120. return value->getValue();
  15121. }
  15122. Value::operator const var() const
  15123. {
  15124. return getValue();
  15125. }
  15126. void Value::setValue (const var& newValue)
  15127. {
  15128. value->setValue (newValue);
  15129. }
  15130. const String Value::toString() const
  15131. {
  15132. return value->getValue().toString();
  15133. }
  15134. Value& Value::operator= (const var& newValue)
  15135. {
  15136. value->setValue (newValue);
  15137. return *this;
  15138. }
  15139. void Value::referTo (const Value& valueToReferTo)
  15140. {
  15141. if (valueToReferTo.value != value)
  15142. {
  15143. if (listeners.size() > 0)
  15144. {
  15145. value->valuesWithListeners.removeValue (this);
  15146. valueToReferTo.value->valuesWithListeners.add (this);
  15147. }
  15148. value = valueToReferTo.value;
  15149. callListeners();
  15150. }
  15151. }
  15152. bool Value::refersToSameSourceAs (const Value& other) const
  15153. {
  15154. return value == other.value;
  15155. }
  15156. bool Value::operator== (const Value& other) const
  15157. {
  15158. return value == other.value || value->getValue() == other.getValue();
  15159. }
  15160. bool Value::operator!= (const Value& other) const
  15161. {
  15162. return value != other.value && value->getValue() != other.getValue();
  15163. }
  15164. void Value::addListener (Listener* const listener)
  15165. {
  15166. if (listener != 0)
  15167. {
  15168. if (listeners.size() == 0)
  15169. value->valuesWithListeners.add (this);
  15170. listeners.add (listener);
  15171. }
  15172. }
  15173. void Value::removeListener (Listener* const listener)
  15174. {
  15175. listeners.remove (listener);
  15176. if (listeners.size() == 0)
  15177. value->valuesWithListeners.removeValue (this);
  15178. }
  15179. void Value::callListeners()
  15180. {
  15181. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15182. listeners.call (&Value::Listener::valueChanged, v);
  15183. }
  15184. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15185. {
  15186. return stream << value.toString();
  15187. }
  15188. END_JUCE_NAMESPACE
  15189. /*** End of inlined file: juce_Value.cpp ***/
  15190. /*** Start of inlined file: juce_Application.cpp ***/
  15191. BEGIN_JUCE_NAMESPACE
  15192. #if JUCE_MAC
  15193. extern void juce_initialiseMacMainMenu();
  15194. #endif
  15195. JUCEApplication::JUCEApplication()
  15196. : appReturnValue (0),
  15197. stillInitialising (true)
  15198. {
  15199. jassert (isStandaloneApp() && appInstance == 0);
  15200. appInstance = this;
  15201. }
  15202. JUCEApplication::~JUCEApplication()
  15203. {
  15204. if (appLock != 0)
  15205. {
  15206. appLock->exit();
  15207. appLock = 0;
  15208. }
  15209. jassert (appInstance == this);
  15210. appInstance = 0;
  15211. }
  15212. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15213. JUCEApplication* JUCEApplication::appInstance = 0;
  15214. bool JUCEApplication::moreThanOneInstanceAllowed()
  15215. {
  15216. return true;
  15217. }
  15218. void JUCEApplication::anotherInstanceStarted (const String&)
  15219. {
  15220. }
  15221. void JUCEApplication::systemRequestedQuit()
  15222. {
  15223. quit();
  15224. }
  15225. void JUCEApplication::quit()
  15226. {
  15227. MessageManager::getInstance()->stopDispatchLoop();
  15228. }
  15229. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15230. {
  15231. appReturnValue = newReturnValue;
  15232. }
  15233. void JUCEApplication::actionListenerCallback (const String& message)
  15234. {
  15235. if (message.startsWith (getApplicationName() + "/"))
  15236. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15237. }
  15238. void JUCEApplication::unhandledException (const std::exception*,
  15239. const String&,
  15240. const int)
  15241. {
  15242. jassertfalse;
  15243. }
  15244. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15245. const char* const sourceFile,
  15246. const int lineNumber)
  15247. {
  15248. if (appInstance != 0)
  15249. appInstance->unhandledException (e, sourceFile, lineNumber);
  15250. }
  15251. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15252. {
  15253. return 0;
  15254. }
  15255. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15256. {
  15257. commands.add (StandardApplicationCommandIDs::quit);
  15258. }
  15259. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15260. {
  15261. if (commandID == StandardApplicationCommandIDs::quit)
  15262. {
  15263. result.setInfo (TRANS("Quit"),
  15264. TRANS("Quits the application"),
  15265. "Application",
  15266. 0);
  15267. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15268. }
  15269. }
  15270. bool JUCEApplication::perform (const InvocationInfo& info)
  15271. {
  15272. if (info.commandID == StandardApplicationCommandIDs::quit)
  15273. {
  15274. systemRequestedQuit();
  15275. return true;
  15276. }
  15277. return false;
  15278. }
  15279. bool JUCEApplication::initialiseApp (const String& commandLine)
  15280. {
  15281. commandLineParameters = commandLine.trim();
  15282. #if ! JUCE_IOS
  15283. jassert (appLock == 0); // initialiseApp must only be called once!
  15284. if (! moreThanOneInstanceAllowed())
  15285. {
  15286. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15287. if (! appLock->enter(0))
  15288. {
  15289. appLock = 0;
  15290. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15291. DBG ("Another instance is running - quitting...");
  15292. return false;
  15293. }
  15294. }
  15295. #endif
  15296. // let the app do its setting-up..
  15297. initialise (commandLineParameters);
  15298. #if JUCE_MAC
  15299. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15300. #endif
  15301. // register for broadcast new app messages
  15302. MessageManager::getInstance()->registerBroadcastListener (this);
  15303. stillInitialising = false;
  15304. return true;
  15305. }
  15306. int JUCEApplication::shutdownApp()
  15307. {
  15308. jassert (appInstance == this);
  15309. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15310. JUCE_TRY
  15311. {
  15312. // give the app a chance to clean up..
  15313. shutdown();
  15314. }
  15315. JUCE_CATCH_EXCEPTION
  15316. return getApplicationReturnValue();
  15317. }
  15318. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15319. void JUCEApplication::appWillTerminateByForce()
  15320. {
  15321. {
  15322. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15323. if (app != 0)
  15324. app->shutdownApp();
  15325. }
  15326. shutdownJuce_GUI();
  15327. }
  15328. int JUCEApplication::main (const String& commandLine)
  15329. {
  15330. ScopedJuceInitialiser_GUI libraryInitialiser;
  15331. jassert (createInstance != 0);
  15332. int returnCode = 0;
  15333. {
  15334. const ScopedPointer<JUCEApplication> app (createInstance());
  15335. if (! app->initialiseApp (commandLine))
  15336. return 0;
  15337. JUCE_TRY
  15338. {
  15339. // loop until a quit message is received..
  15340. MessageManager::getInstance()->runDispatchLoop();
  15341. }
  15342. JUCE_CATCH_EXCEPTION
  15343. returnCode = app->shutdownApp();
  15344. }
  15345. return returnCode;
  15346. }
  15347. #if JUCE_IOS
  15348. extern int juce_iOSMain (int argc, const char* argv[]);
  15349. #endif
  15350. #if ! JUCE_WINDOWS
  15351. extern const char* juce_Argv0;
  15352. #endif
  15353. int JUCEApplication::main (int argc, const char* argv[])
  15354. {
  15355. JUCE_AUTORELEASEPOOL
  15356. #if ! JUCE_WINDOWS
  15357. jassert (createInstance != 0);
  15358. juce_Argv0 = argv[0];
  15359. #endif
  15360. #if JUCE_IOS
  15361. return juce_iOSMain (argc, argv);
  15362. #else
  15363. String cmd;
  15364. for (int i = 1; i < argc; ++i)
  15365. cmd << argv[i] << ' ';
  15366. return JUCEApplication::main (cmd);
  15367. #endif
  15368. }
  15369. END_JUCE_NAMESPACE
  15370. /*** End of inlined file: juce_Application.cpp ***/
  15371. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15372. BEGIN_JUCE_NAMESPACE
  15373. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15374. : commandID (commandID_),
  15375. flags (0)
  15376. {
  15377. }
  15378. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15379. const String& description_,
  15380. const String& categoryName_,
  15381. const int flags_) throw()
  15382. {
  15383. shortName = shortName_;
  15384. description = description_;
  15385. categoryName = categoryName_;
  15386. flags = flags_;
  15387. }
  15388. void ApplicationCommandInfo::setActive (const bool b) throw()
  15389. {
  15390. if (b)
  15391. flags &= ~isDisabled;
  15392. else
  15393. flags |= isDisabled;
  15394. }
  15395. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15396. {
  15397. if (b)
  15398. flags |= isTicked;
  15399. else
  15400. flags &= ~isTicked;
  15401. }
  15402. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15403. {
  15404. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15405. }
  15406. END_JUCE_NAMESPACE
  15407. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15408. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15409. BEGIN_JUCE_NAMESPACE
  15410. ApplicationCommandManager::ApplicationCommandManager()
  15411. : firstTarget (0)
  15412. {
  15413. keyMappings = new KeyPressMappingSet (this);
  15414. Desktop::getInstance().addFocusChangeListener (this);
  15415. }
  15416. ApplicationCommandManager::~ApplicationCommandManager()
  15417. {
  15418. Desktop::getInstance().removeFocusChangeListener (this);
  15419. keyMappings = 0;
  15420. }
  15421. void ApplicationCommandManager::clearCommands()
  15422. {
  15423. commands.clear();
  15424. keyMappings->clearAllKeyPresses();
  15425. triggerAsyncUpdate();
  15426. }
  15427. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15428. {
  15429. // zero isn't a valid command ID!
  15430. jassert (newCommand.commandID != 0);
  15431. // the name isn't optional!
  15432. jassert (newCommand.shortName.isNotEmpty());
  15433. if (getCommandForID (newCommand.commandID) == 0)
  15434. {
  15435. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15436. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15437. commands.add (newInfo);
  15438. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15439. triggerAsyncUpdate();
  15440. }
  15441. else
  15442. {
  15443. // trying to re-register the same command with different parameters?
  15444. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15445. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15446. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15447. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15448. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15449. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15450. }
  15451. }
  15452. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15453. {
  15454. if (target != 0)
  15455. {
  15456. Array <CommandID> commandIDs;
  15457. target->getAllCommands (commandIDs);
  15458. for (int i = 0; i < commandIDs.size(); ++i)
  15459. {
  15460. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15461. target->getCommandInfo (info.commandID, info);
  15462. registerCommand (info);
  15463. }
  15464. }
  15465. }
  15466. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15467. {
  15468. for (int i = commands.size(); --i >= 0;)
  15469. {
  15470. if (commands.getUnchecked (i)->commandID == commandID)
  15471. {
  15472. commands.remove (i);
  15473. triggerAsyncUpdate();
  15474. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15475. for (int j = keys.size(); --j >= 0;)
  15476. keyMappings->removeKeyPress (keys.getReference (j));
  15477. }
  15478. }
  15479. }
  15480. void ApplicationCommandManager::commandStatusChanged()
  15481. {
  15482. triggerAsyncUpdate();
  15483. }
  15484. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15485. {
  15486. for (int i = commands.size(); --i >= 0;)
  15487. if (commands.getUnchecked(i)->commandID == commandID)
  15488. return commands.getUnchecked(i);
  15489. return 0;
  15490. }
  15491. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15492. {
  15493. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15494. return (ci != 0) ? ci->shortName : String::empty;
  15495. }
  15496. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15497. {
  15498. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15499. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15500. : String::empty;
  15501. }
  15502. const StringArray ApplicationCommandManager::getCommandCategories() const
  15503. {
  15504. StringArray s;
  15505. for (int i = 0; i < commands.size(); ++i)
  15506. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15507. return s;
  15508. }
  15509. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15510. {
  15511. Array <CommandID> results;
  15512. for (int i = 0; i < commands.size(); ++i)
  15513. if (commands.getUnchecked(i)->categoryName == categoryName)
  15514. results.add (commands.getUnchecked(i)->commandID);
  15515. return results;
  15516. }
  15517. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15518. {
  15519. ApplicationCommandTarget::InvocationInfo info (commandID);
  15520. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15521. return invoke (info, asynchronously);
  15522. }
  15523. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15524. {
  15525. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15526. // manager first..
  15527. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15528. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15529. if (target == 0)
  15530. return false;
  15531. ApplicationCommandInfo commandInfo (0);
  15532. target->getCommandInfo (info_.commandID, commandInfo);
  15533. ApplicationCommandTarget::InvocationInfo info (info_);
  15534. info.commandFlags = commandInfo.flags;
  15535. sendListenerInvokeCallback (info);
  15536. const bool ok = target->invoke (info, asynchronously);
  15537. commandStatusChanged();
  15538. return ok;
  15539. }
  15540. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15541. {
  15542. return firstTarget != 0 ? firstTarget
  15543. : findDefaultComponentTarget();
  15544. }
  15545. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15546. {
  15547. firstTarget = newTarget;
  15548. }
  15549. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15550. ApplicationCommandInfo& upToDateInfo)
  15551. {
  15552. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15553. if (target == 0)
  15554. target = JUCEApplication::getInstance();
  15555. if (target != 0)
  15556. target = target->getTargetForCommand (commandID);
  15557. if (target != 0)
  15558. target->getCommandInfo (commandID, upToDateInfo);
  15559. return target;
  15560. }
  15561. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15562. {
  15563. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15564. if (target == 0 && c != 0)
  15565. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15566. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15567. return target;
  15568. }
  15569. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15570. {
  15571. Component* c = Component::getCurrentlyFocusedComponent();
  15572. if (c == 0)
  15573. {
  15574. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15575. if (activeWindow != 0)
  15576. {
  15577. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15578. if (c == 0)
  15579. c = activeWindow;
  15580. }
  15581. }
  15582. if (c == 0 && Process::isForegroundProcess())
  15583. {
  15584. // getting a bit desperate now - try all desktop comps..
  15585. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15586. {
  15587. ApplicationCommandTarget* const target
  15588. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15589. ->getPeer()->getLastFocusedSubcomponent());
  15590. if (target != 0)
  15591. return target;
  15592. }
  15593. }
  15594. if (c != 0)
  15595. {
  15596. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15597. // if we're focused on a ResizableWindow, chances are that it's the content
  15598. // component that really should get the event. And if not, the event will
  15599. // still be passed up to the top level window anyway, so let's send it to the
  15600. // content comp.
  15601. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15602. c = resizableWindow->getContentComponent();
  15603. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15604. if (target != 0)
  15605. return target;
  15606. }
  15607. return JUCEApplication::getInstance();
  15608. }
  15609. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15610. {
  15611. listeners.add (listener);
  15612. }
  15613. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15614. {
  15615. listeners.remove (listener);
  15616. }
  15617. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15618. {
  15619. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15620. }
  15621. void ApplicationCommandManager::handleAsyncUpdate()
  15622. {
  15623. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15624. }
  15625. void ApplicationCommandManager::globalFocusChanged (Component*)
  15626. {
  15627. commandStatusChanged();
  15628. }
  15629. END_JUCE_NAMESPACE
  15630. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15631. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15632. BEGIN_JUCE_NAMESPACE
  15633. ApplicationCommandTarget::ApplicationCommandTarget()
  15634. {
  15635. }
  15636. ApplicationCommandTarget::~ApplicationCommandTarget()
  15637. {
  15638. messageInvoker = 0;
  15639. }
  15640. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15641. {
  15642. if (isCommandActive (info.commandID))
  15643. {
  15644. if (async)
  15645. {
  15646. if (messageInvoker == 0)
  15647. messageInvoker = new CommandTargetMessageInvoker (this);
  15648. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15649. return true;
  15650. }
  15651. else
  15652. {
  15653. const bool success = perform (info);
  15654. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15655. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15656. // returns the command's info.
  15657. return success;
  15658. }
  15659. }
  15660. return false;
  15661. }
  15662. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15663. {
  15664. Component* c = dynamic_cast <Component*> (this);
  15665. if (c != 0)
  15666. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15667. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15668. return 0;
  15669. }
  15670. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15671. {
  15672. ApplicationCommandTarget* target = this;
  15673. int depth = 0;
  15674. while (target != 0)
  15675. {
  15676. Array <CommandID> commandIDs;
  15677. target->getAllCommands (commandIDs);
  15678. if (commandIDs.contains (commandID))
  15679. return target;
  15680. target = target->getNextCommandTarget();
  15681. ++depth;
  15682. jassert (depth < 100); // could be a recursive command chain??
  15683. jassert (target != this); // definitely a recursive command chain!
  15684. if (depth > 100 || target == this)
  15685. break;
  15686. }
  15687. if (target == 0)
  15688. {
  15689. target = JUCEApplication::getInstance();
  15690. if (target != 0)
  15691. {
  15692. Array <CommandID> commandIDs;
  15693. target->getAllCommands (commandIDs);
  15694. if (commandIDs.contains (commandID))
  15695. return target;
  15696. }
  15697. }
  15698. return 0;
  15699. }
  15700. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15701. {
  15702. ApplicationCommandInfo info (commandID);
  15703. info.flags = ApplicationCommandInfo::isDisabled;
  15704. getCommandInfo (commandID, info);
  15705. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15706. }
  15707. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15708. {
  15709. ApplicationCommandTarget* target = this;
  15710. int depth = 0;
  15711. while (target != 0)
  15712. {
  15713. if (target->tryToInvoke (info, async))
  15714. return true;
  15715. target = target->getNextCommandTarget();
  15716. ++depth;
  15717. jassert (depth < 100); // could be a recursive command chain??
  15718. jassert (target != this); // definitely a recursive command chain!
  15719. if (depth > 100 || target == this)
  15720. break;
  15721. }
  15722. if (target == 0)
  15723. {
  15724. target = JUCEApplication::getInstance();
  15725. if (target != 0)
  15726. return target->tryToInvoke (info, async);
  15727. }
  15728. return false;
  15729. }
  15730. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15731. {
  15732. ApplicationCommandTarget::InvocationInfo info (commandID);
  15733. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15734. return invoke (info, asynchronously);
  15735. }
  15736. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15737. : commandID (commandID_),
  15738. commandFlags (0),
  15739. invocationMethod (direct),
  15740. originatingComponent (0),
  15741. isKeyDown (false),
  15742. millisecsSinceKeyPressed (0)
  15743. {
  15744. }
  15745. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15746. : owner (owner_)
  15747. {
  15748. }
  15749. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15750. {
  15751. }
  15752. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15753. {
  15754. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15755. owner->tryToInvoke (*info, false);
  15756. }
  15757. END_JUCE_NAMESPACE
  15758. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15759. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15760. BEGIN_JUCE_NAMESPACE
  15761. juce_ImplementSingleton (ApplicationProperties)
  15762. ApplicationProperties::ApplicationProperties()
  15763. : msBeforeSaving (3000),
  15764. options (PropertiesFile::storeAsBinary),
  15765. commonSettingsAreReadOnly (0),
  15766. processLock (0)
  15767. {
  15768. }
  15769. ApplicationProperties::~ApplicationProperties()
  15770. {
  15771. closeFiles();
  15772. clearSingletonInstance();
  15773. }
  15774. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15775. const String& fileNameSuffix,
  15776. const String& folderName_,
  15777. const int millisecondsBeforeSaving,
  15778. const int propertiesFileOptions,
  15779. InterProcessLock* processLock_)
  15780. {
  15781. appName = applicationName;
  15782. fileSuffix = fileNameSuffix;
  15783. folderName = folderName_;
  15784. msBeforeSaving = millisecondsBeforeSaving;
  15785. options = propertiesFileOptions;
  15786. processLock = processLock_;
  15787. }
  15788. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15789. const bool testCommonSettings,
  15790. const bool showWarningDialogOnFailure)
  15791. {
  15792. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15793. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15794. if (! (userOk && commonOk))
  15795. {
  15796. if (showWarningDialogOnFailure)
  15797. {
  15798. String filenames;
  15799. if (userProps != 0 && ! userOk)
  15800. filenames << '\n' << userProps->getFile().getFullPathName();
  15801. if (commonProps != 0 && ! commonOk)
  15802. filenames << '\n' << commonProps->getFile().getFullPathName();
  15803. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15804. appName + TRANS(" - Unable to save settings"),
  15805. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15806. + appName + TRANS(" needs to be able to write to the following files:\n")
  15807. + filenames
  15808. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15809. }
  15810. return false;
  15811. }
  15812. return true;
  15813. }
  15814. void ApplicationProperties::openFiles()
  15815. {
  15816. // You need to call setStorageParameters() before trying to get hold of the
  15817. // properties!
  15818. jassert (appName.isNotEmpty());
  15819. if (appName.isNotEmpty())
  15820. {
  15821. if (userProps == 0)
  15822. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15823. false, msBeforeSaving, options, processLock);
  15824. if (commonProps == 0)
  15825. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15826. true, msBeforeSaving, options, processLock);
  15827. userProps->setFallbackPropertySet (commonProps);
  15828. }
  15829. }
  15830. PropertiesFile* ApplicationProperties::getUserSettings()
  15831. {
  15832. if (userProps == 0)
  15833. openFiles();
  15834. return userProps;
  15835. }
  15836. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15837. {
  15838. if (commonProps == 0)
  15839. openFiles();
  15840. if (returnUserPropsIfReadOnly)
  15841. {
  15842. if (commonSettingsAreReadOnly == 0)
  15843. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15844. if (commonSettingsAreReadOnly > 0)
  15845. return userProps;
  15846. }
  15847. return commonProps;
  15848. }
  15849. bool ApplicationProperties::saveIfNeeded()
  15850. {
  15851. return (userProps == 0 || userProps->saveIfNeeded())
  15852. && (commonProps == 0 || commonProps->saveIfNeeded());
  15853. }
  15854. void ApplicationProperties::closeFiles()
  15855. {
  15856. userProps = 0;
  15857. commonProps = 0;
  15858. }
  15859. END_JUCE_NAMESPACE
  15860. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15861. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15862. BEGIN_JUCE_NAMESPACE
  15863. namespace PropertyFileConstants
  15864. {
  15865. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15866. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15867. static const char* const fileTag = "PROPERTIES";
  15868. static const char* const valueTag = "VALUE";
  15869. static const char* const nameAttribute = "name";
  15870. static const char* const valueAttribute = "val";
  15871. }
  15872. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15873. const int options_, InterProcessLock* const processLock_)
  15874. : PropertySet (ignoreCaseOfKeyNames),
  15875. file (f),
  15876. timerInterval (millisecondsBeforeSaving),
  15877. options (options_),
  15878. loadedOk (false),
  15879. needsWriting (false),
  15880. processLock (processLock_)
  15881. {
  15882. // You need to correctly specify just one storage format for the file
  15883. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15884. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15885. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15886. ProcessScopedLock pl (createProcessLock());
  15887. if (pl != 0 && ! pl->isLocked())
  15888. return; // locking failure..
  15889. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15890. if (fileStream != 0)
  15891. {
  15892. int magicNumber = fileStream->readInt();
  15893. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15894. {
  15895. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15896. magicNumber = PropertyFileConstants::magicNumber;
  15897. }
  15898. if (magicNumber == PropertyFileConstants::magicNumber)
  15899. {
  15900. loadedOk = true;
  15901. BufferedInputStream in (fileStream.release(), 2048, true);
  15902. int numValues = in.readInt();
  15903. while (--numValues >= 0 && ! in.isExhausted())
  15904. {
  15905. const String key (in.readString());
  15906. const String value (in.readString());
  15907. jassert (key.isNotEmpty());
  15908. if (key.isNotEmpty())
  15909. getAllProperties().set (key, value);
  15910. }
  15911. }
  15912. else
  15913. {
  15914. // Not a binary props file - let's see if it's XML..
  15915. fileStream = 0;
  15916. XmlDocument parser (f);
  15917. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15918. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15919. {
  15920. doc = parser.getDocumentElement();
  15921. if (doc != 0)
  15922. {
  15923. loadedOk = true;
  15924. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15925. {
  15926. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15927. if (name.isNotEmpty())
  15928. {
  15929. getAllProperties().set (name,
  15930. e->getFirstChildElement() != 0
  15931. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15932. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15933. }
  15934. }
  15935. }
  15936. else
  15937. {
  15938. // must be a pretty broken XML file we're trying to parse here,
  15939. // or a sign that this object needs an InterProcessLock,
  15940. // or just a failure reading the file. This last reason is why
  15941. // we don't jassertfalse here.
  15942. }
  15943. }
  15944. }
  15945. }
  15946. else
  15947. {
  15948. loadedOk = ! f.exists();
  15949. }
  15950. }
  15951. PropertiesFile::~PropertiesFile()
  15952. {
  15953. if (! saveIfNeeded())
  15954. jassertfalse;
  15955. }
  15956. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15957. {
  15958. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15959. }
  15960. bool PropertiesFile::saveIfNeeded()
  15961. {
  15962. const ScopedLock sl (getLock());
  15963. return (! needsWriting) || save();
  15964. }
  15965. bool PropertiesFile::needsToBeSaved() const
  15966. {
  15967. const ScopedLock sl (getLock());
  15968. return needsWriting;
  15969. }
  15970. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15971. {
  15972. const ScopedLock sl (getLock());
  15973. needsWriting = needsToBeSaved_;
  15974. }
  15975. bool PropertiesFile::save()
  15976. {
  15977. const ScopedLock sl (getLock());
  15978. stopTimer();
  15979. if (file == File::nonexistent
  15980. || file.isDirectory()
  15981. || ! file.getParentDirectory().createDirectory())
  15982. return false;
  15983. if ((options & storeAsXML) != 0)
  15984. {
  15985. XmlElement doc (PropertyFileConstants::fileTag);
  15986. for (int i = 0; i < getAllProperties().size(); ++i)
  15987. {
  15988. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15989. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15990. // if the value seems to contain xml, store it as such..
  15991. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  15992. XmlElement* const childElement = xmlContent.getDocumentElement();
  15993. if (childElement != 0)
  15994. e->addChildElement (childElement);
  15995. else
  15996. e->setAttribute (PropertyFileConstants::valueAttribute,
  15997. getAllProperties().getAllValues() [i]);
  15998. }
  15999. ProcessScopedLock pl (createProcessLock());
  16000. if (pl != 0 && ! pl->isLocked())
  16001. return false; // locking failure..
  16002. if (doc.writeToFile (file, String::empty))
  16003. {
  16004. needsWriting = false;
  16005. return true;
  16006. }
  16007. }
  16008. else
  16009. {
  16010. ProcessScopedLock pl (createProcessLock());
  16011. if (pl != 0 && ! pl->isLocked())
  16012. return false; // locking failure..
  16013. TemporaryFile tempFile (file);
  16014. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16015. if (out != 0)
  16016. {
  16017. if ((options & storeAsCompressedBinary) != 0)
  16018. {
  16019. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16020. out->flush();
  16021. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16022. }
  16023. else
  16024. {
  16025. // have you set up the storage option flags correctly?
  16026. jassert ((options & storeAsBinary) != 0);
  16027. out->writeInt (PropertyFileConstants::magicNumber);
  16028. }
  16029. const int numProperties = getAllProperties().size();
  16030. out->writeInt (numProperties);
  16031. for (int i = 0; i < numProperties; ++i)
  16032. {
  16033. out->writeString (getAllProperties().getAllKeys() [i]);
  16034. out->writeString (getAllProperties().getAllValues() [i]);
  16035. }
  16036. out = 0;
  16037. if (tempFile.overwriteTargetFileWithTemporary())
  16038. {
  16039. needsWriting = false;
  16040. return true;
  16041. }
  16042. }
  16043. }
  16044. return false;
  16045. }
  16046. void PropertiesFile::timerCallback()
  16047. {
  16048. saveIfNeeded();
  16049. }
  16050. void PropertiesFile::propertyChanged()
  16051. {
  16052. sendChangeMessage (this);
  16053. needsWriting = true;
  16054. if (timerInterval > 0)
  16055. startTimer (timerInterval);
  16056. else if (timerInterval == 0)
  16057. saveIfNeeded();
  16058. }
  16059. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16060. const String& fileNameSuffix,
  16061. const String& folderName,
  16062. const bool commonToAllUsers)
  16063. {
  16064. // mustn't have illegal characters in this name..
  16065. jassert (applicationName == File::createLegalFileName (applicationName));
  16066. #if JUCE_MAC || JUCE_IOS
  16067. File dir (commonToAllUsers ? "/Library/Preferences"
  16068. : "~/Library/Preferences");
  16069. if (folderName.isNotEmpty())
  16070. dir = dir.getChildFile (folderName);
  16071. #endif
  16072. #ifdef JUCE_LINUX
  16073. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16074. + (folderName.isNotEmpty() ? folderName
  16075. : ("." + applicationName)));
  16076. #endif
  16077. #if JUCE_WINDOWS
  16078. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16079. : File::userApplicationDataDirectory));
  16080. if (dir == File::nonexistent)
  16081. return File::nonexistent;
  16082. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16083. : applicationName);
  16084. #endif
  16085. return dir.getChildFile (applicationName)
  16086. .withFileExtension (fileNameSuffix);
  16087. }
  16088. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16089. const String& fileNameSuffix,
  16090. const String& folderName,
  16091. const bool commonToAllUsers,
  16092. const int millisecondsBeforeSaving,
  16093. const int propertiesFileOptions,
  16094. InterProcessLock* processLock_)
  16095. {
  16096. const File file (getDefaultAppSettingsFile (applicationName,
  16097. fileNameSuffix,
  16098. folderName,
  16099. commonToAllUsers));
  16100. jassert (file != File::nonexistent);
  16101. if (file == File::nonexistent)
  16102. return 0;
  16103. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16104. }
  16105. END_JUCE_NAMESPACE
  16106. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16107. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16108. BEGIN_JUCE_NAMESPACE
  16109. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16110. const String& fileWildcard_,
  16111. const String& openFileDialogTitle_,
  16112. const String& saveFileDialogTitle_)
  16113. : changedSinceSave (false),
  16114. fileExtension (fileExtension_),
  16115. fileWildcard (fileWildcard_),
  16116. openFileDialogTitle (openFileDialogTitle_),
  16117. saveFileDialogTitle (saveFileDialogTitle_)
  16118. {
  16119. }
  16120. FileBasedDocument::~FileBasedDocument()
  16121. {
  16122. }
  16123. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16124. {
  16125. if (changedSinceSave != hasChanged)
  16126. {
  16127. changedSinceSave = hasChanged;
  16128. sendChangeMessage (this);
  16129. }
  16130. }
  16131. void FileBasedDocument::changed()
  16132. {
  16133. changedSinceSave = true;
  16134. sendChangeMessage (this);
  16135. }
  16136. void FileBasedDocument::setFile (const File& newFile)
  16137. {
  16138. if (documentFile != newFile)
  16139. {
  16140. documentFile = newFile;
  16141. changed();
  16142. }
  16143. }
  16144. bool FileBasedDocument::loadFrom (const File& newFile,
  16145. const bool showMessageOnFailure)
  16146. {
  16147. MouseCursor::showWaitCursor();
  16148. const File oldFile (documentFile);
  16149. documentFile = newFile;
  16150. String error;
  16151. if (newFile.existsAsFile())
  16152. {
  16153. error = loadDocument (newFile);
  16154. if (error.isEmpty())
  16155. {
  16156. setChangedFlag (false);
  16157. MouseCursor::hideWaitCursor();
  16158. setLastDocumentOpened (newFile);
  16159. return true;
  16160. }
  16161. }
  16162. else
  16163. {
  16164. error = "The file doesn't exist";
  16165. }
  16166. documentFile = oldFile;
  16167. MouseCursor::hideWaitCursor();
  16168. if (showMessageOnFailure)
  16169. {
  16170. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16171. TRANS("Failed to open file..."),
  16172. TRANS("There was an error while trying to load the file:\n\n")
  16173. + newFile.getFullPathName()
  16174. + "\n\n"
  16175. + error);
  16176. }
  16177. return false;
  16178. }
  16179. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16180. {
  16181. FileChooser fc (openFileDialogTitle,
  16182. getLastDocumentOpened(),
  16183. fileWildcard);
  16184. if (fc.browseForFileToOpen())
  16185. return loadFrom (fc.getResult(), showMessageOnFailure);
  16186. return false;
  16187. }
  16188. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16189. const bool showMessageOnFailure)
  16190. {
  16191. return saveAs (documentFile,
  16192. false,
  16193. askUserForFileIfNotSpecified,
  16194. showMessageOnFailure);
  16195. }
  16196. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16197. const bool warnAboutOverwritingExistingFiles,
  16198. const bool askUserForFileIfNotSpecified,
  16199. const bool showMessageOnFailure)
  16200. {
  16201. if (newFile == File::nonexistent)
  16202. {
  16203. if (askUserForFileIfNotSpecified)
  16204. {
  16205. return saveAsInteractive (true);
  16206. }
  16207. else
  16208. {
  16209. // can't save to an unspecified file
  16210. jassertfalse;
  16211. return failedToWriteToFile;
  16212. }
  16213. }
  16214. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16215. {
  16216. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16217. TRANS("File already exists"),
  16218. TRANS("There's already a file called:\n\n")
  16219. + newFile.getFullPathName()
  16220. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16221. TRANS("overwrite"),
  16222. TRANS("cancel")))
  16223. {
  16224. return userCancelledSave;
  16225. }
  16226. }
  16227. MouseCursor::showWaitCursor();
  16228. const File oldFile (documentFile);
  16229. documentFile = newFile;
  16230. String error (saveDocument (newFile));
  16231. if (error.isEmpty())
  16232. {
  16233. setChangedFlag (false);
  16234. MouseCursor::hideWaitCursor();
  16235. return savedOk;
  16236. }
  16237. documentFile = oldFile;
  16238. MouseCursor::hideWaitCursor();
  16239. if (showMessageOnFailure)
  16240. {
  16241. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16242. TRANS("Error writing to file..."),
  16243. TRANS("An error occurred while trying to save \"")
  16244. + getDocumentTitle()
  16245. + TRANS("\" to the file:\n\n")
  16246. + newFile.getFullPathName()
  16247. + "\n\n"
  16248. + error);
  16249. }
  16250. return failedToWriteToFile;
  16251. }
  16252. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16253. {
  16254. if (! hasChangedSinceSaved())
  16255. return savedOk;
  16256. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16257. TRANS("Closing document..."),
  16258. TRANS("Do you want to save the changes to \"")
  16259. + getDocumentTitle() + "\"?",
  16260. TRANS("save"),
  16261. TRANS("discard changes"),
  16262. TRANS("cancel"));
  16263. if (r == 1)
  16264. {
  16265. // save changes
  16266. return save (true, true);
  16267. }
  16268. else if (r == 2)
  16269. {
  16270. // discard changes
  16271. return savedOk;
  16272. }
  16273. return userCancelledSave;
  16274. }
  16275. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16276. {
  16277. File f;
  16278. if (documentFile.existsAsFile())
  16279. f = documentFile;
  16280. else
  16281. f = getLastDocumentOpened();
  16282. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16283. if (legalFilename.isEmpty())
  16284. legalFilename = "unnamed";
  16285. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16286. f = f.getSiblingFile (legalFilename);
  16287. else
  16288. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16289. f = f.withFileExtension (fileExtension)
  16290. .getNonexistentSibling (true);
  16291. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16292. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16293. {
  16294. File chosen (fc.getResult());
  16295. if (chosen.getFileExtension().isEmpty())
  16296. {
  16297. chosen = chosen.withFileExtension (fileExtension);
  16298. if (chosen.exists())
  16299. {
  16300. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16301. TRANS("File already exists"),
  16302. TRANS("There's already a file called:")
  16303. + "\n\n" + chosen.getFullPathName()
  16304. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16305. TRANS("overwrite"),
  16306. TRANS("cancel")))
  16307. {
  16308. return userCancelledSave;
  16309. }
  16310. }
  16311. }
  16312. setLastDocumentOpened (chosen);
  16313. return saveAs (chosen, false, false, true);
  16314. }
  16315. return userCancelledSave;
  16316. }
  16317. END_JUCE_NAMESPACE
  16318. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16319. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16320. BEGIN_JUCE_NAMESPACE
  16321. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16322. : maxNumberOfItems (10)
  16323. {
  16324. }
  16325. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16326. {
  16327. }
  16328. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16329. {
  16330. maxNumberOfItems = jmax (1, newMaxNumber);
  16331. while (getNumFiles() > maxNumberOfItems)
  16332. files.remove (getNumFiles() - 1);
  16333. }
  16334. int RecentlyOpenedFilesList::getNumFiles() const
  16335. {
  16336. return files.size();
  16337. }
  16338. const File RecentlyOpenedFilesList::getFile (const int index) const
  16339. {
  16340. return File (files [index]);
  16341. }
  16342. void RecentlyOpenedFilesList::clear()
  16343. {
  16344. files.clear();
  16345. }
  16346. void RecentlyOpenedFilesList::addFile (const File& file)
  16347. {
  16348. const String path (file.getFullPathName());
  16349. files.removeString (path, true);
  16350. files.insert (0, path);
  16351. setMaxNumberOfItems (maxNumberOfItems);
  16352. }
  16353. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16354. {
  16355. for (int i = getNumFiles(); --i >= 0;)
  16356. if (! getFile(i).exists())
  16357. files.remove (i);
  16358. }
  16359. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16360. const int baseItemId,
  16361. const bool showFullPaths,
  16362. const bool dontAddNonExistentFiles,
  16363. const File** filesToAvoid)
  16364. {
  16365. int num = 0;
  16366. for (int i = 0; i < getNumFiles(); ++i)
  16367. {
  16368. const File f (getFile(i));
  16369. if ((! dontAddNonExistentFiles) || f.exists())
  16370. {
  16371. bool needsAvoiding = false;
  16372. if (filesToAvoid != 0)
  16373. {
  16374. const File** avoid = filesToAvoid;
  16375. while (*avoid != 0)
  16376. {
  16377. if (f == **avoid)
  16378. {
  16379. needsAvoiding = true;
  16380. break;
  16381. }
  16382. ++avoid;
  16383. }
  16384. }
  16385. if (! needsAvoiding)
  16386. {
  16387. menuToAddTo.addItem (baseItemId + i,
  16388. showFullPaths ? f.getFullPathName()
  16389. : f.getFileName());
  16390. ++num;
  16391. }
  16392. }
  16393. }
  16394. return num;
  16395. }
  16396. const String RecentlyOpenedFilesList::toString() const
  16397. {
  16398. return files.joinIntoString ("\n");
  16399. }
  16400. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16401. {
  16402. clear();
  16403. files.addLines (stringifiedVersion);
  16404. setMaxNumberOfItems (maxNumberOfItems);
  16405. }
  16406. END_JUCE_NAMESPACE
  16407. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16408. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16409. BEGIN_JUCE_NAMESPACE
  16410. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16411. const int minimumTransactions)
  16412. : totalUnitsStored (0),
  16413. nextIndex (0),
  16414. newTransaction (true),
  16415. reentrancyCheck (false)
  16416. {
  16417. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16418. minimumTransactions);
  16419. }
  16420. UndoManager::~UndoManager()
  16421. {
  16422. clearUndoHistory();
  16423. }
  16424. void UndoManager::clearUndoHistory()
  16425. {
  16426. transactions.clear();
  16427. transactionNames.clear();
  16428. totalUnitsStored = 0;
  16429. nextIndex = 0;
  16430. sendChangeMessage (this);
  16431. }
  16432. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16433. {
  16434. return totalUnitsStored;
  16435. }
  16436. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16437. const int minimumTransactions)
  16438. {
  16439. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16440. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16441. }
  16442. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16443. {
  16444. if (command_ != 0)
  16445. {
  16446. ScopedPointer<UndoableAction> command (command_);
  16447. if (actionName.isNotEmpty())
  16448. currentTransactionName = actionName;
  16449. if (reentrancyCheck)
  16450. {
  16451. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16452. // undo() methods, or else these actions won't actually get done.
  16453. return false;
  16454. }
  16455. else if (command->perform())
  16456. {
  16457. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16458. if (commandSet != 0 && ! newTransaction)
  16459. {
  16460. UndoableAction* lastAction = commandSet->getLast();
  16461. if (lastAction != 0)
  16462. {
  16463. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16464. if (coalescedAction != 0)
  16465. {
  16466. command = coalescedAction;
  16467. totalUnitsStored -= lastAction->getSizeInUnits();
  16468. commandSet->removeLast();
  16469. }
  16470. }
  16471. }
  16472. else
  16473. {
  16474. commandSet = new OwnedArray<UndoableAction>();
  16475. transactions.insert (nextIndex, commandSet);
  16476. transactionNames.insert (nextIndex, currentTransactionName);
  16477. ++nextIndex;
  16478. }
  16479. totalUnitsStored += command->getSizeInUnits();
  16480. commandSet->add (command.release());
  16481. newTransaction = false;
  16482. while (nextIndex < transactions.size())
  16483. {
  16484. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16485. for (int i = lastSet->size(); --i >= 0;)
  16486. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16487. transactions.removeLast();
  16488. transactionNames.remove (transactionNames.size() - 1);
  16489. }
  16490. while (nextIndex > 0
  16491. && totalUnitsStored > maxNumUnitsToKeep
  16492. && transactions.size() > minimumTransactionsToKeep)
  16493. {
  16494. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16495. for (int i = firstSet->size(); --i >= 0;)
  16496. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16497. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16498. transactions.remove (0);
  16499. transactionNames.remove (0);
  16500. --nextIndex;
  16501. }
  16502. sendChangeMessage (this);
  16503. return true;
  16504. }
  16505. }
  16506. return false;
  16507. }
  16508. void UndoManager::beginNewTransaction (const String& actionName)
  16509. {
  16510. newTransaction = true;
  16511. currentTransactionName = actionName;
  16512. }
  16513. void UndoManager::setCurrentTransactionName (const String& newName)
  16514. {
  16515. currentTransactionName = newName;
  16516. }
  16517. bool UndoManager::canUndo() const
  16518. {
  16519. return nextIndex > 0;
  16520. }
  16521. bool UndoManager::canRedo() const
  16522. {
  16523. return nextIndex < transactions.size();
  16524. }
  16525. const String UndoManager::getUndoDescription() const
  16526. {
  16527. return transactionNames [nextIndex - 1];
  16528. }
  16529. const String UndoManager::getRedoDescription() const
  16530. {
  16531. return transactionNames [nextIndex];
  16532. }
  16533. bool UndoManager::undo()
  16534. {
  16535. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16536. if (commandSet == 0)
  16537. return false;
  16538. reentrancyCheck = true;
  16539. bool failed = false;
  16540. for (int i = commandSet->size(); --i >= 0;)
  16541. {
  16542. if (! commandSet->getUnchecked(i)->undo())
  16543. {
  16544. jassertfalse;
  16545. failed = true;
  16546. break;
  16547. }
  16548. }
  16549. reentrancyCheck = false;
  16550. if (failed)
  16551. clearUndoHistory();
  16552. else
  16553. --nextIndex;
  16554. beginNewTransaction();
  16555. sendChangeMessage (this);
  16556. return true;
  16557. }
  16558. bool UndoManager::redo()
  16559. {
  16560. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16561. if (commandSet == 0)
  16562. return false;
  16563. reentrancyCheck = true;
  16564. bool failed = false;
  16565. for (int i = 0; i < commandSet->size(); ++i)
  16566. {
  16567. if (! commandSet->getUnchecked(i)->perform())
  16568. {
  16569. jassertfalse;
  16570. failed = true;
  16571. break;
  16572. }
  16573. }
  16574. reentrancyCheck = false;
  16575. if (failed)
  16576. clearUndoHistory();
  16577. else
  16578. ++nextIndex;
  16579. beginNewTransaction();
  16580. sendChangeMessage (this);
  16581. return true;
  16582. }
  16583. bool UndoManager::undoCurrentTransactionOnly()
  16584. {
  16585. return newTransaction ? false : undo();
  16586. }
  16587. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16588. {
  16589. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16590. if (commandSet != 0 && ! newTransaction)
  16591. {
  16592. for (int i = 0; i < commandSet->size(); ++i)
  16593. actionsFound.add (commandSet->getUnchecked(i));
  16594. }
  16595. }
  16596. int UndoManager::getNumActionsInCurrentTransaction() const
  16597. {
  16598. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16599. if (commandSet != 0 && ! newTransaction)
  16600. return commandSet->size();
  16601. return 0;
  16602. }
  16603. END_JUCE_NAMESPACE
  16604. /*** End of inlined file: juce_UndoManager.cpp ***/
  16605. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16606. BEGIN_JUCE_NAMESPACE
  16607. static const char* const aiffFormatName = "AIFF file";
  16608. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16609. class AiffAudioFormatReader : public AudioFormatReader
  16610. {
  16611. public:
  16612. int bytesPerFrame;
  16613. int64 dataChunkStart;
  16614. bool littleEndian;
  16615. AiffAudioFormatReader (InputStream* in)
  16616. : AudioFormatReader (in, TRANS (aiffFormatName))
  16617. {
  16618. if (input->readInt() == chunkName ("FORM"))
  16619. {
  16620. const int len = input->readIntBigEndian();
  16621. const int64 end = input->getPosition() + len;
  16622. const int nextType = input->readInt();
  16623. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16624. {
  16625. bool hasGotVer = false;
  16626. bool hasGotData = false;
  16627. bool hasGotType = false;
  16628. while (input->getPosition() < end)
  16629. {
  16630. const int type = input->readInt();
  16631. const uint32 length = (uint32) input->readIntBigEndian();
  16632. const int64 chunkEnd = input->getPosition() + length;
  16633. if (type == chunkName ("FVER"))
  16634. {
  16635. hasGotVer = true;
  16636. const int ver = input->readIntBigEndian();
  16637. if (ver != 0 && ver != (int) 0xa2805140)
  16638. break;
  16639. }
  16640. else if (type == chunkName ("COMM"))
  16641. {
  16642. hasGotType = true;
  16643. numChannels = (unsigned int) input->readShortBigEndian();
  16644. lengthInSamples = input->readIntBigEndian();
  16645. bitsPerSample = input->readShortBigEndian();
  16646. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16647. unsigned char sampleRateBytes[10];
  16648. input->read (sampleRateBytes, 10);
  16649. const int byte0 = sampleRateBytes[0];
  16650. if ((byte0 & 0x80) != 0
  16651. || byte0 <= 0x3F || byte0 > 0x40
  16652. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16653. break;
  16654. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16655. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16656. sampleRate = (int) sampRate;
  16657. if (length <= 18)
  16658. {
  16659. // some types don't have a chunk large enough to include a compression
  16660. // type, so assume it's just big-endian pcm
  16661. littleEndian = false;
  16662. }
  16663. else
  16664. {
  16665. const int compType = input->readInt();
  16666. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16667. {
  16668. littleEndian = false;
  16669. }
  16670. else if (compType == chunkName ("sowt"))
  16671. {
  16672. littleEndian = true;
  16673. }
  16674. else
  16675. {
  16676. sampleRate = 0;
  16677. break;
  16678. }
  16679. }
  16680. }
  16681. else if (type == chunkName ("SSND"))
  16682. {
  16683. hasGotData = true;
  16684. const int offset = input->readIntBigEndian();
  16685. dataChunkStart = input->getPosition() + 4 + offset;
  16686. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16687. }
  16688. else if ((hasGotVer && hasGotData && hasGotType)
  16689. || chunkEnd < input->getPosition()
  16690. || input->isExhausted())
  16691. {
  16692. break;
  16693. }
  16694. input->setPosition (chunkEnd);
  16695. }
  16696. }
  16697. }
  16698. }
  16699. ~AiffAudioFormatReader()
  16700. {
  16701. }
  16702. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16703. int64 startSampleInFile, int numSamples)
  16704. {
  16705. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16706. if (samplesAvailable < numSamples)
  16707. {
  16708. for (int i = numDestChannels; --i >= 0;)
  16709. if (destSamples[i] != 0)
  16710. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16711. numSamples = (int) samplesAvailable;
  16712. }
  16713. if (numSamples <= 0)
  16714. return true;
  16715. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16716. while (numSamples > 0)
  16717. {
  16718. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16719. char tempBuffer [tempBufSize];
  16720. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16721. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16722. if (bytesRead < numThisTime * bytesPerFrame)
  16723. {
  16724. jassert (bytesRead >= 0);
  16725. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16726. }
  16727. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16728. if (littleEndian)
  16729. {
  16730. switch (bitsPerSample)
  16731. {
  16732. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16733. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16734. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16735. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16736. default: jassertfalse; break;
  16737. }
  16738. }
  16739. else
  16740. {
  16741. switch (bitsPerSample)
  16742. {
  16743. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16744. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16745. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16746. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16747. default: jassertfalse; break;
  16748. }
  16749. }
  16750. startOffsetInDestBuffer += numThisTime;
  16751. numSamples -= numThisTime;
  16752. }
  16753. return true;
  16754. }
  16755. juce_UseDebuggingNewOperator
  16756. private:
  16757. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16758. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16759. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16760. };
  16761. class AiffAudioFormatWriter : public AudioFormatWriter
  16762. {
  16763. public:
  16764. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16765. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16766. lengthInSamples (0),
  16767. bytesWritten (0),
  16768. writeFailed (false)
  16769. {
  16770. headerPosition = out->getPosition();
  16771. writeHeader();
  16772. }
  16773. ~AiffAudioFormatWriter()
  16774. {
  16775. if ((bytesWritten & 1) != 0)
  16776. output->writeByte (0);
  16777. writeHeader();
  16778. }
  16779. bool write (const int** data, int numSamples)
  16780. {
  16781. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16782. if (writeFailed)
  16783. return false;
  16784. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16785. tempBlock.ensureSize (bytes, false);
  16786. switch (bitsPerSample)
  16787. {
  16788. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16789. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16790. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16791. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16792. default: jassertfalse; break;
  16793. }
  16794. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16795. || ! output->write (tempBlock.getData(), bytes))
  16796. {
  16797. // failed to write to disk, so let's try writing the header.
  16798. // If it's just run out of disk space, then if it does manage
  16799. // to write the header, we'll still have a useable file..
  16800. writeHeader();
  16801. writeFailed = true;
  16802. return false;
  16803. }
  16804. else
  16805. {
  16806. bytesWritten += bytes;
  16807. lengthInSamples += numSamples;
  16808. return true;
  16809. }
  16810. }
  16811. juce_UseDebuggingNewOperator
  16812. private:
  16813. MemoryBlock tempBlock;
  16814. uint32 lengthInSamples, bytesWritten;
  16815. int64 headerPosition;
  16816. bool writeFailed;
  16817. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16818. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16819. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16820. void writeHeader()
  16821. {
  16822. const bool couldSeekOk = output->setPosition (headerPosition);
  16823. (void) couldSeekOk;
  16824. // if this fails, you've given it an output stream that can't seek! It needs
  16825. // to be able to seek back to write the header
  16826. jassert (couldSeekOk);
  16827. const int headerLen = 54;
  16828. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16829. audioBytes += (audioBytes & 1);
  16830. output->writeInt (chunkName ("FORM"));
  16831. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16832. output->writeInt (chunkName ("AIFF"));
  16833. output->writeInt (chunkName ("COMM"));
  16834. output->writeIntBigEndian (18);
  16835. output->writeShortBigEndian ((short) numChannels);
  16836. output->writeIntBigEndian (lengthInSamples);
  16837. output->writeShortBigEndian ((short) bitsPerSample);
  16838. uint8 sampleRateBytes[10];
  16839. zeromem (sampleRateBytes, 10);
  16840. if (sampleRate <= 1)
  16841. {
  16842. sampleRateBytes[0] = 0x3f;
  16843. sampleRateBytes[1] = 0xff;
  16844. sampleRateBytes[2] = 0x80;
  16845. }
  16846. else
  16847. {
  16848. int mask = 0x40000000;
  16849. sampleRateBytes[0] = 0x40;
  16850. if (sampleRate >= mask)
  16851. {
  16852. jassertfalse;
  16853. sampleRateBytes[1] = 0x1d;
  16854. }
  16855. else
  16856. {
  16857. int n = (int) sampleRate;
  16858. int i;
  16859. for (i = 0; i <= 32 ; ++i)
  16860. {
  16861. if ((n & mask) != 0)
  16862. break;
  16863. mask >>= 1;
  16864. }
  16865. n = n << (i + 1);
  16866. sampleRateBytes[1] = (uint8) (29 - i);
  16867. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16868. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16869. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16870. sampleRateBytes[5] = (uint8) (n & 0xff);
  16871. }
  16872. }
  16873. output->write (sampleRateBytes, 10);
  16874. output->writeInt (chunkName ("SSND"));
  16875. output->writeIntBigEndian (audioBytes + 8);
  16876. output->writeInt (0);
  16877. output->writeInt (0);
  16878. jassert (output->getPosition() == headerLen);
  16879. }
  16880. };
  16881. AiffAudioFormat::AiffAudioFormat()
  16882. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16883. {
  16884. }
  16885. AiffAudioFormat::~AiffAudioFormat()
  16886. {
  16887. }
  16888. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16889. {
  16890. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16891. return Array <int> (rates);
  16892. }
  16893. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16894. {
  16895. const int depths[] = { 8, 16, 24, 0 };
  16896. return Array <int> (depths);
  16897. }
  16898. bool AiffAudioFormat::canDoStereo() { return true; }
  16899. bool AiffAudioFormat::canDoMono() { return true; }
  16900. #if JUCE_MAC
  16901. bool AiffAudioFormat::canHandleFile (const File& f)
  16902. {
  16903. if (AudioFormat::canHandleFile (f))
  16904. return true;
  16905. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16906. return type == 'AIFF' || type == 'AIFC'
  16907. || type == 'aiff' || type == 'aifc';
  16908. }
  16909. #endif
  16910. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16911. {
  16912. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16913. if (w->sampleRate != 0)
  16914. return w.release();
  16915. if (! deleteStreamIfOpeningFails)
  16916. w->input = 0;
  16917. return 0;
  16918. }
  16919. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16920. double sampleRate,
  16921. unsigned int numberOfChannels,
  16922. int bitsPerSample,
  16923. const StringPairArray& /*metadataValues*/,
  16924. int /*qualityOptionIndex*/)
  16925. {
  16926. if (getPossibleBitDepths().contains (bitsPerSample))
  16927. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16928. return 0;
  16929. }
  16930. END_JUCE_NAMESPACE
  16931. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16932. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16933. BEGIN_JUCE_NAMESPACE
  16934. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16935. : formatName (name),
  16936. fileExtensions (extensions)
  16937. {
  16938. }
  16939. AudioFormat::~AudioFormat()
  16940. {
  16941. }
  16942. bool AudioFormat::canHandleFile (const File& f)
  16943. {
  16944. for (int i = 0; i < fileExtensions.size(); ++i)
  16945. if (f.hasFileExtension (fileExtensions[i]))
  16946. return true;
  16947. return false;
  16948. }
  16949. const String& AudioFormat::getFormatName() const { return formatName; }
  16950. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16951. bool AudioFormat::isCompressed() { return false; }
  16952. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16953. END_JUCE_NAMESPACE
  16954. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16955. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16956. BEGIN_JUCE_NAMESPACE
  16957. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16958. const String& formatName_)
  16959. : sampleRate (0),
  16960. bitsPerSample (0),
  16961. lengthInSamples (0),
  16962. numChannels (0),
  16963. usesFloatingPointData (false),
  16964. input (in),
  16965. formatName (formatName_)
  16966. {
  16967. }
  16968. AudioFormatReader::~AudioFormatReader()
  16969. {
  16970. delete input;
  16971. }
  16972. bool AudioFormatReader::read (int* const* destSamples,
  16973. int numDestChannels,
  16974. int64 startSampleInSource,
  16975. int numSamplesToRead,
  16976. const bool fillLeftoverChannelsWithCopies)
  16977. {
  16978. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16979. int startOffsetInDestBuffer = 0;
  16980. if (startSampleInSource < 0)
  16981. {
  16982. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16983. for (int i = numDestChannels; --i >= 0;)
  16984. if (destSamples[i] != 0)
  16985. zeromem (destSamples[i], sizeof (int) * silence);
  16986. startOffsetInDestBuffer += silence;
  16987. numSamplesToRead -= silence;
  16988. startSampleInSource = 0;
  16989. }
  16990. if (numSamplesToRead <= 0)
  16991. return true;
  16992. if (! readSamples (const_cast<int**> (destSamples),
  16993. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16994. startSampleInSource, numSamplesToRead))
  16995. return false;
  16996. if (numDestChannels > (int) numChannels)
  16997. {
  16998. if (fillLeftoverChannelsWithCopies)
  16999. {
  17000. int* lastFullChannel = destSamples[0];
  17001. for (int i = (int) numChannels; --i > 0;)
  17002. {
  17003. if (destSamples[i] != 0)
  17004. {
  17005. lastFullChannel = destSamples[i];
  17006. break;
  17007. }
  17008. }
  17009. if (lastFullChannel != 0)
  17010. for (int i = numChannels; i < numDestChannels; ++i)
  17011. if (destSamples[i] != 0)
  17012. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17013. }
  17014. else
  17015. {
  17016. for (int i = numChannels; i < numDestChannels; ++i)
  17017. if (destSamples[i] != 0)
  17018. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17019. }
  17020. }
  17021. return true;
  17022. }
  17023. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17024. {
  17025. float mn = buffer[0];
  17026. float mx = mn;
  17027. for (int i = 1; i < num; ++i)
  17028. {
  17029. const float s = buffer[i];
  17030. if (s > mx) mx = s;
  17031. if (s < mn) mn = s;
  17032. }
  17033. maxVal = mx;
  17034. minVal = mn;
  17035. }
  17036. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17037. int64 numSamples,
  17038. float& lowestLeft, float& highestLeft,
  17039. float& lowestRight, float& highestRight)
  17040. {
  17041. if (numSamples <= 0)
  17042. {
  17043. lowestLeft = 0;
  17044. lowestRight = 0;
  17045. highestLeft = 0;
  17046. highestRight = 0;
  17047. return;
  17048. }
  17049. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17050. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17051. int* tempBuffer[3];
  17052. tempBuffer[0] = tempSpace.getData();
  17053. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17054. tempBuffer[2] = 0;
  17055. if (usesFloatingPointData)
  17056. {
  17057. float lmin = 1.0e6f;
  17058. float lmax = -lmin;
  17059. float rmin = lmin;
  17060. float rmax = lmax;
  17061. while (numSamples > 0)
  17062. {
  17063. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17064. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17065. numSamples -= numToDo;
  17066. startSampleInFile += numToDo;
  17067. float bufmin, bufmax;
  17068. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17069. lmin = jmin (lmin, bufmin);
  17070. lmax = jmax (lmax, bufmax);
  17071. if (numChannels > 1)
  17072. {
  17073. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17074. rmin = jmin (rmin, bufmin);
  17075. rmax = jmax (rmax, bufmax);
  17076. }
  17077. }
  17078. if (numChannels <= 1)
  17079. {
  17080. rmax = lmax;
  17081. rmin = lmin;
  17082. }
  17083. lowestLeft = lmin;
  17084. highestLeft = lmax;
  17085. lowestRight = rmin;
  17086. highestRight = rmax;
  17087. }
  17088. else
  17089. {
  17090. int lmax = std::numeric_limits<int>::min();
  17091. int lmin = std::numeric_limits<int>::max();
  17092. int rmax = std::numeric_limits<int>::min();
  17093. int rmin = std::numeric_limits<int>::max();
  17094. while (numSamples > 0)
  17095. {
  17096. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17097. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17098. numSamples -= numToDo;
  17099. startSampleInFile += numToDo;
  17100. for (int j = numChannels; --j >= 0;)
  17101. {
  17102. int bufMax = std::numeric_limits<int>::min();
  17103. int bufMin = std::numeric_limits<int>::max();
  17104. const int* const b = tempBuffer[j];
  17105. for (int i = 0; i < numToDo; ++i)
  17106. {
  17107. const int samp = b[i];
  17108. if (samp < bufMin)
  17109. bufMin = samp;
  17110. if (samp > bufMax)
  17111. bufMax = samp;
  17112. }
  17113. if (j == 0)
  17114. {
  17115. lmax = jmax (lmax, bufMax);
  17116. lmin = jmin (lmin, bufMin);
  17117. }
  17118. else
  17119. {
  17120. rmax = jmax (rmax, bufMax);
  17121. rmin = jmin (rmin, bufMin);
  17122. }
  17123. }
  17124. }
  17125. if (numChannels <= 1)
  17126. {
  17127. rmax = lmax;
  17128. rmin = lmin;
  17129. }
  17130. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17131. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17132. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17133. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17134. }
  17135. }
  17136. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17137. int64 numSamplesToSearch,
  17138. const double magnitudeRangeMinimum,
  17139. const double magnitudeRangeMaximum,
  17140. const int minimumConsecutiveSamples)
  17141. {
  17142. if (numSamplesToSearch == 0)
  17143. return -1;
  17144. const int bufferSize = 4096;
  17145. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17146. int* tempBuffer[3];
  17147. tempBuffer[0] = tempSpace.getData();
  17148. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17149. tempBuffer[2] = 0;
  17150. int consecutive = 0;
  17151. int64 firstMatchPos = -1;
  17152. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17153. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17154. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17155. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17156. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17157. while (numSamplesToSearch != 0)
  17158. {
  17159. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17160. int64 bufferStart = startSample;
  17161. if (numSamplesToSearch < 0)
  17162. bufferStart -= numThisTime;
  17163. if (bufferStart >= (int) lengthInSamples)
  17164. break;
  17165. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17166. int num = numThisTime;
  17167. while (--num >= 0)
  17168. {
  17169. if (numSamplesToSearch < 0)
  17170. --startSample;
  17171. bool matches = false;
  17172. const int index = (int) (startSample - bufferStart);
  17173. if (usesFloatingPointData)
  17174. {
  17175. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17176. if (sample1 >= magnitudeRangeMinimum
  17177. && sample1 <= magnitudeRangeMaximum)
  17178. {
  17179. matches = true;
  17180. }
  17181. else if (numChannels > 1)
  17182. {
  17183. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17184. matches = (sample2 >= magnitudeRangeMinimum
  17185. && sample2 <= magnitudeRangeMaximum);
  17186. }
  17187. }
  17188. else
  17189. {
  17190. const int sample1 = abs (tempBuffer[0] [index]);
  17191. if (sample1 >= intMagnitudeRangeMinimum
  17192. && sample1 <= intMagnitudeRangeMaximum)
  17193. {
  17194. matches = true;
  17195. }
  17196. else if (numChannels > 1)
  17197. {
  17198. const int sample2 = abs (tempBuffer[1][index]);
  17199. matches = (sample2 >= intMagnitudeRangeMinimum
  17200. && sample2 <= intMagnitudeRangeMaximum);
  17201. }
  17202. }
  17203. if (matches)
  17204. {
  17205. if (firstMatchPos < 0)
  17206. firstMatchPos = startSample;
  17207. if (++consecutive >= minimumConsecutiveSamples)
  17208. {
  17209. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17210. return -1;
  17211. return firstMatchPos;
  17212. }
  17213. }
  17214. else
  17215. {
  17216. consecutive = 0;
  17217. firstMatchPos = -1;
  17218. }
  17219. if (numSamplesToSearch > 0)
  17220. ++startSample;
  17221. }
  17222. if (numSamplesToSearch > 0)
  17223. numSamplesToSearch -= numThisTime;
  17224. else
  17225. numSamplesToSearch += numThisTime;
  17226. }
  17227. return -1;
  17228. }
  17229. END_JUCE_NAMESPACE
  17230. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17231. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17232. BEGIN_JUCE_NAMESPACE
  17233. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17234. const String& formatName_,
  17235. const double rate,
  17236. const unsigned int numChannels_,
  17237. const unsigned int bitsPerSample_)
  17238. : sampleRate (rate),
  17239. numChannels (numChannels_),
  17240. bitsPerSample (bitsPerSample_),
  17241. usesFloatingPointData (false),
  17242. output (out),
  17243. formatName (formatName_)
  17244. {
  17245. }
  17246. AudioFormatWriter::~AudioFormatWriter()
  17247. {
  17248. delete output;
  17249. }
  17250. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17251. int64 startSample,
  17252. int64 numSamplesToRead)
  17253. {
  17254. const int bufferSize = 16384;
  17255. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17256. int* buffers [128];
  17257. zerostruct (buffers);
  17258. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17259. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17260. if (numSamplesToRead < 0)
  17261. numSamplesToRead = reader.lengthInSamples;
  17262. while (numSamplesToRead > 0)
  17263. {
  17264. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17265. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17266. return false;
  17267. if (reader.usesFloatingPointData != isFloatingPoint())
  17268. {
  17269. int** bufferChan = buffers;
  17270. while (*bufferChan != 0)
  17271. {
  17272. int* b = *bufferChan++;
  17273. if (isFloatingPoint())
  17274. {
  17275. // int -> float
  17276. const double factor = 1.0 / std::numeric_limits<int>::max();
  17277. for (int i = 0; i < numToDo; ++i)
  17278. ((float*) b)[i] = (float) (factor * b[i]);
  17279. }
  17280. else
  17281. {
  17282. // float -> int
  17283. for (int i = 0; i < numToDo; ++i)
  17284. {
  17285. const double samp = *(const float*) b;
  17286. if (samp <= -1.0)
  17287. *b++ = std::numeric_limits<int>::min();
  17288. else if (samp >= 1.0)
  17289. *b++ = std::numeric_limits<int>::max();
  17290. else
  17291. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17292. }
  17293. }
  17294. }
  17295. }
  17296. if (! write (const_cast<const int**> (buffers), numToDo))
  17297. return false;
  17298. numSamplesToRead -= numToDo;
  17299. startSample += numToDo;
  17300. }
  17301. return true;
  17302. }
  17303. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17304. {
  17305. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17306. while (numSamplesToRead > 0)
  17307. {
  17308. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17309. AudioSourceChannelInfo info;
  17310. info.buffer = &tempBuffer;
  17311. info.startSample = 0;
  17312. info.numSamples = numToDo;
  17313. info.clearActiveBufferRegion();
  17314. source.getNextAudioBlock (info);
  17315. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17316. return false;
  17317. numSamplesToRead -= numToDo;
  17318. }
  17319. return true;
  17320. }
  17321. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17322. {
  17323. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17324. if (numSamples <= 0)
  17325. return true;
  17326. HeapBlock<int> tempBuffer;
  17327. HeapBlock<int*> chans (numChannels + 1);
  17328. chans [numChannels] = 0;
  17329. if (isFloatingPoint())
  17330. {
  17331. for (int i = numChannels; --i >= 0;)
  17332. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17333. }
  17334. else
  17335. {
  17336. tempBuffer.malloc (numSamples * numChannels);
  17337. for (unsigned int i = 0; i < numChannels; ++i)
  17338. {
  17339. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17340. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17341. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17342. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17343. destData.convertSamples (sourceData, numSamples);
  17344. }
  17345. }
  17346. return write ((const int**) chans.getData(), numSamples);
  17347. }
  17348. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17349. public AbstractFifo
  17350. {
  17351. public:
  17352. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17353. : AbstractFifo (bufferSize),
  17354. buffer (numChannels, bufferSize),
  17355. timeSliceThread (timeSliceThread_),
  17356. writer (writer_), isRunning (true)
  17357. {
  17358. timeSliceThread.addTimeSliceClient (this);
  17359. }
  17360. ~Buffer()
  17361. {
  17362. isRunning = false;
  17363. timeSliceThread.removeTimeSliceClient (this);
  17364. while (useTimeSlice())
  17365. {}
  17366. }
  17367. bool write (const float** data, int numSamples)
  17368. {
  17369. if (numSamples <= 0 || ! isRunning)
  17370. return true;
  17371. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17372. int start1, size1, start2, size2;
  17373. prepareToWrite (numSamples, start1, size1, start2, size2);
  17374. if (size1 + size2 < numSamples)
  17375. return false;
  17376. for (int i = buffer.getNumChannels(); --i >= 0;)
  17377. {
  17378. buffer.copyFrom (i, start1, data[i], size1);
  17379. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17380. }
  17381. finishedWrite (size1 + size2);
  17382. timeSliceThread.notify();
  17383. return true;
  17384. }
  17385. bool useTimeSlice()
  17386. {
  17387. const int numToDo = getTotalSize() / 4;
  17388. int start1, size1, start2, size2;
  17389. prepareToRead (numToDo, start1, size1, start2, size2);
  17390. if (size1 <= 0)
  17391. return false;
  17392. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17393. if (size2 > 0)
  17394. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17395. finishedRead (size1 + size2);
  17396. return true;
  17397. }
  17398. private:
  17399. AudioSampleBuffer buffer;
  17400. TimeSliceThread& timeSliceThread;
  17401. ScopedPointer<AudioFormatWriter> writer;
  17402. volatile bool isRunning;
  17403. Buffer (const Buffer&);
  17404. Buffer& operator= (const Buffer&);
  17405. };
  17406. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17407. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17408. {
  17409. }
  17410. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17411. {
  17412. }
  17413. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17414. {
  17415. return buffer->write (data, numSamples);
  17416. }
  17417. END_JUCE_NAMESPACE
  17418. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17419. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17420. BEGIN_JUCE_NAMESPACE
  17421. AudioFormatManager::AudioFormatManager()
  17422. : defaultFormatIndex (0)
  17423. {
  17424. }
  17425. AudioFormatManager::~AudioFormatManager()
  17426. {
  17427. clearFormats();
  17428. clearSingletonInstance();
  17429. }
  17430. juce_ImplementSingleton (AudioFormatManager);
  17431. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17432. const bool makeThisTheDefaultFormat)
  17433. {
  17434. jassert (newFormat != 0);
  17435. if (newFormat != 0)
  17436. {
  17437. #if JUCE_DEBUG
  17438. for (int i = getNumKnownFormats(); --i >= 0;)
  17439. {
  17440. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17441. {
  17442. jassertfalse; // trying to add the same format twice!
  17443. }
  17444. }
  17445. #endif
  17446. if (makeThisTheDefaultFormat)
  17447. defaultFormatIndex = getNumKnownFormats();
  17448. knownFormats.add (newFormat);
  17449. }
  17450. }
  17451. void AudioFormatManager::registerBasicFormats()
  17452. {
  17453. #if JUCE_MAC
  17454. registerFormat (new AiffAudioFormat(), true);
  17455. registerFormat (new WavAudioFormat(), false);
  17456. #else
  17457. registerFormat (new WavAudioFormat(), true);
  17458. registerFormat (new AiffAudioFormat(), false);
  17459. #endif
  17460. #if JUCE_USE_FLAC
  17461. registerFormat (new FlacAudioFormat(), false);
  17462. #endif
  17463. #if JUCE_USE_OGGVORBIS
  17464. registerFormat (new OggVorbisAudioFormat(), false);
  17465. #endif
  17466. }
  17467. void AudioFormatManager::clearFormats()
  17468. {
  17469. knownFormats.clear();
  17470. defaultFormatIndex = 0;
  17471. }
  17472. int AudioFormatManager::getNumKnownFormats() const
  17473. {
  17474. return knownFormats.size();
  17475. }
  17476. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17477. {
  17478. return knownFormats [index];
  17479. }
  17480. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17481. {
  17482. return getKnownFormat (defaultFormatIndex);
  17483. }
  17484. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17485. {
  17486. String e (fileExtension);
  17487. if (! e.startsWithChar ('.'))
  17488. e = "." + e;
  17489. for (int i = 0; i < getNumKnownFormats(); ++i)
  17490. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17491. return getKnownFormat(i);
  17492. return 0;
  17493. }
  17494. const String AudioFormatManager::getWildcardForAllFormats() const
  17495. {
  17496. StringArray allExtensions;
  17497. int i;
  17498. for (i = 0; i < getNumKnownFormats(); ++i)
  17499. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17500. allExtensions.trim();
  17501. allExtensions.removeEmptyStrings();
  17502. String s;
  17503. for (i = 0; i < allExtensions.size(); ++i)
  17504. {
  17505. s << '*';
  17506. if (! allExtensions[i].startsWithChar ('.'))
  17507. s << '.';
  17508. s << allExtensions[i];
  17509. if (i < allExtensions.size() - 1)
  17510. s << ';';
  17511. }
  17512. return s;
  17513. }
  17514. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17515. {
  17516. // you need to actually register some formats before the manager can
  17517. // use them to open a file!
  17518. jassert (getNumKnownFormats() > 0);
  17519. for (int i = 0; i < getNumKnownFormats(); ++i)
  17520. {
  17521. AudioFormat* const af = getKnownFormat(i);
  17522. if (af->canHandleFile (file))
  17523. {
  17524. InputStream* const in = file.createInputStream();
  17525. if (in != 0)
  17526. {
  17527. AudioFormatReader* const r = af->createReaderFor (in, true);
  17528. if (r != 0)
  17529. return r;
  17530. }
  17531. }
  17532. }
  17533. return 0;
  17534. }
  17535. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17536. {
  17537. // you need to actually register some formats before the manager can
  17538. // use them to open a file!
  17539. jassert (getNumKnownFormats() > 0);
  17540. ScopedPointer <InputStream> in (audioFileStream);
  17541. if (in != 0)
  17542. {
  17543. const int64 originalStreamPos = in->getPosition();
  17544. for (int i = 0; i < getNumKnownFormats(); ++i)
  17545. {
  17546. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17547. if (r != 0)
  17548. {
  17549. in.release();
  17550. return r;
  17551. }
  17552. in->setPosition (originalStreamPos);
  17553. // the stream that is passed-in must be capable of being repositioned so
  17554. // that all the formats can have a go at opening it.
  17555. jassert (in->getPosition() == originalStreamPos);
  17556. }
  17557. }
  17558. return 0;
  17559. }
  17560. END_JUCE_NAMESPACE
  17561. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17562. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17563. BEGIN_JUCE_NAMESPACE
  17564. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17565. const int64 startSample_,
  17566. const int64 length_,
  17567. const bool deleteSourceWhenDeleted_)
  17568. : AudioFormatReader (0, source_->getFormatName()),
  17569. source (source_),
  17570. startSample (startSample_),
  17571. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17572. {
  17573. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17574. sampleRate = source->sampleRate;
  17575. bitsPerSample = source->bitsPerSample;
  17576. lengthInSamples = length;
  17577. numChannels = source->numChannels;
  17578. usesFloatingPointData = source->usesFloatingPointData;
  17579. }
  17580. AudioSubsectionReader::~AudioSubsectionReader()
  17581. {
  17582. if (deleteSourceWhenDeleted)
  17583. delete source;
  17584. }
  17585. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17586. int64 startSampleInFile, int numSamples)
  17587. {
  17588. if (startSampleInFile + numSamples > length)
  17589. {
  17590. for (int i = numDestChannels; --i >= 0;)
  17591. if (destSamples[i] != 0)
  17592. zeromem (destSamples[i], sizeof (int) * numSamples);
  17593. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17594. if (numSamples <= 0)
  17595. return true;
  17596. }
  17597. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17598. startSampleInFile + startSample, numSamples);
  17599. }
  17600. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17601. int64 numSamples,
  17602. float& lowestLeft,
  17603. float& highestLeft,
  17604. float& lowestRight,
  17605. float& highestRight)
  17606. {
  17607. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17608. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17609. source->readMaxLevels (startSampleInFile + startSample,
  17610. numSamples,
  17611. lowestLeft,
  17612. highestLeft,
  17613. lowestRight,
  17614. highestRight);
  17615. }
  17616. END_JUCE_NAMESPACE
  17617. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17618. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17619. BEGIN_JUCE_NAMESPACE
  17620. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17621. AudioFormatManager& formatManagerToUse_,
  17622. AudioThumbnailCache& cacheToUse)
  17623. : formatManagerToUse (formatManagerToUse_),
  17624. cache (cacheToUse),
  17625. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17626. timeBeforeDeletingReader (2000)
  17627. {
  17628. clear();
  17629. }
  17630. AudioThumbnail::~AudioThumbnail()
  17631. {
  17632. cache.removeThumbnail (this);
  17633. const ScopedLock sl (readerLock);
  17634. reader = 0;
  17635. }
  17636. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17637. {
  17638. jassert (data.getData() != 0);
  17639. return static_cast <DataFormat*> (data.getData());
  17640. }
  17641. void AudioThumbnail::setSource (InputSource* const newSource)
  17642. {
  17643. cache.removeThumbnail (this);
  17644. timerCallback(); // stops the timer and deletes the reader
  17645. source = newSource;
  17646. clear();
  17647. if (newSource != 0
  17648. && ! (cache.loadThumb (*this, newSource->hashCode())
  17649. && isFullyLoaded()))
  17650. {
  17651. {
  17652. const ScopedLock sl (readerLock);
  17653. reader = createReader();
  17654. }
  17655. if (reader != 0)
  17656. {
  17657. initialiseFromAudioFile (*reader);
  17658. cache.addThumbnail (this);
  17659. }
  17660. }
  17661. sendChangeMessage (this);
  17662. }
  17663. bool AudioThumbnail::useTimeSlice()
  17664. {
  17665. const ScopedLock sl (readerLock);
  17666. if (isFullyLoaded())
  17667. {
  17668. if (reader != 0)
  17669. startTimer (timeBeforeDeletingReader);
  17670. cache.removeThumbnail (this);
  17671. return false;
  17672. }
  17673. if (reader == 0)
  17674. reader = createReader();
  17675. if (reader != 0)
  17676. {
  17677. readNextBlockFromAudioFile (*reader);
  17678. stopTimer();
  17679. sendChangeMessage (this);
  17680. const bool justFinished = isFullyLoaded();
  17681. if (justFinished)
  17682. cache.storeThumb (*this, source->hashCode());
  17683. return ! justFinished;
  17684. }
  17685. return false;
  17686. }
  17687. AudioFormatReader* AudioThumbnail::createReader() const
  17688. {
  17689. if (source != 0)
  17690. {
  17691. InputStream* const audioFileStream = source->createInputStream();
  17692. if (audioFileStream != 0)
  17693. return formatManagerToUse.createReaderFor (audioFileStream);
  17694. }
  17695. return 0;
  17696. }
  17697. void AudioThumbnail::timerCallback()
  17698. {
  17699. stopTimer();
  17700. const ScopedLock sl (readerLock);
  17701. reader = 0;
  17702. }
  17703. void AudioThumbnail::clear()
  17704. {
  17705. data.setSize (sizeof (DataFormat) + 3);
  17706. DataFormat* const d = getData();
  17707. d->thumbnailMagic[0] = 'j';
  17708. d->thumbnailMagic[1] = 'a';
  17709. d->thumbnailMagic[2] = 't';
  17710. d->thumbnailMagic[3] = 'm';
  17711. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17712. d->totalSamples = 0;
  17713. d->numFinishedSamples = 0;
  17714. d->numThumbnailSamples = 0;
  17715. d->numChannels = 0;
  17716. d->sampleRate = 0;
  17717. numSamplesCached = 0;
  17718. cacheNeedsRefilling = true;
  17719. }
  17720. void AudioThumbnail::loadFrom (InputStream& input)
  17721. {
  17722. const ScopedLock sl (readerLock);
  17723. data.setSize (0);
  17724. input.readIntoMemoryBlock (data);
  17725. DataFormat* const d = getData();
  17726. d->flipEndiannessIfBigEndian();
  17727. if (! (d->thumbnailMagic[0] == 'j'
  17728. && d->thumbnailMagic[1] == 'a'
  17729. && d->thumbnailMagic[2] == 't'
  17730. && d->thumbnailMagic[3] == 'm'))
  17731. {
  17732. clear();
  17733. }
  17734. numSamplesCached = 0;
  17735. cacheNeedsRefilling = true;
  17736. }
  17737. void AudioThumbnail::saveTo (OutputStream& output) const
  17738. {
  17739. const ScopedLock sl (readerLock);
  17740. DataFormat* const d = getData();
  17741. d->flipEndiannessIfBigEndian();
  17742. output.write (d, (int) data.getSize());
  17743. d->flipEndiannessIfBigEndian();
  17744. }
  17745. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17746. {
  17747. DataFormat* d = getData();
  17748. d->totalSamples = fileReader.lengthInSamples;
  17749. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17750. d->numFinishedSamples = 0;
  17751. d->sampleRate = roundToInt (fileReader.sampleRate);
  17752. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17753. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17754. d = getData();
  17755. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17756. return d->totalSamples > 0;
  17757. }
  17758. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17759. {
  17760. DataFormat* const d = getData();
  17761. if (d->numFinishedSamples < d->totalSamples)
  17762. {
  17763. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17764. generateSection (fileReader,
  17765. d->numFinishedSamples,
  17766. numToDo);
  17767. d->numFinishedSamples += numToDo;
  17768. }
  17769. cacheNeedsRefilling = true;
  17770. return d->numFinishedSamples < d->totalSamples;
  17771. }
  17772. int AudioThumbnail::getNumChannels() const throw()
  17773. {
  17774. return getData()->numChannels;
  17775. }
  17776. double AudioThumbnail::getTotalLength() const throw()
  17777. {
  17778. const DataFormat* const d = getData();
  17779. if (d->sampleRate > 0)
  17780. return d->totalSamples / (double) d->sampleRate;
  17781. else
  17782. return 0.0;
  17783. }
  17784. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17785. int64 startSample,
  17786. int numSamples)
  17787. {
  17788. DataFormat* const d = getData();
  17789. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17790. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17791. char* const l = getChannelData (0);
  17792. char* const r = getChannelData (1);
  17793. for (int i = firstDataPos; i < lastDataPos; ++i)
  17794. {
  17795. const int sourceStart = i * d->samplesPerThumbSample;
  17796. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17797. float lowestLeft, highestLeft, lowestRight, highestRight;
  17798. fileReader.readMaxLevels (sourceStart,
  17799. sourceEnd - sourceStart,
  17800. lowestLeft,
  17801. highestLeft,
  17802. lowestRight,
  17803. highestRight);
  17804. int n = i * 2;
  17805. if (r != 0)
  17806. {
  17807. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17808. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17809. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17810. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17811. }
  17812. else
  17813. {
  17814. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17815. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17816. }
  17817. }
  17818. }
  17819. char* AudioThumbnail::getChannelData (int channel) const
  17820. {
  17821. DataFormat* const d = getData();
  17822. if (channel >= 0 && channel < d->numChannels)
  17823. return d->data + (channel * 2 * d->numThumbnailSamples);
  17824. return 0;
  17825. }
  17826. bool AudioThumbnail::isFullyLoaded() const throw()
  17827. {
  17828. const DataFormat* const d = getData();
  17829. return d->numFinishedSamples >= d->totalSamples;
  17830. }
  17831. void AudioThumbnail::refillCache (const int numSamples,
  17832. double startTime,
  17833. const double timePerPixel)
  17834. {
  17835. const DataFormat* const d = getData();
  17836. if (numSamples <= 0
  17837. || timePerPixel <= 0.0
  17838. || d->sampleRate <= 0)
  17839. {
  17840. numSamplesCached = 0;
  17841. cacheNeedsRefilling = true;
  17842. return;
  17843. }
  17844. if (numSamples == numSamplesCached
  17845. && numChannelsCached == d->numChannels
  17846. && startTime == cachedStart
  17847. && timePerPixel == cachedTimePerPixel
  17848. && ! cacheNeedsRefilling)
  17849. {
  17850. return;
  17851. }
  17852. numSamplesCached = numSamples;
  17853. numChannelsCached = d->numChannels;
  17854. cachedStart = startTime;
  17855. cachedTimePerPixel = timePerPixel;
  17856. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17857. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17858. const ScopedLock sl (readerLock);
  17859. cacheNeedsRefilling = false;
  17860. if (needExtraDetail && reader == 0)
  17861. reader = createReader();
  17862. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17863. {
  17864. startTimer (timeBeforeDeletingReader);
  17865. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17866. int sample = roundToInt (startTime * d->sampleRate);
  17867. for (int i = numSamples; --i >= 0;)
  17868. {
  17869. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17870. if (sample >= 0)
  17871. {
  17872. if (sample >= reader->lengthInSamples)
  17873. break;
  17874. float lmin, lmax, rmin, rmax;
  17875. reader->readMaxLevels (sample,
  17876. jmax (1, nextSample - sample),
  17877. lmin, lmax, rmin, rmax);
  17878. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17879. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17880. if (numChannelsCached > 1)
  17881. {
  17882. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17883. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17884. }
  17885. cacheData += 2 * numChannelsCached;
  17886. }
  17887. startTime += timePerPixel;
  17888. sample = nextSample;
  17889. }
  17890. }
  17891. else
  17892. {
  17893. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17894. {
  17895. char* const channelData = getChannelData (channelNum);
  17896. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17897. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17898. startTime = cachedStart;
  17899. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17900. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17901. for (int i = numSamples; --i >= 0;)
  17902. {
  17903. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17904. if (sample >= 0 && channelData != 0)
  17905. {
  17906. char mx = -128;
  17907. char mn = 127;
  17908. while (sample <= nextSample)
  17909. {
  17910. if (sample >= numFinished)
  17911. break;
  17912. const int n = sample << 1;
  17913. const char sampMin = channelData [n];
  17914. const char sampMax = channelData [n + 1];
  17915. if (sampMin < mn)
  17916. mn = sampMin;
  17917. if (sampMax > mx)
  17918. mx = sampMax;
  17919. ++sample;
  17920. }
  17921. if (mn <= mx)
  17922. {
  17923. cacheData[0] = mn;
  17924. cacheData[1] = mx;
  17925. }
  17926. else
  17927. {
  17928. cacheData[0] = 1;
  17929. cacheData[1] = 0;
  17930. }
  17931. }
  17932. else
  17933. {
  17934. cacheData[0] = 1;
  17935. cacheData[1] = 0;
  17936. }
  17937. cacheData += numChannelsCached * 2;
  17938. startTime += timePerPixel;
  17939. sample = nextSample;
  17940. }
  17941. }
  17942. }
  17943. }
  17944. void AudioThumbnail::drawChannel (Graphics& g,
  17945. int x, int y, int w, int h,
  17946. double startTime,
  17947. double endTime,
  17948. int channelNum,
  17949. const float verticalZoomFactor)
  17950. {
  17951. refillCache (w, startTime, (endTime - startTime) / w);
  17952. if (numSamplesCached >= w
  17953. && channelNum >= 0
  17954. && channelNum < numChannelsCached)
  17955. {
  17956. const float topY = (float) y;
  17957. const float bottomY = topY + h;
  17958. const float midY = topY + h * 0.5f;
  17959. const float vscale = verticalZoomFactor * h / 256.0f;
  17960. const Rectangle<int> clip (g.getClipBounds());
  17961. const int skipLeft = jlimit (0, w, clip.getX() - x);
  17962. w -= skipLeft;
  17963. x += skipLeft;
  17964. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  17965. + (channelNum << 1)
  17966. + skipLeft * (numChannelsCached << 1);
  17967. while (--w >= 0)
  17968. {
  17969. const char mn = cacheData[0];
  17970. const char mx = cacheData[1];
  17971. cacheData += numChannelsCached << 1;
  17972. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  17973. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  17974. jmin (midY - mn * vscale + 0.3f, bottomY));
  17975. if (++x >= clip.getRight())
  17976. break;
  17977. }
  17978. }
  17979. }
  17980. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  17981. {
  17982. #if JUCE_BIG_ENDIAN
  17983. struct Flipper
  17984. {
  17985. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  17986. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  17987. };
  17988. Flipper::flip (samplesPerThumbSample);
  17989. Flipper::flip (totalSamples);
  17990. Flipper::flip (numFinishedSamples);
  17991. Flipper::flip (numThumbnailSamples);
  17992. Flipper::flip (numChannels);
  17993. Flipper::flip (sampleRate);
  17994. #endif
  17995. }
  17996. END_JUCE_NAMESPACE
  17997. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17998. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17999. BEGIN_JUCE_NAMESPACE
  18000. struct ThumbnailCacheEntry
  18001. {
  18002. int64 hash;
  18003. uint32 lastUsed;
  18004. MemoryBlock data;
  18005. juce_UseDebuggingNewOperator
  18006. };
  18007. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18008. : TimeSliceThread ("thumb cache"),
  18009. maxNumThumbsToStore (maxNumThumbsToStore_)
  18010. {
  18011. startThread (2);
  18012. }
  18013. AudioThumbnailCache::~AudioThumbnailCache()
  18014. {
  18015. }
  18016. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18017. {
  18018. for (int i = thumbs.size(); --i >= 0;)
  18019. {
  18020. if (thumbs[i]->hash == hashCode)
  18021. {
  18022. MemoryInputStream in (thumbs[i]->data, false);
  18023. thumb.loadFrom (in);
  18024. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18025. return true;
  18026. }
  18027. }
  18028. return false;
  18029. }
  18030. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18031. const int64 hashCode)
  18032. {
  18033. MemoryOutputStream out;
  18034. thumb.saveTo (out);
  18035. ThumbnailCacheEntry* te = 0;
  18036. for (int i = thumbs.size(); --i >= 0;)
  18037. {
  18038. if (thumbs[i]->hash == hashCode)
  18039. {
  18040. te = thumbs[i];
  18041. break;
  18042. }
  18043. }
  18044. if (te == 0)
  18045. {
  18046. te = new ThumbnailCacheEntry();
  18047. te->hash = hashCode;
  18048. if (thumbs.size() < maxNumThumbsToStore)
  18049. {
  18050. thumbs.add (te);
  18051. }
  18052. else
  18053. {
  18054. int oldest = 0;
  18055. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18056. int i;
  18057. for (i = thumbs.size(); --i >= 0;)
  18058. if (thumbs[i]->lastUsed < oldestTime)
  18059. oldest = i;
  18060. thumbs.set (i, te);
  18061. }
  18062. }
  18063. te->lastUsed = Time::getMillisecondCounter();
  18064. te->data.setSize (0);
  18065. te->data.append (out.getData(), out.getDataSize());
  18066. }
  18067. void AudioThumbnailCache::clear()
  18068. {
  18069. thumbs.clear();
  18070. }
  18071. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18072. {
  18073. addTimeSliceClient (thumb);
  18074. }
  18075. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18076. {
  18077. removeTimeSliceClient (thumb);
  18078. }
  18079. END_JUCE_NAMESPACE
  18080. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18081. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18082. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18083. #if ! JUCE_WINDOWS
  18084. #include <QuickTime/Movies.h>
  18085. #include <QuickTime/QTML.h>
  18086. #include <QuickTime/QuickTimeComponents.h>
  18087. #include <QuickTime/MediaHandlers.h>
  18088. #include <QuickTime/ImageCodec.h>
  18089. #else
  18090. #if JUCE_MSVC
  18091. #pragma warning (push)
  18092. #pragma warning (disable : 4100)
  18093. #endif
  18094. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18095. add its header directory to your include path.
  18096. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18097. flag in juce_Config.h
  18098. */
  18099. #include <Movies.h>
  18100. #include <QTML.h>
  18101. #include <QuickTimeComponents.h>
  18102. #include <MediaHandlers.h>
  18103. #include <ImageCodec.h>
  18104. #if JUCE_MSVC
  18105. #pragma warning (pop)
  18106. #endif
  18107. #endif
  18108. BEGIN_JUCE_NAMESPACE
  18109. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18110. static const char* const quickTimeFormatName = "QuickTime file";
  18111. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18112. class QTAudioReader : public AudioFormatReader
  18113. {
  18114. public:
  18115. QTAudioReader (InputStream* const input_, const int trackNum_)
  18116. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18117. ok (false),
  18118. movie (0),
  18119. trackNum (trackNum_),
  18120. lastSampleRead (0),
  18121. lastThreadId (0),
  18122. extractor (0),
  18123. dataHandle (0)
  18124. {
  18125. bufferList.calloc (256, 1);
  18126. #if JUCE_WINDOWS
  18127. if (InitializeQTML (0) != noErr)
  18128. return;
  18129. #endif
  18130. if (EnterMovies() != noErr)
  18131. return;
  18132. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18133. if (! opened)
  18134. return;
  18135. {
  18136. const int numTracks = GetMovieTrackCount (movie);
  18137. int trackCount = 0;
  18138. for (int i = 1; i <= numTracks; ++i)
  18139. {
  18140. track = GetMovieIndTrack (movie, i);
  18141. media = GetTrackMedia (track);
  18142. OSType mediaType;
  18143. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18144. if (mediaType == SoundMediaType
  18145. && trackCount++ == trackNum_)
  18146. {
  18147. ok = true;
  18148. break;
  18149. }
  18150. }
  18151. }
  18152. if (! ok)
  18153. return;
  18154. ok = false;
  18155. lengthInSamples = GetMediaDecodeDuration (media);
  18156. usesFloatingPointData = false;
  18157. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18158. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18159. / GetMediaTimeScale (media);
  18160. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18161. unsigned long output_layout_size;
  18162. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18163. kQTPropertyClass_MovieAudioExtraction_Audio,
  18164. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18165. 0, &output_layout_size, 0);
  18166. if (err != noErr)
  18167. return;
  18168. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18169. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18170. err = MovieAudioExtractionGetProperty (extractor,
  18171. kQTPropertyClass_MovieAudioExtraction_Audio,
  18172. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18173. output_layout_size, qt_audio_channel_layout, 0);
  18174. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18175. err = MovieAudioExtractionSetProperty (extractor,
  18176. kQTPropertyClass_MovieAudioExtraction_Audio,
  18177. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18178. output_layout_size,
  18179. qt_audio_channel_layout);
  18180. err = MovieAudioExtractionGetProperty (extractor,
  18181. kQTPropertyClass_MovieAudioExtraction_Audio,
  18182. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18183. sizeof (inputStreamDesc),
  18184. &inputStreamDesc, 0);
  18185. if (err != noErr)
  18186. return;
  18187. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18188. | kAudioFormatFlagIsPacked
  18189. | kAudioFormatFlagsNativeEndian;
  18190. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18191. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18192. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18193. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18194. err = MovieAudioExtractionSetProperty (extractor,
  18195. kQTPropertyClass_MovieAudioExtraction_Audio,
  18196. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18197. sizeof (inputStreamDesc),
  18198. &inputStreamDesc);
  18199. if (err != noErr)
  18200. return;
  18201. Boolean allChannelsDiscrete = false;
  18202. err = MovieAudioExtractionSetProperty (extractor,
  18203. kQTPropertyClass_MovieAudioExtraction_Movie,
  18204. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18205. sizeof (allChannelsDiscrete),
  18206. &allChannelsDiscrete);
  18207. if (err != noErr)
  18208. return;
  18209. bufferList->mNumberBuffers = 1;
  18210. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18211. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18212. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18213. bufferList->mBuffers[0].mData = dataBuffer;
  18214. sampleRate = inputStreamDesc.mSampleRate;
  18215. bitsPerSample = 16;
  18216. numChannels = inputStreamDesc.mChannelsPerFrame;
  18217. detachThread();
  18218. ok = true;
  18219. }
  18220. ~QTAudioReader()
  18221. {
  18222. if (dataHandle != 0)
  18223. DisposeHandle (dataHandle);
  18224. if (extractor != 0)
  18225. {
  18226. MovieAudioExtractionEnd (extractor);
  18227. extractor = 0;
  18228. }
  18229. checkThreadIsAttached();
  18230. DisposeMovie (movie);
  18231. #if JUCE_MAC
  18232. ExitMoviesOnThread ();
  18233. #endif
  18234. }
  18235. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18236. int64 startSampleInFile, int numSamples)
  18237. {
  18238. checkThreadIsAttached();
  18239. bool ok = true;
  18240. while (numSamples > 0)
  18241. {
  18242. if (lastSampleRead != startSampleInFile)
  18243. {
  18244. TimeRecord time;
  18245. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18246. time.base = 0;
  18247. time.value.hi = 0;
  18248. time.value.lo = (UInt32) startSampleInFile;
  18249. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18250. kQTPropertyClass_MovieAudioExtraction_Movie,
  18251. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18252. sizeof (time), &time);
  18253. if (err != noErr)
  18254. {
  18255. ok = false;
  18256. break;
  18257. }
  18258. }
  18259. int framesToDo = jmin (numSamples, bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame);
  18260. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18261. UInt32 outFlags = 0;
  18262. UInt32 actualNumFrames = framesToDo;
  18263. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18264. if (err != noErr)
  18265. {
  18266. ok = false;
  18267. break;
  18268. }
  18269. lastSampleRead = startSampleInFile + actualNumFrames;
  18270. const int samplesReceived = actualNumFrames;
  18271. for (int j = numDestChannels; --j >= 0;)
  18272. {
  18273. if (destSamples[j] != 0)
  18274. {
  18275. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18276. for (int i = 0; i < samplesReceived; ++i)
  18277. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18278. }
  18279. }
  18280. startOffsetInDestBuffer += samplesReceived;
  18281. startSampleInFile += samplesReceived;
  18282. numSamples -= samplesReceived;
  18283. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18284. {
  18285. for (int j = numDestChannels; --j >= 0;)
  18286. if (destSamples[j] != 0)
  18287. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18288. break;
  18289. }
  18290. }
  18291. detachThread();
  18292. return ok;
  18293. }
  18294. juce_UseDebuggingNewOperator
  18295. bool ok;
  18296. private:
  18297. Movie movie;
  18298. Media media;
  18299. Track track;
  18300. const int trackNum;
  18301. double trackUnitsPerFrame;
  18302. int samplesPerFrame;
  18303. int64 lastSampleRead;
  18304. Thread::ThreadID lastThreadId;
  18305. MovieAudioExtractionRef extractor;
  18306. AudioStreamBasicDescription inputStreamDesc;
  18307. HeapBlock <AudioBufferList> bufferList;
  18308. HeapBlock <char> dataBuffer;
  18309. Handle dataHandle;
  18310. void checkThreadIsAttached()
  18311. {
  18312. #if JUCE_MAC
  18313. if (Thread::getCurrentThreadId() != lastThreadId)
  18314. EnterMoviesOnThread (0);
  18315. AttachMovieToCurrentThread (movie);
  18316. #endif
  18317. }
  18318. void detachThread()
  18319. {
  18320. #if JUCE_MAC
  18321. DetachMovieFromCurrentThread (movie);
  18322. #endif
  18323. }
  18324. QTAudioReader (const QTAudioReader&);
  18325. QTAudioReader& operator= (const QTAudioReader&);
  18326. };
  18327. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18328. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18329. {
  18330. }
  18331. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18332. {
  18333. }
  18334. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18335. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18336. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18337. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18338. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18339. const bool deleteStreamIfOpeningFails)
  18340. {
  18341. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18342. if (r->ok)
  18343. return r.release();
  18344. if (! deleteStreamIfOpeningFails)
  18345. r->input = 0;
  18346. return 0;
  18347. }
  18348. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18349. double /*sampleRateToUse*/,
  18350. unsigned int /*numberOfChannels*/,
  18351. int /*bitsPerSample*/,
  18352. const StringPairArray& /*metadataValues*/,
  18353. int /*qualityOptionIndex*/)
  18354. {
  18355. jassertfalse; // not yet implemented!
  18356. return 0;
  18357. }
  18358. END_JUCE_NAMESPACE
  18359. #endif
  18360. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18361. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18362. BEGIN_JUCE_NAMESPACE
  18363. static const char* const wavFormatName = "WAV file";
  18364. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18365. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18366. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18367. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18368. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18369. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18370. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18371. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18372. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18373. const String& originator,
  18374. const String& originatorRef,
  18375. const Time& date,
  18376. const int64 timeReferenceSamples,
  18377. const String& codingHistory)
  18378. {
  18379. StringPairArray m;
  18380. m.set (bwavDescription, description);
  18381. m.set (bwavOriginator, originator);
  18382. m.set (bwavOriginatorRef, originatorRef);
  18383. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18384. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18385. m.set (bwavTimeReference, String (timeReferenceSamples));
  18386. m.set (bwavCodingHistory, codingHistory);
  18387. return m;
  18388. }
  18389. #if JUCE_MSVC
  18390. #pragma pack (push, 1)
  18391. #define PACKED
  18392. #elif JUCE_GCC
  18393. #define PACKED __attribute__((packed))
  18394. #else
  18395. #define PACKED
  18396. #endif
  18397. struct BWAVChunk
  18398. {
  18399. char description [256];
  18400. char originator [32];
  18401. char originatorRef [32];
  18402. char originationDate [10];
  18403. char originationTime [8];
  18404. uint32 timeRefLow;
  18405. uint32 timeRefHigh;
  18406. uint16 version;
  18407. uint8 umid[64];
  18408. uint8 reserved[190];
  18409. char codingHistory[1];
  18410. void copyTo (StringPairArray& values) const
  18411. {
  18412. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18413. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18414. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18415. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18416. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18417. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18418. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18419. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18420. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18421. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18422. }
  18423. static MemoryBlock createFrom (const StringPairArray& values)
  18424. {
  18425. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18426. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18427. data.fillWith (0);
  18428. BWAVChunk* b = (BWAVChunk*) data.getData();
  18429. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18430. // as they get called in the right order..
  18431. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18432. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18433. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18434. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18435. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18436. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18437. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18438. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18439. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18440. if (b->description[0] != 0
  18441. || b->originator[0] != 0
  18442. || b->originationDate[0] != 0
  18443. || b->originationTime[0] != 0
  18444. || b->codingHistory[0] != 0
  18445. || time != 0)
  18446. {
  18447. return data;
  18448. }
  18449. return MemoryBlock();
  18450. }
  18451. } PACKED;
  18452. struct SMPLChunk
  18453. {
  18454. struct SampleLoop
  18455. {
  18456. uint32 identifier;
  18457. uint32 type;
  18458. uint32 start;
  18459. uint32 end;
  18460. uint32 fraction;
  18461. uint32 playCount;
  18462. } PACKED;
  18463. uint32 manufacturer;
  18464. uint32 product;
  18465. uint32 samplePeriod;
  18466. uint32 midiUnityNote;
  18467. uint32 midiPitchFraction;
  18468. uint32 smpteFormat;
  18469. uint32 smpteOffset;
  18470. uint32 numSampleLoops;
  18471. uint32 samplerData;
  18472. SampleLoop loops[1];
  18473. void copyTo (StringPairArray& values, const int totalSize) const
  18474. {
  18475. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18476. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18477. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18478. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18479. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18480. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18481. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18482. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18483. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18484. for (uint32 i = 0; i < numSampleLoops; ++i)
  18485. {
  18486. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18487. break;
  18488. const String prefix ("Loop" + String(i));
  18489. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18490. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18491. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18492. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18493. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18494. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18495. }
  18496. }
  18497. static MemoryBlock createFrom (const StringPairArray& values)
  18498. {
  18499. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18500. if (numLoops <= 0)
  18501. return MemoryBlock();
  18502. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18503. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18504. data.fillWith (0);
  18505. SMPLChunk* s = (SMPLChunk*) data.getData();
  18506. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18507. // as they get called in the right order..
  18508. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18509. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18510. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18511. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18512. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18513. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18514. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18515. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18516. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18517. for (int i = 0; i < numLoops; ++i)
  18518. {
  18519. const String prefix ("Loop" + String(i));
  18520. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18521. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18522. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18523. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18524. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18525. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18526. }
  18527. return data;
  18528. }
  18529. } PACKED;
  18530. struct ExtensibleWavSubFormat
  18531. {
  18532. uint32 data1;
  18533. uint16 data2;
  18534. uint16 data3;
  18535. uint8 data4[8];
  18536. } PACKED;
  18537. #if JUCE_MSVC
  18538. #pragma pack (pop)
  18539. #endif
  18540. #undef PACKED
  18541. class WavAudioFormatReader : public AudioFormatReader
  18542. {
  18543. public:
  18544. WavAudioFormatReader (InputStream* const in)
  18545. : AudioFormatReader (in, TRANS (wavFormatName)),
  18546. dataLength (0),
  18547. bwavChunkStart (0),
  18548. bwavSize (0)
  18549. {
  18550. if (input->readInt() == chunkName ("RIFF"))
  18551. {
  18552. const uint32 len = (uint32) input->readInt();
  18553. const int64 end = input->getPosition() + len;
  18554. bool hasGotType = false;
  18555. bool hasGotData = false;
  18556. if (input->readInt() == chunkName ("WAVE"))
  18557. {
  18558. while (input->getPosition() < end
  18559. && ! input->isExhausted())
  18560. {
  18561. const int chunkType = input->readInt();
  18562. uint32 length = (uint32) input->readInt();
  18563. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18564. if (chunkType == chunkName ("fmt "))
  18565. {
  18566. // read the format chunk
  18567. const unsigned short format = input->readShort();
  18568. const short numChans = input->readShort();
  18569. sampleRate = input->readInt();
  18570. const int bytesPerSec = input->readInt();
  18571. numChannels = numChans;
  18572. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18573. bitsPerSample = 8 * bytesPerFrame / numChans;
  18574. if (format == 3)
  18575. {
  18576. usesFloatingPointData = true;
  18577. }
  18578. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18579. {
  18580. if (length < 40) // too short
  18581. {
  18582. bytesPerFrame = 0;
  18583. }
  18584. else
  18585. {
  18586. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18587. ExtensibleWavSubFormat subFormat;
  18588. subFormat.data1 = input->readInt();
  18589. subFormat.data2 = input->readShort();
  18590. subFormat.data3 = input->readShort();
  18591. input->read (subFormat.data4, sizeof (subFormat.data4));
  18592. const ExtensibleWavSubFormat pcmFormat
  18593. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18594. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18595. {
  18596. const ExtensibleWavSubFormat ambisonicFormat
  18597. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18598. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18599. bytesPerFrame = 0;
  18600. }
  18601. }
  18602. }
  18603. else if (format != 1)
  18604. {
  18605. bytesPerFrame = 0;
  18606. }
  18607. hasGotType = true;
  18608. }
  18609. else if (chunkType == chunkName ("data"))
  18610. {
  18611. // get the data chunk's position
  18612. dataLength = length;
  18613. dataChunkStart = input->getPosition();
  18614. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18615. hasGotData = true;
  18616. }
  18617. else if (chunkType == chunkName ("bext"))
  18618. {
  18619. bwavChunkStart = input->getPosition();
  18620. bwavSize = length;
  18621. // Broadcast-wav extension chunk..
  18622. HeapBlock <BWAVChunk> bwav;
  18623. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18624. input->read (bwav, length);
  18625. bwav->copyTo (metadataValues);
  18626. }
  18627. else if (chunkType == chunkName ("smpl"))
  18628. {
  18629. HeapBlock <SMPLChunk> smpl;
  18630. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18631. input->read (smpl, length);
  18632. smpl->copyTo (metadataValues, length);
  18633. }
  18634. else if (chunkEnd <= input->getPosition())
  18635. {
  18636. break;
  18637. }
  18638. input->setPosition (chunkEnd);
  18639. }
  18640. }
  18641. }
  18642. }
  18643. ~WavAudioFormatReader()
  18644. {
  18645. }
  18646. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18647. int64 startSampleInFile, int numSamples)
  18648. {
  18649. jassert (destSamples != 0);
  18650. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18651. if (samplesAvailable < numSamples)
  18652. {
  18653. for (int i = numDestChannels; --i >= 0;)
  18654. if (destSamples[i] != 0)
  18655. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18656. numSamples = (int) samplesAvailable;
  18657. }
  18658. if (numSamples <= 0)
  18659. return true;
  18660. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18661. while (numSamples > 0)
  18662. {
  18663. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18664. char tempBuffer [tempBufSize];
  18665. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18666. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18667. if (bytesRead < numThisTime * bytesPerFrame)
  18668. {
  18669. jassert (bytesRead >= 0);
  18670. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18671. }
  18672. switch (bitsPerSample)
  18673. {
  18674. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18675. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18676. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18677. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18678. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18679. default: jassertfalse; break;
  18680. }
  18681. startOffsetInDestBuffer += numThisTime;
  18682. numSamples -= numThisTime;
  18683. }
  18684. return true;
  18685. }
  18686. int64 bwavChunkStart, bwavSize;
  18687. juce_UseDebuggingNewOperator
  18688. private:
  18689. ScopedPointer<AudioData::Converter> converter;
  18690. int bytesPerFrame;
  18691. int64 dataChunkStart, dataLength;
  18692. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18693. WavAudioFormatReader (const WavAudioFormatReader&);
  18694. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18695. };
  18696. class WavAudioFormatWriter : public AudioFormatWriter
  18697. {
  18698. public:
  18699. WavAudioFormatWriter (OutputStream* const out,
  18700. const double sampleRate_,
  18701. const unsigned int numChannels_,
  18702. const int bits,
  18703. const StringPairArray& metadataValues)
  18704. : AudioFormatWriter (out,
  18705. TRANS (wavFormatName),
  18706. sampleRate_,
  18707. numChannels_,
  18708. bits),
  18709. lengthInSamples (0),
  18710. bytesWritten (0),
  18711. writeFailed (false)
  18712. {
  18713. if (metadataValues.size() > 0)
  18714. {
  18715. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18716. smplChunk = SMPLChunk::createFrom (metadataValues);
  18717. }
  18718. headerPosition = out->getPosition();
  18719. writeHeader();
  18720. }
  18721. ~WavAudioFormatWriter()
  18722. {
  18723. writeHeader();
  18724. }
  18725. bool write (const int** data, int numSamples)
  18726. {
  18727. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18728. if (writeFailed)
  18729. return false;
  18730. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18731. tempBlock.ensureSize (bytes, false);
  18732. switch (bitsPerSample)
  18733. {
  18734. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18735. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18736. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18737. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18738. default: jassertfalse; break;
  18739. }
  18740. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18741. || ! output->write (tempBlock.getData(), bytes))
  18742. {
  18743. // failed to write to disk, so let's try writing the header.
  18744. // If it's just run out of disk space, then if it does manage
  18745. // to write the header, we'll still have a useable file..
  18746. writeHeader();
  18747. writeFailed = true;
  18748. return false;
  18749. }
  18750. else
  18751. {
  18752. bytesWritten += bytes;
  18753. lengthInSamples += numSamples;
  18754. return true;
  18755. }
  18756. }
  18757. juce_UseDebuggingNewOperator
  18758. private:
  18759. ScopedPointer<AudioData::Converter> converter;
  18760. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18761. uint32 lengthInSamples, bytesWritten;
  18762. int64 headerPosition;
  18763. bool writeFailed;
  18764. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18765. void writeHeader()
  18766. {
  18767. const bool seekedOk = output->setPosition (headerPosition);
  18768. (void) seekedOk;
  18769. // if this fails, you've given it an output stream that can't seek! It needs
  18770. // to be able to seek back to write the header
  18771. jassert (seekedOk);
  18772. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18773. output->writeInt (chunkName ("RIFF"));
  18774. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18775. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18776. output->writeInt (chunkName ("WAVE"));
  18777. output->writeInt (chunkName ("fmt "));
  18778. output->writeInt (16);
  18779. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18780. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18781. output->writeShort ((short) numChannels);
  18782. output->writeInt ((int) sampleRate);
  18783. output->writeInt (bytesPerFrame * (int) sampleRate);
  18784. output->writeShort ((short) bytesPerFrame);
  18785. output->writeShort ((short) bitsPerSample);
  18786. if (bwavChunk.getSize() > 0)
  18787. {
  18788. output->writeInt (chunkName ("bext"));
  18789. output->writeInt ((int) bwavChunk.getSize());
  18790. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18791. }
  18792. if (smplChunk.getSize() > 0)
  18793. {
  18794. output->writeInt (chunkName ("smpl"));
  18795. output->writeInt ((int) smplChunk.getSize());
  18796. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18797. }
  18798. output->writeInt (chunkName ("data"));
  18799. output->writeInt (lengthInSamples * bytesPerFrame);
  18800. usesFloatingPointData = (bitsPerSample == 32);
  18801. }
  18802. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18803. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18804. };
  18805. WavAudioFormat::WavAudioFormat()
  18806. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18807. {
  18808. }
  18809. WavAudioFormat::~WavAudioFormat()
  18810. {
  18811. }
  18812. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18813. {
  18814. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18815. return Array <int> (rates);
  18816. }
  18817. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18818. {
  18819. const int depths[] = { 8, 16, 24, 32, 0 };
  18820. return Array <int> (depths);
  18821. }
  18822. bool WavAudioFormat::canDoStereo() { return true; }
  18823. bool WavAudioFormat::canDoMono() { return true; }
  18824. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18825. const bool deleteStreamIfOpeningFails)
  18826. {
  18827. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18828. if (r->sampleRate != 0)
  18829. return r.release();
  18830. if (! deleteStreamIfOpeningFails)
  18831. r->input = 0;
  18832. return 0;
  18833. }
  18834. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18835. double sampleRate,
  18836. unsigned int numChannels,
  18837. int bitsPerSample,
  18838. const StringPairArray& metadataValues,
  18839. int /*qualityOptionIndex*/)
  18840. {
  18841. if (getPossibleBitDepths().contains (bitsPerSample))
  18842. {
  18843. return new WavAudioFormatWriter (out,
  18844. sampleRate,
  18845. numChannels,
  18846. bitsPerSample,
  18847. metadataValues);
  18848. }
  18849. return 0;
  18850. }
  18851. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18852. {
  18853. TemporaryFile tempFile (file);
  18854. WavAudioFormat wav;
  18855. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18856. if (reader != 0)
  18857. {
  18858. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18859. if (outStream != 0)
  18860. {
  18861. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18862. reader->numChannels, reader->bitsPerSample,
  18863. metadata, 0));
  18864. if (writer != 0)
  18865. {
  18866. outStream.release();
  18867. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18868. writer = 0;
  18869. reader = 0;
  18870. return ok && tempFile.overwriteTargetFileWithTemporary();
  18871. }
  18872. }
  18873. }
  18874. return false;
  18875. }
  18876. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18877. {
  18878. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18879. if (reader != 0)
  18880. {
  18881. const int64 bwavPos = reader->bwavChunkStart;
  18882. const int64 bwavSize = reader->bwavSize;
  18883. reader = 0;
  18884. if (bwavSize > 0)
  18885. {
  18886. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18887. if (chunk.getSize() <= (size_t) bwavSize)
  18888. {
  18889. // the new one will fit in the space available, so write it directly..
  18890. const int64 oldSize = wavFile.getSize();
  18891. {
  18892. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18893. out->setPosition (bwavPos);
  18894. out->write (chunk.getData(), (int) chunk.getSize());
  18895. out->setPosition (oldSize);
  18896. }
  18897. jassert (wavFile.getSize() == oldSize);
  18898. return true;
  18899. }
  18900. }
  18901. }
  18902. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18903. }
  18904. END_JUCE_NAMESPACE
  18905. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18906. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18907. #if JUCE_USE_CDREADER
  18908. BEGIN_JUCE_NAMESPACE
  18909. int AudioCDReader::getNumTracks() const
  18910. {
  18911. return trackStartSamples.size() - 1;
  18912. }
  18913. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18914. {
  18915. return trackStartSamples [trackNum];
  18916. }
  18917. const Array<int>& AudioCDReader::getTrackOffsets() const
  18918. {
  18919. return trackStartSamples;
  18920. }
  18921. int AudioCDReader::getCDDBId()
  18922. {
  18923. int checksum = 0;
  18924. const int numTracks = getNumTracks();
  18925. for (int i = 0; i < numTracks; ++i)
  18926. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18927. checksum += offset % 10;
  18928. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18929. // CCLLLLTT: checksum, length, tracks
  18930. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18931. }
  18932. END_JUCE_NAMESPACE
  18933. #endif
  18934. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18935. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18936. BEGIN_JUCE_NAMESPACE
  18937. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18938. const bool deleteReaderWhenThisIsDeleted)
  18939. : reader (reader_),
  18940. deleteReader (deleteReaderWhenThisIsDeleted),
  18941. nextPlayPos (0),
  18942. looping (false)
  18943. {
  18944. jassert (reader != 0);
  18945. }
  18946. AudioFormatReaderSource::~AudioFormatReaderSource()
  18947. {
  18948. releaseResources();
  18949. if (deleteReader)
  18950. delete reader;
  18951. }
  18952. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18953. {
  18954. nextPlayPos = newPosition;
  18955. }
  18956. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18957. {
  18958. looping = shouldLoop;
  18959. }
  18960. int AudioFormatReaderSource::getNextReadPosition() const
  18961. {
  18962. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18963. : nextPlayPos;
  18964. }
  18965. int AudioFormatReaderSource::getTotalLength() const
  18966. {
  18967. return (int) reader->lengthInSamples;
  18968. }
  18969. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18970. double /*sampleRate*/)
  18971. {
  18972. }
  18973. void AudioFormatReaderSource::releaseResources()
  18974. {
  18975. }
  18976. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18977. {
  18978. if (info.numSamples > 0)
  18979. {
  18980. const int start = nextPlayPos;
  18981. if (looping)
  18982. {
  18983. const int newStart = start % (int) reader->lengthInSamples;
  18984. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18985. if (newEnd > newStart)
  18986. {
  18987. info.buffer->readFromAudioReader (reader,
  18988. info.startSample,
  18989. newEnd - newStart,
  18990. newStart,
  18991. true, true);
  18992. }
  18993. else
  18994. {
  18995. const int endSamps = (int) reader->lengthInSamples - newStart;
  18996. info.buffer->readFromAudioReader (reader,
  18997. info.startSample,
  18998. endSamps,
  18999. newStart,
  19000. true, true);
  19001. info.buffer->readFromAudioReader (reader,
  19002. info.startSample + endSamps,
  19003. newEnd,
  19004. 0,
  19005. true, true);
  19006. }
  19007. nextPlayPos = newEnd;
  19008. }
  19009. else
  19010. {
  19011. info.buffer->readFromAudioReader (reader,
  19012. info.startSample,
  19013. info.numSamples,
  19014. start,
  19015. true, true);
  19016. nextPlayPos += info.numSamples;
  19017. }
  19018. }
  19019. }
  19020. END_JUCE_NAMESPACE
  19021. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19022. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19023. BEGIN_JUCE_NAMESPACE
  19024. AudioSourcePlayer::AudioSourcePlayer()
  19025. : source (0),
  19026. sampleRate (0),
  19027. bufferSize (0),
  19028. tempBuffer (2, 8),
  19029. lastGain (1.0f),
  19030. gain (1.0f)
  19031. {
  19032. }
  19033. AudioSourcePlayer::~AudioSourcePlayer()
  19034. {
  19035. setSource (0);
  19036. }
  19037. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19038. {
  19039. if (source != newSource)
  19040. {
  19041. AudioSource* const oldSource = source;
  19042. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19043. newSource->prepareToPlay (bufferSize, sampleRate);
  19044. {
  19045. const ScopedLock sl (readLock);
  19046. source = newSource;
  19047. }
  19048. if (oldSource != 0)
  19049. oldSource->releaseResources();
  19050. }
  19051. }
  19052. void AudioSourcePlayer::setGain (const float newGain) throw()
  19053. {
  19054. gain = newGain;
  19055. }
  19056. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19057. int totalNumInputChannels,
  19058. float** outputChannelData,
  19059. int totalNumOutputChannels,
  19060. int numSamples)
  19061. {
  19062. // these should have been prepared by audioDeviceAboutToStart()...
  19063. jassert (sampleRate > 0 && bufferSize > 0);
  19064. const ScopedLock sl (readLock);
  19065. if (source != 0)
  19066. {
  19067. AudioSourceChannelInfo info;
  19068. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19069. // messy stuff needed to compact the channels down into an array
  19070. // of non-zero pointers..
  19071. for (i = 0; i < totalNumInputChannels; ++i)
  19072. {
  19073. if (inputChannelData[i] != 0)
  19074. {
  19075. inputChans [numInputs++] = inputChannelData[i];
  19076. if (numInputs >= numElementsInArray (inputChans))
  19077. break;
  19078. }
  19079. }
  19080. for (i = 0; i < totalNumOutputChannels; ++i)
  19081. {
  19082. if (outputChannelData[i] != 0)
  19083. {
  19084. outputChans [numOutputs++] = outputChannelData[i];
  19085. if (numOutputs >= numElementsInArray (outputChans))
  19086. break;
  19087. }
  19088. }
  19089. if (numInputs > numOutputs)
  19090. {
  19091. // if there aren't enough output channels for the number of
  19092. // inputs, we need to create some temporary extra ones (can't
  19093. // use the input data in case it gets written to)
  19094. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19095. false, false, true);
  19096. for (i = 0; i < numOutputs; ++i)
  19097. {
  19098. channels[numActiveChans] = outputChans[i];
  19099. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19100. ++numActiveChans;
  19101. }
  19102. for (i = numOutputs; i < numInputs; ++i)
  19103. {
  19104. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19105. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19106. ++numActiveChans;
  19107. }
  19108. }
  19109. else
  19110. {
  19111. for (i = 0; i < numInputs; ++i)
  19112. {
  19113. channels[numActiveChans] = outputChans[i];
  19114. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19115. ++numActiveChans;
  19116. }
  19117. for (i = numInputs; i < numOutputs; ++i)
  19118. {
  19119. channels[numActiveChans] = outputChans[i];
  19120. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19121. ++numActiveChans;
  19122. }
  19123. }
  19124. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19125. info.buffer = &buffer;
  19126. info.startSample = 0;
  19127. info.numSamples = numSamples;
  19128. source->getNextAudioBlock (info);
  19129. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19130. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19131. lastGain = gain;
  19132. }
  19133. else
  19134. {
  19135. for (int i = 0; i < totalNumOutputChannels; ++i)
  19136. if (outputChannelData[i] != 0)
  19137. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19138. }
  19139. }
  19140. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19141. {
  19142. sampleRate = device->getCurrentSampleRate();
  19143. bufferSize = device->getCurrentBufferSizeSamples();
  19144. zeromem (channels, sizeof (channels));
  19145. if (source != 0)
  19146. source->prepareToPlay (bufferSize, sampleRate);
  19147. }
  19148. void AudioSourcePlayer::audioDeviceStopped()
  19149. {
  19150. if (source != 0)
  19151. source->releaseResources();
  19152. sampleRate = 0.0;
  19153. bufferSize = 0;
  19154. tempBuffer.setSize (2, 8);
  19155. }
  19156. END_JUCE_NAMESPACE
  19157. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19158. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19159. BEGIN_JUCE_NAMESPACE
  19160. AudioTransportSource::AudioTransportSource()
  19161. : source (0),
  19162. resamplerSource (0),
  19163. bufferingSource (0),
  19164. positionableSource (0),
  19165. masterSource (0),
  19166. gain (1.0f),
  19167. lastGain (1.0f),
  19168. playing (false),
  19169. stopped (true),
  19170. sampleRate (44100.0),
  19171. sourceSampleRate (0.0),
  19172. blockSize (128),
  19173. readAheadBufferSize (0),
  19174. isPrepared (false),
  19175. inputStreamEOF (false)
  19176. {
  19177. }
  19178. AudioTransportSource::~AudioTransportSource()
  19179. {
  19180. setSource (0);
  19181. releaseResources();
  19182. }
  19183. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19184. int readAheadBufferSize_,
  19185. double sourceSampleRateToCorrectFor)
  19186. {
  19187. if (source == newSource)
  19188. {
  19189. if (source == 0)
  19190. return;
  19191. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19192. }
  19193. readAheadBufferSize = readAheadBufferSize_;
  19194. sourceSampleRate = sourceSampleRateToCorrectFor;
  19195. ResamplingAudioSource* newResamplerSource = 0;
  19196. BufferingAudioSource* newBufferingSource = 0;
  19197. PositionableAudioSource* newPositionableSource = 0;
  19198. AudioSource* newMasterSource = 0;
  19199. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19200. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19201. AudioSource* oldMasterSource = masterSource;
  19202. if (newSource != 0)
  19203. {
  19204. newPositionableSource = newSource;
  19205. if (readAheadBufferSize_ > 0)
  19206. newPositionableSource = newBufferingSource
  19207. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19208. newPositionableSource->setNextReadPosition (0);
  19209. if (sourceSampleRateToCorrectFor != 0)
  19210. newMasterSource = newResamplerSource
  19211. = new ResamplingAudioSource (newPositionableSource, false);
  19212. else
  19213. newMasterSource = newPositionableSource;
  19214. if (isPrepared)
  19215. {
  19216. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19217. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19218. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19219. }
  19220. }
  19221. {
  19222. const ScopedLock sl (callbackLock);
  19223. source = newSource;
  19224. resamplerSource = newResamplerSource;
  19225. bufferingSource = newBufferingSource;
  19226. masterSource = newMasterSource;
  19227. positionableSource = newPositionableSource;
  19228. playing = false;
  19229. }
  19230. if (oldMasterSource != 0)
  19231. oldMasterSource->releaseResources();
  19232. }
  19233. void AudioTransportSource::start()
  19234. {
  19235. if ((! playing) && masterSource != 0)
  19236. {
  19237. {
  19238. const ScopedLock sl (callbackLock);
  19239. playing = true;
  19240. stopped = false;
  19241. inputStreamEOF = false;
  19242. }
  19243. sendChangeMessage (this);
  19244. }
  19245. }
  19246. void AudioTransportSource::stop()
  19247. {
  19248. if (playing)
  19249. {
  19250. {
  19251. const ScopedLock sl (callbackLock);
  19252. playing = false;
  19253. }
  19254. int n = 500;
  19255. while (--n >= 0 && ! stopped)
  19256. Thread::sleep (2);
  19257. sendChangeMessage (this);
  19258. }
  19259. }
  19260. void AudioTransportSource::setPosition (double newPosition)
  19261. {
  19262. if (sampleRate > 0.0)
  19263. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19264. }
  19265. double AudioTransportSource::getCurrentPosition() const
  19266. {
  19267. if (sampleRate > 0.0)
  19268. return getNextReadPosition() / sampleRate;
  19269. else
  19270. return 0.0;
  19271. }
  19272. void AudioTransportSource::setNextReadPosition (int newPosition)
  19273. {
  19274. if (positionableSource != 0)
  19275. {
  19276. if (sampleRate > 0 && sourceSampleRate > 0)
  19277. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19278. positionableSource->setNextReadPosition (newPosition);
  19279. }
  19280. }
  19281. int AudioTransportSource::getNextReadPosition() const
  19282. {
  19283. if (positionableSource != 0)
  19284. {
  19285. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19286. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19287. }
  19288. return 0;
  19289. }
  19290. int AudioTransportSource::getTotalLength() const
  19291. {
  19292. const ScopedLock sl (callbackLock);
  19293. if (positionableSource != 0)
  19294. {
  19295. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19296. return roundToInt (positionableSource->getTotalLength() * ratio);
  19297. }
  19298. return 0;
  19299. }
  19300. bool AudioTransportSource::isLooping() const
  19301. {
  19302. const ScopedLock sl (callbackLock);
  19303. return positionableSource != 0
  19304. && positionableSource->isLooping();
  19305. }
  19306. void AudioTransportSource::setGain (const float newGain) throw()
  19307. {
  19308. gain = newGain;
  19309. }
  19310. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19311. double sampleRate_)
  19312. {
  19313. const ScopedLock sl (callbackLock);
  19314. sampleRate = sampleRate_;
  19315. blockSize = samplesPerBlockExpected;
  19316. if (masterSource != 0)
  19317. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19318. if (resamplerSource != 0 && sourceSampleRate != 0)
  19319. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19320. isPrepared = true;
  19321. }
  19322. void AudioTransportSource::releaseResources()
  19323. {
  19324. const ScopedLock sl (callbackLock);
  19325. if (masterSource != 0)
  19326. masterSource->releaseResources();
  19327. isPrepared = false;
  19328. }
  19329. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19330. {
  19331. const ScopedLock sl (callbackLock);
  19332. inputStreamEOF = false;
  19333. if (masterSource != 0 && ! stopped)
  19334. {
  19335. masterSource->getNextAudioBlock (info);
  19336. if (! playing)
  19337. {
  19338. // just stopped playing, so fade out the last block..
  19339. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19340. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19341. if (info.numSamples > 256)
  19342. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19343. }
  19344. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19345. && ! positionableSource->isLooping())
  19346. {
  19347. playing = false;
  19348. inputStreamEOF = true;
  19349. sendChangeMessage (this);
  19350. }
  19351. stopped = ! playing;
  19352. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19353. {
  19354. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19355. lastGain, gain);
  19356. }
  19357. }
  19358. else
  19359. {
  19360. info.clearActiveBufferRegion();
  19361. stopped = true;
  19362. }
  19363. lastGain = gain;
  19364. }
  19365. END_JUCE_NAMESPACE
  19366. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19367. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19368. BEGIN_JUCE_NAMESPACE
  19369. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19370. public Thread,
  19371. private Timer
  19372. {
  19373. public:
  19374. SharedBufferingAudioSourceThread()
  19375. : Thread ("Audio Buffer")
  19376. {
  19377. }
  19378. ~SharedBufferingAudioSourceThread()
  19379. {
  19380. stopThread (10000);
  19381. clearSingletonInstance();
  19382. }
  19383. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19384. void addSource (BufferingAudioSource* source)
  19385. {
  19386. const ScopedLock sl (lock);
  19387. if (! sources.contains (source))
  19388. {
  19389. sources.add (source);
  19390. startThread();
  19391. stopTimer();
  19392. }
  19393. notify();
  19394. }
  19395. void removeSource (BufferingAudioSource* source)
  19396. {
  19397. const ScopedLock sl (lock);
  19398. sources.removeValue (source);
  19399. if (sources.size() == 0)
  19400. startTimer (5000);
  19401. }
  19402. private:
  19403. Array <BufferingAudioSource*> sources;
  19404. CriticalSection lock;
  19405. void run()
  19406. {
  19407. while (! threadShouldExit())
  19408. {
  19409. bool busy = false;
  19410. for (int i = sources.size(); --i >= 0;)
  19411. {
  19412. if (threadShouldExit())
  19413. return;
  19414. const ScopedLock sl (lock);
  19415. BufferingAudioSource* const b = sources[i];
  19416. if (b != 0 && b->readNextBufferChunk())
  19417. busy = true;
  19418. }
  19419. if (! busy)
  19420. wait (500);
  19421. }
  19422. }
  19423. void timerCallback()
  19424. {
  19425. stopTimer();
  19426. if (sources.size() == 0)
  19427. deleteInstance();
  19428. }
  19429. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19430. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19431. };
  19432. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19433. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19434. const bool deleteSourceWhenDeleted_,
  19435. int numberOfSamplesToBuffer_)
  19436. : source (source_),
  19437. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19438. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19439. buffer (2, 0),
  19440. bufferValidStart (0),
  19441. bufferValidEnd (0),
  19442. nextPlayPos (0),
  19443. wasSourceLooping (false)
  19444. {
  19445. jassert (source_ != 0);
  19446. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19447. // not using a larger buffer..
  19448. }
  19449. BufferingAudioSource::~BufferingAudioSource()
  19450. {
  19451. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19452. if (thread != 0)
  19453. thread->removeSource (this);
  19454. if (deleteSourceWhenDeleted)
  19455. delete source;
  19456. }
  19457. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19458. {
  19459. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19460. sampleRate = sampleRate_;
  19461. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19462. buffer.clear();
  19463. bufferValidStart = 0;
  19464. bufferValidEnd = 0;
  19465. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19466. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19467. buffer.getNumSamples() / 2))
  19468. {
  19469. SharedBufferingAudioSourceThread::getInstance()->notify();
  19470. Thread::sleep (5);
  19471. }
  19472. }
  19473. void BufferingAudioSource::releaseResources()
  19474. {
  19475. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19476. if (thread != 0)
  19477. thread->removeSource (this);
  19478. buffer.setSize (2, 0);
  19479. source->releaseResources();
  19480. }
  19481. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19482. {
  19483. const ScopedLock sl (bufferStartPosLock);
  19484. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19485. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19486. if (validStart == validEnd)
  19487. {
  19488. // total cache miss
  19489. info.clearActiveBufferRegion();
  19490. }
  19491. else
  19492. {
  19493. if (validStart > 0)
  19494. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19495. if (validEnd < info.numSamples)
  19496. info.buffer->clear (info.startSample + validEnd,
  19497. info.numSamples - validEnd); // partial cache miss at end
  19498. if (validStart < validEnd)
  19499. {
  19500. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19501. {
  19502. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19503. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19504. if (startBufferIndex < endBufferIndex)
  19505. {
  19506. info.buffer->copyFrom (chan, info.startSample + validStart,
  19507. buffer,
  19508. chan, startBufferIndex,
  19509. validEnd - validStart);
  19510. }
  19511. else
  19512. {
  19513. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19514. info.buffer->copyFrom (chan, info.startSample + validStart,
  19515. buffer,
  19516. chan, startBufferIndex,
  19517. initialSize);
  19518. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19519. buffer,
  19520. chan, 0,
  19521. (validEnd - validStart) - initialSize);
  19522. }
  19523. }
  19524. }
  19525. nextPlayPos += info.numSamples;
  19526. if (source->isLooping() && nextPlayPos > 0)
  19527. nextPlayPos %= source->getTotalLength();
  19528. }
  19529. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19530. if (thread != 0)
  19531. thread->notify();
  19532. }
  19533. int BufferingAudioSource::getNextReadPosition() const
  19534. {
  19535. return (source->isLooping() && nextPlayPos > 0)
  19536. ? nextPlayPos % source->getTotalLength()
  19537. : nextPlayPos;
  19538. }
  19539. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19540. {
  19541. const ScopedLock sl (bufferStartPosLock);
  19542. nextPlayPos = newPosition;
  19543. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19544. if (thread != 0)
  19545. thread->notify();
  19546. }
  19547. bool BufferingAudioSource::readNextBufferChunk()
  19548. {
  19549. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19550. {
  19551. const ScopedLock sl (bufferStartPosLock);
  19552. if (wasSourceLooping != isLooping())
  19553. {
  19554. wasSourceLooping = isLooping();
  19555. bufferValidStart = 0;
  19556. bufferValidEnd = 0;
  19557. }
  19558. newBVS = jmax (0, nextPlayPos);
  19559. newBVE = newBVS + buffer.getNumSamples() - 4;
  19560. sectionToReadStart = 0;
  19561. sectionToReadEnd = 0;
  19562. const int maxChunkSize = 2048;
  19563. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19564. {
  19565. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19566. sectionToReadStart = newBVS;
  19567. sectionToReadEnd = newBVE;
  19568. bufferValidStart = 0;
  19569. bufferValidEnd = 0;
  19570. }
  19571. else if (abs (newBVS - bufferValidStart) > 512
  19572. || abs (newBVE - bufferValidEnd) > 512)
  19573. {
  19574. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19575. sectionToReadStart = bufferValidEnd;
  19576. sectionToReadEnd = newBVE;
  19577. bufferValidStart = newBVS;
  19578. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19579. }
  19580. }
  19581. if (sectionToReadStart != sectionToReadEnd)
  19582. {
  19583. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19584. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19585. if (bufferIndexStart < bufferIndexEnd)
  19586. {
  19587. readBufferSection (sectionToReadStart,
  19588. sectionToReadEnd - sectionToReadStart,
  19589. bufferIndexStart);
  19590. }
  19591. else
  19592. {
  19593. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19594. readBufferSection (sectionToReadStart,
  19595. initialSize,
  19596. bufferIndexStart);
  19597. readBufferSection (sectionToReadStart + initialSize,
  19598. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19599. 0);
  19600. }
  19601. const ScopedLock sl2 (bufferStartPosLock);
  19602. bufferValidStart = newBVS;
  19603. bufferValidEnd = newBVE;
  19604. return true;
  19605. }
  19606. else
  19607. {
  19608. return false;
  19609. }
  19610. }
  19611. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19612. {
  19613. if (source->getNextReadPosition() != start)
  19614. source->setNextReadPosition (start);
  19615. AudioSourceChannelInfo info;
  19616. info.buffer = &buffer;
  19617. info.startSample = bufferOffset;
  19618. info.numSamples = length;
  19619. source->getNextAudioBlock (info);
  19620. }
  19621. END_JUCE_NAMESPACE
  19622. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19623. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19624. BEGIN_JUCE_NAMESPACE
  19625. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19626. const bool deleteSourceWhenDeleted_)
  19627. : requiredNumberOfChannels (2),
  19628. source (source_),
  19629. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19630. buffer (2, 16)
  19631. {
  19632. remappedInfo.buffer = &buffer;
  19633. remappedInfo.startSample = 0;
  19634. }
  19635. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19636. {
  19637. if (deleteSourceWhenDeleted)
  19638. delete source;
  19639. }
  19640. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19641. {
  19642. const ScopedLock sl (lock);
  19643. requiredNumberOfChannels = requiredNumberOfChannels_;
  19644. }
  19645. void ChannelRemappingAudioSource::clearAllMappings()
  19646. {
  19647. const ScopedLock sl (lock);
  19648. remappedInputs.clear();
  19649. remappedOutputs.clear();
  19650. }
  19651. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19652. {
  19653. const ScopedLock sl (lock);
  19654. while (remappedInputs.size() < destIndex)
  19655. remappedInputs.add (-1);
  19656. remappedInputs.set (destIndex, sourceIndex);
  19657. }
  19658. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19659. {
  19660. const ScopedLock sl (lock);
  19661. while (remappedOutputs.size() < sourceIndex)
  19662. remappedOutputs.add (-1);
  19663. remappedOutputs.set (sourceIndex, destIndex);
  19664. }
  19665. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19666. {
  19667. const ScopedLock sl (lock);
  19668. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19669. return remappedInputs.getUnchecked (inputChannelIndex);
  19670. return -1;
  19671. }
  19672. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19673. {
  19674. const ScopedLock sl (lock);
  19675. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19676. return remappedOutputs .getUnchecked (outputChannelIndex);
  19677. return -1;
  19678. }
  19679. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19680. {
  19681. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19682. }
  19683. void ChannelRemappingAudioSource::releaseResources()
  19684. {
  19685. source->releaseResources();
  19686. }
  19687. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19688. {
  19689. const ScopedLock sl (lock);
  19690. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19691. const int numChans = bufferToFill.buffer->getNumChannels();
  19692. int i;
  19693. for (i = 0; i < buffer.getNumChannels(); ++i)
  19694. {
  19695. const int remappedChan = getRemappedInputChannel (i);
  19696. if (remappedChan >= 0 && remappedChan < numChans)
  19697. {
  19698. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19699. remappedChan,
  19700. bufferToFill.startSample,
  19701. bufferToFill.numSamples);
  19702. }
  19703. else
  19704. {
  19705. buffer.clear (i, 0, bufferToFill.numSamples);
  19706. }
  19707. }
  19708. remappedInfo.numSamples = bufferToFill.numSamples;
  19709. source->getNextAudioBlock (remappedInfo);
  19710. bufferToFill.clearActiveBufferRegion();
  19711. for (i = 0; i < requiredNumberOfChannels; ++i)
  19712. {
  19713. const int remappedChan = getRemappedOutputChannel (i);
  19714. if (remappedChan >= 0 && remappedChan < numChans)
  19715. {
  19716. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19717. buffer, i, 0, bufferToFill.numSamples);
  19718. }
  19719. }
  19720. }
  19721. XmlElement* ChannelRemappingAudioSource::createXml() const
  19722. {
  19723. XmlElement* e = new XmlElement ("MAPPINGS");
  19724. String ins, outs;
  19725. int i;
  19726. const ScopedLock sl (lock);
  19727. for (i = 0; i < remappedInputs.size(); ++i)
  19728. ins << remappedInputs.getUnchecked(i) << ' ';
  19729. for (i = 0; i < remappedOutputs.size(); ++i)
  19730. outs << remappedOutputs.getUnchecked(i) << ' ';
  19731. e->setAttribute ("inputs", ins.trimEnd());
  19732. e->setAttribute ("outputs", outs.trimEnd());
  19733. return e;
  19734. }
  19735. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19736. {
  19737. if (e.hasTagName ("MAPPINGS"))
  19738. {
  19739. const ScopedLock sl (lock);
  19740. clearAllMappings();
  19741. StringArray ins, outs;
  19742. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19743. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19744. int i;
  19745. for (i = 0; i < ins.size(); ++i)
  19746. remappedInputs.add (ins[i].getIntValue());
  19747. for (i = 0; i < outs.size(); ++i)
  19748. remappedOutputs.add (outs[i].getIntValue());
  19749. }
  19750. }
  19751. END_JUCE_NAMESPACE
  19752. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19753. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19754. BEGIN_JUCE_NAMESPACE
  19755. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19756. const bool deleteInputWhenDeleted_)
  19757. : input (inputSource),
  19758. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19759. {
  19760. jassert (inputSource != 0);
  19761. for (int i = 2; --i >= 0;)
  19762. iirFilters.add (new IIRFilter());
  19763. }
  19764. IIRFilterAudioSource::~IIRFilterAudioSource()
  19765. {
  19766. if (deleteInputWhenDeleted)
  19767. delete input;
  19768. }
  19769. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19770. {
  19771. for (int i = iirFilters.size(); --i >= 0;)
  19772. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19773. }
  19774. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19775. {
  19776. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19777. for (int i = iirFilters.size(); --i >= 0;)
  19778. iirFilters.getUnchecked(i)->reset();
  19779. }
  19780. void IIRFilterAudioSource::releaseResources()
  19781. {
  19782. input->releaseResources();
  19783. }
  19784. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19785. {
  19786. input->getNextAudioBlock (bufferToFill);
  19787. const int numChannels = bufferToFill.buffer->getNumChannels();
  19788. while (numChannels > iirFilters.size())
  19789. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19790. for (int i = 0; i < numChannels; ++i)
  19791. iirFilters.getUnchecked(i)
  19792. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19793. bufferToFill.numSamples);
  19794. }
  19795. END_JUCE_NAMESPACE
  19796. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19797. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19798. BEGIN_JUCE_NAMESPACE
  19799. MixerAudioSource::MixerAudioSource()
  19800. : tempBuffer (2, 0),
  19801. currentSampleRate (0.0),
  19802. bufferSizeExpected (0)
  19803. {
  19804. }
  19805. MixerAudioSource::~MixerAudioSource()
  19806. {
  19807. removeAllInputs();
  19808. }
  19809. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19810. {
  19811. if (input != 0 && ! inputs.contains (input))
  19812. {
  19813. double localRate;
  19814. int localBufferSize;
  19815. {
  19816. const ScopedLock sl (lock);
  19817. localRate = currentSampleRate;
  19818. localBufferSize = bufferSizeExpected;
  19819. }
  19820. if (localRate != 0.0)
  19821. input->prepareToPlay (localBufferSize, localRate);
  19822. const ScopedLock sl (lock);
  19823. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19824. inputs.add (input);
  19825. }
  19826. }
  19827. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19828. {
  19829. if (input != 0)
  19830. {
  19831. int index;
  19832. {
  19833. const ScopedLock sl (lock);
  19834. index = inputs.indexOf (input);
  19835. if (index >= 0)
  19836. {
  19837. inputsToDelete.shiftBits (index, 1);
  19838. inputs.remove (index);
  19839. }
  19840. }
  19841. if (index >= 0)
  19842. {
  19843. input->releaseResources();
  19844. if (deleteInput)
  19845. delete input;
  19846. }
  19847. }
  19848. }
  19849. void MixerAudioSource::removeAllInputs()
  19850. {
  19851. OwnedArray<AudioSource> toDelete;
  19852. {
  19853. const ScopedLock sl (lock);
  19854. for (int i = inputs.size(); --i >= 0;)
  19855. if (inputsToDelete[i])
  19856. toDelete.add (inputs.getUnchecked(i));
  19857. }
  19858. }
  19859. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19860. {
  19861. tempBuffer.setSize (2, samplesPerBlockExpected);
  19862. const ScopedLock sl (lock);
  19863. currentSampleRate = sampleRate;
  19864. bufferSizeExpected = samplesPerBlockExpected;
  19865. for (int i = inputs.size(); --i >= 0;)
  19866. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19867. }
  19868. void MixerAudioSource::releaseResources()
  19869. {
  19870. const ScopedLock sl (lock);
  19871. for (int i = inputs.size(); --i >= 0;)
  19872. inputs.getUnchecked(i)->releaseResources();
  19873. tempBuffer.setSize (2, 0);
  19874. currentSampleRate = 0;
  19875. bufferSizeExpected = 0;
  19876. }
  19877. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19878. {
  19879. const ScopedLock sl (lock);
  19880. if (inputs.size() > 0)
  19881. {
  19882. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19883. if (inputs.size() > 1)
  19884. {
  19885. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19886. info.buffer->getNumSamples());
  19887. AudioSourceChannelInfo info2;
  19888. info2.buffer = &tempBuffer;
  19889. info2.numSamples = info.numSamples;
  19890. info2.startSample = 0;
  19891. for (int i = 1; i < inputs.size(); ++i)
  19892. {
  19893. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19894. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19895. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19896. }
  19897. }
  19898. }
  19899. else
  19900. {
  19901. info.clearActiveBufferRegion();
  19902. }
  19903. }
  19904. END_JUCE_NAMESPACE
  19905. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19906. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19907. BEGIN_JUCE_NAMESPACE
  19908. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19909. const bool deleteInputWhenDeleted_,
  19910. const int numChannels_)
  19911. : input (inputSource),
  19912. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19913. ratio (1.0),
  19914. lastRatio (1.0),
  19915. buffer (numChannels_, 0),
  19916. sampsInBuffer (0),
  19917. numChannels (numChannels_)
  19918. {
  19919. jassert (input != 0);
  19920. }
  19921. ResamplingAudioSource::~ResamplingAudioSource()
  19922. {
  19923. if (deleteInputWhenDeleted)
  19924. delete input;
  19925. }
  19926. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19927. {
  19928. jassert (samplesInPerOutputSample > 0);
  19929. const ScopedLock sl (ratioLock);
  19930. ratio = jmax (0.0, samplesInPerOutputSample);
  19931. }
  19932. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19933. double sampleRate)
  19934. {
  19935. const ScopedLock sl (ratioLock);
  19936. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19937. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19938. buffer.clear();
  19939. sampsInBuffer = 0;
  19940. bufferPos = 0;
  19941. subSampleOffset = 0.0;
  19942. filterStates.calloc (numChannels);
  19943. srcBuffers.calloc (numChannels);
  19944. destBuffers.calloc (numChannels);
  19945. createLowPass (ratio);
  19946. resetFilters();
  19947. }
  19948. void ResamplingAudioSource::releaseResources()
  19949. {
  19950. input->releaseResources();
  19951. buffer.setSize (numChannels, 0);
  19952. }
  19953. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19954. {
  19955. const ScopedLock sl (ratioLock);
  19956. if (lastRatio != ratio)
  19957. {
  19958. createLowPass (ratio);
  19959. lastRatio = ratio;
  19960. }
  19961. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19962. int bufferSize = buffer.getNumSamples();
  19963. if (bufferSize < sampsNeeded + 8)
  19964. {
  19965. bufferPos %= bufferSize;
  19966. bufferSize = sampsNeeded + 32;
  19967. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19968. }
  19969. bufferPos %= bufferSize;
  19970. int endOfBufferPos = bufferPos + sampsInBuffer;
  19971. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19972. while (sampsNeeded > sampsInBuffer)
  19973. {
  19974. endOfBufferPos %= bufferSize;
  19975. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19976. bufferSize - endOfBufferPos);
  19977. AudioSourceChannelInfo readInfo;
  19978. readInfo.buffer = &buffer;
  19979. readInfo.numSamples = numToDo;
  19980. readInfo.startSample = endOfBufferPos;
  19981. input->getNextAudioBlock (readInfo);
  19982. if (ratio > 1.0001)
  19983. {
  19984. // for down-sampling, pre-apply the filter..
  19985. for (int i = channelsToProcess; --i >= 0;)
  19986. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19987. }
  19988. sampsInBuffer += numToDo;
  19989. endOfBufferPos += numToDo;
  19990. }
  19991. for (int channel = 0; channel < channelsToProcess; ++channel)
  19992. {
  19993. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19994. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19995. }
  19996. int nextPos = (bufferPos + 1) % bufferSize;
  19997. for (int m = info.numSamples; --m >= 0;)
  19998. {
  19999. const float alpha = (float) subSampleOffset;
  20000. const float invAlpha = 1.0f - alpha;
  20001. for (int channel = 0; channel < channelsToProcess; ++channel)
  20002. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20003. subSampleOffset += ratio;
  20004. jassert (sampsInBuffer > 0);
  20005. while (subSampleOffset >= 1.0)
  20006. {
  20007. if (++bufferPos >= bufferSize)
  20008. bufferPos = 0;
  20009. --sampsInBuffer;
  20010. nextPos = (bufferPos + 1) % bufferSize;
  20011. subSampleOffset -= 1.0;
  20012. }
  20013. }
  20014. if (ratio < 0.9999)
  20015. {
  20016. // for up-sampling, apply the filter after transposing..
  20017. for (int i = channelsToProcess; --i >= 0;)
  20018. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20019. }
  20020. else if (ratio <= 1.0001)
  20021. {
  20022. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20023. for (int i = channelsToProcess; --i >= 0;)
  20024. {
  20025. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20026. FilterState& fs = filterStates[i];
  20027. if (info.numSamples > 1)
  20028. {
  20029. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20030. }
  20031. else
  20032. {
  20033. fs.y2 = fs.y1;
  20034. fs.x2 = fs.x1;
  20035. }
  20036. fs.y1 = fs.x1 = *endOfBuffer;
  20037. }
  20038. }
  20039. jassert (sampsInBuffer >= 0);
  20040. }
  20041. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20042. {
  20043. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20044. : 0.5 * frequencyRatio;
  20045. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20046. const double nSquared = n * n;
  20047. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20048. setFilterCoefficients (c1,
  20049. c1 * 2.0f,
  20050. c1,
  20051. 1.0,
  20052. c1 * 2.0 * (1.0 - nSquared),
  20053. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20054. }
  20055. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20056. {
  20057. const double a = 1.0 / c4;
  20058. c1 *= a;
  20059. c2 *= a;
  20060. c3 *= a;
  20061. c5 *= a;
  20062. c6 *= a;
  20063. coefficients[0] = c1;
  20064. coefficients[1] = c2;
  20065. coefficients[2] = c3;
  20066. coefficients[3] = c4;
  20067. coefficients[4] = c5;
  20068. coefficients[5] = c6;
  20069. }
  20070. void ResamplingAudioSource::resetFilters()
  20071. {
  20072. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20073. }
  20074. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20075. {
  20076. while (--num >= 0)
  20077. {
  20078. const double in = *samples;
  20079. double out = coefficients[0] * in
  20080. + coefficients[1] * fs.x1
  20081. + coefficients[2] * fs.x2
  20082. - coefficients[4] * fs.y1
  20083. - coefficients[5] * fs.y2;
  20084. #if JUCE_INTEL
  20085. if (! (out < -1.0e-8 || out > 1.0e-8))
  20086. out = 0;
  20087. #endif
  20088. fs.x2 = fs.x1;
  20089. fs.x1 = in;
  20090. fs.y2 = fs.y1;
  20091. fs.y1 = out;
  20092. *samples++ = (float) out;
  20093. }
  20094. }
  20095. END_JUCE_NAMESPACE
  20096. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20097. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20098. BEGIN_JUCE_NAMESPACE
  20099. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20100. : frequency (1000.0),
  20101. sampleRate (44100.0),
  20102. currentPhase (0.0),
  20103. phasePerSample (0.0),
  20104. amplitude (0.5f)
  20105. {
  20106. }
  20107. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20108. {
  20109. }
  20110. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20111. {
  20112. amplitude = newAmplitude;
  20113. }
  20114. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20115. {
  20116. frequency = newFrequencyHz;
  20117. phasePerSample = 0.0;
  20118. }
  20119. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20120. double sampleRate_)
  20121. {
  20122. currentPhase = 0.0;
  20123. phasePerSample = 0.0;
  20124. sampleRate = sampleRate_;
  20125. }
  20126. void ToneGeneratorAudioSource::releaseResources()
  20127. {
  20128. }
  20129. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20130. {
  20131. if (phasePerSample == 0.0)
  20132. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20133. for (int i = 0; i < info.numSamples; ++i)
  20134. {
  20135. const float sample = amplitude * (float) std::sin (currentPhase);
  20136. currentPhase += phasePerSample;
  20137. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20138. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20139. }
  20140. }
  20141. END_JUCE_NAMESPACE
  20142. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20143. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20144. BEGIN_JUCE_NAMESPACE
  20145. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20146. : sampleRate (0),
  20147. bufferSize (0),
  20148. useDefaultInputChannels (true),
  20149. useDefaultOutputChannels (true)
  20150. {
  20151. }
  20152. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20153. {
  20154. return outputDeviceName == other.outputDeviceName
  20155. && inputDeviceName == other.inputDeviceName
  20156. && sampleRate == other.sampleRate
  20157. && bufferSize == other.bufferSize
  20158. && inputChannels == other.inputChannels
  20159. && useDefaultInputChannels == other.useDefaultInputChannels
  20160. && outputChannels == other.outputChannels
  20161. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20162. }
  20163. AudioDeviceManager::AudioDeviceManager()
  20164. : currentAudioDevice (0),
  20165. numInputChansNeeded (0),
  20166. numOutputChansNeeded (2),
  20167. listNeedsScanning (true),
  20168. useInputNames (false),
  20169. inputLevelMeasurementEnabledCount (0),
  20170. inputLevel (0),
  20171. tempBuffer (2, 2),
  20172. defaultMidiOutput (0),
  20173. cpuUsageMs (0),
  20174. timeToCpuScale (0)
  20175. {
  20176. callbackHandler.owner = this;
  20177. }
  20178. AudioDeviceManager::~AudioDeviceManager()
  20179. {
  20180. currentAudioDevice = 0;
  20181. defaultMidiOutput = 0;
  20182. }
  20183. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20184. {
  20185. if (availableDeviceTypes.size() == 0)
  20186. {
  20187. createAudioDeviceTypes (availableDeviceTypes);
  20188. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20189. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20190. if (availableDeviceTypes.size() > 0)
  20191. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20192. }
  20193. }
  20194. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20195. {
  20196. scanDevicesIfNeeded();
  20197. return availableDeviceTypes;
  20198. }
  20199. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20200. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20201. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20202. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20203. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20204. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20205. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20206. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20207. {
  20208. (void) list; // (to avoid 'unused param' warnings)
  20209. #if JUCE_WINDOWS
  20210. #if JUCE_WASAPI
  20211. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20212. list.add (juce_createAudioIODeviceType_WASAPI());
  20213. #endif
  20214. #if JUCE_DIRECTSOUND
  20215. list.add (juce_createAudioIODeviceType_DirectSound());
  20216. #endif
  20217. #if JUCE_ASIO
  20218. list.add (juce_createAudioIODeviceType_ASIO());
  20219. #endif
  20220. #endif
  20221. #if JUCE_MAC
  20222. list.add (juce_createAudioIODeviceType_CoreAudio());
  20223. #endif
  20224. #if JUCE_IOS
  20225. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20226. #endif
  20227. #if JUCE_LINUX && JUCE_ALSA
  20228. list.add (juce_createAudioIODeviceType_ALSA());
  20229. #endif
  20230. #if JUCE_LINUX && JUCE_JACK
  20231. list.add (juce_createAudioIODeviceType_JACK());
  20232. #endif
  20233. }
  20234. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20235. const int numOutputChannelsNeeded,
  20236. const XmlElement* const e,
  20237. const bool selectDefaultDeviceOnFailure,
  20238. const String& preferredDefaultDeviceName,
  20239. const AudioDeviceSetup* preferredSetupOptions)
  20240. {
  20241. scanDevicesIfNeeded();
  20242. numInputChansNeeded = numInputChannelsNeeded;
  20243. numOutputChansNeeded = numOutputChannelsNeeded;
  20244. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20245. {
  20246. lastExplicitSettings = new XmlElement (*e);
  20247. String error;
  20248. AudioDeviceSetup setup;
  20249. if (preferredSetupOptions != 0)
  20250. setup = *preferredSetupOptions;
  20251. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20252. {
  20253. setup.inputDeviceName = setup.outputDeviceName
  20254. = e->getStringAttribute ("audioDeviceName");
  20255. }
  20256. else
  20257. {
  20258. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20259. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20260. }
  20261. currentDeviceType = e->getStringAttribute ("deviceType");
  20262. if (currentDeviceType.isEmpty())
  20263. {
  20264. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20265. if (type != 0)
  20266. currentDeviceType = type->getTypeName();
  20267. else if (availableDeviceTypes.size() > 0)
  20268. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20269. }
  20270. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20271. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20272. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20273. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20274. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20275. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20276. error = setAudioDeviceSetup (setup, true);
  20277. midiInsFromXml.clear();
  20278. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20279. midiInsFromXml.add (c->getStringAttribute ("name"));
  20280. const StringArray allMidiIns (MidiInput::getDevices());
  20281. for (int i = allMidiIns.size(); --i >= 0;)
  20282. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20283. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20284. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20285. false, preferredDefaultDeviceName);
  20286. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20287. return error;
  20288. }
  20289. else
  20290. {
  20291. AudioDeviceSetup setup;
  20292. if (preferredSetupOptions != 0)
  20293. {
  20294. setup = *preferredSetupOptions;
  20295. }
  20296. else if (preferredDefaultDeviceName.isNotEmpty())
  20297. {
  20298. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20299. {
  20300. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20301. StringArray outs (type->getDeviceNames (false));
  20302. int i;
  20303. for (i = 0; i < outs.size(); ++i)
  20304. {
  20305. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20306. {
  20307. setup.outputDeviceName = outs[i];
  20308. break;
  20309. }
  20310. }
  20311. StringArray ins (type->getDeviceNames (true));
  20312. for (i = 0; i < ins.size(); ++i)
  20313. {
  20314. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20315. {
  20316. setup.inputDeviceName = ins[i];
  20317. break;
  20318. }
  20319. }
  20320. }
  20321. }
  20322. insertDefaultDeviceNames (setup);
  20323. return setAudioDeviceSetup (setup, false);
  20324. }
  20325. }
  20326. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20327. {
  20328. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20329. if (type != 0)
  20330. {
  20331. if (setup.outputDeviceName.isEmpty())
  20332. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20333. if (setup.inputDeviceName.isEmpty())
  20334. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20335. }
  20336. }
  20337. XmlElement* AudioDeviceManager::createStateXml() const
  20338. {
  20339. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20340. }
  20341. void AudioDeviceManager::scanDevicesIfNeeded()
  20342. {
  20343. if (listNeedsScanning)
  20344. {
  20345. listNeedsScanning = false;
  20346. createDeviceTypesIfNeeded();
  20347. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20348. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20349. }
  20350. }
  20351. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20352. {
  20353. scanDevicesIfNeeded();
  20354. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20355. {
  20356. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20357. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20358. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20359. {
  20360. return type;
  20361. }
  20362. }
  20363. return 0;
  20364. }
  20365. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20366. {
  20367. setup = currentSetup;
  20368. }
  20369. void AudioDeviceManager::deleteCurrentDevice()
  20370. {
  20371. currentAudioDevice = 0;
  20372. currentSetup.inputDeviceName = String::empty;
  20373. currentSetup.outputDeviceName = String::empty;
  20374. }
  20375. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20376. const bool treatAsChosenDevice)
  20377. {
  20378. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20379. {
  20380. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20381. && currentDeviceType != type)
  20382. {
  20383. currentDeviceType = type;
  20384. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20385. insertDefaultDeviceNames (s);
  20386. setAudioDeviceSetup (s, treatAsChosenDevice);
  20387. sendChangeMessage (this);
  20388. break;
  20389. }
  20390. }
  20391. }
  20392. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20393. {
  20394. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20395. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20396. return availableDeviceTypes[i];
  20397. return availableDeviceTypes[0];
  20398. }
  20399. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20400. const bool treatAsChosenDevice)
  20401. {
  20402. jassert (&newSetup != &currentSetup); // this will have no effect
  20403. if (newSetup == currentSetup && currentAudioDevice != 0)
  20404. return String::empty;
  20405. if (! (newSetup == currentSetup))
  20406. sendChangeMessage (this);
  20407. stopDevice();
  20408. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20409. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20410. String error;
  20411. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20412. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20413. {
  20414. deleteCurrentDevice();
  20415. if (treatAsChosenDevice)
  20416. updateXml();
  20417. return String::empty;
  20418. }
  20419. if (currentSetup.inputDeviceName != newInputDeviceName
  20420. || currentSetup.outputDeviceName != newOutputDeviceName
  20421. || currentAudioDevice == 0)
  20422. {
  20423. deleteCurrentDevice();
  20424. scanDevicesIfNeeded();
  20425. if (newOutputDeviceName.isNotEmpty()
  20426. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20427. {
  20428. return "No such device: " + newOutputDeviceName;
  20429. }
  20430. if (newInputDeviceName.isNotEmpty()
  20431. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20432. {
  20433. return "No such device: " + newInputDeviceName;
  20434. }
  20435. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20436. if (currentAudioDevice == 0)
  20437. 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!";
  20438. else
  20439. error = currentAudioDevice->getLastError();
  20440. if (error.isNotEmpty())
  20441. {
  20442. deleteCurrentDevice();
  20443. return error;
  20444. }
  20445. if (newSetup.useDefaultInputChannels)
  20446. {
  20447. inputChannels.clear();
  20448. inputChannels.setRange (0, numInputChansNeeded, true);
  20449. }
  20450. if (newSetup.useDefaultOutputChannels)
  20451. {
  20452. outputChannels.clear();
  20453. outputChannels.setRange (0, numOutputChansNeeded, true);
  20454. }
  20455. if (newInputDeviceName.isEmpty())
  20456. inputChannels.clear();
  20457. if (newOutputDeviceName.isEmpty())
  20458. outputChannels.clear();
  20459. }
  20460. if (! newSetup.useDefaultInputChannels)
  20461. inputChannels = newSetup.inputChannels;
  20462. if (! newSetup.useDefaultOutputChannels)
  20463. outputChannels = newSetup.outputChannels;
  20464. currentSetup = newSetup;
  20465. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20466. error = currentAudioDevice->open (inputChannels,
  20467. outputChannels,
  20468. currentSetup.sampleRate,
  20469. currentSetup.bufferSize);
  20470. if (error.isEmpty())
  20471. {
  20472. currentDeviceType = currentAudioDevice->getTypeName();
  20473. currentAudioDevice->start (&callbackHandler);
  20474. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20475. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20476. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20477. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20478. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20479. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20480. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20481. if (treatAsChosenDevice)
  20482. updateXml();
  20483. }
  20484. else
  20485. {
  20486. deleteCurrentDevice();
  20487. }
  20488. return error;
  20489. }
  20490. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20491. {
  20492. jassert (currentAudioDevice != 0);
  20493. if (rate > 0)
  20494. {
  20495. bool ok = false;
  20496. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20497. {
  20498. const double sr = currentAudioDevice->getSampleRate (i);
  20499. if (sr == rate)
  20500. ok = true;
  20501. }
  20502. if (! ok)
  20503. rate = 0;
  20504. }
  20505. if (rate == 0)
  20506. {
  20507. double lowestAbove44 = 0.0;
  20508. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20509. {
  20510. const double sr = currentAudioDevice->getSampleRate (i);
  20511. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20512. lowestAbove44 = sr;
  20513. }
  20514. if (lowestAbove44 == 0.0)
  20515. rate = currentAudioDevice->getSampleRate (0);
  20516. else
  20517. rate = lowestAbove44;
  20518. }
  20519. return rate;
  20520. }
  20521. void AudioDeviceManager::stopDevice()
  20522. {
  20523. if (currentAudioDevice != 0)
  20524. currentAudioDevice->stop();
  20525. testSound = 0;
  20526. }
  20527. void AudioDeviceManager::closeAudioDevice()
  20528. {
  20529. stopDevice();
  20530. currentAudioDevice = 0;
  20531. }
  20532. void AudioDeviceManager::restartLastAudioDevice()
  20533. {
  20534. if (currentAudioDevice == 0)
  20535. {
  20536. if (currentSetup.inputDeviceName.isEmpty()
  20537. && currentSetup.outputDeviceName.isEmpty())
  20538. {
  20539. // This method will only reload the last device that was running
  20540. // before closeAudioDevice() was called - you need to actually open
  20541. // one first, with setAudioDevice().
  20542. jassertfalse;
  20543. return;
  20544. }
  20545. AudioDeviceSetup s (currentSetup);
  20546. setAudioDeviceSetup (s, false);
  20547. }
  20548. }
  20549. void AudioDeviceManager::updateXml()
  20550. {
  20551. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20552. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20553. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20554. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20555. if (currentAudioDevice != 0)
  20556. {
  20557. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20558. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20559. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20560. if (! currentSetup.useDefaultInputChannels)
  20561. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20562. if (! currentSetup.useDefaultOutputChannels)
  20563. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20564. }
  20565. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20566. {
  20567. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20568. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20569. }
  20570. if (midiInsFromXml.size() > 0)
  20571. {
  20572. // Add any midi devices that have been enabled before, but which aren't currently
  20573. // open because the device has been disconnected.
  20574. const StringArray availableMidiDevices (MidiInput::getDevices());
  20575. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20576. {
  20577. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20578. {
  20579. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20580. m->setAttribute ("name", midiInsFromXml[i]);
  20581. }
  20582. }
  20583. }
  20584. if (defaultMidiOutputName.isNotEmpty())
  20585. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20586. }
  20587. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20588. {
  20589. {
  20590. const ScopedLock sl (audioCallbackLock);
  20591. if (callbacks.contains (newCallback))
  20592. return;
  20593. }
  20594. if (currentAudioDevice != 0 && newCallback != 0)
  20595. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20596. const ScopedLock sl (audioCallbackLock);
  20597. callbacks.add (newCallback);
  20598. }
  20599. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20600. {
  20601. if (callback != 0)
  20602. {
  20603. bool needsDeinitialising = currentAudioDevice != 0;
  20604. {
  20605. const ScopedLock sl (audioCallbackLock);
  20606. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20607. callbacks.removeValue (callback);
  20608. }
  20609. if (needsDeinitialising)
  20610. callback->audioDeviceStopped();
  20611. }
  20612. }
  20613. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20614. int numInputChannels,
  20615. float** outputChannelData,
  20616. int numOutputChannels,
  20617. int numSamples)
  20618. {
  20619. const ScopedLock sl (audioCallbackLock);
  20620. if (inputLevelMeasurementEnabledCount > 0)
  20621. {
  20622. for (int j = 0; j < numSamples; ++j)
  20623. {
  20624. float s = 0;
  20625. for (int i = 0; i < numInputChannels; ++i)
  20626. s += std::abs (inputChannelData[i][j]);
  20627. s /= numInputChannels;
  20628. const double decayFactor = 0.99992;
  20629. if (s > inputLevel)
  20630. inputLevel = s;
  20631. else if (inputLevel > 0.001f)
  20632. inputLevel *= decayFactor;
  20633. else
  20634. inputLevel = 0;
  20635. }
  20636. }
  20637. if (callbacks.size() > 0)
  20638. {
  20639. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20640. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20641. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20642. outputChannelData, numOutputChannels, numSamples);
  20643. float** const tempChans = tempBuffer.getArrayOfChannels();
  20644. for (int i = callbacks.size(); --i > 0;)
  20645. {
  20646. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20647. tempChans, numOutputChannels, numSamples);
  20648. for (int chan = 0; chan < numOutputChannels; ++chan)
  20649. {
  20650. const float* const src = tempChans [chan];
  20651. float* const dst = outputChannelData [chan];
  20652. if (src != 0 && dst != 0)
  20653. for (int j = 0; j < numSamples; ++j)
  20654. dst[j] += src[j];
  20655. }
  20656. }
  20657. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20658. const double filterAmount = 0.2;
  20659. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20660. }
  20661. else
  20662. {
  20663. for (int i = 0; i < numOutputChannels; ++i)
  20664. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20665. }
  20666. if (testSound != 0)
  20667. {
  20668. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20669. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20670. for (int i = 0; i < numOutputChannels; ++i)
  20671. for (int j = 0; j < numSamps; ++j)
  20672. outputChannelData [i][j] += src[j];
  20673. testSoundPosition += numSamps;
  20674. if (testSoundPosition >= testSound->getNumSamples())
  20675. testSound = 0;
  20676. }
  20677. }
  20678. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20679. {
  20680. cpuUsageMs = 0;
  20681. const double sampleRate = device->getCurrentSampleRate();
  20682. const int blockSize = device->getCurrentBufferSizeSamples();
  20683. if (sampleRate > 0.0 && blockSize > 0)
  20684. {
  20685. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20686. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20687. }
  20688. {
  20689. const ScopedLock sl (audioCallbackLock);
  20690. for (int i = callbacks.size(); --i >= 0;)
  20691. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20692. }
  20693. sendChangeMessage (this);
  20694. }
  20695. void AudioDeviceManager::audioDeviceStoppedInt()
  20696. {
  20697. cpuUsageMs = 0;
  20698. timeToCpuScale = 0;
  20699. sendChangeMessage (this);
  20700. const ScopedLock sl (audioCallbackLock);
  20701. for (int i = callbacks.size(); --i >= 0;)
  20702. callbacks.getUnchecked(i)->audioDeviceStopped();
  20703. }
  20704. double AudioDeviceManager::getCpuUsage() const
  20705. {
  20706. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20707. }
  20708. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20709. const bool enabled)
  20710. {
  20711. if (enabled != isMidiInputEnabled (name))
  20712. {
  20713. if (enabled)
  20714. {
  20715. const int index = MidiInput::getDevices().indexOf (name);
  20716. if (index >= 0)
  20717. {
  20718. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20719. if (min != 0)
  20720. {
  20721. enabledMidiInputs.add (min);
  20722. min->start();
  20723. }
  20724. }
  20725. }
  20726. else
  20727. {
  20728. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20729. if (enabledMidiInputs[i]->getName() == name)
  20730. enabledMidiInputs.remove (i);
  20731. }
  20732. updateXml();
  20733. sendChangeMessage (this);
  20734. }
  20735. }
  20736. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20737. {
  20738. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20739. if (enabledMidiInputs[i]->getName() == name)
  20740. return true;
  20741. return false;
  20742. }
  20743. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20744. MidiInputCallback* callback)
  20745. {
  20746. removeMidiInputCallback (name, callback);
  20747. if (name.isEmpty())
  20748. {
  20749. midiCallbacks.add (callback);
  20750. midiCallbackDevices.add (0);
  20751. }
  20752. else
  20753. {
  20754. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20755. {
  20756. if (enabledMidiInputs[i]->getName() == name)
  20757. {
  20758. const ScopedLock sl (midiCallbackLock);
  20759. midiCallbacks.add (callback);
  20760. midiCallbackDevices.add (enabledMidiInputs[i]);
  20761. break;
  20762. }
  20763. }
  20764. }
  20765. }
  20766. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20767. MidiInputCallback* /*callback*/)
  20768. {
  20769. const ScopedLock sl (midiCallbackLock);
  20770. for (int i = midiCallbacks.size(); --i >= 0;)
  20771. {
  20772. String devName;
  20773. if (midiCallbackDevices.getUnchecked(i) != 0)
  20774. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20775. if (devName == name)
  20776. {
  20777. midiCallbacks.remove (i);
  20778. midiCallbackDevices.remove (i);
  20779. }
  20780. }
  20781. }
  20782. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20783. const MidiMessage& message)
  20784. {
  20785. if (! message.isActiveSense())
  20786. {
  20787. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20788. const ScopedLock sl (midiCallbackLock);
  20789. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20790. {
  20791. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20792. if (md == source || (md == 0 && isDefaultSource))
  20793. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20794. }
  20795. }
  20796. }
  20797. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20798. {
  20799. if (defaultMidiOutputName != deviceName)
  20800. {
  20801. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20802. {
  20803. const ScopedLock sl (audioCallbackLock);
  20804. oldCallbacks = callbacks;
  20805. callbacks.clear();
  20806. }
  20807. if (currentAudioDevice != 0)
  20808. for (int i = oldCallbacks.size(); --i >= 0;)
  20809. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20810. defaultMidiOutput = 0;
  20811. defaultMidiOutputName = deviceName;
  20812. if (deviceName.isNotEmpty())
  20813. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20814. if (currentAudioDevice != 0)
  20815. for (int i = oldCallbacks.size(); --i >= 0;)
  20816. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20817. {
  20818. const ScopedLock sl (audioCallbackLock);
  20819. callbacks = oldCallbacks;
  20820. }
  20821. updateXml();
  20822. sendChangeMessage (this);
  20823. }
  20824. }
  20825. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20826. int numInputChannels,
  20827. float** outputChannelData,
  20828. int numOutputChannels,
  20829. int numSamples)
  20830. {
  20831. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20832. }
  20833. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20834. {
  20835. owner->audioDeviceAboutToStartInt (device);
  20836. }
  20837. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20838. {
  20839. owner->audioDeviceStoppedInt();
  20840. }
  20841. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20842. {
  20843. owner->handleIncomingMidiMessageInt (source, message);
  20844. }
  20845. void AudioDeviceManager::playTestSound()
  20846. {
  20847. { // cunningly nested to swap, unlock and delete in that order.
  20848. ScopedPointer <AudioSampleBuffer> oldSound;
  20849. {
  20850. const ScopedLock sl (audioCallbackLock);
  20851. oldSound = testSound;
  20852. }
  20853. }
  20854. testSoundPosition = 0;
  20855. if (currentAudioDevice != 0)
  20856. {
  20857. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20858. const int soundLength = (int) sampleRate;
  20859. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20860. float* samples = newSound->getSampleData (0);
  20861. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20862. const float amplitude = 0.5f;
  20863. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20864. for (int i = 0; i < soundLength; ++i)
  20865. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20866. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20867. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20868. const ScopedLock sl (audioCallbackLock);
  20869. testSound = newSound;
  20870. }
  20871. }
  20872. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20873. {
  20874. const ScopedLock sl (audioCallbackLock);
  20875. if (enableMeasurement)
  20876. ++inputLevelMeasurementEnabledCount;
  20877. else
  20878. --inputLevelMeasurementEnabledCount;
  20879. inputLevel = 0;
  20880. }
  20881. double AudioDeviceManager::getCurrentInputLevel() const
  20882. {
  20883. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20884. return inputLevel;
  20885. }
  20886. END_JUCE_NAMESPACE
  20887. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20888. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20889. BEGIN_JUCE_NAMESPACE
  20890. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20891. : name (deviceName),
  20892. typeName (typeName_)
  20893. {
  20894. }
  20895. AudioIODevice::~AudioIODevice()
  20896. {
  20897. }
  20898. bool AudioIODevice::hasControlPanel() const
  20899. {
  20900. return false;
  20901. }
  20902. bool AudioIODevice::showControlPanel()
  20903. {
  20904. jassertfalse; // this should only be called for devices which return true from
  20905. // their hasControlPanel() method.
  20906. return false;
  20907. }
  20908. END_JUCE_NAMESPACE
  20909. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20910. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20911. BEGIN_JUCE_NAMESPACE
  20912. AudioIODeviceType::AudioIODeviceType (const String& name)
  20913. : typeName (name)
  20914. {
  20915. }
  20916. AudioIODeviceType::~AudioIODeviceType()
  20917. {
  20918. }
  20919. END_JUCE_NAMESPACE
  20920. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20921. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20922. BEGIN_JUCE_NAMESPACE
  20923. MidiOutput::MidiOutput()
  20924. : Thread ("midi out"),
  20925. internal (0),
  20926. firstMessage (0)
  20927. {
  20928. }
  20929. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20930. const double sampleNumber)
  20931. : message (data, len, sampleNumber)
  20932. {
  20933. }
  20934. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20935. const double millisecondCounterToStartAt,
  20936. double samplesPerSecondForBuffer)
  20937. {
  20938. // You've got to call startBackgroundThread() for this to actually work..
  20939. jassert (isThreadRunning());
  20940. // this needs to be a value in the future - RTFM for this method!
  20941. jassert (millisecondCounterToStartAt > 0);
  20942. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20943. MidiBuffer::Iterator i (buffer);
  20944. const uint8* data;
  20945. int len, time;
  20946. while (i.getNextEvent (data, len, time))
  20947. {
  20948. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20949. PendingMessage* const m
  20950. = new PendingMessage (data, len, eventTime);
  20951. const ScopedLock sl (lock);
  20952. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20953. {
  20954. m->next = firstMessage;
  20955. firstMessage = m;
  20956. }
  20957. else
  20958. {
  20959. PendingMessage* mm = firstMessage;
  20960. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20961. mm = mm->next;
  20962. m->next = mm->next;
  20963. mm->next = m;
  20964. }
  20965. }
  20966. notify();
  20967. }
  20968. void MidiOutput::clearAllPendingMessages()
  20969. {
  20970. const ScopedLock sl (lock);
  20971. while (firstMessage != 0)
  20972. {
  20973. PendingMessage* const m = firstMessage;
  20974. firstMessage = firstMessage->next;
  20975. delete m;
  20976. }
  20977. }
  20978. void MidiOutput::startBackgroundThread()
  20979. {
  20980. startThread (9);
  20981. }
  20982. void MidiOutput::stopBackgroundThread()
  20983. {
  20984. stopThread (5000);
  20985. }
  20986. void MidiOutput::run()
  20987. {
  20988. while (! threadShouldExit())
  20989. {
  20990. uint32 now = Time::getMillisecondCounter();
  20991. uint32 eventTime = 0;
  20992. uint32 timeToWait = 500;
  20993. PendingMessage* message;
  20994. {
  20995. const ScopedLock sl (lock);
  20996. message = firstMessage;
  20997. if (message != 0)
  20998. {
  20999. eventTime = roundToInt (message->message.getTimeStamp());
  21000. if (eventTime > now + 20)
  21001. {
  21002. timeToWait = eventTime - (now + 20);
  21003. message = 0;
  21004. }
  21005. else
  21006. {
  21007. firstMessage = message->next;
  21008. }
  21009. }
  21010. }
  21011. if (message != 0)
  21012. {
  21013. if (eventTime > now)
  21014. {
  21015. Time::waitForMillisecondCounter (eventTime);
  21016. if (threadShouldExit())
  21017. break;
  21018. }
  21019. if (eventTime > now - 200)
  21020. sendMessageNow (message->message);
  21021. delete message;
  21022. }
  21023. else
  21024. {
  21025. jassert (timeToWait < 1000 * 30);
  21026. wait (timeToWait);
  21027. }
  21028. }
  21029. clearAllPendingMessages();
  21030. }
  21031. END_JUCE_NAMESPACE
  21032. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21033. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21034. BEGIN_JUCE_NAMESPACE
  21035. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21036. {
  21037. const double maxVal = (double) 0x7fff;
  21038. char* intData = static_cast <char*> (dest);
  21039. if (dest != (void*) source || destBytesPerSample <= 4)
  21040. {
  21041. for (int i = 0; i < numSamples; ++i)
  21042. {
  21043. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21044. intData += destBytesPerSample;
  21045. }
  21046. }
  21047. else
  21048. {
  21049. intData += destBytesPerSample * numSamples;
  21050. for (int i = numSamples; --i >= 0;)
  21051. {
  21052. intData -= destBytesPerSample;
  21053. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21054. }
  21055. }
  21056. }
  21057. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21058. {
  21059. const double maxVal = (double) 0x7fff;
  21060. char* intData = static_cast <char*> (dest);
  21061. if (dest != (void*) source || destBytesPerSample <= 4)
  21062. {
  21063. for (int i = 0; i < numSamples; ++i)
  21064. {
  21065. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21066. intData += destBytesPerSample;
  21067. }
  21068. }
  21069. else
  21070. {
  21071. intData += destBytesPerSample * numSamples;
  21072. for (int i = numSamples; --i >= 0;)
  21073. {
  21074. intData -= destBytesPerSample;
  21075. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21076. }
  21077. }
  21078. }
  21079. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21080. {
  21081. const double maxVal = (double) 0x7fffff;
  21082. char* intData = static_cast <char*> (dest);
  21083. if (dest != (void*) source || destBytesPerSample <= 4)
  21084. {
  21085. for (int i = 0; i < numSamples; ++i)
  21086. {
  21087. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21088. intData += destBytesPerSample;
  21089. }
  21090. }
  21091. else
  21092. {
  21093. intData += destBytesPerSample * numSamples;
  21094. for (int i = numSamples; --i >= 0;)
  21095. {
  21096. intData -= destBytesPerSample;
  21097. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21098. }
  21099. }
  21100. }
  21101. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21102. {
  21103. const double maxVal = (double) 0x7fffff;
  21104. char* intData = static_cast <char*> (dest);
  21105. if (dest != (void*) source || destBytesPerSample <= 4)
  21106. {
  21107. for (int i = 0; i < numSamples; ++i)
  21108. {
  21109. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21110. intData += destBytesPerSample;
  21111. }
  21112. }
  21113. else
  21114. {
  21115. intData += destBytesPerSample * numSamples;
  21116. for (int i = numSamples; --i >= 0;)
  21117. {
  21118. intData -= destBytesPerSample;
  21119. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21120. }
  21121. }
  21122. }
  21123. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21124. {
  21125. const double maxVal = (double) 0x7fffffff;
  21126. char* intData = static_cast <char*> (dest);
  21127. if (dest != (void*) source || destBytesPerSample <= 4)
  21128. {
  21129. for (int i = 0; i < numSamples; ++i)
  21130. {
  21131. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21132. intData += destBytesPerSample;
  21133. }
  21134. }
  21135. else
  21136. {
  21137. intData += destBytesPerSample * numSamples;
  21138. for (int i = numSamples; --i >= 0;)
  21139. {
  21140. intData -= destBytesPerSample;
  21141. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21142. }
  21143. }
  21144. }
  21145. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21146. {
  21147. const double maxVal = (double) 0x7fffffff;
  21148. char* intData = static_cast <char*> (dest);
  21149. if (dest != (void*) source || destBytesPerSample <= 4)
  21150. {
  21151. for (int i = 0; i < numSamples; ++i)
  21152. {
  21153. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21154. intData += destBytesPerSample;
  21155. }
  21156. }
  21157. else
  21158. {
  21159. intData += destBytesPerSample * numSamples;
  21160. for (int i = numSamples; --i >= 0;)
  21161. {
  21162. intData -= destBytesPerSample;
  21163. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21164. }
  21165. }
  21166. }
  21167. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21168. {
  21169. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21170. char* d = static_cast <char*> (dest);
  21171. for (int i = 0; i < numSamples; ++i)
  21172. {
  21173. *(float*) d = source[i];
  21174. #if JUCE_BIG_ENDIAN
  21175. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21176. #endif
  21177. d += destBytesPerSample;
  21178. }
  21179. }
  21180. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21181. {
  21182. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21183. char* d = static_cast <char*> (dest);
  21184. for (int i = 0; i < numSamples; ++i)
  21185. {
  21186. *(float*) d = source[i];
  21187. #if JUCE_LITTLE_ENDIAN
  21188. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21189. #endif
  21190. d += destBytesPerSample;
  21191. }
  21192. }
  21193. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21194. {
  21195. const float scale = 1.0f / 0x7fff;
  21196. const char* intData = static_cast <const char*> (source);
  21197. if (source != (void*) dest || srcBytesPerSample >= 4)
  21198. {
  21199. for (int i = 0; i < numSamples; ++i)
  21200. {
  21201. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21202. intData += srcBytesPerSample;
  21203. }
  21204. }
  21205. else
  21206. {
  21207. intData += srcBytesPerSample * numSamples;
  21208. for (int i = numSamples; --i >= 0;)
  21209. {
  21210. intData -= srcBytesPerSample;
  21211. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21212. }
  21213. }
  21214. }
  21215. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21216. {
  21217. const float scale = 1.0f / 0x7fff;
  21218. const char* intData = static_cast <const char*> (source);
  21219. if (source != (void*) dest || srcBytesPerSample >= 4)
  21220. {
  21221. for (int i = 0; i < numSamples; ++i)
  21222. {
  21223. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21224. intData += srcBytesPerSample;
  21225. }
  21226. }
  21227. else
  21228. {
  21229. intData += srcBytesPerSample * numSamples;
  21230. for (int i = numSamples; --i >= 0;)
  21231. {
  21232. intData -= srcBytesPerSample;
  21233. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21234. }
  21235. }
  21236. }
  21237. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21238. {
  21239. const float scale = 1.0f / 0x7fffff;
  21240. const char* intData = static_cast <const char*> (source);
  21241. if (source != (void*) dest || srcBytesPerSample >= 4)
  21242. {
  21243. for (int i = 0; i < numSamples; ++i)
  21244. {
  21245. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21246. intData += srcBytesPerSample;
  21247. }
  21248. }
  21249. else
  21250. {
  21251. intData += srcBytesPerSample * numSamples;
  21252. for (int i = numSamples; --i >= 0;)
  21253. {
  21254. intData -= srcBytesPerSample;
  21255. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21256. }
  21257. }
  21258. }
  21259. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21260. {
  21261. const float scale = 1.0f / 0x7fffff;
  21262. const char* intData = static_cast <const char*> (source);
  21263. if (source != (void*) dest || srcBytesPerSample >= 4)
  21264. {
  21265. for (int i = 0; i < numSamples; ++i)
  21266. {
  21267. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21268. intData += srcBytesPerSample;
  21269. }
  21270. }
  21271. else
  21272. {
  21273. intData += srcBytesPerSample * numSamples;
  21274. for (int i = numSamples; --i >= 0;)
  21275. {
  21276. intData -= srcBytesPerSample;
  21277. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21278. }
  21279. }
  21280. }
  21281. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21282. {
  21283. const float scale = 1.0f / 0x7fffffff;
  21284. const char* intData = static_cast <const char*> (source);
  21285. if (source != (void*) dest || srcBytesPerSample >= 4)
  21286. {
  21287. for (int i = 0; i < numSamples; ++i)
  21288. {
  21289. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21290. intData += srcBytesPerSample;
  21291. }
  21292. }
  21293. else
  21294. {
  21295. intData += srcBytesPerSample * numSamples;
  21296. for (int i = numSamples; --i >= 0;)
  21297. {
  21298. intData -= srcBytesPerSample;
  21299. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21300. }
  21301. }
  21302. }
  21303. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21304. {
  21305. const float scale = 1.0f / 0x7fffffff;
  21306. const char* intData = static_cast <const char*> (source);
  21307. if (source != (void*) dest || srcBytesPerSample >= 4)
  21308. {
  21309. for (int i = 0; i < numSamples; ++i)
  21310. {
  21311. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21312. intData += srcBytesPerSample;
  21313. }
  21314. }
  21315. else
  21316. {
  21317. intData += srcBytesPerSample * numSamples;
  21318. for (int i = numSamples; --i >= 0;)
  21319. {
  21320. intData -= srcBytesPerSample;
  21321. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21322. }
  21323. }
  21324. }
  21325. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21326. {
  21327. const char* s = static_cast <const char*> (source);
  21328. for (int i = 0; i < numSamples; ++i)
  21329. {
  21330. dest[i] = *(float*)s;
  21331. #if JUCE_BIG_ENDIAN
  21332. uint32* const d = (uint32*) (dest + i);
  21333. *d = ByteOrder::swap (*d);
  21334. #endif
  21335. s += srcBytesPerSample;
  21336. }
  21337. }
  21338. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21339. {
  21340. const char* s = static_cast <const char*> (source);
  21341. for (int i = 0; i < numSamples; ++i)
  21342. {
  21343. dest[i] = *(float*)s;
  21344. #if JUCE_LITTLE_ENDIAN
  21345. uint32* const d = (uint32*) (dest + i);
  21346. *d = ByteOrder::swap (*d);
  21347. #endif
  21348. s += srcBytesPerSample;
  21349. }
  21350. }
  21351. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21352. const float* const source,
  21353. void* const dest,
  21354. const int numSamples)
  21355. {
  21356. switch (destFormat)
  21357. {
  21358. case int16LE:
  21359. convertFloatToInt16LE (source, dest, numSamples);
  21360. break;
  21361. case int16BE:
  21362. convertFloatToInt16BE (source, dest, numSamples);
  21363. break;
  21364. case int24LE:
  21365. convertFloatToInt24LE (source, dest, numSamples);
  21366. break;
  21367. case int24BE:
  21368. convertFloatToInt24BE (source, dest, numSamples);
  21369. break;
  21370. case int32LE:
  21371. convertFloatToInt32LE (source, dest, numSamples);
  21372. break;
  21373. case int32BE:
  21374. convertFloatToInt32BE (source, dest, numSamples);
  21375. break;
  21376. case float32LE:
  21377. convertFloatToFloat32LE (source, dest, numSamples);
  21378. break;
  21379. case float32BE:
  21380. convertFloatToFloat32BE (source, dest, numSamples);
  21381. break;
  21382. default:
  21383. jassertfalse;
  21384. break;
  21385. }
  21386. }
  21387. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21388. const void* const source,
  21389. float* const dest,
  21390. const int numSamples)
  21391. {
  21392. switch (sourceFormat)
  21393. {
  21394. case int16LE:
  21395. convertInt16LEToFloat (source, dest, numSamples);
  21396. break;
  21397. case int16BE:
  21398. convertInt16BEToFloat (source, dest, numSamples);
  21399. break;
  21400. case int24LE:
  21401. convertInt24LEToFloat (source, dest, numSamples);
  21402. break;
  21403. case int24BE:
  21404. convertInt24BEToFloat (source, dest, numSamples);
  21405. break;
  21406. case int32LE:
  21407. convertInt32LEToFloat (source, dest, numSamples);
  21408. break;
  21409. case int32BE:
  21410. convertInt32BEToFloat (source, dest, numSamples);
  21411. break;
  21412. case float32LE:
  21413. convertFloat32LEToFloat (source, dest, numSamples);
  21414. break;
  21415. case float32BE:
  21416. convertFloat32BEToFloat (source, dest, numSamples);
  21417. break;
  21418. default:
  21419. jassertfalse;
  21420. break;
  21421. }
  21422. }
  21423. void AudioDataConverters::interleaveSamples (const float** const source,
  21424. float* const dest,
  21425. const int numSamples,
  21426. const int numChannels)
  21427. {
  21428. for (int chan = 0; chan < numChannels; ++chan)
  21429. {
  21430. int i = chan;
  21431. const float* src = source [chan];
  21432. for (int j = 0; j < numSamples; ++j)
  21433. {
  21434. dest [i] = src [j];
  21435. i += numChannels;
  21436. }
  21437. }
  21438. }
  21439. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21440. float** const dest,
  21441. const int numSamples,
  21442. const int numChannels)
  21443. {
  21444. for (int chan = 0; chan < numChannels; ++chan)
  21445. {
  21446. int i = chan;
  21447. float* dst = dest [chan];
  21448. for (int j = 0; j < numSamples; ++j)
  21449. {
  21450. dst [j] = source [i];
  21451. i += numChannels;
  21452. }
  21453. }
  21454. }
  21455. #if JUCE_UNIT_TESTS
  21456. class AudioConversionTests : public UnitTest
  21457. {
  21458. public:
  21459. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21460. template <class F1, class E1, class F2, class E2>
  21461. struct Test5
  21462. {
  21463. static void test (UnitTest& unitTest)
  21464. {
  21465. test (unitTest, false);
  21466. test (unitTest, true);
  21467. }
  21468. static void test (UnitTest& unitTest, bool inPlace)
  21469. {
  21470. const int numSamples = 2048;
  21471. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21472. {
  21473. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21474. bool clippingFailed = false;
  21475. for (int i = 0; i < numSamples / 2; ++i)
  21476. {
  21477. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21478. if (! d.isFloatingPoint())
  21479. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21480. ++d;
  21481. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21482. ++d;
  21483. }
  21484. unitTest.expect (! clippingFailed);
  21485. }
  21486. // convert data from the source to dest format..
  21487. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21488. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21489. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21490. // ..and back again..
  21491. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21492. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21493. if (! inPlace)
  21494. zerostruct (reversed);
  21495. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21496. {
  21497. int biggestDiff = 0;
  21498. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21499. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21500. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21501. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21502. for (int i = 0; i < numSamples; ++i)
  21503. {
  21504. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21505. ++d1;
  21506. ++d2;
  21507. }
  21508. unitTest.expect (biggestDiff <= errorMargin);
  21509. }
  21510. }
  21511. };
  21512. template <class F1, class E1, class FormatType>
  21513. struct Test3
  21514. {
  21515. static void test (UnitTest& unitTest)
  21516. {
  21517. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21518. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21519. }
  21520. };
  21521. template <class FormatType, class Endianness>
  21522. struct Test2
  21523. {
  21524. static void test (UnitTest& unitTest)
  21525. {
  21526. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21527. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21528. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21529. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21530. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21531. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21532. }
  21533. };
  21534. template <class FormatType>
  21535. struct Test1
  21536. {
  21537. static void test (UnitTest& unitTest)
  21538. {
  21539. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21540. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21541. }
  21542. };
  21543. void runTest()
  21544. {
  21545. beginTest ("Round-trip conversion");
  21546. Test1 <AudioData::Int8>::test (*this);
  21547. Test1 <AudioData::Int16>::test (*this);
  21548. Test1 <AudioData::Int24>::test (*this);
  21549. Test1 <AudioData::Int32>::test (*this);
  21550. Test1 <AudioData::Float32>::test (*this);
  21551. }
  21552. };
  21553. static AudioConversionTests audioConversionUnitTests;
  21554. #endif
  21555. END_JUCE_NAMESPACE
  21556. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21557. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21558. BEGIN_JUCE_NAMESPACE
  21559. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21560. const int numSamples) throw()
  21561. : numChannels (numChannels_),
  21562. size (numSamples)
  21563. {
  21564. jassert (numSamples >= 0);
  21565. jassert (numChannels_ > 0);
  21566. allocateData();
  21567. }
  21568. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21569. : numChannels (other.numChannels),
  21570. size (other.size)
  21571. {
  21572. allocateData();
  21573. const size_t numBytes = size * sizeof (float);
  21574. for (int i = 0; i < numChannels; ++i)
  21575. memcpy (channels[i], other.channels[i], numBytes);
  21576. }
  21577. void AudioSampleBuffer::allocateData()
  21578. {
  21579. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21580. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21581. allocatedData.malloc (allocatedBytes);
  21582. channels = reinterpret_cast <float**> (allocatedData.getData());
  21583. float* chan = (float*) (allocatedData + channelListSize);
  21584. for (int i = 0; i < numChannels; ++i)
  21585. {
  21586. channels[i] = chan;
  21587. chan += size;
  21588. }
  21589. channels [numChannels] = 0;
  21590. }
  21591. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21592. const int numChannels_,
  21593. const int numSamples) throw()
  21594. : numChannels (numChannels_),
  21595. size (numSamples),
  21596. allocatedBytes (0)
  21597. {
  21598. jassert (numChannels_ > 0);
  21599. allocateChannels (dataToReferTo);
  21600. }
  21601. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21602. const int newNumChannels,
  21603. const int newNumSamples) throw()
  21604. {
  21605. jassert (newNumChannels > 0);
  21606. allocatedBytes = 0;
  21607. allocatedData.free();
  21608. numChannels = newNumChannels;
  21609. size = newNumSamples;
  21610. allocateChannels (dataToReferTo);
  21611. }
  21612. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21613. {
  21614. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21615. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21616. {
  21617. channels = static_cast <float**> (preallocatedChannelSpace);
  21618. }
  21619. else
  21620. {
  21621. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21622. channels = reinterpret_cast <float**> (allocatedData.getData());
  21623. }
  21624. for (int i = 0; i < numChannels; ++i)
  21625. {
  21626. // you have to pass in the same number of valid pointers as numChannels
  21627. jassert (dataToReferTo[i] != 0);
  21628. channels[i] = dataToReferTo[i];
  21629. }
  21630. channels [numChannels] = 0;
  21631. }
  21632. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21633. {
  21634. if (this != &other)
  21635. {
  21636. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21637. const size_t numBytes = size * sizeof (float);
  21638. for (int i = 0; i < numChannels; ++i)
  21639. memcpy (channels[i], other.channels[i], numBytes);
  21640. }
  21641. return *this;
  21642. }
  21643. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21644. {
  21645. }
  21646. void AudioSampleBuffer::setSize (const int newNumChannels,
  21647. const int newNumSamples,
  21648. const bool keepExistingContent,
  21649. const bool clearExtraSpace,
  21650. const bool avoidReallocating) throw()
  21651. {
  21652. jassert (newNumChannels > 0);
  21653. if (newNumSamples != size || newNumChannels != numChannels)
  21654. {
  21655. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21656. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21657. if (keepExistingContent)
  21658. {
  21659. HeapBlock <char> newData;
  21660. newData.allocate (newTotalBytes, clearExtraSpace);
  21661. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21662. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21663. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21664. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21665. for (int i = 0; i < numChansToCopy; ++i)
  21666. {
  21667. memcpy (newChan, channels[i], numBytesToCopy);
  21668. newChannels[i] = newChan;
  21669. newChan += newNumSamples;
  21670. }
  21671. allocatedData.swapWith (newData);
  21672. allocatedBytes = (int) newTotalBytes;
  21673. channels = newChannels;
  21674. }
  21675. else
  21676. {
  21677. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21678. {
  21679. if (clearExtraSpace)
  21680. zeromem (allocatedData, newTotalBytes);
  21681. }
  21682. else
  21683. {
  21684. allocatedBytes = newTotalBytes;
  21685. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21686. channels = reinterpret_cast <float**> (allocatedData.getData());
  21687. }
  21688. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21689. for (int i = 0; i < newNumChannels; ++i)
  21690. {
  21691. channels[i] = chan;
  21692. chan += newNumSamples;
  21693. }
  21694. }
  21695. channels [newNumChannels] = 0;
  21696. size = newNumSamples;
  21697. numChannels = newNumChannels;
  21698. }
  21699. }
  21700. void AudioSampleBuffer::clear() throw()
  21701. {
  21702. for (int i = 0; i < numChannels; ++i)
  21703. zeromem (channels[i], size * sizeof (float));
  21704. }
  21705. void AudioSampleBuffer::clear (const int startSample,
  21706. const int numSamples) throw()
  21707. {
  21708. jassert (startSample >= 0 && startSample + numSamples <= size);
  21709. for (int i = 0; i < numChannels; ++i)
  21710. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21711. }
  21712. void AudioSampleBuffer::clear (const int channel,
  21713. const int startSample,
  21714. const int numSamples) throw()
  21715. {
  21716. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21717. jassert (startSample >= 0 && startSample + numSamples <= size);
  21718. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21719. }
  21720. void AudioSampleBuffer::applyGain (const int channel,
  21721. const int startSample,
  21722. int numSamples,
  21723. const float gain) throw()
  21724. {
  21725. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21726. jassert (startSample >= 0 && startSample + numSamples <= size);
  21727. if (gain != 1.0f)
  21728. {
  21729. float* d = channels [channel] + startSample;
  21730. if (gain == 0.0f)
  21731. {
  21732. zeromem (d, sizeof (float) * numSamples);
  21733. }
  21734. else
  21735. {
  21736. while (--numSamples >= 0)
  21737. *d++ *= gain;
  21738. }
  21739. }
  21740. }
  21741. void AudioSampleBuffer::applyGainRamp (const int channel,
  21742. const int startSample,
  21743. int numSamples,
  21744. float startGain,
  21745. float endGain) throw()
  21746. {
  21747. if (startGain == endGain)
  21748. {
  21749. applyGain (channel, startSample, numSamples, startGain);
  21750. }
  21751. else
  21752. {
  21753. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21754. jassert (startSample >= 0 && startSample + numSamples <= size);
  21755. const float increment = (endGain - startGain) / numSamples;
  21756. float* d = channels [channel] + startSample;
  21757. while (--numSamples >= 0)
  21758. {
  21759. *d++ *= startGain;
  21760. startGain += increment;
  21761. }
  21762. }
  21763. }
  21764. void AudioSampleBuffer::applyGain (const int startSample,
  21765. const int numSamples,
  21766. const float gain) throw()
  21767. {
  21768. for (int i = 0; i < numChannels; ++i)
  21769. applyGain (i, startSample, numSamples, gain);
  21770. }
  21771. void AudioSampleBuffer::addFrom (const int destChannel,
  21772. const int destStartSample,
  21773. const AudioSampleBuffer& source,
  21774. const int sourceChannel,
  21775. const int sourceStartSample,
  21776. int numSamples,
  21777. const float gain) throw()
  21778. {
  21779. jassert (&source != this || sourceChannel != destChannel);
  21780. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21781. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21782. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21783. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21784. if (gain != 0.0f && numSamples > 0)
  21785. {
  21786. float* d = channels [destChannel] + destStartSample;
  21787. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21788. if (gain != 1.0f)
  21789. {
  21790. while (--numSamples >= 0)
  21791. *d++ += gain * *s++;
  21792. }
  21793. else
  21794. {
  21795. while (--numSamples >= 0)
  21796. *d++ += *s++;
  21797. }
  21798. }
  21799. }
  21800. void AudioSampleBuffer::addFrom (const int destChannel,
  21801. const int destStartSample,
  21802. const float* source,
  21803. int numSamples,
  21804. const float gain) throw()
  21805. {
  21806. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21807. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21808. jassert (source != 0);
  21809. if (gain != 0.0f && numSamples > 0)
  21810. {
  21811. float* d = channels [destChannel] + destStartSample;
  21812. if (gain != 1.0f)
  21813. {
  21814. while (--numSamples >= 0)
  21815. *d++ += gain * *source++;
  21816. }
  21817. else
  21818. {
  21819. while (--numSamples >= 0)
  21820. *d++ += *source++;
  21821. }
  21822. }
  21823. }
  21824. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21825. const int destStartSample,
  21826. const float* source,
  21827. int numSamples,
  21828. float startGain,
  21829. const float endGain) throw()
  21830. {
  21831. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21832. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21833. jassert (source != 0);
  21834. if (startGain == endGain)
  21835. {
  21836. addFrom (destChannel,
  21837. destStartSample,
  21838. source,
  21839. numSamples,
  21840. startGain);
  21841. }
  21842. else
  21843. {
  21844. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21845. {
  21846. const float increment = (endGain - startGain) / numSamples;
  21847. float* d = channels [destChannel] + destStartSample;
  21848. while (--numSamples >= 0)
  21849. {
  21850. *d++ += startGain * *source++;
  21851. startGain += increment;
  21852. }
  21853. }
  21854. }
  21855. }
  21856. void AudioSampleBuffer::copyFrom (const int destChannel,
  21857. const int destStartSample,
  21858. const AudioSampleBuffer& source,
  21859. const int sourceChannel,
  21860. const int sourceStartSample,
  21861. int numSamples) throw()
  21862. {
  21863. jassert (&source != this || sourceChannel != destChannel);
  21864. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21865. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21866. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21867. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21868. if (numSamples > 0)
  21869. {
  21870. memcpy (channels [destChannel] + destStartSample,
  21871. source.channels [sourceChannel] + sourceStartSample,
  21872. sizeof (float) * numSamples);
  21873. }
  21874. }
  21875. void AudioSampleBuffer::copyFrom (const int destChannel,
  21876. const int destStartSample,
  21877. const float* source,
  21878. int numSamples) throw()
  21879. {
  21880. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21881. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21882. jassert (source != 0);
  21883. if (numSamples > 0)
  21884. {
  21885. memcpy (channels [destChannel] + destStartSample,
  21886. source,
  21887. sizeof (float) * numSamples);
  21888. }
  21889. }
  21890. void AudioSampleBuffer::copyFrom (const int destChannel,
  21891. const int destStartSample,
  21892. const float* source,
  21893. int numSamples,
  21894. const float gain) throw()
  21895. {
  21896. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21897. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21898. jassert (source != 0);
  21899. if (numSamples > 0)
  21900. {
  21901. float* d = channels [destChannel] + destStartSample;
  21902. if (gain != 1.0f)
  21903. {
  21904. if (gain == 0)
  21905. {
  21906. zeromem (d, sizeof (float) * numSamples);
  21907. }
  21908. else
  21909. {
  21910. while (--numSamples >= 0)
  21911. *d++ = gain * *source++;
  21912. }
  21913. }
  21914. else
  21915. {
  21916. memcpy (d, source, sizeof (float) * numSamples);
  21917. }
  21918. }
  21919. }
  21920. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21921. const int destStartSample,
  21922. const float* source,
  21923. int numSamples,
  21924. float startGain,
  21925. float endGain) throw()
  21926. {
  21927. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21928. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21929. jassert (source != 0);
  21930. if (startGain == endGain)
  21931. {
  21932. copyFrom (destChannel,
  21933. destStartSample,
  21934. source,
  21935. numSamples,
  21936. startGain);
  21937. }
  21938. else
  21939. {
  21940. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21941. {
  21942. const float increment = (endGain - startGain) / numSamples;
  21943. float* d = channels [destChannel] + destStartSample;
  21944. while (--numSamples >= 0)
  21945. {
  21946. *d++ = startGain * *source++;
  21947. startGain += increment;
  21948. }
  21949. }
  21950. }
  21951. }
  21952. void AudioSampleBuffer::findMinMax (const int channel,
  21953. const int startSample,
  21954. int numSamples,
  21955. float& minVal,
  21956. float& maxVal) const throw()
  21957. {
  21958. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21959. jassert (startSample >= 0 && startSample + numSamples <= size);
  21960. if (numSamples <= 0)
  21961. {
  21962. minVal = 0.0f;
  21963. maxVal = 0.0f;
  21964. }
  21965. else
  21966. {
  21967. const float* d = channels [channel] + startSample;
  21968. float mn = *d++;
  21969. float mx = mn;
  21970. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21971. {
  21972. const float samp = *d++;
  21973. if (samp > mx)
  21974. mx = samp;
  21975. if (samp < mn)
  21976. mn = samp;
  21977. }
  21978. maxVal = mx;
  21979. minVal = mn;
  21980. }
  21981. }
  21982. float AudioSampleBuffer::getMagnitude (const int channel,
  21983. const int startSample,
  21984. const int numSamples) const throw()
  21985. {
  21986. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21987. jassert (startSample >= 0 && startSample + numSamples <= size);
  21988. float mn, mx;
  21989. findMinMax (channel, startSample, numSamples, mn, mx);
  21990. return jmax (mn, -mn, mx, -mx);
  21991. }
  21992. float AudioSampleBuffer::getMagnitude (const int startSample,
  21993. const int numSamples) const throw()
  21994. {
  21995. float mag = 0.0f;
  21996. for (int i = 0; i < numChannels; ++i)
  21997. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21998. return mag;
  21999. }
  22000. float AudioSampleBuffer::getRMSLevel (const int channel,
  22001. const int startSample,
  22002. const int numSamples) const throw()
  22003. {
  22004. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22005. jassert (startSample >= 0 && startSample + numSamples <= size);
  22006. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22007. return 0.0f;
  22008. const float* const data = channels [channel] + startSample;
  22009. double sum = 0.0;
  22010. for (int i = 0; i < numSamples; ++i)
  22011. {
  22012. const float sample = data [i];
  22013. sum += sample * sample;
  22014. }
  22015. return (float) std::sqrt (sum / numSamples);
  22016. }
  22017. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22018. const int startSample,
  22019. const int numSamples,
  22020. const int readerStartSample,
  22021. const bool useLeftChan,
  22022. const bool useRightChan)
  22023. {
  22024. jassert (reader != 0);
  22025. jassert (startSample >= 0 && startSample + numSamples <= size);
  22026. if (numSamples > 0)
  22027. {
  22028. int* chans[3];
  22029. if (useLeftChan == useRightChan)
  22030. {
  22031. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22032. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22033. }
  22034. else if (useLeftChan || (reader->numChannels == 1))
  22035. {
  22036. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22037. chans[1] = 0;
  22038. }
  22039. else if (useRightChan)
  22040. {
  22041. chans[0] = 0;
  22042. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22043. }
  22044. chans[2] = 0;
  22045. reader->read (chans, 2, readerStartSample, numSamples, true);
  22046. if (! reader->usesFloatingPointData)
  22047. {
  22048. for (int j = 0; j < 2; ++j)
  22049. {
  22050. float* const d = reinterpret_cast <float*> (chans[j]);
  22051. if (d != 0)
  22052. {
  22053. const float multiplier = 1.0f / 0x7fffffff;
  22054. for (int i = 0; i < numSamples; ++i)
  22055. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22056. }
  22057. }
  22058. }
  22059. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22060. {
  22061. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22062. memcpy (getSampleData (1, startSample),
  22063. getSampleData (0, startSample),
  22064. sizeof (float) * numSamples);
  22065. }
  22066. }
  22067. }
  22068. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22069. const int startSample,
  22070. const int numSamples) const
  22071. {
  22072. jassert (writer != 0);
  22073. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22074. }
  22075. END_JUCE_NAMESPACE
  22076. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22077. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22078. BEGIN_JUCE_NAMESPACE
  22079. IIRFilter::IIRFilter()
  22080. : active (false)
  22081. {
  22082. reset();
  22083. }
  22084. IIRFilter::IIRFilter (const IIRFilter& other)
  22085. : active (other.active)
  22086. {
  22087. const ScopedLock sl (other.processLock);
  22088. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22089. reset();
  22090. }
  22091. IIRFilter::~IIRFilter()
  22092. {
  22093. }
  22094. void IIRFilter::reset() throw()
  22095. {
  22096. const ScopedLock sl (processLock);
  22097. x1 = 0;
  22098. x2 = 0;
  22099. y1 = 0;
  22100. y2 = 0;
  22101. }
  22102. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22103. {
  22104. float out = coefficients[0] * in
  22105. + coefficients[1] * x1
  22106. + coefficients[2] * x2
  22107. - coefficients[4] * y1
  22108. - coefficients[5] * y2;
  22109. #if JUCE_INTEL
  22110. if (! (out < -1.0e-8 || out > 1.0e-8))
  22111. out = 0;
  22112. #endif
  22113. x2 = x1;
  22114. x1 = in;
  22115. y2 = y1;
  22116. y1 = out;
  22117. return out;
  22118. }
  22119. void IIRFilter::processSamples (float* const samples,
  22120. const int numSamples) throw()
  22121. {
  22122. const ScopedLock sl (processLock);
  22123. if (active)
  22124. {
  22125. for (int i = 0; i < numSamples; ++i)
  22126. {
  22127. const float in = samples[i];
  22128. float out = coefficients[0] * in
  22129. + coefficients[1] * x1
  22130. + coefficients[2] * x2
  22131. - coefficients[4] * y1
  22132. - coefficients[5] * y2;
  22133. #if JUCE_INTEL
  22134. if (! (out < -1.0e-8 || out > 1.0e-8))
  22135. out = 0;
  22136. #endif
  22137. x2 = x1;
  22138. x1 = in;
  22139. y2 = y1;
  22140. y1 = out;
  22141. samples[i] = out;
  22142. }
  22143. }
  22144. }
  22145. void IIRFilter::makeLowPass (const double sampleRate,
  22146. const double frequency) throw()
  22147. {
  22148. jassert (sampleRate > 0);
  22149. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22150. const double nSquared = n * n;
  22151. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22152. setCoefficients (c1,
  22153. c1 * 2.0f,
  22154. c1,
  22155. 1.0,
  22156. c1 * 2.0 * (1.0 - nSquared),
  22157. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22158. }
  22159. void IIRFilter::makeHighPass (const double sampleRate,
  22160. const double frequency) throw()
  22161. {
  22162. const double n = tan (double_Pi * frequency / sampleRate);
  22163. const double nSquared = n * n;
  22164. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22165. setCoefficients (c1,
  22166. c1 * -2.0f,
  22167. c1,
  22168. 1.0,
  22169. c1 * 2.0 * (nSquared - 1.0),
  22170. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22171. }
  22172. void IIRFilter::makeLowShelf (const double sampleRate,
  22173. const double cutOffFrequency,
  22174. const double Q,
  22175. const float gainFactor) throw()
  22176. {
  22177. jassert (sampleRate > 0);
  22178. jassert (Q > 0);
  22179. const double A = jmax (0.0f, gainFactor);
  22180. const double aminus1 = A - 1.0;
  22181. const double aplus1 = A + 1.0;
  22182. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22183. const double coso = std::cos (omega);
  22184. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22185. const double aminus1TimesCoso = aminus1 * coso;
  22186. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22187. A * 2.0 * (aminus1 - aplus1 * coso),
  22188. A * (aplus1 - aminus1TimesCoso - beta),
  22189. aplus1 + aminus1TimesCoso + beta,
  22190. -2.0 * (aminus1 + aplus1 * coso),
  22191. aplus1 + aminus1TimesCoso - beta);
  22192. }
  22193. void IIRFilter::makeHighShelf (const double sampleRate,
  22194. const double cutOffFrequency,
  22195. const double Q,
  22196. const float gainFactor) throw()
  22197. {
  22198. jassert (sampleRate > 0);
  22199. jassert (Q > 0);
  22200. const double A = jmax (0.0f, gainFactor);
  22201. const double aminus1 = A - 1.0;
  22202. const double aplus1 = A + 1.0;
  22203. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22204. const double coso = std::cos (omega);
  22205. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22206. const double aminus1TimesCoso = aminus1 * coso;
  22207. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22208. A * -2.0 * (aminus1 + aplus1 * coso),
  22209. A * (aplus1 + aminus1TimesCoso - beta),
  22210. aplus1 - aminus1TimesCoso + beta,
  22211. 2.0 * (aminus1 - aplus1 * coso),
  22212. aplus1 - aminus1TimesCoso - beta);
  22213. }
  22214. void IIRFilter::makeBandPass (const double sampleRate,
  22215. const double centreFrequency,
  22216. const double Q,
  22217. const float gainFactor) throw()
  22218. {
  22219. jassert (sampleRate > 0);
  22220. jassert (Q > 0);
  22221. const double A = jmax (0.0f, gainFactor);
  22222. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22223. const double alpha = 0.5 * std::sin (omega) / Q;
  22224. const double c2 = -2.0 * std::cos (omega);
  22225. const double alphaTimesA = alpha * A;
  22226. const double alphaOverA = alpha / A;
  22227. setCoefficients (1.0 + alphaTimesA,
  22228. c2,
  22229. 1.0 - alphaTimesA,
  22230. 1.0 + alphaOverA,
  22231. c2,
  22232. 1.0 - alphaOverA);
  22233. }
  22234. void IIRFilter::makeInactive() throw()
  22235. {
  22236. const ScopedLock sl (processLock);
  22237. active = false;
  22238. }
  22239. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22240. {
  22241. const ScopedLock sl (processLock);
  22242. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22243. active = other.active;
  22244. }
  22245. void IIRFilter::setCoefficients (double c1,
  22246. double c2,
  22247. double c3,
  22248. double c4,
  22249. double c5,
  22250. double c6) throw()
  22251. {
  22252. const double a = 1.0 / c4;
  22253. c1 *= a;
  22254. c2 *= a;
  22255. c3 *= a;
  22256. c5 *= a;
  22257. c6 *= a;
  22258. const ScopedLock sl (processLock);
  22259. coefficients[0] = (float) c1;
  22260. coefficients[1] = (float) c2;
  22261. coefficients[2] = (float) c3;
  22262. coefficients[3] = (float) c4;
  22263. coefficients[4] = (float) c5;
  22264. coefficients[5] = (float) c6;
  22265. active = true;
  22266. }
  22267. END_JUCE_NAMESPACE
  22268. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22269. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22270. BEGIN_JUCE_NAMESPACE
  22271. MidiBuffer::MidiBuffer() throw()
  22272. : bytesUsed (0)
  22273. {
  22274. }
  22275. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22276. : bytesUsed (0)
  22277. {
  22278. addEvent (message, 0);
  22279. }
  22280. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22281. : data (other.data),
  22282. bytesUsed (other.bytesUsed)
  22283. {
  22284. }
  22285. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22286. {
  22287. bytesUsed = other.bytesUsed;
  22288. data = other.data;
  22289. return *this;
  22290. }
  22291. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22292. {
  22293. data.swapWith (other.data);
  22294. swapVariables <int> (bytesUsed, other.bytesUsed);
  22295. }
  22296. MidiBuffer::~MidiBuffer()
  22297. {
  22298. }
  22299. inline uint8* MidiBuffer::getData() const throw()
  22300. {
  22301. return static_cast <uint8*> (data.getData());
  22302. }
  22303. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22304. {
  22305. return *static_cast <const int*> (d);
  22306. }
  22307. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22308. {
  22309. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22310. }
  22311. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22312. {
  22313. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22314. }
  22315. void MidiBuffer::clear() throw()
  22316. {
  22317. bytesUsed = 0;
  22318. }
  22319. void MidiBuffer::clear (const int startSample, const int numSamples)
  22320. {
  22321. uint8* const start = findEventAfter (getData(), startSample - 1);
  22322. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22323. if (end > start)
  22324. {
  22325. const int bytesToMove = bytesUsed - (int) (end - getData());
  22326. if (bytesToMove > 0)
  22327. memmove (start, end, bytesToMove);
  22328. bytesUsed -= (int) (end - start);
  22329. }
  22330. }
  22331. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22332. {
  22333. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22334. }
  22335. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22336. {
  22337. unsigned int byte = (unsigned int) *data;
  22338. int size = 0;
  22339. if (byte == 0xf0 || byte == 0xf7)
  22340. {
  22341. const uint8* d = data + 1;
  22342. while (d < data + maxBytes)
  22343. if (*d++ == 0xf7)
  22344. break;
  22345. size = (int) (d - data);
  22346. }
  22347. else if (byte == 0xff)
  22348. {
  22349. int n;
  22350. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22351. size = jmin (maxBytes, n + 2 + bytesLeft);
  22352. }
  22353. else if (byte >= 0x80)
  22354. {
  22355. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22356. }
  22357. return size;
  22358. }
  22359. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22360. {
  22361. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22362. if (numBytes > 0)
  22363. {
  22364. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22365. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22366. uint8* d = findEventAfter (getData(), sampleNumber);
  22367. const int bytesToMove = bytesUsed - (int) (d - getData());
  22368. if (bytesToMove > 0)
  22369. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22370. *reinterpret_cast <int*> (d) = sampleNumber;
  22371. d += sizeof (int);
  22372. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22373. d += sizeof (uint16);
  22374. memcpy (d, newData, numBytes);
  22375. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22376. }
  22377. }
  22378. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22379. const int startSample,
  22380. const int numSamples,
  22381. const int sampleDeltaToAdd)
  22382. {
  22383. Iterator i (otherBuffer);
  22384. i.setNextSamplePosition (startSample);
  22385. const uint8* eventData;
  22386. int eventSize, position;
  22387. while (i.getNextEvent (eventData, eventSize, position)
  22388. && (position < startSample + numSamples || numSamples < 0))
  22389. {
  22390. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22391. }
  22392. }
  22393. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22394. {
  22395. data.ensureSize (minimumNumBytes);
  22396. }
  22397. bool MidiBuffer::isEmpty() const throw()
  22398. {
  22399. return bytesUsed == 0;
  22400. }
  22401. int MidiBuffer::getNumEvents() const throw()
  22402. {
  22403. int n = 0;
  22404. const uint8* d = getData();
  22405. const uint8* const end = d + bytesUsed;
  22406. while (d < end)
  22407. {
  22408. d += getEventTotalSize (d);
  22409. ++n;
  22410. }
  22411. return n;
  22412. }
  22413. int MidiBuffer::getFirstEventTime() const throw()
  22414. {
  22415. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22416. }
  22417. int MidiBuffer::getLastEventTime() const throw()
  22418. {
  22419. if (bytesUsed == 0)
  22420. return 0;
  22421. const uint8* d = getData();
  22422. const uint8* const endData = d + bytesUsed;
  22423. for (;;)
  22424. {
  22425. const uint8* const nextOne = d + getEventTotalSize (d);
  22426. if (nextOne >= endData)
  22427. return getEventTime (d);
  22428. d = nextOne;
  22429. }
  22430. }
  22431. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22432. {
  22433. const uint8* const endData = getData() + bytesUsed;
  22434. while (d < endData && getEventTime (d) <= samplePosition)
  22435. d += getEventTotalSize (d);
  22436. return d;
  22437. }
  22438. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22439. : buffer (buffer_),
  22440. data (buffer_.getData())
  22441. {
  22442. }
  22443. MidiBuffer::Iterator::~Iterator() throw()
  22444. {
  22445. }
  22446. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22447. {
  22448. data = buffer.getData();
  22449. const uint8* dataEnd = data + buffer.bytesUsed;
  22450. while (data < dataEnd && getEventTime (data) < samplePosition)
  22451. data += getEventTotalSize (data);
  22452. }
  22453. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22454. {
  22455. if (data >= buffer.getData() + buffer.bytesUsed)
  22456. return false;
  22457. samplePosition = getEventTime (data);
  22458. numBytes = getEventDataSize (data);
  22459. data += sizeof (int) + sizeof (uint16);
  22460. midiData = data;
  22461. data += numBytes;
  22462. return true;
  22463. }
  22464. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22465. {
  22466. if (data >= buffer.getData() + buffer.bytesUsed)
  22467. return false;
  22468. samplePosition = getEventTime (data);
  22469. const int numBytes = getEventDataSize (data);
  22470. data += sizeof (int) + sizeof (uint16);
  22471. result = MidiMessage (data, numBytes, samplePosition);
  22472. data += numBytes;
  22473. return true;
  22474. }
  22475. END_JUCE_NAMESPACE
  22476. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22477. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22478. BEGIN_JUCE_NAMESPACE
  22479. namespace MidiFileHelpers
  22480. {
  22481. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22482. {
  22483. unsigned int buffer = v & 0x7F;
  22484. while ((v >>= 7) != 0)
  22485. {
  22486. buffer <<= 8;
  22487. buffer |= ((v & 0x7F) | 0x80);
  22488. }
  22489. for (;;)
  22490. {
  22491. out.writeByte ((char) buffer);
  22492. if (buffer & 0x80)
  22493. buffer >>= 8;
  22494. else
  22495. break;
  22496. }
  22497. }
  22498. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22499. {
  22500. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22501. data += 4;
  22502. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22503. {
  22504. bool ok = false;
  22505. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22506. {
  22507. for (int i = 0; i < 8; ++i)
  22508. {
  22509. ch = ByteOrder::bigEndianInt (data);
  22510. data += 4;
  22511. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22512. {
  22513. ok = true;
  22514. break;
  22515. }
  22516. }
  22517. }
  22518. if (! ok)
  22519. return false;
  22520. }
  22521. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22522. data += 4;
  22523. fileType = (short) ByteOrder::bigEndianShort (data);
  22524. data += 2;
  22525. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22526. data += 2;
  22527. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22528. data += 2;
  22529. bytesRemaining -= 6;
  22530. data += bytesRemaining;
  22531. return true;
  22532. }
  22533. static double convertTicksToSeconds (const double time,
  22534. const MidiMessageSequence& tempoEvents,
  22535. const int timeFormat)
  22536. {
  22537. if (timeFormat > 0)
  22538. {
  22539. int numer = 4, denom = 4;
  22540. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22541. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22542. double secsPerTick = 0.5 * tickLen;
  22543. const int numEvents = tempoEvents.getNumEvents();
  22544. for (int i = 0; i < numEvents; ++i)
  22545. {
  22546. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22547. if (time <= m.getTimeStamp())
  22548. break;
  22549. if (timeFormat > 0)
  22550. {
  22551. correctedTempoTime = correctedTempoTime
  22552. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22553. }
  22554. else
  22555. {
  22556. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22557. }
  22558. tempoTime = m.getTimeStamp();
  22559. if (m.isTempoMetaEvent())
  22560. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22561. else if (m.isTimeSignatureMetaEvent())
  22562. m.getTimeSignatureInfo (numer, denom);
  22563. while (i + 1 < numEvents)
  22564. {
  22565. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22566. if (m2.getTimeStamp() == tempoTime)
  22567. {
  22568. ++i;
  22569. if (m2.isTempoMetaEvent())
  22570. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22571. else if (m2.isTimeSignatureMetaEvent())
  22572. m2.getTimeSignatureInfo (numer, denom);
  22573. }
  22574. else
  22575. {
  22576. break;
  22577. }
  22578. }
  22579. }
  22580. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22581. }
  22582. else
  22583. {
  22584. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22585. }
  22586. }
  22587. // a comparator that puts all the note-offs before note-ons that have the same time
  22588. struct Sorter
  22589. {
  22590. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22591. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22592. {
  22593. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22594. if (diff == 0)
  22595. {
  22596. if (first->message.isNoteOff() && second->message.isNoteOn())
  22597. return -1;
  22598. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22599. return 1;
  22600. else
  22601. return 0;
  22602. }
  22603. else
  22604. {
  22605. return (diff > 0) ? 1 : -1;
  22606. }
  22607. }
  22608. };
  22609. }
  22610. MidiFile::MidiFile()
  22611. : timeFormat ((short) (unsigned short) 0xe728)
  22612. {
  22613. }
  22614. MidiFile::~MidiFile()
  22615. {
  22616. clear();
  22617. }
  22618. void MidiFile::clear()
  22619. {
  22620. tracks.clear();
  22621. }
  22622. int MidiFile::getNumTracks() const throw()
  22623. {
  22624. return tracks.size();
  22625. }
  22626. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22627. {
  22628. return tracks [index];
  22629. }
  22630. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22631. {
  22632. tracks.add (new MidiMessageSequence (trackSequence));
  22633. }
  22634. short MidiFile::getTimeFormat() const throw()
  22635. {
  22636. return timeFormat;
  22637. }
  22638. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22639. {
  22640. timeFormat = (short) ticks;
  22641. }
  22642. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22643. const int subframeResolution) throw()
  22644. {
  22645. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22646. }
  22647. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22648. {
  22649. for (int i = tracks.size(); --i >= 0;)
  22650. {
  22651. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22652. for (int j = 0; j < numEvents; ++j)
  22653. {
  22654. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22655. if (m.isTempoMetaEvent())
  22656. tempoChangeEvents.addEvent (m);
  22657. }
  22658. }
  22659. }
  22660. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22661. {
  22662. for (int i = tracks.size(); --i >= 0;)
  22663. {
  22664. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22665. for (int j = 0; j < numEvents; ++j)
  22666. {
  22667. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22668. if (m.isTimeSignatureMetaEvent())
  22669. timeSigEvents.addEvent (m);
  22670. }
  22671. }
  22672. }
  22673. double MidiFile::getLastTimestamp() const
  22674. {
  22675. double t = 0.0;
  22676. for (int i = tracks.size(); --i >= 0;)
  22677. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22678. return t;
  22679. }
  22680. bool MidiFile::readFrom (InputStream& sourceStream)
  22681. {
  22682. clear();
  22683. MemoryBlock data;
  22684. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22685. // (put a sanity-check on the file size, as midi files are generally small)
  22686. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22687. {
  22688. size_t size = data.getSize();
  22689. const uint8* d = static_cast <const uint8*> (data.getData());
  22690. short fileType, expectedTracks;
  22691. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22692. {
  22693. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22694. int track = 0;
  22695. while (size > 0 && track < expectedTracks)
  22696. {
  22697. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22698. d += 4;
  22699. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22700. d += 4;
  22701. if (chunkSize <= 0)
  22702. break;
  22703. if (size < 0)
  22704. return false;
  22705. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22706. {
  22707. readNextTrack (d, chunkSize);
  22708. }
  22709. size -= chunkSize + 8;
  22710. d += chunkSize;
  22711. ++track;
  22712. }
  22713. return true;
  22714. }
  22715. }
  22716. return false;
  22717. }
  22718. void MidiFile::readNextTrack (const uint8* data, int size)
  22719. {
  22720. double time = 0;
  22721. char lastStatusByte = 0;
  22722. MidiMessageSequence result;
  22723. while (size > 0)
  22724. {
  22725. int bytesUsed;
  22726. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22727. data += bytesUsed;
  22728. size -= bytesUsed;
  22729. time += delay;
  22730. int messSize = 0;
  22731. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22732. if (messSize <= 0)
  22733. break;
  22734. size -= messSize;
  22735. data += messSize;
  22736. result.addEvent (mm);
  22737. const char firstByte = *(mm.getRawData());
  22738. if ((firstByte & 0xf0) != 0xf0)
  22739. lastStatusByte = firstByte;
  22740. }
  22741. // use a sort that puts all the note-offs before note-ons that have the same time
  22742. MidiFileHelpers::Sorter sorter;
  22743. result.list.sort (sorter, true);
  22744. result.updateMatchedPairs();
  22745. addTrack (result);
  22746. }
  22747. void MidiFile::convertTimestampTicksToSeconds()
  22748. {
  22749. MidiMessageSequence tempoEvents;
  22750. findAllTempoEvents (tempoEvents);
  22751. findAllTimeSigEvents (tempoEvents);
  22752. for (int i = 0; i < tracks.size(); ++i)
  22753. {
  22754. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22755. for (int j = ms.getNumEvents(); --j >= 0;)
  22756. {
  22757. MidiMessage& m = ms.getEventPointer(j)->message;
  22758. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22759. tempoEvents,
  22760. timeFormat));
  22761. }
  22762. }
  22763. }
  22764. bool MidiFile::writeTo (OutputStream& out)
  22765. {
  22766. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22767. out.writeIntBigEndian (6);
  22768. out.writeShortBigEndian (1); // type
  22769. out.writeShortBigEndian ((short) tracks.size());
  22770. out.writeShortBigEndian (timeFormat);
  22771. for (int i = 0; i < tracks.size(); ++i)
  22772. writeTrack (out, i);
  22773. out.flush();
  22774. return true;
  22775. }
  22776. void MidiFile::writeTrack (OutputStream& mainOut,
  22777. const int trackNum)
  22778. {
  22779. MemoryOutputStream out;
  22780. const MidiMessageSequence& ms = *tracks[trackNum];
  22781. int lastTick = 0;
  22782. char lastStatusByte = 0;
  22783. for (int i = 0; i < ms.getNumEvents(); ++i)
  22784. {
  22785. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22786. const int tick = roundToInt (mm.getTimeStamp());
  22787. const int delta = jmax (0, tick - lastTick);
  22788. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22789. lastTick = tick;
  22790. const char statusByte = *(mm.getRawData());
  22791. if ((statusByte == lastStatusByte)
  22792. && ((statusByte & 0xf0) != 0xf0)
  22793. && i > 0
  22794. && mm.getRawDataSize() > 1)
  22795. {
  22796. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22797. }
  22798. else
  22799. {
  22800. out.write (mm.getRawData(), mm.getRawDataSize());
  22801. }
  22802. lastStatusByte = statusByte;
  22803. }
  22804. out.writeByte (0);
  22805. const MidiMessage m (MidiMessage::endOfTrack());
  22806. out.write (m.getRawData(),
  22807. m.getRawDataSize());
  22808. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22809. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22810. mainOut.write (out.getData(), (int) out.getDataSize());
  22811. }
  22812. END_JUCE_NAMESPACE
  22813. /*** End of inlined file: juce_MidiFile.cpp ***/
  22814. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22815. BEGIN_JUCE_NAMESPACE
  22816. MidiKeyboardState::MidiKeyboardState()
  22817. {
  22818. zerostruct (noteStates);
  22819. }
  22820. MidiKeyboardState::~MidiKeyboardState()
  22821. {
  22822. }
  22823. void MidiKeyboardState::reset()
  22824. {
  22825. const ScopedLock sl (lock);
  22826. zerostruct (noteStates);
  22827. eventsToAdd.clear();
  22828. }
  22829. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22830. {
  22831. jassert (midiChannel >= 0 && midiChannel <= 16);
  22832. return ((unsigned int) n) < 128
  22833. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22834. }
  22835. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22836. {
  22837. return ((unsigned int) n) < 128
  22838. && (noteStates[n] & midiChannelMask) != 0;
  22839. }
  22840. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22841. {
  22842. jassert (midiChannel >= 0 && midiChannel <= 16);
  22843. jassert (((unsigned int) midiNoteNumber) < 128);
  22844. const ScopedLock sl (lock);
  22845. if (((unsigned int) midiNoteNumber) < 128)
  22846. {
  22847. const int timeNow = (int) Time::getMillisecondCounter();
  22848. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22849. eventsToAdd.clear (0, timeNow - 500);
  22850. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22851. }
  22852. }
  22853. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22854. {
  22855. if (((unsigned int) midiNoteNumber) < 128)
  22856. {
  22857. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22858. for (int i = listeners.size(); --i >= 0;)
  22859. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22860. }
  22861. }
  22862. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22863. {
  22864. const ScopedLock sl (lock);
  22865. if (isNoteOn (midiChannel, midiNoteNumber))
  22866. {
  22867. const int timeNow = (int) Time::getMillisecondCounter();
  22868. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22869. eventsToAdd.clear (0, timeNow - 500);
  22870. noteOffInternal (midiChannel, midiNoteNumber);
  22871. }
  22872. }
  22873. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22874. {
  22875. if (isNoteOn (midiChannel, midiNoteNumber))
  22876. {
  22877. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22878. for (int i = listeners.size(); --i >= 0;)
  22879. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22880. }
  22881. }
  22882. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22883. {
  22884. const ScopedLock sl (lock);
  22885. if (midiChannel <= 0)
  22886. {
  22887. for (int i = 1; i <= 16; ++i)
  22888. allNotesOff (i);
  22889. }
  22890. else
  22891. {
  22892. for (int i = 0; i < 128; ++i)
  22893. noteOff (midiChannel, i);
  22894. }
  22895. }
  22896. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22897. {
  22898. if (message.isNoteOn())
  22899. {
  22900. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22901. }
  22902. else if (message.isNoteOff())
  22903. {
  22904. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22905. }
  22906. else if (message.isAllNotesOff())
  22907. {
  22908. for (int i = 0; i < 128; ++i)
  22909. noteOffInternal (message.getChannel(), i);
  22910. }
  22911. }
  22912. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22913. const int startSample,
  22914. const int numSamples,
  22915. const bool injectIndirectEvents)
  22916. {
  22917. MidiBuffer::Iterator i (buffer);
  22918. MidiMessage message (0xf4, 0.0);
  22919. int time;
  22920. const ScopedLock sl (lock);
  22921. while (i.getNextEvent (message, time))
  22922. processNextMidiEvent (message);
  22923. if (injectIndirectEvents)
  22924. {
  22925. MidiBuffer::Iterator i2 (eventsToAdd);
  22926. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22927. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22928. while (i2.getNextEvent (message, time))
  22929. {
  22930. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22931. buffer.addEvent (message, startSample + pos);
  22932. }
  22933. }
  22934. eventsToAdd.clear();
  22935. }
  22936. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22937. {
  22938. const ScopedLock sl (lock);
  22939. listeners.addIfNotAlreadyThere (listener);
  22940. }
  22941. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22942. {
  22943. const ScopedLock sl (lock);
  22944. listeners.removeValue (listener);
  22945. }
  22946. END_JUCE_NAMESPACE
  22947. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22948. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22949. BEGIN_JUCE_NAMESPACE
  22950. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22951. {
  22952. numBytesUsed = 0;
  22953. int v = 0;
  22954. int i;
  22955. do
  22956. {
  22957. i = (int) *data++;
  22958. if (++numBytesUsed > 6)
  22959. break;
  22960. v = (v << 7) + (i & 0x7f);
  22961. } while (i & 0x80);
  22962. return v;
  22963. }
  22964. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22965. {
  22966. // this method only works for valid starting bytes of a short midi message
  22967. jassert (firstByte >= 0x80
  22968. && firstByte != 0xf0
  22969. && firstByte != 0xf7);
  22970. static const char messageLengths[] =
  22971. {
  22972. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22973. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22974. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22975. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22976. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22977. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22978. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22979. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22980. };
  22981. return messageLengths [firstByte & 0x7f];
  22982. }
  22983. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22984. : timeStamp (t),
  22985. size (dataSize)
  22986. {
  22987. jassert (dataSize > 0);
  22988. if (dataSize <= 4)
  22989. data = static_cast<uint8*> (preallocatedData.asBytes);
  22990. else
  22991. data = new uint8 [dataSize];
  22992. memcpy (data, d, dataSize);
  22993. // check that the length matches the data..
  22994. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22995. }
  22996. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22997. : timeStamp (t),
  22998. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22999. size (1)
  23000. {
  23001. data[0] = (uint8) byte1;
  23002. // check that the length matches the data..
  23003. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23004. }
  23005. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23006. : timeStamp (t),
  23007. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23008. size (2)
  23009. {
  23010. data[0] = (uint8) byte1;
  23011. data[1] = (uint8) byte2;
  23012. // check that the length matches the data..
  23013. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23014. }
  23015. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23016. : timeStamp (t),
  23017. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23018. size (3)
  23019. {
  23020. data[0] = (uint8) byte1;
  23021. data[1] = (uint8) byte2;
  23022. data[2] = (uint8) byte3;
  23023. // check that the length matches the data..
  23024. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23025. }
  23026. MidiMessage::MidiMessage (const MidiMessage& other)
  23027. : timeStamp (other.timeStamp),
  23028. size (other.size)
  23029. {
  23030. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23031. {
  23032. data = new uint8 [size];
  23033. memcpy (data, other.data, size);
  23034. }
  23035. else
  23036. {
  23037. data = static_cast<uint8*> (preallocatedData.asBytes);
  23038. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23039. }
  23040. }
  23041. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23042. : timeStamp (newTimeStamp),
  23043. size (other.size)
  23044. {
  23045. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23046. {
  23047. data = new uint8 [size];
  23048. memcpy (data, other.data, size);
  23049. }
  23050. else
  23051. {
  23052. data = static_cast<uint8*> (preallocatedData.asBytes);
  23053. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23054. }
  23055. }
  23056. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23057. : timeStamp (t),
  23058. data (static_cast<uint8*> (preallocatedData.asBytes))
  23059. {
  23060. const uint8* src = static_cast <const uint8*> (src_);
  23061. unsigned int byte = (unsigned int) *src;
  23062. if (byte < 0x80)
  23063. {
  23064. byte = (unsigned int) (uint8) lastStatusByte;
  23065. numBytesUsed = -1;
  23066. }
  23067. else
  23068. {
  23069. numBytesUsed = 0;
  23070. --sz;
  23071. ++src;
  23072. }
  23073. if (byte >= 0x80)
  23074. {
  23075. if (byte == 0xf0)
  23076. {
  23077. const uint8* d = src;
  23078. while (d < src + sz)
  23079. {
  23080. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23081. {
  23082. if (*d == 0xf7) // include an 0xf7 if we hit one
  23083. ++d;
  23084. break;
  23085. }
  23086. ++d;
  23087. }
  23088. size = 1 + (int) (d - src);
  23089. data = new uint8 [size];
  23090. *data = (uint8) byte;
  23091. memcpy (data + 1, src, size - 1);
  23092. }
  23093. else if (byte == 0xff)
  23094. {
  23095. int n;
  23096. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23097. size = jmin (sz + 1, n + 2 + bytesLeft);
  23098. data = new uint8 [size];
  23099. *data = (uint8) byte;
  23100. memcpy (data + 1, src, size - 1);
  23101. }
  23102. else
  23103. {
  23104. preallocatedData.asInt32 = 0;
  23105. size = getMessageLengthFromFirstByte ((uint8) byte);
  23106. data[0] = (uint8) byte;
  23107. if (size > 1)
  23108. {
  23109. data[1] = src[0];
  23110. if (size > 2)
  23111. data[2] = src[1];
  23112. }
  23113. }
  23114. numBytesUsed += size;
  23115. }
  23116. else
  23117. {
  23118. preallocatedData.asInt32 = 0;
  23119. size = 0;
  23120. }
  23121. }
  23122. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23123. {
  23124. if (this != &other)
  23125. {
  23126. timeStamp = other.timeStamp;
  23127. size = other.size;
  23128. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23129. delete[] data;
  23130. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23131. {
  23132. data = new uint8 [size];
  23133. memcpy (data, other.data, size);
  23134. }
  23135. else
  23136. {
  23137. data = static_cast<uint8*> (preallocatedData.asBytes);
  23138. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23139. }
  23140. }
  23141. return *this;
  23142. }
  23143. MidiMessage::~MidiMessage()
  23144. {
  23145. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23146. delete[] data;
  23147. }
  23148. int MidiMessage::getChannel() const throw()
  23149. {
  23150. if ((data[0] & 0xf0) != 0xf0)
  23151. return (data[0] & 0xf) + 1;
  23152. else
  23153. return 0;
  23154. }
  23155. bool MidiMessage::isForChannel (const int channel) const throw()
  23156. {
  23157. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23158. return ((data[0] & 0xf) == channel - 1)
  23159. && ((data[0] & 0xf0) != 0xf0);
  23160. }
  23161. void MidiMessage::setChannel (const int channel) throw()
  23162. {
  23163. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23164. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23165. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23166. | (uint8)(channel - 1));
  23167. }
  23168. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23169. {
  23170. return ((data[0] & 0xf0) == 0x90)
  23171. && (returnTrueForVelocity0 || data[2] != 0);
  23172. }
  23173. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23174. {
  23175. return ((data[0] & 0xf0) == 0x80)
  23176. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23177. }
  23178. bool MidiMessage::isNoteOnOrOff() const throw()
  23179. {
  23180. const int d = data[0] & 0xf0;
  23181. return (d == 0x90) || (d == 0x80);
  23182. }
  23183. int MidiMessage::getNoteNumber() const throw()
  23184. {
  23185. return data[1];
  23186. }
  23187. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23188. {
  23189. if (isNoteOnOrOff())
  23190. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23191. }
  23192. uint8 MidiMessage::getVelocity() const throw()
  23193. {
  23194. if (isNoteOnOrOff())
  23195. return data[2];
  23196. else
  23197. return 0;
  23198. }
  23199. float MidiMessage::getFloatVelocity() const throw()
  23200. {
  23201. return getVelocity() * (1.0f / 127.0f);
  23202. }
  23203. void MidiMessage::setVelocity (const float newVelocity) throw()
  23204. {
  23205. if (isNoteOnOrOff())
  23206. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23207. }
  23208. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23209. {
  23210. if (isNoteOnOrOff())
  23211. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23212. }
  23213. bool MidiMessage::isAftertouch() const throw()
  23214. {
  23215. return (data[0] & 0xf0) == 0xa0;
  23216. }
  23217. int MidiMessage::getAfterTouchValue() const throw()
  23218. {
  23219. return data[2];
  23220. }
  23221. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23222. const int noteNum,
  23223. const int aftertouchValue) throw()
  23224. {
  23225. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23226. jassert (((unsigned int) noteNum) <= 127);
  23227. jassert (((unsigned int) aftertouchValue) <= 127);
  23228. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23229. noteNum & 0x7f,
  23230. aftertouchValue & 0x7f);
  23231. }
  23232. bool MidiMessage::isChannelPressure() const throw()
  23233. {
  23234. return (data[0] & 0xf0) == 0xd0;
  23235. }
  23236. int MidiMessage::getChannelPressureValue() const throw()
  23237. {
  23238. jassert (isChannelPressure());
  23239. return data[1];
  23240. }
  23241. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23242. const int pressure) throw()
  23243. {
  23244. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23245. jassert (((unsigned int) pressure) <= 127);
  23246. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23247. pressure & 0x7f);
  23248. }
  23249. bool MidiMessage::isProgramChange() const throw()
  23250. {
  23251. return (data[0] & 0xf0) == 0xc0;
  23252. }
  23253. int MidiMessage::getProgramChangeNumber() const throw()
  23254. {
  23255. return data[1];
  23256. }
  23257. const MidiMessage MidiMessage::programChange (const int channel,
  23258. const int programNumber) throw()
  23259. {
  23260. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23261. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23262. programNumber & 0x7f);
  23263. }
  23264. bool MidiMessage::isPitchWheel() const throw()
  23265. {
  23266. return (data[0] & 0xf0) == 0xe0;
  23267. }
  23268. int MidiMessage::getPitchWheelValue() const throw()
  23269. {
  23270. return data[1] | (data[2] << 7);
  23271. }
  23272. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23273. const int position) throw()
  23274. {
  23275. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23276. jassert (((unsigned int) position) <= 0x3fff);
  23277. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23278. position & 127,
  23279. (position >> 7) & 127);
  23280. }
  23281. bool MidiMessage::isController() const throw()
  23282. {
  23283. return (data[0] & 0xf0) == 0xb0;
  23284. }
  23285. int MidiMessage::getControllerNumber() const throw()
  23286. {
  23287. jassert (isController());
  23288. return data[1];
  23289. }
  23290. int MidiMessage::getControllerValue() const throw()
  23291. {
  23292. jassert (isController());
  23293. return data[2];
  23294. }
  23295. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23296. const int controllerType,
  23297. const int value) throw()
  23298. {
  23299. // the channel must be between 1 and 16 inclusive
  23300. jassert (channel > 0 && channel <= 16);
  23301. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23302. controllerType & 127,
  23303. value & 127);
  23304. }
  23305. const MidiMessage MidiMessage::noteOn (const int channel,
  23306. const int noteNumber,
  23307. const float velocity) throw()
  23308. {
  23309. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23310. }
  23311. const MidiMessage MidiMessage::noteOn (const int channel,
  23312. const int noteNumber,
  23313. const uint8 velocity) throw()
  23314. {
  23315. jassert (channel > 0 && channel <= 16);
  23316. jassert (((unsigned int) noteNumber) <= 127);
  23317. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23318. noteNumber & 127,
  23319. jlimit (0, 127, roundToInt (velocity)));
  23320. }
  23321. const MidiMessage MidiMessage::noteOff (const int channel,
  23322. const int noteNumber) throw()
  23323. {
  23324. jassert (channel > 0 && channel <= 16);
  23325. jassert (((unsigned int) noteNumber) <= 127);
  23326. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23327. }
  23328. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23329. {
  23330. return controllerEvent (channel, 123, 0);
  23331. }
  23332. bool MidiMessage::isAllNotesOff() const throw()
  23333. {
  23334. return (data[0] & 0xf0) == 0xb0
  23335. && data[1] == 123;
  23336. }
  23337. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23338. {
  23339. return controllerEvent (channel, 120, 0);
  23340. }
  23341. bool MidiMessage::isAllSoundOff() const throw()
  23342. {
  23343. return (data[0] & 0xf0) == 0xb0
  23344. && data[1] == 120;
  23345. }
  23346. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23347. {
  23348. return controllerEvent (channel, 121, 0);
  23349. }
  23350. const MidiMessage MidiMessage::masterVolume (const float volume)
  23351. {
  23352. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23353. uint8 buf[8];
  23354. buf[0] = 0xf0;
  23355. buf[1] = 0x7f;
  23356. buf[2] = 0x7f;
  23357. buf[3] = 0x04;
  23358. buf[4] = 0x01;
  23359. buf[5] = (uint8) (vol & 0x7f);
  23360. buf[6] = (uint8) (vol >> 7);
  23361. buf[7] = 0xf7;
  23362. return MidiMessage (buf, 8);
  23363. }
  23364. bool MidiMessage::isSysEx() const throw()
  23365. {
  23366. return *data == 0xf0;
  23367. }
  23368. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23369. {
  23370. MemoryBlock mm (dataSize + 2);
  23371. uint8* const m = static_cast <uint8*> (mm.getData());
  23372. m[0] = 0xf0;
  23373. memcpy (m + 1, sysexData, dataSize);
  23374. m[dataSize + 1] = 0xf7;
  23375. return MidiMessage (m, dataSize + 2);
  23376. }
  23377. const uint8* MidiMessage::getSysExData() const throw()
  23378. {
  23379. return (isSysEx()) ? getRawData() + 1 : 0;
  23380. }
  23381. int MidiMessage::getSysExDataSize() const throw()
  23382. {
  23383. return (isSysEx()) ? size - 2 : 0;
  23384. }
  23385. bool MidiMessage::isMetaEvent() const throw()
  23386. {
  23387. return *data == 0xff;
  23388. }
  23389. bool MidiMessage::isActiveSense() const throw()
  23390. {
  23391. return *data == 0xfe;
  23392. }
  23393. int MidiMessage::getMetaEventType() const throw()
  23394. {
  23395. if (*data != 0xff)
  23396. return -1;
  23397. else
  23398. return data[1];
  23399. }
  23400. int MidiMessage::getMetaEventLength() const throw()
  23401. {
  23402. if (*data == 0xff)
  23403. {
  23404. int n;
  23405. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23406. }
  23407. return 0;
  23408. }
  23409. const uint8* MidiMessage::getMetaEventData() const throw()
  23410. {
  23411. int n;
  23412. const uint8* d = data + 2;
  23413. readVariableLengthVal (d, n);
  23414. return d + n;
  23415. }
  23416. bool MidiMessage::isTrackMetaEvent() const throw()
  23417. {
  23418. return getMetaEventType() == 0;
  23419. }
  23420. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23421. {
  23422. return getMetaEventType() == 47;
  23423. }
  23424. bool MidiMessage::isTextMetaEvent() const throw()
  23425. {
  23426. const int t = getMetaEventType();
  23427. return t > 0 && t < 16;
  23428. }
  23429. const String MidiMessage::getTextFromTextMetaEvent() const
  23430. {
  23431. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23432. }
  23433. bool MidiMessage::isTrackNameEvent() const throw()
  23434. {
  23435. return (data[1] == 3)
  23436. && (*data == 0xff);
  23437. }
  23438. bool MidiMessage::isTempoMetaEvent() const throw()
  23439. {
  23440. return (data[1] == 81)
  23441. && (*data == 0xff);
  23442. }
  23443. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23444. {
  23445. return (data[1] == 0x20)
  23446. && (*data == 0xff)
  23447. && (data[2] == 1);
  23448. }
  23449. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23450. {
  23451. return data[3] + 1;
  23452. }
  23453. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23454. {
  23455. if (! isTempoMetaEvent())
  23456. return 0.0;
  23457. const uint8* const d = getMetaEventData();
  23458. return (((unsigned int) d[0] << 16)
  23459. | ((unsigned int) d[1] << 8)
  23460. | d[2])
  23461. / 1000000.0;
  23462. }
  23463. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23464. {
  23465. if (timeFormat > 0)
  23466. {
  23467. if (! isTempoMetaEvent())
  23468. return 0.5 / timeFormat;
  23469. return getTempoSecondsPerQuarterNote() / timeFormat;
  23470. }
  23471. else
  23472. {
  23473. const int frameCode = (-timeFormat) >> 8;
  23474. double framesPerSecond;
  23475. switch (frameCode)
  23476. {
  23477. case 24: framesPerSecond = 24.0; break;
  23478. case 25: framesPerSecond = 25.0; break;
  23479. case 29: framesPerSecond = 29.97; break;
  23480. case 30: framesPerSecond = 30.0; break;
  23481. default: framesPerSecond = 30.0; break;
  23482. }
  23483. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23484. }
  23485. }
  23486. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23487. {
  23488. uint8 d[8];
  23489. d[0] = 0xff;
  23490. d[1] = 81;
  23491. d[2] = 3;
  23492. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23493. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23494. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23495. return MidiMessage (d, 6, 0.0);
  23496. }
  23497. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23498. {
  23499. return (data[1] == 0x58)
  23500. && (*data == (uint8) 0xff);
  23501. }
  23502. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23503. {
  23504. if (isTimeSignatureMetaEvent())
  23505. {
  23506. const uint8* const d = getMetaEventData();
  23507. numerator = d[0];
  23508. denominator = 1 << d[1];
  23509. }
  23510. else
  23511. {
  23512. numerator = 4;
  23513. denominator = 4;
  23514. }
  23515. }
  23516. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23517. {
  23518. uint8 d[8];
  23519. d[0] = 0xff;
  23520. d[1] = 0x58;
  23521. d[2] = 0x04;
  23522. d[3] = (uint8) numerator;
  23523. int n = 1;
  23524. int powerOfTwo = 0;
  23525. while (n < denominator)
  23526. {
  23527. n <<= 1;
  23528. ++powerOfTwo;
  23529. }
  23530. d[4] = (uint8) powerOfTwo;
  23531. d[5] = 0x01;
  23532. d[6] = 96;
  23533. return MidiMessage (d, 7, 0.0);
  23534. }
  23535. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23536. {
  23537. uint8 d[8];
  23538. d[0] = 0xff;
  23539. d[1] = 0x20;
  23540. d[2] = 0x01;
  23541. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23542. return MidiMessage (d, 4, 0.0);
  23543. }
  23544. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23545. {
  23546. return getMetaEventType() == 89;
  23547. }
  23548. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23549. {
  23550. return (int) *getMetaEventData();
  23551. }
  23552. const MidiMessage MidiMessage::endOfTrack() throw()
  23553. {
  23554. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23555. }
  23556. bool MidiMessage::isSongPositionPointer() const throw()
  23557. {
  23558. return *data == 0xf2;
  23559. }
  23560. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23561. {
  23562. return data[1] | (data[2] << 7);
  23563. }
  23564. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23565. {
  23566. return MidiMessage (0xf2,
  23567. positionInMidiBeats & 127,
  23568. (positionInMidiBeats >> 7) & 127);
  23569. }
  23570. bool MidiMessage::isMidiStart() const throw()
  23571. {
  23572. return *data == 0xfa;
  23573. }
  23574. const MidiMessage MidiMessage::midiStart() throw()
  23575. {
  23576. return MidiMessage (0xfa);
  23577. }
  23578. bool MidiMessage::isMidiContinue() const throw()
  23579. {
  23580. return *data == 0xfb;
  23581. }
  23582. const MidiMessage MidiMessage::midiContinue() throw()
  23583. {
  23584. return MidiMessage (0xfb);
  23585. }
  23586. bool MidiMessage::isMidiStop() const throw()
  23587. {
  23588. return *data == 0xfc;
  23589. }
  23590. const MidiMessage MidiMessage::midiStop() throw()
  23591. {
  23592. return MidiMessage (0xfc);
  23593. }
  23594. bool MidiMessage::isMidiClock() const throw()
  23595. {
  23596. return *data == 0xf8;
  23597. }
  23598. const MidiMessage MidiMessage::midiClock() throw()
  23599. {
  23600. return MidiMessage (0xf8);
  23601. }
  23602. bool MidiMessage::isQuarterFrame() const throw()
  23603. {
  23604. return *data == 0xf1;
  23605. }
  23606. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23607. {
  23608. return ((int) data[1]) >> 4;
  23609. }
  23610. int MidiMessage::getQuarterFrameValue() const throw()
  23611. {
  23612. return ((int) data[1]) & 0x0f;
  23613. }
  23614. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23615. const int value) throw()
  23616. {
  23617. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23618. }
  23619. bool MidiMessage::isFullFrame() const throw()
  23620. {
  23621. return data[0] == 0xf0
  23622. && data[1] == 0x7f
  23623. && size >= 10
  23624. && data[3] == 0x01
  23625. && data[4] == 0x01;
  23626. }
  23627. void MidiMessage::getFullFrameParameters (int& hours,
  23628. int& minutes,
  23629. int& seconds,
  23630. int& frames,
  23631. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23632. {
  23633. jassert (isFullFrame());
  23634. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23635. hours = data[5] & 0x1f;
  23636. minutes = data[6];
  23637. seconds = data[7];
  23638. frames = data[8];
  23639. }
  23640. const MidiMessage MidiMessage::fullFrame (const int hours,
  23641. const int minutes,
  23642. const int seconds,
  23643. const int frames,
  23644. MidiMessage::SmpteTimecodeType timecodeType)
  23645. {
  23646. uint8 d[10];
  23647. d[0] = 0xf0;
  23648. d[1] = 0x7f;
  23649. d[2] = 0x7f;
  23650. d[3] = 0x01;
  23651. d[4] = 0x01;
  23652. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23653. d[6] = (uint8) minutes;
  23654. d[7] = (uint8) seconds;
  23655. d[8] = (uint8) frames;
  23656. d[9] = 0xf7;
  23657. return MidiMessage (d, 10, 0.0);
  23658. }
  23659. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23660. {
  23661. return data[0] == 0xf0
  23662. && data[1] == 0x7f
  23663. && data[3] == 0x06
  23664. && size > 5;
  23665. }
  23666. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23667. {
  23668. jassert (isMidiMachineControlMessage());
  23669. return (MidiMachineControlCommand) data[4];
  23670. }
  23671. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23672. {
  23673. uint8 d[6];
  23674. d[0] = 0xf0;
  23675. d[1] = 0x7f;
  23676. d[2] = 0x00;
  23677. d[3] = 0x06;
  23678. d[4] = (uint8) command;
  23679. d[5] = 0xf7;
  23680. return MidiMessage (d, 6, 0.0);
  23681. }
  23682. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23683. int& minutes,
  23684. int& seconds,
  23685. int& frames) const throw()
  23686. {
  23687. if (size >= 12
  23688. && data[0] == 0xf0
  23689. && data[1] == 0x7f
  23690. && data[3] == 0x06
  23691. && data[4] == 0x44
  23692. && data[5] == 0x06
  23693. && data[6] == 0x01)
  23694. {
  23695. hours = data[7] % 24; // (that some machines send out hours > 24)
  23696. minutes = data[8];
  23697. seconds = data[9];
  23698. frames = data[10];
  23699. return true;
  23700. }
  23701. return false;
  23702. }
  23703. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23704. int minutes,
  23705. int seconds,
  23706. int frames)
  23707. {
  23708. uint8 d[12];
  23709. d[0] = 0xf0;
  23710. d[1] = 0x7f;
  23711. d[2] = 0x00;
  23712. d[3] = 0x06;
  23713. d[4] = 0x44;
  23714. d[5] = 0x06;
  23715. d[6] = 0x01;
  23716. d[7] = (uint8) hours;
  23717. d[8] = (uint8) minutes;
  23718. d[9] = (uint8) seconds;
  23719. d[10] = (uint8) frames;
  23720. d[11] = 0xf7;
  23721. return MidiMessage (d, 12, 0.0);
  23722. }
  23723. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23724. {
  23725. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23726. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23727. if (((unsigned int) note) < 128)
  23728. {
  23729. String s (useSharps ? sharpNoteNames [note % 12]
  23730. : flatNoteNames [note % 12]);
  23731. if (includeOctaveNumber)
  23732. s << (note / 12 + (octaveNumForMiddleC - 5));
  23733. return s;
  23734. }
  23735. return String::empty;
  23736. }
  23737. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23738. {
  23739. noteNumber -= 12 * 6 + 9; // now 0 = A
  23740. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23741. }
  23742. const String MidiMessage::getGMInstrumentName (const int n)
  23743. {
  23744. const char* names[] =
  23745. {
  23746. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23747. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23748. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23749. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23750. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23751. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23752. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23753. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23754. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23755. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23756. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23757. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23758. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23759. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23760. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23761. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23762. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23763. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23764. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23765. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23766. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23767. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23768. "Applause", "Gunshot"
  23769. };
  23770. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23771. }
  23772. const String MidiMessage::getGMInstrumentBankName (const int n)
  23773. {
  23774. const char* names[] =
  23775. {
  23776. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23777. "Bass", "Strings", "Ensemble", "Brass",
  23778. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23779. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23780. };
  23781. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23782. }
  23783. const String MidiMessage::getRhythmInstrumentName (const int n)
  23784. {
  23785. const char* names[] =
  23786. {
  23787. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23788. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23789. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23790. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23791. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23792. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23793. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23794. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23795. "Mute Triangle", "Open Triangle"
  23796. };
  23797. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23798. }
  23799. const String MidiMessage::getControllerName (const int n)
  23800. {
  23801. const char* names[] =
  23802. {
  23803. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23804. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23805. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23806. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23807. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23808. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23809. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23810. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23811. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23812. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23813. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23814. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23815. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23816. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23817. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23818. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23819. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23820. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23821. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23823. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23824. "Poly Operation"
  23825. };
  23826. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23827. }
  23828. END_JUCE_NAMESPACE
  23829. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23830. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23831. BEGIN_JUCE_NAMESPACE
  23832. MidiMessageCollector::MidiMessageCollector()
  23833. : lastCallbackTime (0),
  23834. sampleRate (44100.0001)
  23835. {
  23836. }
  23837. MidiMessageCollector::~MidiMessageCollector()
  23838. {
  23839. }
  23840. void MidiMessageCollector::reset (const double sampleRate_)
  23841. {
  23842. jassert (sampleRate_ > 0);
  23843. const ScopedLock sl (midiCallbackLock);
  23844. sampleRate = sampleRate_;
  23845. incomingMessages.clear();
  23846. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23847. }
  23848. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23849. {
  23850. // you need to call reset() to set the correct sample rate before using this object
  23851. jassert (sampleRate != 44100.0001);
  23852. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23853. // for details of what the number should be.
  23854. jassert (message.getTimeStamp() != 0);
  23855. const ScopedLock sl (midiCallbackLock);
  23856. const int sampleNumber
  23857. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23858. incomingMessages.addEvent (message, sampleNumber);
  23859. // if the messages don't get used for over a second, we'd better
  23860. // get rid of any old ones to avoid the queue getting too big
  23861. if (sampleNumber > sampleRate)
  23862. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23863. }
  23864. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23865. const int numSamples)
  23866. {
  23867. // you need to call reset() to set the correct sample rate before using this object
  23868. jassert (sampleRate != 44100.0001);
  23869. const double timeNow = Time::getMillisecondCounterHiRes();
  23870. const double msElapsed = timeNow - lastCallbackTime;
  23871. const ScopedLock sl (midiCallbackLock);
  23872. lastCallbackTime = timeNow;
  23873. if (! incomingMessages.isEmpty())
  23874. {
  23875. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23876. int startSample = 0;
  23877. int scale = 1 << 16;
  23878. const uint8* midiData;
  23879. int numBytes, samplePosition;
  23880. MidiBuffer::Iterator iter (incomingMessages);
  23881. if (numSourceSamples > numSamples)
  23882. {
  23883. // if our list of events is longer than the buffer we're being
  23884. // asked for, scale them down to squeeze them all in..
  23885. const int maxBlockLengthToUse = numSamples << 5;
  23886. if (numSourceSamples > maxBlockLengthToUse)
  23887. {
  23888. startSample = numSourceSamples - maxBlockLengthToUse;
  23889. numSourceSamples = maxBlockLengthToUse;
  23890. iter.setNextSamplePosition (startSample);
  23891. }
  23892. scale = (numSamples << 10) / numSourceSamples;
  23893. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23894. {
  23895. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23896. destBuffer.addEvent (midiData, numBytes,
  23897. jlimit (0, numSamples - 1, samplePosition));
  23898. }
  23899. }
  23900. else
  23901. {
  23902. // if our event list is shorter than the number we need, put them
  23903. // towards the end of the buffer
  23904. startSample = numSamples - numSourceSamples;
  23905. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23906. {
  23907. destBuffer.addEvent (midiData, numBytes,
  23908. jlimit (0, numSamples - 1, samplePosition + startSample));
  23909. }
  23910. }
  23911. incomingMessages.clear();
  23912. }
  23913. }
  23914. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23915. {
  23916. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23917. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23918. addMessageToQueue (m);
  23919. }
  23920. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23921. {
  23922. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23923. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23924. addMessageToQueue (m);
  23925. }
  23926. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23927. {
  23928. addMessageToQueue (message);
  23929. }
  23930. END_JUCE_NAMESPACE
  23931. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23932. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23933. BEGIN_JUCE_NAMESPACE
  23934. MidiMessageSequence::MidiMessageSequence()
  23935. {
  23936. }
  23937. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23938. {
  23939. list.ensureStorageAllocated (other.list.size());
  23940. for (int i = 0; i < other.list.size(); ++i)
  23941. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23942. }
  23943. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23944. {
  23945. MidiMessageSequence otherCopy (other);
  23946. swapWith (otherCopy);
  23947. return *this;
  23948. }
  23949. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23950. {
  23951. list.swapWithArray (other.list);
  23952. }
  23953. MidiMessageSequence::~MidiMessageSequence()
  23954. {
  23955. }
  23956. void MidiMessageSequence::clear()
  23957. {
  23958. list.clear();
  23959. }
  23960. int MidiMessageSequence::getNumEvents() const
  23961. {
  23962. return list.size();
  23963. }
  23964. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23965. {
  23966. return list [index];
  23967. }
  23968. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23969. {
  23970. const MidiEventHolder* const meh = list [index];
  23971. if (meh != 0 && meh->noteOffObject != 0)
  23972. return meh->noteOffObject->message.getTimeStamp();
  23973. else
  23974. return 0.0;
  23975. }
  23976. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23977. {
  23978. const MidiEventHolder* const meh = list [index];
  23979. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23980. }
  23981. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23982. {
  23983. return list.indexOf (event);
  23984. }
  23985. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23986. {
  23987. const int numEvents = list.size();
  23988. int i;
  23989. for (i = 0; i < numEvents; ++i)
  23990. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23991. break;
  23992. return i;
  23993. }
  23994. double MidiMessageSequence::getStartTime() const
  23995. {
  23996. if (list.size() > 0)
  23997. return list.getUnchecked(0)->message.getTimeStamp();
  23998. else
  23999. return 0;
  24000. }
  24001. double MidiMessageSequence::getEndTime() const
  24002. {
  24003. if (list.size() > 0)
  24004. return list.getLast()->message.getTimeStamp();
  24005. else
  24006. return 0;
  24007. }
  24008. double MidiMessageSequence::getEventTime (const int index) const
  24009. {
  24010. if (((unsigned int) index) < (unsigned int) list.size())
  24011. return list.getUnchecked (index)->message.getTimeStamp();
  24012. return 0.0;
  24013. }
  24014. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24015. double timeAdjustment)
  24016. {
  24017. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24018. timeAdjustment += newMessage.getTimeStamp();
  24019. newOne->message.setTimeStamp (timeAdjustment);
  24020. int i;
  24021. for (i = list.size(); --i >= 0;)
  24022. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24023. break;
  24024. list.insert (i + 1, newOne);
  24025. }
  24026. void MidiMessageSequence::deleteEvent (const int index,
  24027. const bool deleteMatchingNoteUp)
  24028. {
  24029. if (((unsigned int) index) < (unsigned int) list.size())
  24030. {
  24031. if (deleteMatchingNoteUp)
  24032. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24033. list.remove (index);
  24034. }
  24035. }
  24036. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24037. double timeAdjustment,
  24038. double firstAllowableTime,
  24039. double endOfAllowableDestTimes)
  24040. {
  24041. firstAllowableTime -= timeAdjustment;
  24042. endOfAllowableDestTimes -= timeAdjustment;
  24043. for (int i = 0; i < other.list.size(); ++i)
  24044. {
  24045. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24046. const double t = m.getTimeStamp();
  24047. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24048. {
  24049. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24050. newOne->message.setTimeStamp (timeAdjustment + t);
  24051. list.add (newOne);
  24052. }
  24053. }
  24054. sort();
  24055. }
  24056. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24057. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24058. {
  24059. const double diff = first->message.getTimeStamp()
  24060. - second->message.getTimeStamp();
  24061. return (diff > 0) - (diff < 0);
  24062. }
  24063. void MidiMessageSequence::sort()
  24064. {
  24065. list.sort (*this, true);
  24066. }
  24067. void MidiMessageSequence::updateMatchedPairs()
  24068. {
  24069. for (int i = 0; i < list.size(); ++i)
  24070. {
  24071. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24072. if (m1.isNoteOn())
  24073. {
  24074. list.getUnchecked(i)->noteOffObject = 0;
  24075. const int note = m1.getNoteNumber();
  24076. const int chan = m1.getChannel();
  24077. const int len = list.size();
  24078. for (int j = i + 1; j < len; ++j)
  24079. {
  24080. const MidiMessage& m = list.getUnchecked(j)->message;
  24081. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24082. {
  24083. if (m.isNoteOff())
  24084. {
  24085. list.getUnchecked(i)->noteOffObject = list[j];
  24086. break;
  24087. }
  24088. else if (m.isNoteOn())
  24089. {
  24090. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24091. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24092. list.getUnchecked(i)->noteOffObject = list[j];
  24093. break;
  24094. }
  24095. }
  24096. }
  24097. }
  24098. }
  24099. }
  24100. void MidiMessageSequence::addTimeToMessages (const double delta)
  24101. {
  24102. for (int i = list.size(); --i >= 0;)
  24103. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24104. + delta);
  24105. }
  24106. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24107. MidiMessageSequence& destSequence,
  24108. const bool alsoIncludeMetaEvents) const
  24109. {
  24110. for (int i = 0; i < list.size(); ++i)
  24111. {
  24112. const MidiMessage& mm = list.getUnchecked(i)->message;
  24113. if (mm.isForChannel (channelNumberToExtract)
  24114. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24115. {
  24116. destSequence.addEvent (mm);
  24117. }
  24118. }
  24119. }
  24120. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24121. {
  24122. for (int i = 0; i < list.size(); ++i)
  24123. {
  24124. const MidiMessage& mm = list.getUnchecked(i)->message;
  24125. if (mm.isSysEx())
  24126. destSequence.addEvent (mm);
  24127. }
  24128. }
  24129. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24130. {
  24131. for (int i = list.size(); --i >= 0;)
  24132. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24133. list.remove(i);
  24134. }
  24135. void MidiMessageSequence::deleteSysExMessages()
  24136. {
  24137. for (int i = list.size(); --i >= 0;)
  24138. if (list.getUnchecked(i)->message.isSysEx())
  24139. list.remove(i);
  24140. }
  24141. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24142. const double time,
  24143. OwnedArray<MidiMessage>& dest)
  24144. {
  24145. bool doneProg = false;
  24146. bool donePitchWheel = false;
  24147. Array <int> doneControllers;
  24148. doneControllers.ensureStorageAllocated (32);
  24149. for (int i = list.size(); --i >= 0;)
  24150. {
  24151. const MidiMessage& mm = list.getUnchecked(i)->message;
  24152. if (mm.isForChannel (channelNumber)
  24153. && mm.getTimeStamp() <= time)
  24154. {
  24155. if (mm.isProgramChange())
  24156. {
  24157. if (! doneProg)
  24158. {
  24159. dest.add (new MidiMessage (mm, 0.0));
  24160. doneProg = true;
  24161. }
  24162. }
  24163. else if (mm.isController())
  24164. {
  24165. if (! doneControllers.contains (mm.getControllerNumber()))
  24166. {
  24167. dest.add (new MidiMessage (mm, 0.0));
  24168. doneControllers.add (mm.getControllerNumber());
  24169. }
  24170. }
  24171. else if (mm.isPitchWheel())
  24172. {
  24173. if (! donePitchWheel)
  24174. {
  24175. dest.add (new MidiMessage (mm, 0.0));
  24176. donePitchWheel = true;
  24177. }
  24178. }
  24179. }
  24180. }
  24181. }
  24182. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24183. : message (message_),
  24184. noteOffObject (0)
  24185. {
  24186. }
  24187. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24188. {
  24189. }
  24190. END_JUCE_NAMESPACE
  24191. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24192. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24193. BEGIN_JUCE_NAMESPACE
  24194. AudioPluginFormat::AudioPluginFormat() throw()
  24195. {
  24196. }
  24197. AudioPluginFormat::~AudioPluginFormat()
  24198. {
  24199. }
  24200. END_JUCE_NAMESPACE
  24201. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24202. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24203. BEGIN_JUCE_NAMESPACE
  24204. AudioPluginFormatManager::AudioPluginFormatManager()
  24205. {
  24206. }
  24207. AudioPluginFormatManager::~AudioPluginFormatManager()
  24208. {
  24209. clearSingletonInstance();
  24210. }
  24211. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24212. void AudioPluginFormatManager::addDefaultFormats()
  24213. {
  24214. #if JUCE_DEBUG
  24215. // you should only call this method once!
  24216. for (int i = formats.size(); --i >= 0;)
  24217. {
  24218. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24219. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24220. #endif
  24221. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24222. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24223. #endif
  24224. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24225. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24226. #endif
  24227. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24228. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24229. #endif
  24230. }
  24231. #endif
  24232. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24233. formats.add (new AudioUnitPluginFormat());
  24234. #endif
  24235. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24236. formats.add (new VSTPluginFormat());
  24237. #endif
  24238. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24239. formats.add (new DirectXPluginFormat());
  24240. #endif
  24241. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24242. formats.add (new LADSPAPluginFormat());
  24243. #endif
  24244. }
  24245. int AudioPluginFormatManager::getNumFormats()
  24246. {
  24247. return formats.size();
  24248. }
  24249. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24250. {
  24251. return formats [index];
  24252. }
  24253. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24254. {
  24255. formats.add (format);
  24256. }
  24257. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24258. String& errorMessage) const
  24259. {
  24260. AudioPluginInstance* result = 0;
  24261. for (int i = 0; i < formats.size(); ++i)
  24262. {
  24263. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24264. if (result != 0)
  24265. break;
  24266. }
  24267. if (result == 0)
  24268. {
  24269. if (! doesPluginStillExist (description))
  24270. errorMessage = TRANS ("This plug-in file no longer exists");
  24271. else
  24272. errorMessage = TRANS ("This plug-in failed to load correctly");
  24273. }
  24274. return result;
  24275. }
  24276. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24277. {
  24278. for (int i = 0; i < formats.size(); ++i)
  24279. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24280. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24281. return false;
  24282. }
  24283. END_JUCE_NAMESPACE
  24284. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24285. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24286. #define JUCE_PLUGIN_HOST 1
  24287. BEGIN_JUCE_NAMESPACE
  24288. AudioPluginInstance::AudioPluginInstance()
  24289. {
  24290. }
  24291. AudioPluginInstance::~AudioPluginInstance()
  24292. {
  24293. }
  24294. END_JUCE_NAMESPACE
  24295. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24296. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24297. BEGIN_JUCE_NAMESPACE
  24298. KnownPluginList::KnownPluginList()
  24299. {
  24300. }
  24301. KnownPluginList::~KnownPluginList()
  24302. {
  24303. }
  24304. void KnownPluginList::clear()
  24305. {
  24306. if (types.size() > 0)
  24307. {
  24308. types.clear();
  24309. sendChangeMessage (this);
  24310. }
  24311. }
  24312. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24313. {
  24314. for (int i = 0; i < types.size(); ++i)
  24315. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24316. return types.getUnchecked(i);
  24317. return 0;
  24318. }
  24319. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24320. {
  24321. for (int i = 0; i < types.size(); ++i)
  24322. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24323. return types.getUnchecked(i);
  24324. return 0;
  24325. }
  24326. bool KnownPluginList::addType (const PluginDescription& type)
  24327. {
  24328. for (int i = types.size(); --i >= 0;)
  24329. {
  24330. if (types.getUnchecked(i)->isDuplicateOf (type))
  24331. {
  24332. // strange - found a duplicate plugin with different info..
  24333. jassert (types.getUnchecked(i)->name == type.name);
  24334. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24335. *types.getUnchecked(i) = type;
  24336. return false;
  24337. }
  24338. }
  24339. types.add (new PluginDescription (type));
  24340. sendChangeMessage (this);
  24341. return true;
  24342. }
  24343. void KnownPluginList::removeType (const int index)
  24344. {
  24345. types.remove (index);
  24346. sendChangeMessage (this);
  24347. }
  24348. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24349. {
  24350. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24351. return File (fileOrIdentifier).getLastModificationTime();
  24352. return Time (0);
  24353. }
  24354. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24355. {
  24356. return t1 != t2 || t1 == Time (0);
  24357. }
  24358. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24359. {
  24360. if (getTypeForFile (fileOrIdentifier) == 0)
  24361. return false;
  24362. for (int i = types.size(); --i >= 0;)
  24363. {
  24364. const PluginDescription* const d = types.getUnchecked(i);
  24365. if (d->fileOrIdentifier == fileOrIdentifier
  24366. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24367. {
  24368. return false;
  24369. }
  24370. }
  24371. return true;
  24372. }
  24373. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24374. const bool dontRescanIfAlreadyInList,
  24375. OwnedArray <PluginDescription>& typesFound,
  24376. AudioPluginFormat& format)
  24377. {
  24378. bool addedOne = false;
  24379. if (dontRescanIfAlreadyInList
  24380. && getTypeForFile (fileOrIdentifier) != 0)
  24381. {
  24382. bool needsRescanning = false;
  24383. for (int i = types.size(); --i >= 0;)
  24384. {
  24385. const PluginDescription* const d = types.getUnchecked(i);
  24386. if (d->fileOrIdentifier == fileOrIdentifier)
  24387. {
  24388. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24389. needsRescanning = true;
  24390. else
  24391. typesFound.add (new PluginDescription (*d));
  24392. }
  24393. }
  24394. if (! needsRescanning)
  24395. return false;
  24396. }
  24397. OwnedArray <PluginDescription> found;
  24398. format.findAllTypesForFile (found, fileOrIdentifier);
  24399. for (int i = 0; i < found.size(); ++i)
  24400. {
  24401. PluginDescription* const desc = found.getUnchecked(i);
  24402. jassert (desc != 0);
  24403. if (addType (*desc))
  24404. addedOne = true;
  24405. typesFound.add (new PluginDescription (*desc));
  24406. }
  24407. return addedOne;
  24408. }
  24409. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24410. OwnedArray <PluginDescription>& typesFound)
  24411. {
  24412. for (int i = 0; i < files.size(); ++i)
  24413. {
  24414. bool loaded = false;
  24415. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24416. {
  24417. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24418. if (scanAndAddFile (files[i], true, typesFound, *format))
  24419. loaded = true;
  24420. }
  24421. if (! loaded)
  24422. {
  24423. const File f (files[i]);
  24424. if (f.isDirectory())
  24425. {
  24426. StringArray s;
  24427. {
  24428. Array<File> subFiles;
  24429. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24430. for (int j = 0; j < subFiles.size(); ++j)
  24431. s.add (subFiles.getReference(j).getFullPathName());
  24432. }
  24433. scanAndAddDragAndDroppedFiles (s, typesFound);
  24434. }
  24435. }
  24436. }
  24437. }
  24438. class PluginSorter
  24439. {
  24440. public:
  24441. KnownPluginList::SortMethod method;
  24442. PluginSorter() throw() {}
  24443. int compareElements (const PluginDescription* const first,
  24444. const PluginDescription* const second) const
  24445. {
  24446. int diff = 0;
  24447. if (method == KnownPluginList::sortByCategory)
  24448. diff = first->category.compareLexicographically (second->category);
  24449. else if (method == KnownPluginList::sortByManufacturer)
  24450. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24451. else if (method == KnownPluginList::sortByFileSystemLocation)
  24452. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24453. .upToLastOccurrenceOf ("/", false, false)
  24454. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24455. .upToLastOccurrenceOf ("/", false, false));
  24456. if (diff == 0)
  24457. diff = first->name.compareLexicographically (second->name);
  24458. return diff;
  24459. }
  24460. };
  24461. void KnownPluginList::sort (const SortMethod method)
  24462. {
  24463. if (method != defaultOrder)
  24464. {
  24465. PluginSorter sorter;
  24466. sorter.method = method;
  24467. types.sort (sorter, true);
  24468. sendChangeMessage (this);
  24469. }
  24470. }
  24471. XmlElement* KnownPluginList::createXml() const
  24472. {
  24473. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24474. for (int i = 0; i < types.size(); ++i)
  24475. e->addChildElement (types.getUnchecked(i)->createXml());
  24476. return e;
  24477. }
  24478. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24479. {
  24480. clear();
  24481. if (xml.hasTagName ("KNOWNPLUGINS"))
  24482. {
  24483. forEachXmlChildElement (xml, e)
  24484. {
  24485. PluginDescription info;
  24486. if (info.loadFromXml (*e))
  24487. addType (info);
  24488. }
  24489. }
  24490. }
  24491. const int menuIdBase = 0x324503f4;
  24492. // This is used to turn a bunch of paths into a nested menu structure.
  24493. struct PluginFilesystemTree
  24494. {
  24495. private:
  24496. String folder;
  24497. OwnedArray <PluginFilesystemTree> subFolders;
  24498. Array <PluginDescription*> plugins;
  24499. void addPlugin (PluginDescription* const pd, const String& path)
  24500. {
  24501. if (path.isEmpty())
  24502. {
  24503. plugins.add (pd);
  24504. }
  24505. else
  24506. {
  24507. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24508. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24509. for (int i = subFolders.size(); --i >= 0;)
  24510. {
  24511. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24512. {
  24513. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24514. return;
  24515. }
  24516. }
  24517. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24518. newFolder->folder = firstSubFolder;
  24519. subFolders.add (newFolder);
  24520. newFolder->addPlugin (pd, remainingPath);
  24521. }
  24522. }
  24523. // removes any deeply nested folders that don't contain any actual plugins
  24524. void optimise()
  24525. {
  24526. for (int i = subFolders.size(); --i >= 0;)
  24527. {
  24528. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24529. sub->optimise();
  24530. if (sub->plugins.size() == 0)
  24531. {
  24532. for (int j = 0; j < sub->subFolders.size(); ++j)
  24533. subFolders.add (sub->subFolders.getUnchecked(j));
  24534. sub->subFolders.clear (false);
  24535. subFolders.remove (i);
  24536. }
  24537. }
  24538. }
  24539. public:
  24540. void buildTree (const Array <PluginDescription*>& allPlugins)
  24541. {
  24542. for (int i = 0; i < allPlugins.size(); ++i)
  24543. {
  24544. String path (allPlugins.getUnchecked(i)
  24545. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24546. .upToLastOccurrenceOf ("/", false, false));
  24547. if (path.substring (1, 2) == ":")
  24548. path = path.substring (2);
  24549. addPlugin (allPlugins.getUnchecked(i), path);
  24550. }
  24551. optimise();
  24552. }
  24553. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24554. {
  24555. int i;
  24556. for (i = 0; i < subFolders.size(); ++i)
  24557. {
  24558. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24559. PopupMenu subMenu;
  24560. sub->addToMenu (subMenu, allPlugins);
  24561. #if JUCE_MAC
  24562. // avoid the special AU formatting nonsense on Mac..
  24563. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24564. #else
  24565. m.addSubMenu (sub->folder, subMenu);
  24566. #endif
  24567. }
  24568. for (i = 0; i < plugins.size(); ++i)
  24569. {
  24570. PluginDescription* const plugin = plugins.getUnchecked(i);
  24571. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24572. plugin->name, true, false);
  24573. }
  24574. }
  24575. };
  24576. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24577. {
  24578. Array <PluginDescription*> sorted;
  24579. {
  24580. PluginSorter sorter;
  24581. sorter.method = sortMethod;
  24582. for (int i = 0; i < types.size(); ++i)
  24583. sorted.addSorted (sorter, types.getUnchecked(i));
  24584. }
  24585. if (sortMethod == sortByCategory
  24586. || sortMethod == sortByManufacturer)
  24587. {
  24588. String lastSubMenuName;
  24589. PopupMenu sub;
  24590. for (int i = 0; i < sorted.size(); ++i)
  24591. {
  24592. const PluginDescription* const pd = sorted.getUnchecked(i);
  24593. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24594. : pd->manufacturerName);
  24595. if (! thisSubMenuName.containsNonWhitespaceChars())
  24596. thisSubMenuName = "Other";
  24597. if (thisSubMenuName != lastSubMenuName)
  24598. {
  24599. if (sub.getNumItems() > 0)
  24600. {
  24601. menu.addSubMenu (lastSubMenuName, sub);
  24602. sub.clear();
  24603. }
  24604. lastSubMenuName = thisSubMenuName;
  24605. }
  24606. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24607. }
  24608. if (sub.getNumItems() > 0)
  24609. menu.addSubMenu (lastSubMenuName, sub);
  24610. }
  24611. else if (sortMethod == sortByFileSystemLocation)
  24612. {
  24613. PluginFilesystemTree root;
  24614. root.buildTree (sorted);
  24615. root.addToMenu (menu, types);
  24616. }
  24617. else
  24618. {
  24619. for (int i = 0; i < sorted.size(); ++i)
  24620. {
  24621. const PluginDescription* const pd = sorted.getUnchecked(i);
  24622. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24623. }
  24624. }
  24625. }
  24626. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24627. {
  24628. const int i = menuResultCode - menuIdBase;
  24629. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24630. }
  24631. END_JUCE_NAMESPACE
  24632. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24633. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24634. BEGIN_JUCE_NAMESPACE
  24635. PluginDescription::PluginDescription()
  24636. : uid (0),
  24637. isInstrument (false),
  24638. numInputChannels (0),
  24639. numOutputChannels (0)
  24640. {
  24641. }
  24642. PluginDescription::~PluginDescription()
  24643. {
  24644. }
  24645. PluginDescription::PluginDescription (const PluginDescription& other)
  24646. : name (other.name),
  24647. pluginFormatName (other.pluginFormatName),
  24648. category (other.category),
  24649. manufacturerName (other.manufacturerName),
  24650. version (other.version),
  24651. fileOrIdentifier (other.fileOrIdentifier),
  24652. lastFileModTime (other.lastFileModTime),
  24653. uid (other.uid),
  24654. isInstrument (other.isInstrument),
  24655. numInputChannels (other.numInputChannels),
  24656. numOutputChannels (other.numOutputChannels)
  24657. {
  24658. }
  24659. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24660. {
  24661. name = other.name;
  24662. pluginFormatName = other.pluginFormatName;
  24663. category = other.category;
  24664. manufacturerName = other.manufacturerName;
  24665. version = other.version;
  24666. fileOrIdentifier = other.fileOrIdentifier;
  24667. uid = other.uid;
  24668. isInstrument = other.isInstrument;
  24669. lastFileModTime = other.lastFileModTime;
  24670. numInputChannels = other.numInputChannels;
  24671. numOutputChannels = other.numOutputChannels;
  24672. return *this;
  24673. }
  24674. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24675. {
  24676. return fileOrIdentifier == other.fileOrIdentifier
  24677. && uid == other.uid;
  24678. }
  24679. const String PluginDescription::createIdentifierString() const
  24680. {
  24681. return pluginFormatName
  24682. + "-" + name
  24683. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24684. + "-" + String::toHexString (uid);
  24685. }
  24686. XmlElement* PluginDescription::createXml() const
  24687. {
  24688. XmlElement* const e = new XmlElement ("PLUGIN");
  24689. e->setAttribute ("name", name);
  24690. e->setAttribute ("format", pluginFormatName);
  24691. e->setAttribute ("category", category);
  24692. e->setAttribute ("manufacturer", manufacturerName);
  24693. e->setAttribute ("version", version);
  24694. e->setAttribute ("file", fileOrIdentifier);
  24695. e->setAttribute ("uid", String::toHexString (uid));
  24696. e->setAttribute ("isInstrument", isInstrument);
  24697. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24698. e->setAttribute ("numInputs", numInputChannels);
  24699. e->setAttribute ("numOutputs", numOutputChannels);
  24700. return e;
  24701. }
  24702. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24703. {
  24704. if (xml.hasTagName ("PLUGIN"))
  24705. {
  24706. name = xml.getStringAttribute ("name");
  24707. pluginFormatName = xml.getStringAttribute ("format");
  24708. category = xml.getStringAttribute ("category");
  24709. manufacturerName = xml.getStringAttribute ("manufacturer");
  24710. version = xml.getStringAttribute ("version");
  24711. fileOrIdentifier = xml.getStringAttribute ("file");
  24712. uid = xml.getStringAttribute ("uid").getHexValue32();
  24713. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24714. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24715. numInputChannels = xml.getIntAttribute ("numInputs");
  24716. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24717. return true;
  24718. }
  24719. return false;
  24720. }
  24721. END_JUCE_NAMESPACE
  24722. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24723. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24724. BEGIN_JUCE_NAMESPACE
  24725. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24726. AudioPluginFormat& formatToLookFor,
  24727. FileSearchPath directoriesToSearch,
  24728. const bool recursive,
  24729. const File& deadMansPedalFile_)
  24730. : list (listToAddTo),
  24731. format (formatToLookFor),
  24732. deadMansPedalFile (deadMansPedalFile_),
  24733. nextIndex (0),
  24734. progress (0)
  24735. {
  24736. directoriesToSearch.removeRedundantPaths();
  24737. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24738. // If any plugins have crashed recently when being loaded, move them to the
  24739. // end of the list to give the others a chance to load correctly..
  24740. const StringArray crashedPlugins (getDeadMansPedalFile());
  24741. for (int i = 0; i < crashedPlugins.size(); ++i)
  24742. {
  24743. const String f = crashedPlugins[i];
  24744. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24745. if (f == filesOrIdentifiersToScan[j])
  24746. filesOrIdentifiersToScan.move (j, -1);
  24747. }
  24748. }
  24749. PluginDirectoryScanner::~PluginDirectoryScanner()
  24750. {
  24751. }
  24752. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24753. {
  24754. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24755. }
  24756. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24757. {
  24758. String file (filesOrIdentifiersToScan [nextIndex]);
  24759. if (file.isNotEmpty())
  24760. {
  24761. if (! list.isListingUpToDate (file))
  24762. {
  24763. OwnedArray <PluginDescription> typesFound;
  24764. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24765. StringArray crashedPlugins (getDeadMansPedalFile());
  24766. crashedPlugins.removeString (file);
  24767. crashedPlugins.add (file);
  24768. setDeadMansPedalFile (crashedPlugins);
  24769. list.scanAndAddFile (file,
  24770. dontRescanIfAlreadyInList,
  24771. typesFound,
  24772. format);
  24773. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24774. crashedPlugins.removeString (file);
  24775. setDeadMansPedalFile (crashedPlugins);
  24776. if (typesFound.size() == 0)
  24777. failedFiles.add (file);
  24778. }
  24779. ++nextIndex;
  24780. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24781. }
  24782. return nextIndex < filesOrIdentifiersToScan.size();
  24783. }
  24784. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24785. {
  24786. StringArray lines;
  24787. if (deadMansPedalFile != File::nonexistent)
  24788. {
  24789. lines.addLines (deadMansPedalFile.loadFileAsString());
  24790. lines.removeEmptyStrings();
  24791. }
  24792. return lines;
  24793. }
  24794. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24795. {
  24796. if (deadMansPedalFile != File::nonexistent)
  24797. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24798. }
  24799. END_JUCE_NAMESPACE
  24800. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24801. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24802. BEGIN_JUCE_NAMESPACE
  24803. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24804. const File& deadMansPedalFile_,
  24805. PropertiesFile* const propertiesToUse_)
  24806. : list (listToEdit),
  24807. deadMansPedalFile (deadMansPedalFile_),
  24808. propertiesToUse (propertiesToUse_)
  24809. {
  24810. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24811. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24812. optionsButton->addButtonListener (this);
  24813. optionsButton->setTriggeredOnMouseDown (true);
  24814. setSize (400, 600);
  24815. list.addChangeListener (this);
  24816. changeListenerCallback (0);
  24817. }
  24818. PluginListComponent::~PluginListComponent()
  24819. {
  24820. list.removeChangeListener (this);
  24821. deleteAllChildren();
  24822. }
  24823. void PluginListComponent::resized()
  24824. {
  24825. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24826. optionsButton->changeWidthToFitText (24);
  24827. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24828. }
  24829. void PluginListComponent::changeListenerCallback (void*)
  24830. {
  24831. listBox->updateContent();
  24832. listBox->repaint();
  24833. }
  24834. int PluginListComponent::getNumRows()
  24835. {
  24836. return list.getNumTypes();
  24837. }
  24838. void PluginListComponent::paintListBoxItem (int row,
  24839. Graphics& g,
  24840. int width, int height,
  24841. bool rowIsSelected)
  24842. {
  24843. if (rowIsSelected)
  24844. g.fillAll (findColour (TextEditor::highlightColourId));
  24845. const PluginDescription* const pd = list.getType (row);
  24846. if (pd != 0)
  24847. {
  24848. GlyphArrangement ga;
  24849. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24850. g.setColour (Colours::black);
  24851. ga.draw (g);
  24852. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24853. String desc;
  24854. desc << pd->pluginFormatName
  24855. << (pd->isInstrument ? " instrument" : " effect")
  24856. << " - "
  24857. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24858. << " / "
  24859. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24860. if (pd->manufacturerName.isNotEmpty())
  24861. desc << " - " << pd->manufacturerName;
  24862. if (pd->version.isNotEmpty())
  24863. desc << " - " << pd->version;
  24864. if (pd->category.isNotEmpty())
  24865. desc << " - category: '" << pd->category << '\'';
  24866. g.setColour (Colours::grey);
  24867. ga.clear();
  24868. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24869. ga.draw (g);
  24870. }
  24871. }
  24872. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24873. {
  24874. list.removeType (lastRowSelected);
  24875. }
  24876. void PluginListComponent::buttonClicked (Button* b)
  24877. {
  24878. if (optionsButton == b)
  24879. {
  24880. PopupMenu menu;
  24881. menu.addItem (1, TRANS("Clear list"));
  24882. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24883. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24884. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24885. menu.addSeparator();
  24886. menu.addItem (2, TRANS("Sort alphabetically"));
  24887. menu.addItem (3, TRANS("Sort by category"));
  24888. menu.addItem (4, TRANS("Sort by manufacturer"));
  24889. menu.addSeparator();
  24890. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24891. {
  24892. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24893. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24894. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24895. }
  24896. const int r = menu.showAt (optionsButton);
  24897. if (r == 1)
  24898. {
  24899. list.clear();
  24900. }
  24901. else if (r == 2)
  24902. {
  24903. list.sort (KnownPluginList::sortAlphabetically);
  24904. }
  24905. else if (r == 3)
  24906. {
  24907. list.sort (KnownPluginList::sortByCategory);
  24908. }
  24909. else if (r == 4)
  24910. {
  24911. list.sort (KnownPluginList::sortByManufacturer);
  24912. }
  24913. else if (r == 5)
  24914. {
  24915. const SparseSet <int> selected (listBox->getSelectedRows());
  24916. for (int i = list.getNumTypes(); --i >= 0;)
  24917. if (selected.contains (i))
  24918. list.removeType (i);
  24919. }
  24920. else if (r == 6)
  24921. {
  24922. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24923. if (desc != 0)
  24924. {
  24925. if (File (desc->fileOrIdentifier).existsAsFile())
  24926. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24927. }
  24928. }
  24929. else if (r == 7)
  24930. {
  24931. for (int i = list.getNumTypes(); --i >= 0;)
  24932. {
  24933. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24934. {
  24935. list.removeType (i);
  24936. }
  24937. }
  24938. }
  24939. else if (r != 0)
  24940. {
  24941. typeToScan = r - 10;
  24942. startTimer (1);
  24943. }
  24944. }
  24945. }
  24946. void PluginListComponent::timerCallback()
  24947. {
  24948. stopTimer();
  24949. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24950. }
  24951. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24952. {
  24953. return true;
  24954. }
  24955. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24956. {
  24957. OwnedArray <PluginDescription> typesFound;
  24958. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24959. }
  24960. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24961. {
  24962. if (format == 0)
  24963. return;
  24964. FileSearchPath path (format->getDefaultLocationsToSearch());
  24965. if (propertiesToUse != 0)
  24966. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24967. {
  24968. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24969. FileSearchPathListComponent pathList;
  24970. pathList.setSize (500, 300);
  24971. pathList.setPath (path);
  24972. aw.addCustomComponent (&pathList);
  24973. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24974. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24975. if (aw.runModalLoop() == 0)
  24976. return;
  24977. path = pathList.getPath();
  24978. }
  24979. if (propertiesToUse != 0)
  24980. {
  24981. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24982. propertiesToUse->saveIfNeeded();
  24983. }
  24984. double progress = 0.0;
  24985. AlertWindow aw (TRANS("Scanning for plugins..."),
  24986. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24987. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24988. aw.addProgressBarComponent (progress);
  24989. aw.enterModalState();
  24990. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24991. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24992. for (;;)
  24993. {
  24994. aw.setMessage (TRANS("Testing:\n\n")
  24995. + scanner.getNextPluginFileThatWillBeScanned());
  24996. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24997. if (! scanner.scanNextFile (true))
  24998. break;
  24999. if (! aw.isCurrentlyModal())
  25000. break;
  25001. progress = scanner.getProgress();
  25002. }
  25003. if (scanner.getFailedFiles().size() > 0)
  25004. {
  25005. StringArray shortNames;
  25006. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25007. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25008. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25009. TRANS("Scan complete"),
  25010. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25011. + shortNames.joinIntoString (", "));
  25012. }
  25013. }
  25014. END_JUCE_NAMESPACE
  25015. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25016. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25017. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25018. #include <AudioUnit/AudioUnit.h>
  25019. #include <AudioUnit/AUCocoaUIView.h>
  25020. #include <CoreAudioKit/AUGenericView.h>
  25021. #if JUCE_SUPPORT_CARBON
  25022. #include <AudioToolbox/AudioUnitUtilities.h>
  25023. #include <AudioUnit/AudioUnitCarbonView.h>
  25024. #endif
  25025. BEGIN_JUCE_NAMESPACE
  25026. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25027. #endif
  25028. #if JUCE_MAC
  25029. // Change this to disable logging of various activities
  25030. #ifndef AU_LOGGING
  25031. #define AU_LOGGING 1
  25032. #endif
  25033. #if AU_LOGGING
  25034. #define log(a) Logger::writeToLog(a);
  25035. #else
  25036. #define log(a)
  25037. #endif
  25038. namespace AudioUnitFormatHelpers
  25039. {
  25040. static int insideCallback = 0;
  25041. static const String osTypeToString (OSType type)
  25042. {
  25043. char s[4];
  25044. s[0] = (char) (((uint32) type) >> 24);
  25045. s[1] = (char) (((uint32) type) >> 16);
  25046. s[2] = (char) (((uint32) type) >> 8);
  25047. s[3] = (char) ((uint32) type);
  25048. return String (s, 4);
  25049. }
  25050. static OSType stringToOSType (const String& s1)
  25051. {
  25052. const String s (s1 + " ");
  25053. return (((OSType) (unsigned char) s[0]) << 24)
  25054. | (((OSType) (unsigned char) s[1]) << 16)
  25055. | (((OSType) (unsigned char) s[2]) << 8)
  25056. | ((OSType) (unsigned char) s[3]);
  25057. }
  25058. static const char* auIdentifierPrefix = "AudioUnit:";
  25059. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25060. {
  25061. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25062. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25063. String s (auIdentifierPrefix);
  25064. if (desc.componentType == kAudioUnitType_MusicDevice)
  25065. s << "Synths/";
  25066. else if (desc.componentType == kAudioUnitType_MusicEffect
  25067. || desc.componentType == kAudioUnitType_Effect)
  25068. s << "Effects/";
  25069. else if (desc.componentType == kAudioUnitType_Generator)
  25070. s << "Generators/";
  25071. else if (desc.componentType == kAudioUnitType_Panner)
  25072. s << "Panners/";
  25073. s << osTypeToString (desc.componentType) << ","
  25074. << osTypeToString (desc.componentSubType) << ","
  25075. << osTypeToString (desc.componentManufacturer);
  25076. return s;
  25077. }
  25078. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25079. {
  25080. Handle componentNameHandle = NewHandle (sizeof (void*));
  25081. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25082. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25083. {
  25084. ComponentDescription desc;
  25085. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25086. {
  25087. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25088. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25089. if (nameString != 0 && nameString[0] != 0)
  25090. {
  25091. const String all ((const char*) nameString + 1, nameString[0]);
  25092. DBG ("name: "+ all);
  25093. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25094. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25095. }
  25096. if (infoString != 0 && infoString[0] != 0)
  25097. {
  25098. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25099. }
  25100. if (name.isEmpty())
  25101. name = "<Unknown>";
  25102. }
  25103. DisposeHandle (componentNameHandle);
  25104. DisposeHandle (componentInfoHandle);
  25105. }
  25106. }
  25107. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25108. String& name, String& version, String& manufacturer)
  25109. {
  25110. zerostruct (desc);
  25111. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25112. {
  25113. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25114. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25115. StringArray tokens;
  25116. tokens.addTokens (s, ",", String::empty);
  25117. tokens.trim();
  25118. tokens.removeEmptyStrings();
  25119. if (tokens.size() == 3)
  25120. {
  25121. desc.componentType = stringToOSType (tokens[0]);
  25122. desc.componentSubType = stringToOSType (tokens[1]);
  25123. desc.componentManufacturer = stringToOSType (tokens[2]);
  25124. ComponentRecord* comp = FindNextComponent (0, &desc);
  25125. if (comp != 0)
  25126. {
  25127. getAUDetails (comp, name, manufacturer);
  25128. return true;
  25129. }
  25130. }
  25131. }
  25132. return false;
  25133. }
  25134. }
  25135. class AudioUnitPluginWindowCarbon;
  25136. class AudioUnitPluginWindowCocoa;
  25137. class AudioUnitPluginInstance : public AudioPluginInstance
  25138. {
  25139. public:
  25140. ~AudioUnitPluginInstance();
  25141. void initialise();
  25142. // AudioPluginInstance methods:
  25143. void fillInPluginDescription (PluginDescription& desc) const
  25144. {
  25145. desc.name = pluginName;
  25146. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25147. desc.uid = ((int) componentDesc.componentType)
  25148. ^ ((int) componentDesc.componentSubType)
  25149. ^ ((int) componentDesc.componentManufacturer);
  25150. desc.lastFileModTime = 0;
  25151. desc.pluginFormatName = "AudioUnit";
  25152. desc.category = getCategory();
  25153. desc.manufacturerName = manufacturer;
  25154. desc.version = version;
  25155. desc.numInputChannels = getNumInputChannels();
  25156. desc.numOutputChannels = getNumOutputChannels();
  25157. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25158. }
  25159. const String getName() const { return pluginName; }
  25160. bool acceptsMidi() const { return wantsMidiMessages; }
  25161. bool producesMidi() const { return false; }
  25162. // AudioProcessor methods:
  25163. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25164. void releaseResources();
  25165. void processBlock (AudioSampleBuffer& buffer,
  25166. MidiBuffer& midiMessages);
  25167. bool hasEditor() const;
  25168. AudioProcessorEditor* createEditor();
  25169. const String getInputChannelName (int index) const;
  25170. bool isInputChannelStereoPair (int index) const;
  25171. const String getOutputChannelName (int index) const;
  25172. bool isOutputChannelStereoPair (int index) const;
  25173. int getNumParameters();
  25174. float getParameter (int index);
  25175. void setParameter (int index, float newValue);
  25176. const String getParameterName (int index);
  25177. const String getParameterText (int index);
  25178. bool isParameterAutomatable (int index) const;
  25179. int getNumPrograms();
  25180. int getCurrentProgram();
  25181. void setCurrentProgram (int index);
  25182. const String getProgramName (int index);
  25183. void changeProgramName (int index, const String& newName);
  25184. void getStateInformation (MemoryBlock& destData);
  25185. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25186. void setStateInformation (const void* data, int sizeInBytes);
  25187. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25188. juce_UseDebuggingNewOperator
  25189. private:
  25190. friend class AudioUnitPluginWindowCarbon;
  25191. friend class AudioUnitPluginWindowCocoa;
  25192. friend class AudioUnitPluginFormat;
  25193. ComponentDescription componentDesc;
  25194. String pluginName, manufacturer, version;
  25195. String fileOrIdentifier;
  25196. CriticalSection lock;
  25197. bool wantsMidiMessages, wasPlaying, prepared;
  25198. HeapBlock <AudioBufferList> outputBufferList;
  25199. AudioTimeStamp timeStamp;
  25200. AudioSampleBuffer* currentBuffer;
  25201. AudioUnit audioUnit;
  25202. Array <int> parameterIds;
  25203. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25204. void setPluginCallbacks();
  25205. void getParameterListFromPlugin();
  25206. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25207. const AudioTimeStamp* inTimeStamp,
  25208. UInt32 inBusNumber,
  25209. UInt32 inNumberFrames,
  25210. AudioBufferList* ioData) const;
  25211. static OSStatus renderGetInputCallback (void* inRefCon,
  25212. AudioUnitRenderActionFlags* ioActionFlags,
  25213. const AudioTimeStamp* inTimeStamp,
  25214. UInt32 inBusNumber,
  25215. UInt32 inNumberFrames,
  25216. AudioBufferList* ioData)
  25217. {
  25218. return ((AudioUnitPluginInstance*) inRefCon)
  25219. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25220. }
  25221. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25222. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25223. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25224. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25225. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25226. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25227. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25228. {
  25229. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25230. }
  25231. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25232. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25233. Float64* outCurrentMeasureDownBeat)
  25234. {
  25235. return ((AudioUnitPluginInstance*) inHostUserData)
  25236. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25237. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25238. }
  25239. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25240. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25241. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25242. {
  25243. return ((AudioUnitPluginInstance*) inHostUserData)
  25244. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25245. outCurrentSampleInTimeLine, outIsCycling,
  25246. outCycleStartBeat, outCycleEndBeat);
  25247. }
  25248. void getNumChannels (int& numIns, int& numOuts)
  25249. {
  25250. numIns = 0;
  25251. numOuts = 0;
  25252. AUChannelInfo supportedChannels [128];
  25253. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25254. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25255. 0, supportedChannels, &supportedChannelsSize) == noErr
  25256. && supportedChannelsSize > 0)
  25257. {
  25258. int explicitNumIns = 0;
  25259. int explicitNumOuts = 0;
  25260. int maximumNumIns = 0;
  25261. int maximumNumOuts = 0;
  25262. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25263. {
  25264. const int inChannels = (int) supportedChannels[i].inChannels;
  25265. const int outChannels = (int) supportedChannels[i].outChannels;
  25266. if (inChannels < 0)
  25267. maximumNumIns = jmin (maximumNumIns, inChannels);
  25268. else
  25269. explicitNumIns = jmax (explicitNumIns, inChannels);
  25270. if (outChannels < 0)
  25271. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25272. else
  25273. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25274. }
  25275. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25276. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25277. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25278. {
  25279. numIns = numOuts = 2;
  25280. }
  25281. else
  25282. {
  25283. numIns = explicitNumIns;
  25284. numOuts = explicitNumOuts;
  25285. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25286. numIns = 2;
  25287. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25288. numOuts = 2;
  25289. }
  25290. }
  25291. else
  25292. {
  25293. // (this really means the plugin will take any number of ins/outs as long
  25294. // as they are the same)
  25295. numIns = numOuts = 2;
  25296. }
  25297. }
  25298. const String getCategory() const;
  25299. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25300. };
  25301. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25302. : fileOrIdentifier (fileOrIdentifier),
  25303. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25304. audioUnit (0),
  25305. currentBuffer (0)
  25306. {
  25307. using namespace AudioUnitFormatHelpers;
  25308. try
  25309. {
  25310. ++insideCallback;
  25311. log ("Opening AU: " + fileOrIdentifier);
  25312. if (getComponentDescFromFile (fileOrIdentifier))
  25313. {
  25314. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25315. if (comp != 0)
  25316. {
  25317. audioUnit = (AudioUnit) OpenComponent (comp);
  25318. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25319. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25320. }
  25321. }
  25322. --insideCallback;
  25323. }
  25324. catch (...)
  25325. {
  25326. --insideCallback;
  25327. }
  25328. }
  25329. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25330. {
  25331. const ScopedLock sl (lock);
  25332. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25333. if (audioUnit != 0)
  25334. {
  25335. AudioUnitUninitialize (audioUnit);
  25336. CloseComponent (audioUnit);
  25337. audioUnit = 0;
  25338. }
  25339. }
  25340. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25341. {
  25342. zerostruct (componentDesc);
  25343. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25344. return true;
  25345. const File file (fileOrIdentifier);
  25346. if (! file.hasFileExtension (".component"))
  25347. return false;
  25348. const char* const utf8 = fileOrIdentifier.toUTF8();
  25349. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25350. strlen (utf8), file.isDirectory());
  25351. if (url != 0)
  25352. {
  25353. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25354. CFRelease (url);
  25355. if (bundleRef != 0)
  25356. {
  25357. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25358. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25359. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25360. if (pluginName.isEmpty())
  25361. pluginName = file.getFileNameWithoutExtension();
  25362. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25363. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25364. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25365. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25366. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25367. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25368. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25369. UseResFile (resFileId);
  25370. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25371. {
  25372. Handle h = Get1IndResource ('thng', i);
  25373. if (h != 0)
  25374. {
  25375. HLock (h);
  25376. const uint32* const types = (const uint32*) *h;
  25377. if (types[0] == kAudioUnitType_MusicDevice
  25378. || types[0] == kAudioUnitType_MusicEffect
  25379. || types[0] == kAudioUnitType_Effect
  25380. || types[0] == kAudioUnitType_Generator
  25381. || types[0] == kAudioUnitType_Panner)
  25382. {
  25383. componentDesc.componentType = types[0];
  25384. componentDesc.componentSubType = types[1];
  25385. componentDesc.componentManufacturer = types[2];
  25386. break;
  25387. }
  25388. HUnlock (h);
  25389. ReleaseResource (h);
  25390. }
  25391. }
  25392. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25393. CFRelease (bundleRef);
  25394. }
  25395. }
  25396. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25397. }
  25398. void AudioUnitPluginInstance::initialise()
  25399. {
  25400. getParameterListFromPlugin();
  25401. setPluginCallbacks();
  25402. int numIns, numOuts;
  25403. getNumChannels (numIns, numOuts);
  25404. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25405. setLatencySamples (0);
  25406. }
  25407. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25408. {
  25409. parameterIds.clear();
  25410. if (audioUnit != 0)
  25411. {
  25412. UInt32 paramListSize = 0;
  25413. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25414. 0, 0, &paramListSize);
  25415. if (paramListSize > 0)
  25416. {
  25417. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25418. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25419. 0, &parameterIds.getReference(0), &paramListSize);
  25420. }
  25421. }
  25422. }
  25423. void AudioUnitPluginInstance::setPluginCallbacks()
  25424. {
  25425. if (audioUnit != 0)
  25426. {
  25427. {
  25428. AURenderCallbackStruct info;
  25429. zerostruct (info);
  25430. info.inputProcRefCon = this;
  25431. info.inputProc = renderGetInputCallback;
  25432. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25433. 0, &info, sizeof (info));
  25434. }
  25435. {
  25436. HostCallbackInfo info;
  25437. zerostruct (info);
  25438. info.hostUserData = this;
  25439. info.beatAndTempoProc = getBeatAndTempoCallback;
  25440. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25441. info.transportStateProc = getTransportStateCallback;
  25442. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25443. 0, &info, sizeof (info));
  25444. }
  25445. }
  25446. }
  25447. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25448. int samplesPerBlockExpected)
  25449. {
  25450. if (audioUnit != 0)
  25451. {
  25452. releaseResources();
  25453. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25454. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25455. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25456. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25457. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25458. {
  25459. Float64 sr = sampleRate_;
  25460. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25461. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25462. }
  25463. int numIns, numOuts;
  25464. getNumChannels (numIns, numOuts);
  25465. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25466. Float64 latencySecs = 0.0;
  25467. UInt32 latencySize = sizeof (latencySecs);
  25468. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25469. 0, &latencySecs, &latencySize);
  25470. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25471. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25472. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25473. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25474. {
  25475. AudioStreamBasicDescription stream;
  25476. zerostruct (stream);
  25477. stream.mSampleRate = sampleRate_;
  25478. stream.mFormatID = kAudioFormatLinearPCM;
  25479. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25480. stream.mFramesPerPacket = 1;
  25481. stream.mBytesPerPacket = 4;
  25482. stream.mBytesPerFrame = 4;
  25483. stream.mBitsPerChannel = 32;
  25484. stream.mChannelsPerFrame = numIns;
  25485. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25486. 0, &stream, sizeof (stream));
  25487. stream.mChannelsPerFrame = numOuts;
  25488. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25489. 0, &stream, sizeof (stream));
  25490. }
  25491. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25492. outputBufferList->mNumberBuffers = numOuts;
  25493. for (int i = numOuts; --i >= 0;)
  25494. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25495. zerostruct (timeStamp);
  25496. timeStamp.mSampleTime = 0;
  25497. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25498. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25499. currentBuffer = 0;
  25500. wasPlaying = false;
  25501. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25502. }
  25503. }
  25504. void AudioUnitPluginInstance::releaseResources()
  25505. {
  25506. if (prepared)
  25507. {
  25508. AudioUnitUninitialize (audioUnit);
  25509. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25510. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25511. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25512. outputBufferList.free();
  25513. currentBuffer = 0;
  25514. prepared = false;
  25515. }
  25516. }
  25517. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25518. const AudioTimeStamp* inTimeStamp,
  25519. UInt32 inBusNumber,
  25520. UInt32 inNumberFrames,
  25521. AudioBufferList* ioData) const
  25522. {
  25523. if (inBusNumber == 0
  25524. && currentBuffer != 0)
  25525. {
  25526. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25527. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25528. {
  25529. if (i < currentBuffer->getNumChannels())
  25530. {
  25531. memcpy (ioData->mBuffers[i].mData,
  25532. currentBuffer->getSampleData (i, 0),
  25533. sizeof (float) * inNumberFrames);
  25534. }
  25535. else
  25536. {
  25537. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25538. }
  25539. }
  25540. }
  25541. return noErr;
  25542. }
  25543. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25544. MidiBuffer& midiMessages)
  25545. {
  25546. const int numSamples = buffer.getNumSamples();
  25547. if (prepared)
  25548. {
  25549. AudioUnitRenderActionFlags flags = 0;
  25550. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25551. for (int i = getNumOutputChannels(); --i >= 0;)
  25552. {
  25553. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25554. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25555. }
  25556. currentBuffer = &buffer;
  25557. if (wantsMidiMessages)
  25558. {
  25559. const uint8* midiEventData;
  25560. int midiEventSize, midiEventPosition;
  25561. MidiBuffer::Iterator i (midiMessages);
  25562. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25563. {
  25564. if (midiEventSize <= 3)
  25565. MusicDeviceMIDIEvent (audioUnit,
  25566. midiEventData[0], midiEventData[1], midiEventData[2],
  25567. midiEventPosition);
  25568. else
  25569. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25570. }
  25571. midiMessages.clear();
  25572. }
  25573. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25574. 0, numSamples, outputBufferList);
  25575. timeStamp.mSampleTime += numSamples;
  25576. }
  25577. else
  25578. {
  25579. // Plugin not working correctly, so just bypass..
  25580. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25581. buffer.clear (i, 0, buffer.getNumSamples());
  25582. }
  25583. }
  25584. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25585. {
  25586. AudioPlayHead* const ph = getPlayHead();
  25587. AudioPlayHead::CurrentPositionInfo result;
  25588. if (ph != 0 && ph->getCurrentPosition (result))
  25589. {
  25590. if (outCurrentBeat != 0)
  25591. *outCurrentBeat = result.ppqPosition;
  25592. if (outCurrentTempo != 0)
  25593. *outCurrentTempo = result.bpm;
  25594. }
  25595. else
  25596. {
  25597. if (outCurrentBeat != 0)
  25598. *outCurrentBeat = 0;
  25599. if (outCurrentTempo != 0)
  25600. *outCurrentTempo = 120.0;
  25601. }
  25602. return noErr;
  25603. }
  25604. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25605. Float32* outTimeSig_Numerator,
  25606. UInt32* outTimeSig_Denominator,
  25607. Float64* outCurrentMeasureDownBeat) const
  25608. {
  25609. AudioPlayHead* const ph = getPlayHead();
  25610. AudioPlayHead::CurrentPositionInfo result;
  25611. if (ph != 0 && ph->getCurrentPosition (result))
  25612. {
  25613. if (outTimeSig_Numerator != 0)
  25614. *outTimeSig_Numerator = result.timeSigNumerator;
  25615. if (outTimeSig_Denominator != 0)
  25616. *outTimeSig_Denominator = result.timeSigDenominator;
  25617. if (outDeltaSampleOffsetToNextBeat != 0)
  25618. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25619. if (outCurrentMeasureDownBeat != 0)
  25620. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25621. }
  25622. else
  25623. {
  25624. if (outDeltaSampleOffsetToNextBeat != 0)
  25625. *outDeltaSampleOffsetToNextBeat = 0;
  25626. if (outTimeSig_Numerator != 0)
  25627. *outTimeSig_Numerator = 4;
  25628. if (outTimeSig_Denominator != 0)
  25629. *outTimeSig_Denominator = 4;
  25630. if (outCurrentMeasureDownBeat != 0)
  25631. *outCurrentMeasureDownBeat = 0;
  25632. }
  25633. return noErr;
  25634. }
  25635. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25636. Boolean* outTransportStateChanged,
  25637. Float64* outCurrentSampleInTimeLine,
  25638. Boolean* outIsCycling,
  25639. Float64* outCycleStartBeat,
  25640. Float64* outCycleEndBeat)
  25641. {
  25642. AudioPlayHead* const ph = getPlayHead();
  25643. AudioPlayHead::CurrentPositionInfo result;
  25644. if (ph != 0 && ph->getCurrentPosition (result))
  25645. {
  25646. if (outIsPlaying != 0)
  25647. *outIsPlaying = result.isPlaying;
  25648. if (outTransportStateChanged != 0)
  25649. {
  25650. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25651. wasPlaying = result.isPlaying;
  25652. }
  25653. if (outCurrentSampleInTimeLine != 0)
  25654. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25655. if (outIsCycling != 0)
  25656. *outIsCycling = false;
  25657. if (outCycleStartBeat != 0)
  25658. *outCycleStartBeat = 0;
  25659. if (outCycleEndBeat != 0)
  25660. *outCycleEndBeat = 0;
  25661. }
  25662. else
  25663. {
  25664. if (outIsPlaying != 0)
  25665. *outIsPlaying = false;
  25666. if (outTransportStateChanged != 0)
  25667. *outTransportStateChanged = false;
  25668. if (outCurrentSampleInTimeLine != 0)
  25669. *outCurrentSampleInTimeLine = 0;
  25670. if (outIsCycling != 0)
  25671. *outIsCycling = false;
  25672. if (outCycleStartBeat != 0)
  25673. *outCycleStartBeat = 0;
  25674. if (outCycleEndBeat != 0)
  25675. *outCycleEndBeat = 0;
  25676. }
  25677. return noErr;
  25678. }
  25679. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25680. {
  25681. public:
  25682. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25683. : AudioProcessorEditor (&plugin_),
  25684. plugin (plugin_)
  25685. {
  25686. addAndMakeVisible (&wrapper);
  25687. setOpaque (true);
  25688. setVisible (true);
  25689. setSize (100, 100);
  25690. createView (createGenericViewIfNeeded);
  25691. }
  25692. ~AudioUnitPluginWindowCocoa()
  25693. {
  25694. const bool wasValid = isValid();
  25695. wrapper.setView (0);
  25696. if (wasValid)
  25697. plugin.editorBeingDeleted (this);
  25698. }
  25699. bool isValid() const { return wrapper.getView() != 0; }
  25700. void paint (Graphics& g)
  25701. {
  25702. g.fillAll (Colours::white);
  25703. }
  25704. void resized()
  25705. {
  25706. wrapper.setSize (getWidth(), getHeight());
  25707. }
  25708. private:
  25709. AudioUnitPluginInstance& plugin;
  25710. NSViewComponent wrapper;
  25711. bool createView (const bool createGenericViewIfNeeded)
  25712. {
  25713. NSView* pluginView = 0;
  25714. UInt32 dataSize = 0;
  25715. Boolean isWritable = false;
  25716. AudioUnitInitialize (plugin.audioUnit);
  25717. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25718. 0, &dataSize, &isWritable) == noErr
  25719. && dataSize != 0
  25720. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25721. 0, &dataSize, &isWritable) == noErr)
  25722. {
  25723. HeapBlock <AudioUnitCocoaViewInfo> info;
  25724. info.calloc (dataSize, 1);
  25725. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25726. 0, info, &dataSize) == noErr)
  25727. {
  25728. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25729. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25730. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25731. Class viewClass = [viewBundle classNamed: viewClassName];
  25732. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25733. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25734. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25735. {
  25736. id factory = [[[viewClass alloc] init] autorelease];
  25737. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25738. withSize: NSMakeSize (getWidth(), getHeight())];
  25739. }
  25740. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25741. {
  25742. CFRelease (info->mCocoaAUViewClass[i]);
  25743. CFRelease (info->mCocoaAUViewBundleLocation);
  25744. }
  25745. }
  25746. }
  25747. if (createGenericViewIfNeeded && (pluginView == 0))
  25748. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25749. wrapper.setView (pluginView);
  25750. if (pluginView != 0)
  25751. setSize ([pluginView frame].size.width,
  25752. [pluginView frame].size.height);
  25753. return pluginView != 0;
  25754. }
  25755. };
  25756. #if JUCE_SUPPORT_CARBON
  25757. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25758. {
  25759. public:
  25760. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25761. : AudioProcessorEditor (&plugin_),
  25762. plugin (plugin_),
  25763. viewComponent (0)
  25764. {
  25765. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25766. setOpaque (true);
  25767. setVisible (true);
  25768. setSize (400, 300);
  25769. ComponentDescription viewList [16];
  25770. UInt32 viewListSize = sizeof (viewList);
  25771. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25772. 0, &viewList, &viewListSize);
  25773. componentRecord = FindNextComponent (0, &viewList[0]);
  25774. }
  25775. ~AudioUnitPluginWindowCarbon()
  25776. {
  25777. innerWrapper = 0;
  25778. if (isValid())
  25779. plugin.editorBeingDeleted (this);
  25780. }
  25781. bool isValid() const throw() { return componentRecord != 0; }
  25782. void paint (Graphics& g)
  25783. {
  25784. g.fillAll (Colours::black);
  25785. }
  25786. void resized()
  25787. {
  25788. innerWrapper->setSize (getWidth(), getHeight());
  25789. }
  25790. bool keyStateChanged (bool)
  25791. {
  25792. return false;
  25793. }
  25794. bool keyPressed (const KeyPress&)
  25795. {
  25796. return false;
  25797. }
  25798. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25799. AudioUnitCarbonView getViewComponent()
  25800. {
  25801. if (viewComponent == 0 && componentRecord != 0)
  25802. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25803. return viewComponent;
  25804. }
  25805. void closeViewComponent()
  25806. {
  25807. if (viewComponent != 0)
  25808. {
  25809. log ("Closing AU GUI: " + plugin.getName());
  25810. CloseComponent (viewComponent);
  25811. viewComponent = 0;
  25812. }
  25813. }
  25814. juce_UseDebuggingNewOperator
  25815. private:
  25816. AudioUnitPluginInstance& plugin;
  25817. ComponentRecord* componentRecord;
  25818. AudioUnitCarbonView viewComponent;
  25819. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25820. {
  25821. public:
  25822. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25823. : owner (owner_)
  25824. {
  25825. }
  25826. ~InnerWrapperComponent()
  25827. {
  25828. deleteWindow();
  25829. }
  25830. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25831. {
  25832. log ("Opening AU GUI: " + owner->plugin.getName());
  25833. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25834. if (viewComponent == 0)
  25835. return 0;
  25836. Float32Point pos = { 0, 0 };
  25837. Float32Point size = { 250, 200 };
  25838. HIViewRef pluginView = 0;
  25839. AudioUnitCarbonViewCreate (viewComponent,
  25840. owner->getAudioUnit(),
  25841. windowRef,
  25842. rootView,
  25843. &pos,
  25844. &size,
  25845. (ControlRef*) &pluginView);
  25846. return pluginView;
  25847. }
  25848. void removeView (HIViewRef)
  25849. {
  25850. owner->closeViewComponent();
  25851. }
  25852. private:
  25853. AudioUnitPluginWindowCarbon* const owner;
  25854. };
  25855. friend class InnerWrapperComponent;
  25856. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25857. };
  25858. #endif
  25859. bool AudioUnitPluginInstance::hasEditor() const
  25860. {
  25861. return true;
  25862. }
  25863. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25864. {
  25865. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25866. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25867. w = 0;
  25868. #if JUCE_SUPPORT_CARBON
  25869. if (w == 0)
  25870. {
  25871. w = new AudioUnitPluginWindowCarbon (*this);
  25872. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25873. w = 0;
  25874. }
  25875. #endif
  25876. if (w == 0)
  25877. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25878. return w.release();
  25879. }
  25880. const String AudioUnitPluginInstance::getCategory() const
  25881. {
  25882. const char* result = 0;
  25883. switch (componentDesc.componentType)
  25884. {
  25885. case kAudioUnitType_Effect:
  25886. case kAudioUnitType_MusicEffect:
  25887. result = "Effect";
  25888. break;
  25889. case kAudioUnitType_MusicDevice:
  25890. result = "Synth";
  25891. break;
  25892. case kAudioUnitType_Generator:
  25893. result = "Generator";
  25894. break;
  25895. case kAudioUnitType_Panner:
  25896. result = "Panner";
  25897. break;
  25898. default:
  25899. break;
  25900. }
  25901. return result;
  25902. }
  25903. int AudioUnitPluginInstance::getNumParameters()
  25904. {
  25905. return parameterIds.size();
  25906. }
  25907. float AudioUnitPluginInstance::getParameter (int index)
  25908. {
  25909. const ScopedLock sl (lock);
  25910. Float32 value = 0.0f;
  25911. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25912. {
  25913. AudioUnitGetParameter (audioUnit,
  25914. (UInt32) parameterIds.getUnchecked (index),
  25915. kAudioUnitScope_Global, 0,
  25916. &value);
  25917. }
  25918. return value;
  25919. }
  25920. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25921. {
  25922. const ScopedLock sl (lock);
  25923. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25924. {
  25925. AudioUnitSetParameter (audioUnit,
  25926. (UInt32) parameterIds.getUnchecked (index),
  25927. kAudioUnitScope_Global, 0,
  25928. newValue, 0);
  25929. }
  25930. }
  25931. const String AudioUnitPluginInstance::getParameterName (int index)
  25932. {
  25933. AudioUnitParameterInfo info;
  25934. zerostruct (info);
  25935. UInt32 sz = sizeof (info);
  25936. String name;
  25937. if (AudioUnitGetProperty (audioUnit,
  25938. kAudioUnitProperty_ParameterInfo,
  25939. kAudioUnitScope_Global,
  25940. parameterIds [index], &info, &sz) == noErr)
  25941. {
  25942. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25943. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25944. else
  25945. name = String (info.name, sizeof (info.name));
  25946. }
  25947. return name;
  25948. }
  25949. const String AudioUnitPluginInstance::getParameterText (int index)
  25950. {
  25951. return String (getParameter (index));
  25952. }
  25953. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25954. {
  25955. AudioUnitParameterInfo info;
  25956. UInt32 sz = sizeof (info);
  25957. if (AudioUnitGetProperty (audioUnit,
  25958. kAudioUnitProperty_ParameterInfo,
  25959. kAudioUnitScope_Global,
  25960. parameterIds [index], &info, &sz) == noErr)
  25961. {
  25962. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25963. }
  25964. return true;
  25965. }
  25966. int AudioUnitPluginInstance::getNumPrograms()
  25967. {
  25968. CFArrayRef presets;
  25969. UInt32 sz = sizeof (CFArrayRef);
  25970. int num = 0;
  25971. if (AudioUnitGetProperty (audioUnit,
  25972. kAudioUnitProperty_FactoryPresets,
  25973. kAudioUnitScope_Global,
  25974. 0, &presets, &sz) == noErr)
  25975. {
  25976. num = (int) CFArrayGetCount (presets);
  25977. CFRelease (presets);
  25978. }
  25979. return num;
  25980. }
  25981. int AudioUnitPluginInstance::getCurrentProgram()
  25982. {
  25983. AUPreset current;
  25984. current.presetNumber = 0;
  25985. UInt32 sz = sizeof (AUPreset);
  25986. AudioUnitGetProperty (audioUnit,
  25987. kAudioUnitProperty_FactoryPresets,
  25988. kAudioUnitScope_Global,
  25989. 0, &current, &sz);
  25990. return current.presetNumber;
  25991. }
  25992. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25993. {
  25994. AUPreset current;
  25995. current.presetNumber = newIndex;
  25996. current.presetName = 0;
  25997. AudioUnitSetProperty (audioUnit,
  25998. kAudioUnitProperty_FactoryPresets,
  25999. kAudioUnitScope_Global,
  26000. 0, &current, sizeof (AUPreset));
  26001. }
  26002. const String AudioUnitPluginInstance::getProgramName (int index)
  26003. {
  26004. String s;
  26005. CFArrayRef presets;
  26006. UInt32 sz = sizeof (CFArrayRef);
  26007. if (AudioUnitGetProperty (audioUnit,
  26008. kAudioUnitProperty_FactoryPresets,
  26009. kAudioUnitScope_Global,
  26010. 0, &presets, &sz) == noErr)
  26011. {
  26012. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26013. {
  26014. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26015. if (p != 0 && p->presetNumber == index)
  26016. {
  26017. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26018. break;
  26019. }
  26020. }
  26021. CFRelease (presets);
  26022. }
  26023. return s;
  26024. }
  26025. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26026. {
  26027. jassertfalse; // xxx not implemented!
  26028. }
  26029. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26030. {
  26031. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26032. return "Input " + String (index + 1);
  26033. return String::empty;
  26034. }
  26035. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26036. {
  26037. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26038. return false;
  26039. return true;
  26040. }
  26041. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26042. {
  26043. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26044. return "Output " + String (index + 1);
  26045. return String::empty;
  26046. }
  26047. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26048. {
  26049. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26050. return false;
  26051. return true;
  26052. }
  26053. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26054. {
  26055. getCurrentProgramStateInformation (destData);
  26056. }
  26057. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26058. {
  26059. CFPropertyListRef propertyList = 0;
  26060. UInt32 sz = sizeof (CFPropertyListRef);
  26061. if (AudioUnitGetProperty (audioUnit,
  26062. kAudioUnitProperty_ClassInfo,
  26063. kAudioUnitScope_Global,
  26064. 0, &propertyList, &sz) == noErr)
  26065. {
  26066. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26067. CFWriteStreamOpen (stream);
  26068. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26069. CFWriteStreamClose (stream);
  26070. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26071. destData.setSize (bytesWritten);
  26072. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26073. CFRelease (data);
  26074. CFRelease (stream);
  26075. CFRelease (propertyList);
  26076. }
  26077. }
  26078. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26079. {
  26080. setCurrentProgramStateInformation (data, sizeInBytes);
  26081. }
  26082. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26083. {
  26084. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26085. (const UInt8*) data,
  26086. sizeInBytes,
  26087. kCFAllocatorNull);
  26088. CFReadStreamOpen (stream);
  26089. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26090. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26091. stream,
  26092. 0,
  26093. kCFPropertyListImmutable,
  26094. &format,
  26095. 0);
  26096. CFRelease (stream);
  26097. if (propertyList != 0)
  26098. AudioUnitSetProperty (audioUnit,
  26099. kAudioUnitProperty_ClassInfo,
  26100. kAudioUnitScope_Global,
  26101. 0, &propertyList, sizeof (propertyList));
  26102. }
  26103. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26104. {
  26105. }
  26106. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26107. {
  26108. }
  26109. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26110. const String& fileOrIdentifier)
  26111. {
  26112. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26113. return;
  26114. PluginDescription desc;
  26115. desc.fileOrIdentifier = fileOrIdentifier;
  26116. desc.uid = 0;
  26117. try
  26118. {
  26119. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26120. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26121. if (auInstance != 0)
  26122. {
  26123. auInstance->fillInPluginDescription (desc);
  26124. results.add (new PluginDescription (desc));
  26125. }
  26126. }
  26127. catch (...)
  26128. {
  26129. // crashed while loading...
  26130. }
  26131. }
  26132. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26133. {
  26134. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26135. {
  26136. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26137. if (result->audioUnit != 0)
  26138. {
  26139. result->initialise();
  26140. return result.release();
  26141. }
  26142. }
  26143. return 0;
  26144. }
  26145. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26146. const bool /*recursive*/)
  26147. {
  26148. StringArray result;
  26149. ComponentRecord* comp = 0;
  26150. ComponentDescription desc;
  26151. zerostruct (desc);
  26152. for (;;)
  26153. {
  26154. zerostruct (desc);
  26155. comp = FindNextComponent (comp, &desc);
  26156. if (comp == 0)
  26157. break;
  26158. GetComponentInfo (comp, &desc, 0, 0, 0);
  26159. if (desc.componentType == kAudioUnitType_MusicDevice
  26160. || desc.componentType == kAudioUnitType_MusicEffect
  26161. || desc.componentType == kAudioUnitType_Effect
  26162. || desc.componentType == kAudioUnitType_Generator
  26163. || desc.componentType == kAudioUnitType_Panner)
  26164. {
  26165. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26166. DBG (s);
  26167. result.add (s);
  26168. }
  26169. }
  26170. return result;
  26171. }
  26172. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26173. {
  26174. ComponentDescription desc;
  26175. String name, version, manufacturer;
  26176. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26177. return FindNextComponent (0, &desc) != 0;
  26178. const File f (fileOrIdentifier);
  26179. return f.hasFileExtension (".component")
  26180. && f.isDirectory();
  26181. }
  26182. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26183. {
  26184. ComponentDescription desc;
  26185. String name, version, manufacturer;
  26186. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26187. if (name.isEmpty())
  26188. name = fileOrIdentifier;
  26189. return name;
  26190. }
  26191. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26192. {
  26193. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26194. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26195. else
  26196. return File (desc.fileOrIdentifier).exists();
  26197. }
  26198. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26199. {
  26200. return FileSearchPath ("/(Default AudioUnit locations)");
  26201. }
  26202. #endif
  26203. END_JUCE_NAMESPACE
  26204. #undef log
  26205. #endif
  26206. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26207. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26208. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26209. #define JUCE_MAC_VST_INCLUDED 1
  26210. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26211. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26212. #if JUCE_WINDOWS
  26213. #undef _WIN32_WINNT
  26214. #define _WIN32_WINNT 0x500
  26215. #undef STRICT
  26216. #define STRICT
  26217. #include <windows.h>
  26218. #include <float.h>
  26219. #pragma warning (disable : 4312 4355)
  26220. #elif JUCE_LINUX
  26221. #include <float.h>
  26222. #include <sys/time.h>
  26223. #include <X11/Xlib.h>
  26224. #include <X11/Xutil.h>
  26225. #include <X11/Xatom.h>
  26226. #undef Font
  26227. #undef KeyPress
  26228. #undef Drawable
  26229. #undef Time
  26230. #else
  26231. #include <Cocoa/Cocoa.h>
  26232. #include <Carbon/Carbon.h>
  26233. #endif
  26234. #if ! (JUCE_MAC && JUCE_64BIT)
  26235. BEGIN_JUCE_NAMESPACE
  26236. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26237. #endif
  26238. #undef PRAGMA_ALIGN_SUPPORTED
  26239. #define VST_FORCE_DEPRECATED 0
  26240. #if JUCE_MSVC
  26241. #pragma warning (push)
  26242. #pragma warning (disable: 4996)
  26243. #endif
  26244. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26245. your include path if you want to add VST support.
  26246. If you're not interested in VSTs, you can disable them by changing the
  26247. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26248. */
  26249. #include "pluginterfaces/vst2.x/aeffectx.h"
  26250. #if JUCE_MSVC
  26251. #pragma warning (pop)
  26252. #endif
  26253. #if JUCE_LINUX
  26254. #define Font JUCE_NAMESPACE::Font
  26255. #define KeyPress JUCE_NAMESPACE::KeyPress
  26256. #define Drawable JUCE_NAMESPACE::Drawable
  26257. #define Time JUCE_NAMESPACE::Time
  26258. #endif
  26259. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26260. #ifdef __aeffect__
  26261. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26262. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26263. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26264. events to the list.
  26265. This is used by both the VST hosting code and the plugin wrapper.
  26266. */
  26267. class VSTMidiEventList
  26268. {
  26269. public:
  26270. VSTMidiEventList()
  26271. : numEventsUsed (0), numEventsAllocated (0)
  26272. {
  26273. }
  26274. ~VSTMidiEventList()
  26275. {
  26276. freeEvents();
  26277. }
  26278. void clear()
  26279. {
  26280. numEventsUsed = 0;
  26281. if (events != 0)
  26282. events->numEvents = 0;
  26283. }
  26284. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26285. {
  26286. ensureSize (numEventsUsed + 1);
  26287. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26288. events->numEvents = ++numEventsUsed;
  26289. if (numBytes <= 4)
  26290. {
  26291. if (e->type == kVstSysExType)
  26292. {
  26293. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26294. e->type = kVstMidiType;
  26295. e->byteSize = sizeof (VstMidiEvent);
  26296. e->noteLength = 0;
  26297. e->noteOffset = 0;
  26298. e->detune = 0;
  26299. e->noteOffVelocity = 0;
  26300. }
  26301. e->deltaFrames = frameOffset;
  26302. memcpy (e->midiData, midiData, numBytes);
  26303. }
  26304. else
  26305. {
  26306. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26307. if (se->type == kVstSysExType)
  26308. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26309. else
  26310. se->sysexDump = (char*) juce_malloc (numBytes);
  26311. memcpy (se->sysexDump, midiData, numBytes);
  26312. se->type = kVstSysExType;
  26313. se->byteSize = sizeof (VstMidiSysexEvent);
  26314. se->deltaFrames = frameOffset;
  26315. se->flags = 0;
  26316. se->dumpBytes = numBytes;
  26317. se->resvd1 = 0;
  26318. se->resvd2 = 0;
  26319. }
  26320. }
  26321. // Handy method to pull the events out of an event buffer supplied by the host
  26322. // or plugin.
  26323. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26324. {
  26325. for (int i = 0; i < events->numEvents; ++i)
  26326. {
  26327. const VstEvent* const e = events->events[i];
  26328. if (e != 0)
  26329. {
  26330. if (e->type == kVstMidiType)
  26331. {
  26332. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26333. 4, e->deltaFrames);
  26334. }
  26335. else if (e->type == kVstSysExType)
  26336. {
  26337. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26338. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26339. e->deltaFrames);
  26340. }
  26341. }
  26342. }
  26343. }
  26344. void ensureSize (int numEventsNeeded)
  26345. {
  26346. if (numEventsNeeded > numEventsAllocated)
  26347. {
  26348. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26349. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26350. if (events == 0)
  26351. events.calloc (size, 1);
  26352. else
  26353. events.realloc (size, 1);
  26354. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26355. {
  26356. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26357. (int) sizeof (VstMidiSysexEvent)));
  26358. e->type = kVstMidiType;
  26359. e->byteSize = sizeof (VstMidiEvent);
  26360. events->events[i] = (VstEvent*) e;
  26361. }
  26362. numEventsAllocated = numEventsNeeded;
  26363. }
  26364. }
  26365. void freeEvents()
  26366. {
  26367. if (events != 0)
  26368. {
  26369. for (int i = numEventsAllocated; --i >= 0;)
  26370. {
  26371. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26372. if (e->type == kVstSysExType)
  26373. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26374. juce_free (e);
  26375. }
  26376. events.free();
  26377. numEventsUsed = 0;
  26378. numEventsAllocated = 0;
  26379. }
  26380. }
  26381. HeapBlock <VstEvents> events;
  26382. private:
  26383. int numEventsUsed, numEventsAllocated;
  26384. };
  26385. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26386. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26387. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26388. #if ! JUCE_WINDOWS
  26389. static void _fpreset() {}
  26390. static void _clearfp() {}
  26391. #endif
  26392. extern void juce_callAnyTimersSynchronously();
  26393. const int fxbVersionNum = 1;
  26394. struct fxProgram
  26395. {
  26396. long chunkMagic; // 'CcnK'
  26397. long byteSize; // of this chunk, excl. magic + byteSize
  26398. long fxMagic; // 'FxCk'
  26399. long version;
  26400. long fxID; // fx unique id
  26401. long fxVersion;
  26402. long numParams;
  26403. char prgName[28];
  26404. float params[1]; // variable no. of parameters
  26405. };
  26406. struct fxSet
  26407. {
  26408. long chunkMagic; // 'CcnK'
  26409. long byteSize; // of this chunk, excl. magic + byteSize
  26410. long fxMagic; // 'FxBk'
  26411. long version;
  26412. long fxID; // fx unique id
  26413. long fxVersion;
  26414. long numPrograms;
  26415. char future[128];
  26416. fxProgram programs[1]; // variable no. of programs
  26417. };
  26418. struct fxChunkSet
  26419. {
  26420. long chunkMagic; // 'CcnK'
  26421. long byteSize; // of this chunk, excl. magic + byteSize
  26422. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26423. long version;
  26424. long fxID; // fx unique id
  26425. long fxVersion;
  26426. long numPrograms;
  26427. char future[128];
  26428. long chunkSize;
  26429. char chunk[8]; // variable
  26430. };
  26431. struct fxProgramSet
  26432. {
  26433. long chunkMagic; // 'CcnK'
  26434. long byteSize; // of this chunk, excl. magic + byteSize
  26435. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26436. long version;
  26437. long fxID; // fx unique id
  26438. long fxVersion;
  26439. long numPrograms;
  26440. char name[28];
  26441. long chunkSize;
  26442. char chunk[8]; // variable
  26443. };
  26444. static long vst_swap (const long x) throw()
  26445. {
  26446. #ifdef JUCE_LITTLE_ENDIAN
  26447. return (long) ByteOrder::swap ((uint32) x);
  26448. #else
  26449. return x;
  26450. #endif
  26451. }
  26452. static float vst_swapFloat (const float x) throw()
  26453. {
  26454. #ifdef JUCE_LITTLE_ENDIAN
  26455. union { uint32 asInt; float asFloat; } n;
  26456. n.asFloat = x;
  26457. n.asInt = ByteOrder::swap (n.asInt);
  26458. return n.asFloat;
  26459. #else
  26460. return x;
  26461. #endif
  26462. }
  26463. static double getVSTHostTimeNanoseconds()
  26464. {
  26465. #if JUCE_WINDOWS
  26466. return timeGetTime() * 1000000.0;
  26467. #elif JUCE_LINUX
  26468. timeval micro;
  26469. gettimeofday (&micro, 0);
  26470. return micro.tv_usec * 1000.0;
  26471. #elif JUCE_MAC
  26472. UnsignedWide micro;
  26473. Microseconds (&micro);
  26474. return micro.lo * 1000.0;
  26475. #endif
  26476. }
  26477. typedef AEffect* (*MainCall) (audioMasterCallback);
  26478. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26479. static int shellUIDToCreate = 0;
  26480. static int insideVSTCallback = 0;
  26481. class VSTPluginWindow;
  26482. // Change this to disable logging of various VST activities
  26483. #ifndef VST_LOGGING
  26484. #define VST_LOGGING 1
  26485. #endif
  26486. #if VST_LOGGING
  26487. #define log(a) Logger::writeToLog(a);
  26488. #else
  26489. #define log(a)
  26490. #endif
  26491. #if JUCE_MAC && JUCE_PPC
  26492. static void* NewCFMFromMachO (void* const machofp) throw()
  26493. {
  26494. void* result = juce_malloc (8);
  26495. ((void**) result)[0] = machofp;
  26496. ((void**) result)[1] = result;
  26497. return result;
  26498. }
  26499. #endif
  26500. #if JUCE_LINUX
  26501. extern Display* display;
  26502. extern XContext windowHandleXContext;
  26503. typedef void (*EventProcPtr) (XEvent* ev);
  26504. static bool xErrorTriggered;
  26505. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26506. {
  26507. xErrorTriggered = true;
  26508. return 0;
  26509. }
  26510. static int getPropertyFromXWindow (Window handle, Atom atom)
  26511. {
  26512. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26513. xErrorTriggered = false;
  26514. int userSize;
  26515. unsigned long bytes, userCount;
  26516. unsigned char* data;
  26517. Atom userType;
  26518. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26519. &userType, &userSize, &userCount, &bytes, &data);
  26520. XSetErrorHandler (oldErrorHandler);
  26521. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26522. : 0;
  26523. }
  26524. static Window getChildWindow (Window windowToCheck)
  26525. {
  26526. Window rootWindow, parentWindow;
  26527. Window* childWindows;
  26528. unsigned int numChildren;
  26529. XQueryTree (display,
  26530. windowToCheck,
  26531. &rootWindow,
  26532. &parentWindow,
  26533. &childWindows,
  26534. &numChildren);
  26535. if (numChildren > 0)
  26536. return childWindows [0];
  26537. return 0;
  26538. }
  26539. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26540. {
  26541. if (e.mods.isLeftButtonDown())
  26542. {
  26543. ev.xbutton.button = Button1;
  26544. ev.xbutton.state |= Button1Mask;
  26545. }
  26546. else if (e.mods.isRightButtonDown())
  26547. {
  26548. ev.xbutton.button = Button3;
  26549. ev.xbutton.state |= Button3Mask;
  26550. }
  26551. else if (e.mods.isMiddleButtonDown())
  26552. {
  26553. ev.xbutton.button = Button2;
  26554. ev.xbutton.state |= Button2Mask;
  26555. }
  26556. }
  26557. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26558. {
  26559. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26560. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26561. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26562. }
  26563. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26564. {
  26565. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26566. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26567. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26568. }
  26569. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26570. {
  26571. if (increment < 0)
  26572. {
  26573. ev.xbutton.button = Button5;
  26574. ev.xbutton.state |= Button5Mask;
  26575. }
  26576. else if (increment > 0)
  26577. {
  26578. ev.xbutton.button = Button4;
  26579. ev.xbutton.state |= Button4Mask;
  26580. }
  26581. }
  26582. #endif
  26583. class ModuleHandle : public ReferenceCountedObject
  26584. {
  26585. public:
  26586. File file;
  26587. MainCall moduleMain;
  26588. String pluginName;
  26589. static Array <ModuleHandle*>& getActiveModules()
  26590. {
  26591. static Array <ModuleHandle*> activeModules;
  26592. return activeModules;
  26593. }
  26594. static ModuleHandle* findOrCreateModule (const File& file)
  26595. {
  26596. for (int i = getActiveModules().size(); --i >= 0;)
  26597. {
  26598. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26599. if (module->file == file)
  26600. return module;
  26601. }
  26602. _fpreset(); // (doesn't do any harm)
  26603. ++insideVSTCallback;
  26604. shellUIDToCreate = 0;
  26605. log ("Attempting to load VST: " + file.getFullPathName());
  26606. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26607. if (! m->open())
  26608. m = 0;
  26609. --insideVSTCallback;
  26610. _fpreset(); // (doesn't do any harm)
  26611. return m.release();
  26612. }
  26613. ModuleHandle (const File& file_)
  26614. : file (file_),
  26615. moduleMain (0),
  26616. #if JUCE_WINDOWS || JUCE_LINUX
  26617. hModule (0)
  26618. #elif JUCE_MAC
  26619. fragId (0),
  26620. resHandle (0),
  26621. bundleRef (0),
  26622. resFileId (0)
  26623. #endif
  26624. {
  26625. getActiveModules().add (this);
  26626. #if JUCE_WINDOWS || JUCE_LINUX
  26627. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26628. #elif JUCE_MAC
  26629. FSRef ref;
  26630. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26631. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26632. #endif
  26633. }
  26634. ~ModuleHandle()
  26635. {
  26636. getActiveModules().removeValue (this);
  26637. close();
  26638. }
  26639. juce_UseDebuggingNewOperator
  26640. #if JUCE_WINDOWS || JUCE_LINUX
  26641. void* hModule;
  26642. String fullParentDirectoryPathName;
  26643. bool open()
  26644. {
  26645. #if JUCE_WINDOWS
  26646. static bool timePeriodSet = false;
  26647. if (! timePeriodSet)
  26648. {
  26649. timePeriodSet = true;
  26650. timeBeginPeriod (2);
  26651. }
  26652. #endif
  26653. pluginName = file.getFileNameWithoutExtension();
  26654. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26655. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26656. if (moduleMain == 0)
  26657. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26658. return moduleMain != 0;
  26659. }
  26660. void close()
  26661. {
  26662. _fpreset(); // (doesn't do any harm)
  26663. PlatformUtilities::freeDynamicLibrary (hModule);
  26664. }
  26665. void closeEffect (AEffect* eff)
  26666. {
  26667. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26668. }
  26669. #else
  26670. CFragConnectionID fragId;
  26671. Handle resHandle;
  26672. CFBundleRef bundleRef;
  26673. FSSpec parentDirFSSpec;
  26674. short resFileId;
  26675. bool open()
  26676. {
  26677. bool ok = false;
  26678. const String filename (file.getFullPathName());
  26679. if (file.hasFileExtension (".vst"))
  26680. {
  26681. const char* const utf8 = filename.toUTF8();
  26682. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26683. strlen (utf8), file.isDirectory());
  26684. if (url != 0)
  26685. {
  26686. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26687. CFRelease (url);
  26688. if (bundleRef != 0)
  26689. {
  26690. if (CFBundleLoadExecutable (bundleRef))
  26691. {
  26692. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26693. if (moduleMain == 0)
  26694. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26695. if (moduleMain != 0)
  26696. {
  26697. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26698. if (name != 0)
  26699. {
  26700. if (CFGetTypeID (name) == CFStringGetTypeID())
  26701. {
  26702. char buffer[1024];
  26703. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26704. pluginName = buffer;
  26705. }
  26706. }
  26707. if (pluginName.isEmpty())
  26708. pluginName = file.getFileNameWithoutExtension();
  26709. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26710. ok = true;
  26711. }
  26712. }
  26713. if (! ok)
  26714. {
  26715. CFBundleUnloadExecutable (bundleRef);
  26716. CFRelease (bundleRef);
  26717. bundleRef = 0;
  26718. }
  26719. }
  26720. }
  26721. }
  26722. #if JUCE_PPC
  26723. else
  26724. {
  26725. FSRef fn;
  26726. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26727. {
  26728. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26729. if (resFileId != -1)
  26730. {
  26731. const int numEffs = Count1Resources ('aEff');
  26732. for (int i = 0; i < numEffs; ++i)
  26733. {
  26734. resHandle = Get1IndResource ('aEff', i + 1);
  26735. if (resHandle != 0)
  26736. {
  26737. OSType type;
  26738. Str255 name;
  26739. SInt16 id;
  26740. GetResInfo (resHandle, &id, &type, name);
  26741. pluginName = String ((const char*) name + 1, name[0]);
  26742. DetachResource (resHandle);
  26743. HLock (resHandle);
  26744. Ptr ptr;
  26745. Str255 errorText;
  26746. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26747. name, kPrivateCFragCopy,
  26748. &fragId, &ptr, errorText);
  26749. if (err == noErr)
  26750. {
  26751. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26752. ok = true;
  26753. }
  26754. else
  26755. {
  26756. HUnlock (resHandle);
  26757. }
  26758. break;
  26759. }
  26760. }
  26761. if (! ok)
  26762. CloseResFile (resFileId);
  26763. }
  26764. }
  26765. }
  26766. #endif
  26767. return ok;
  26768. }
  26769. void close()
  26770. {
  26771. #if JUCE_PPC
  26772. if (fragId != 0)
  26773. {
  26774. if (moduleMain != 0)
  26775. disposeMachOFromCFM ((void*) moduleMain);
  26776. CloseConnection (&fragId);
  26777. HUnlock (resHandle);
  26778. if (resFileId != 0)
  26779. CloseResFile (resFileId);
  26780. }
  26781. else
  26782. #endif
  26783. if (bundleRef != 0)
  26784. {
  26785. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26786. if (CFGetRetainCount (bundleRef) == 1)
  26787. CFBundleUnloadExecutable (bundleRef);
  26788. if (CFGetRetainCount (bundleRef) > 0)
  26789. CFRelease (bundleRef);
  26790. }
  26791. }
  26792. void closeEffect (AEffect* eff)
  26793. {
  26794. #if JUCE_PPC
  26795. if (fragId != 0)
  26796. {
  26797. Array<void*> thingsToDelete;
  26798. thingsToDelete.add ((void*) eff->dispatcher);
  26799. thingsToDelete.add ((void*) eff->process);
  26800. thingsToDelete.add ((void*) eff->setParameter);
  26801. thingsToDelete.add ((void*) eff->getParameter);
  26802. thingsToDelete.add ((void*) eff->processReplacing);
  26803. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26804. for (int i = thingsToDelete.size(); --i >= 0;)
  26805. disposeMachOFromCFM (thingsToDelete[i]);
  26806. }
  26807. else
  26808. #endif
  26809. {
  26810. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26811. }
  26812. }
  26813. #if JUCE_PPC
  26814. static void* newMachOFromCFM (void* cfmfp)
  26815. {
  26816. if (cfmfp == 0)
  26817. return 0;
  26818. UInt32* const mfp = new UInt32[6];
  26819. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26820. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26821. mfp[2] = 0x800c0000;
  26822. mfp[3] = 0x804c0004;
  26823. mfp[4] = 0x7c0903a6;
  26824. mfp[5] = 0x4e800420;
  26825. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26826. return mfp;
  26827. }
  26828. static void disposeMachOFromCFM (void* ptr)
  26829. {
  26830. delete[] static_cast <UInt32*> (ptr);
  26831. }
  26832. void coerceAEffectFunctionCalls (AEffect* eff)
  26833. {
  26834. if (fragId != 0)
  26835. {
  26836. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26837. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26838. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26839. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26840. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26841. }
  26842. }
  26843. #endif
  26844. #endif
  26845. };
  26846. /**
  26847. An instance of a plugin, created by a VSTPluginFormat.
  26848. */
  26849. class VSTPluginInstance : public AudioPluginInstance,
  26850. private Timer,
  26851. private AsyncUpdater
  26852. {
  26853. public:
  26854. ~VSTPluginInstance();
  26855. // AudioPluginInstance methods:
  26856. void fillInPluginDescription (PluginDescription& desc) const
  26857. {
  26858. desc.name = name;
  26859. desc.fileOrIdentifier = module->file.getFullPathName();
  26860. desc.uid = getUID();
  26861. desc.lastFileModTime = module->file.getLastModificationTime();
  26862. desc.pluginFormatName = "VST";
  26863. desc.category = getCategory();
  26864. {
  26865. char buffer [kVstMaxVendorStrLen + 8];
  26866. zerostruct (buffer);
  26867. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26868. desc.manufacturerName = buffer;
  26869. }
  26870. desc.version = getVersion();
  26871. desc.numInputChannels = getNumInputChannels();
  26872. desc.numOutputChannels = getNumOutputChannels();
  26873. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26874. }
  26875. const String getName() const { return name; }
  26876. int getUID() const;
  26877. bool acceptsMidi() const { return wantsMidiMessages; }
  26878. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26879. // AudioProcessor methods:
  26880. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26881. void releaseResources();
  26882. void processBlock (AudioSampleBuffer& buffer,
  26883. MidiBuffer& midiMessages);
  26884. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26885. AudioProcessorEditor* createEditor();
  26886. const String getInputChannelName (int index) const;
  26887. bool isInputChannelStereoPair (int index) const;
  26888. const String getOutputChannelName (int index) const;
  26889. bool isOutputChannelStereoPair (int index) const;
  26890. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26891. float getParameter (int index);
  26892. void setParameter (int index, float newValue);
  26893. const String getParameterName (int index);
  26894. const String getParameterText (int index);
  26895. bool isParameterAutomatable (int index) const;
  26896. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26897. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26898. void setCurrentProgram (int index);
  26899. const String getProgramName (int index);
  26900. void changeProgramName (int index, const String& newName);
  26901. void getStateInformation (MemoryBlock& destData);
  26902. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26903. void setStateInformation (const void* data, int sizeInBytes);
  26904. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26905. void timerCallback();
  26906. void handleAsyncUpdate();
  26907. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26908. juce_UseDebuggingNewOperator
  26909. private:
  26910. friend class VSTPluginWindow;
  26911. friend class VSTPluginFormat;
  26912. AEffect* effect;
  26913. String name;
  26914. CriticalSection lock;
  26915. bool wantsMidiMessages, initialised, isPowerOn;
  26916. mutable StringArray programNames;
  26917. AudioSampleBuffer tempBuffer;
  26918. CriticalSection midiInLock;
  26919. MidiBuffer incomingMidi;
  26920. VSTMidiEventList midiEventsToSend;
  26921. VstTimeInfo vstHostTime;
  26922. ReferenceCountedObjectPtr <ModuleHandle> module;
  26923. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26924. bool restoreProgramSettings (const fxProgram* const prog);
  26925. const String getCurrentProgramName();
  26926. void setParamsInProgramBlock (fxProgram* const prog);
  26927. void updateStoredProgramNames();
  26928. void initialise();
  26929. void handleMidiFromPlugin (const VstEvents* const events);
  26930. void createTempParameterStore (MemoryBlock& dest);
  26931. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26932. const String getParameterLabel (int index) const;
  26933. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26934. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26935. void setChunkData (const char* data, int size, bool isPreset);
  26936. bool loadFromFXBFile (const void* data, int numBytes);
  26937. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26938. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26939. const String getVersion() const;
  26940. const String getCategory() const;
  26941. void setPower (const bool on);
  26942. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26943. };
  26944. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26945. : effect (0),
  26946. wantsMidiMessages (false),
  26947. initialised (false),
  26948. isPowerOn (false),
  26949. tempBuffer (1, 1),
  26950. module (module_)
  26951. {
  26952. try
  26953. {
  26954. _fpreset();
  26955. ++insideVSTCallback;
  26956. name = module->pluginName;
  26957. log ("Creating VST instance: " + name);
  26958. #if JUCE_MAC
  26959. if (module->resFileId != 0)
  26960. UseResFile (module->resFileId);
  26961. #if JUCE_PPC
  26962. if (module->fragId != 0)
  26963. {
  26964. static void* audioMasterCoerced = 0;
  26965. if (audioMasterCoerced == 0)
  26966. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26967. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26968. }
  26969. else
  26970. #endif
  26971. #endif
  26972. {
  26973. effect = module->moduleMain (&audioMaster);
  26974. }
  26975. --insideVSTCallback;
  26976. if (effect != 0 && effect->magic == kEffectMagic)
  26977. {
  26978. #if JUCE_PPC
  26979. module->coerceAEffectFunctionCalls (effect);
  26980. #endif
  26981. jassert (effect->resvd2 == 0);
  26982. jassert (effect->object != 0);
  26983. _fpreset(); // some dodgy plugs fuck around with this
  26984. }
  26985. else
  26986. {
  26987. effect = 0;
  26988. }
  26989. }
  26990. catch (...)
  26991. {
  26992. --insideVSTCallback;
  26993. }
  26994. }
  26995. VSTPluginInstance::~VSTPluginInstance()
  26996. {
  26997. const ScopedLock sl (lock);
  26998. jassert (insideVSTCallback == 0);
  26999. if (effect != 0 && effect->magic == kEffectMagic)
  27000. {
  27001. try
  27002. {
  27003. #if JUCE_MAC
  27004. if (module->resFileId != 0)
  27005. UseResFile (module->resFileId);
  27006. #endif
  27007. // Must delete any editors before deleting the plugin instance!
  27008. jassert (getActiveEditor() == 0);
  27009. _fpreset(); // some dodgy plugs fuck around with this
  27010. module->closeEffect (effect);
  27011. }
  27012. catch (...)
  27013. {}
  27014. }
  27015. module = 0;
  27016. effect = 0;
  27017. }
  27018. void VSTPluginInstance::initialise()
  27019. {
  27020. if (initialised || effect == 0)
  27021. return;
  27022. log ("Initialising VST: " + module->pluginName);
  27023. initialised = true;
  27024. dispatch (effIdentify, 0, 0, 0, 0);
  27025. // this code would ask the plugin for its name, but so few plugins
  27026. // actually bother implementing this correctly, that it's better to
  27027. // just ignore it and use the file name instead.
  27028. /* {
  27029. char buffer [256];
  27030. zerostruct (buffer);
  27031. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27032. name = String (buffer).trim();
  27033. if (name.isEmpty())
  27034. name = module->pluginName;
  27035. }
  27036. */
  27037. if (getSampleRate() > 0)
  27038. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27039. if (getBlockSize() > 0)
  27040. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27041. dispatch (effOpen, 0, 0, 0, 0);
  27042. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27043. getSampleRate(), getBlockSize());
  27044. if (getNumPrograms() > 1)
  27045. setCurrentProgram (0);
  27046. else
  27047. dispatch (effSetProgram, 0, 0, 0, 0);
  27048. int i;
  27049. for (i = effect->numInputs; --i >= 0;)
  27050. dispatch (effConnectInput, i, 1, 0, 0);
  27051. for (i = effect->numOutputs; --i >= 0;)
  27052. dispatch (effConnectOutput, i, 1, 0, 0);
  27053. updateStoredProgramNames();
  27054. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27055. setLatencySamples (effect->initialDelay);
  27056. }
  27057. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27058. int samplesPerBlockExpected)
  27059. {
  27060. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27061. sampleRate_, samplesPerBlockExpected);
  27062. setLatencySamples (effect->initialDelay);
  27063. vstHostTime.tempo = 120.0;
  27064. vstHostTime.timeSigNumerator = 4;
  27065. vstHostTime.timeSigDenominator = 4;
  27066. vstHostTime.sampleRate = sampleRate_;
  27067. vstHostTime.samplePos = 0;
  27068. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27069. initialise();
  27070. if (initialised)
  27071. {
  27072. wantsMidiMessages = wantsMidiMessages
  27073. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27074. if (wantsMidiMessages)
  27075. midiEventsToSend.ensureSize (256);
  27076. else
  27077. midiEventsToSend.freeEvents();
  27078. incomingMidi.clear();
  27079. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27080. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27081. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27082. if (! isPowerOn)
  27083. setPower (true);
  27084. // dodgy hack to force some plugins to initialise the sample rate..
  27085. if ((! hasEditor()) && getNumParameters() > 0)
  27086. {
  27087. const float old = getParameter (0);
  27088. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27089. setParameter (0, old);
  27090. }
  27091. dispatch (effStartProcess, 0, 0, 0, 0);
  27092. }
  27093. }
  27094. void VSTPluginInstance::releaseResources()
  27095. {
  27096. if (initialised)
  27097. {
  27098. dispatch (effStopProcess, 0, 0, 0, 0);
  27099. setPower (false);
  27100. }
  27101. tempBuffer.setSize (1, 1);
  27102. incomingMidi.clear();
  27103. midiEventsToSend.freeEvents();
  27104. }
  27105. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27106. MidiBuffer& midiMessages)
  27107. {
  27108. const int numSamples = buffer.getNumSamples();
  27109. if (initialised)
  27110. {
  27111. AudioPlayHead* playHead = getPlayHead();
  27112. if (playHead != 0)
  27113. {
  27114. AudioPlayHead::CurrentPositionInfo position;
  27115. playHead->getCurrentPosition (position);
  27116. vstHostTime.tempo = position.bpm;
  27117. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27118. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27119. vstHostTime.ppqPos = position.ppqPosition;
  27120. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27121. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27122. if (position.isPlaying)
  27123. vstHostTime.flags |= kVstTransportPlaying;
  27124. else
  27125. vstHostTime.flags &= ~kVstTransportPlaying;
  27126. }
  27127. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27128. if (wantsMidiMessages)
  27129. {
  27130. midiEventsToSend.clear();
  27131. midiEventsToSend.ensureSize (1);
  27132. MidiBuffer::Iterator iter (midiMessages);
  27133. const uint8* midiData;
  27134. int numBytesOfMidiData, samplePosition;
  27135. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27136. {
  27137. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27138. jlimit (0, numSamples - 1, samplePosition));
  27139. }
  27140. try
  27141. {
  27142. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27143. }
  27144. catch (...)
  27145. {}
  27146. }
  27147. _clearfp();
  27148. if ((effect->flags & effFlagsCanReplacing) != 0)
  27149. {
  27150. try
  27151. {
  27152. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27153. }
  27154. catch (...)
  27155. {}
  27156. }
  27157. else
  27158. {
  27159. tempBuffer.setSize (effect->numOutputs, numSamples);
  27160. tempBuffer.clear();
  27161. try
  27162. {
  27163. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27164. }
  27165. catch (...)
  27166. {}
  27167. for (int i = effect->numOutputs; --i >= 0;)
  27168. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27169. }
  27170. }
  27171. else
  27172. {
  27173. // Not initialised, so just bypass..
  27174. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27175. buffer.clear (i, 0, buffer.getNumSamples());
  27176. }
  27177. {
  27178. // copy any incoming midi..
  27179. const ScopedLock sl (midiInLock);
  27180. midiMessages.swapWith (incomingMidi);
  27181. incomingMidi.clear();
  27182. }
  27183. }
  27184. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27185. {
  27186. if (events != 0)
  27187. {
  27188. const ScopedLock sl (midiInLock);
  27189. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27190. }
  27191. }
  27192. static Array <VSTPluginWindow*> activeVSTWindows;
  27193. class VSTPluginWindow : public AudioProcessorEditor,
  27194. #if ! JUCE_MAC
  27195. public ComponentMovementWatcher,
  27196. #endif
  27197. public Timer
  27198. {
  27199. public:
  27200. VSTPluginWindow (VSTPluginInstance& plugin_)
  27201. : AudioProcessorEditor (&plugin_),
  27202. #if ! JUCE_MAC
  27203. ComponentMovementWatcher (this),
  27204. #endif
  27205. plugin (plugin_),
  27206. isOpen (false),
  27207. wasShowing (false),
  27208. pluginRefusesToResize (false),
  27209. pluginWantsKeys (false),
  27210. alreadyInside (false),
  27211. recursiveResize (false)
  27212. {
  27213. #if JUCE_WINDOWS
  27214. sizeCheckCount = 0;
  27215. pluginHWND = 0;
  27216. #elif JUCE_LINUX
  27217. pluginWindow = None;
  27218. pluginProc = None;
  27219. #else
  27220. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27221. #endif
  27222. activeVSTWindows.add (this);
  27223. setSize (1, 1);
  27224. setOpaque (true);
  27225. setVisible (true);
  27226. }
  27227. ~VSTPluginWindow()
  27228. {
  27229. #if JUCE_MAC
  27230. innerWrapper = 0;
  27231. #else
  27232. closePluginWindow();
  27233. #endif
  27234. activeVSTWindows.removeValue (this);
  27235. plugin.editorBeingDeleted (this);
  27236. }
  27237. #if ! JUCE_MAC
  27238. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27239. {
  27240. if (recursiveResize)
  27241. return;
  27242. Component* const topComp = getTopLevelComponent();
  27243. if (topComp->getPeer() != 0)
  27244. {
  27245. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27246. recursiveResize = true;
  27247. #if JUCE_WINDOWS
  27248. if (pluginHWND != 0)
  27249. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27250. #elif JUCE_LINUX
  27251. if (pluginWindow != 0)
  27252. {
  27253. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27254. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27255. XMapRaised (display, pluginWindow);
  27256. }
  27257. #endif
  27258. recursiveResize = false;
  27259. }
  27260. }
  27261. void componentVisibilityChanged (Component&)
  27262. {
  27263. const bool isShowingNow = isShowing();
  27264. if (wasShowing != isShowingNow)
  27265. {
  27266. wasShowing = isShowingNow;
  27267. if (isShowingNow)
  27268. openPluginWindow();
  27269. else
  27270. closePluginWindow();
  27271. }
  27272. componentMovedOrResized (true, true);
  27273. }
  27274. void componentPeerChanged()
  27275. {
  27276. closePluginWindow();
  27277. openPluginWindow();
  27278. }
  27279. #endif
  27280. bool keyStateChanged (bool)
  27281. {
  27282. return pluginWantsKeys;
  27283. }
  27284. bool keyPressed (const KeyPress&)
  27285. {
  27286. return pluginWantsKeys;
  27287. }
  27288. #if JUCE_MAC
  27289. void paint (Graphics& g)
  27290. {
  27291. g.fillAll (Colours::black);
  27292. }
  27293. #else
  27294. void paint (Graphics& g)
  27295. {
  27296. if (isOpen)
  27297. {
  27298. ComponentPeer* const peer = getPeer();
  27299. if (peer != 0)
  27300. {
  27301. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27302. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27303. #if JUCE_LINUX
  27304. if (pluginWindow != 0)
  27305. {
  27306. const Rectangle<int> clip (g.getClipBounds());
  27307. XEvent ev;
  27308. zerostruct (ev);
  27309. ev.xexpose.type = Expose;
  27310. ev.xexpose.display = display;
  27311. ev.xexpose.window = pluginWindow;
  27312. ev.xexpose.x = clip.getX();
  27313. ev.xexpose.y = clip.getY();
  27314. ev.xexpose.width = clip.getWidth();
  27315. ev.xexpose.height = clip.getHeight();
  27316. sendEventToChild (&ev);
  27317. }
  27318. #endif
  27319. }
  27320. }
  27321. else
  27322. {
  27323. g.fillAll (Colours::black);
  27324. }
  27325. }
  27326. #endif
  27327. void timerCallback()
  27328. {
  27329. #if JUCE_WINDOWS
  27330. if (--sizeCheckCount <= 0)
  27331. {
  27332. sizeCheckCount = 10;
  27333. checkPluginWindowSize();
  27334. }
  27335. #endif
  27336. try
  27337. {
  27338. static bool reentrant = false;
  27339. if (! reentrant)
  27340. {
  27341. reentrant = true;
  27342. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27343. reentrant = false;
  27344. }
  27345. }
  27346. catch (...)
  27347. {}
  27348. }
  27349. void mouseDown (const MouseEvent& e)
  27350. {
  27351. #if JUCE_LINUX
  27352. if (pluginWindow == 0)
  27353. return;
  27354. toFront (true);
  27355. XEvent ev;
  27356. zerostruct (ev);
  27357. ev.xbutton.display = display;
  27358. ev.xbutton.type = ButtonPress;
  27359. ev.xbutton.window = pluginWindow;
  27360. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27361. ev.xbutton.time = CurrentTime;
  27362. ev.xbutton.x = e.x;
  27363. ev.xbutton.y = e.y;
  27364. ev.xbutton.x_root = e.getScreenX();
  27365. ev.xbutton.y_root = e.getScreenY();
  27366. translateJuceToXButtonModifiers (e, ev);
  27367. sendEventToChild (&ev);
  27368. #elif JUCE_WINDOWS
  27369. (void) e;
  27370. toFront (true);
  27371. #endif
  27372. }
  27373. void broughtToFront()
  27374. {
  27375. activeVSTWindows.removeValue (this);
  27376. activeVSTWindows.add (this);
  27377. #if JUCE_MAC
  27378. dispatch (effEditTop, 0, 0, 0, 0);
  27379. #endif
  27380. }
  27381. juce_UseDebuggingNewOperator
  27382. private:
  27383. VSTPluginInstance& plugin;
  27384. bool isOpen, wasShowing, recursiveResize;
  27385. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27386. #if JUCE_WINDOWS
  27387. HWND pluginHWND;
  27388. void* originalWndProc;
  27389. int sizeCheckCount;
  27390. #elif JUCE_LINUX
  27391. Window pluginWindow;
  27392. EventProcPtr pluginProc;
  27393. #endif
  27394. #if JUCE_MAC
  27395. void openPluginWindow (WindowRef parentWindow)
  27396. {
  27397. if (isOpen || parentWindow == 0)
  27398. return;
  27399. isOpen = true;
  27400. ERect* rect = 0;
  27401. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27402. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27403. // do this before and after like in the steinberg example
  27404. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27405. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27406. // Install keyboard hooks
  27407. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27408. // double-check it's not too tiny
  27409. int w = 250, h = 150;
  27410. if (rect != 0)
  27411. {
  27412. w = rect->right - rect->left;
  27413. h = rect->bottom - rect->top;
  27414. if (w == 0 || h == 0)
  27415. {
  27416. w = 250;
  27417. h = 150;
  27418. }
  27419. }
  27420. w = jmax (w, 32);
  27421. h = jmax (h, 32);
  27422. setSize (w, h);
  27423. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27424. repaint();
  27425. }
  27426. #else
  27427. void openPluginWindow()
  27428. {
  27429. if (isOpen || getWindowHandle() == 0)
  27430. return;
  27431. log ("Opening VST UI: " + plugin.name);
  27432. isOpen = true;
  27433. ERect* rect = 0;
  27434. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27435. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27436. // do this before and after like in the steinberg example
  27437. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27438. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27439. // Install keyboard hooks
  27440. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27441. #if JUCE_WINDOWS
  27442. originalWndProc = 0;
  27443. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27444. if (pluginHWND == 0)
  27445. {
  27446. isOpen = false;
  27447. setSize (300, 150);
  27448. return;
  27449. }
  27450. #pragma warning (push)
  27451. #pragma warning (disable: 4244)
  27452. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27453. if (! pluginWantsKeys)
  27454. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27455. #pragma warning (pop)
  27456. int w, h;
  27457. RECT r;
  27458. GetWindowRect (pluginHWND, &r);
  27459. w = r.right - r.left;
  27460. h = r.bottom - r.top;
  27461. if (rect != 0)
  27462. {
  27463. const int rw = rect->right - rect->left;
  27464. const int rh = rect->bottom - rect->top;
  27465. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27466. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27467. {
  27468. // very dodgy logic to decide which size is right.
  27469. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27470. {
  27471. SetWindowPos (pluginHWND, 0,
  27472. 0, 0, rw, rh,
  27473. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27474. GetWindowRect (pluginHWND, &r);
  27475. w = r.right - r.left;
  27476. h = r.bottom - r.top;
  27477. pluginRefusesToResize = (w != rw) || (h != rh);
  27478. w = rw;
  27479. h = rh;
  27480. }
  27481. }
  27482. }
  27483. #elif JUCE_LINUX
  27484. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27485. if (pluginWindow != 0)
  27486. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27487. XInternAtom (display, "_XEventProc", False));
  27488. int w = 250, h = 150;
  27489. if (rect != 0)
  27490. {
  27491. w = rect->right - rect->left;
  27492. h = rect->bottom - rect->top;
  27493. if (w == 0 || h == 0)
  27494. {
  27495. w = 250;
  27496. h = 150;
  27497. }
  27498. }
  27499. if (pluginWindow != 0)
  27500. XMapRaised (display, pluginWindow);
  27501. #endif
  27502. // double-check it's not too tiny
  27503. w = jmax (w, 32);
  27504. h = jmax (h, 32);
  27505. setSize (w, h);
  27506. #if JUCE_WINDOWS
  27507. checkPluginWindowSize();
  27508. #endif
  27509. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27510. repaint();
  27511. }
  27512. #endif
  27513. #if ! JUCE_MAC
  27514. void closePluginWindow()
  27515. {
  27516. if (isOpen)
  27517. {
  27518. log ("Closing VST UI: " + plugin.getName());
  27519. isOpen = false;
  27520. dispatch (effEditClose, 0, 0, 0, 0);
  27521. #if JUCE_WINDOWS
  27522. #pragma warning (push)
  27523. #pragma warning (disable: 4244)
  27524. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27525. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27526. #pragma warning (pop)
  27527. stopTimer();
  27528. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27529. DestroyWindow (pluginHWND);
  27530. pluginHWND = 0;
  27531. #elif JUCE_LINUX
  27532. stopTimer();
  27533. pluginWindow = 0;
  27534. pluginProc = 0;
  27535. #endif
  27536. }
  27537. }
  27538. #endif
  27539. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27540. {
  27541. return plugin.dispatch (opcode, index, value, ptr, opt);
  27542. }
  27543. #if JUCE_WINDOWS
  27544. void checkPluginWindowSize()
  27545. {
  27546. RECT r;
  27547. GetWindowRect (pluginHWND, &r);
  27548. const int w = r.right - r.left;
  27549. const int h = r.bottom - r.top;
  27550. if (isShowing() && w > 0 && h > 0
  27551. && (w != getWidth() || h != getHeight())
  27552. && ! pluginRefusesToResize)
  27553. {
  27554. setSize (w, h);
  27555. sizeCheckCount = 0;
  27556. }
  27557. }
  27558. // hooks to get keyboard events from VST windows..
  27559. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27560. {
  27561. for (int i = activeVSTWindows.size(); --i >= 0;)
  27562. {
  27563. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27564. if (w->pluginHWND == hW)
  27565. {
  27566. if (message == WM_CHAR
  27567. || message == WM_KEYDOWN
  27568. || message == WM_SYSKEYDOWN
  27569. || message == WM_KEYUP
  27570. || message == WM_SYSKEYUP
  27571. || message == WM_APPCOMMAND)
  27572. {
  27573. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27574. message, wParam, lParam);
  27575. }
  27576. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27577. (HWND) w->pluginHWND,
  27578. message,
  27579. wParam,
  27580. lParam);
  27581. }
  27582. }
  27583. return DefWindowProc (hW, message, wParam, lParam);
  27584. }
  27585. #endif
  27586. #if JUCE_LINUX
  27587. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27588. void sendEventToChild (XEvent* event)
  27589. {
  27590. if (pluginProc != 0)
  27591. {
  27592. // if the plugin publishes an event procedure, pass the event directly..
  27593. pluginProc (event);
  27594. }
  27595. else if (pluginWindow != 0)
  27596. {
  27597. // if the plugin has a window, then send the event to the window so that
  27598. // its message thread will pick it up..
  27599. XSendEvent (display, pluginWindow, False, 0L, event);
  27600. XFlush (display);
  27601. }
  27602. }
  27603. void mouseEnter (const MouseEvent& e)
  27604. {
  27605. if (pluginWindow != 0)
  27606. {
  27607. XEvent ev;
  27608. zerostruct (ev);
  27609. ev.xcrossing.display = display;
  27610. ev.xcrossing.type = EnterNotify;
  27611. ev.xcrossing.window = pluginWindow;
  27612. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27613. ev.xcrossing.time = CurrentTime;
  27614. ev.xcrossing.x = e.x;
  27615. ev.xcrossing.y = e.y;
  27616. ev.xcrossing.x_root = e.getScreenX();
  27617. ev.xcrossing.y_root = e.getScreenY();
  27618. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27619. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27620. translateJuceToXCrossingModifiers (e, ev);
  27621. sendEventToChild (&ev);
  27622. }
  27623. }
  27624. void mouseExit (const MouseEvent& e)
  27625. {
  27626. if (pluginWindow != 0)
  27627. {
  27628. XEvent ev;
  27629. zerostruct (ev);
  27630. ev.xcrossing.display = display;
  27631. ev.xcrossing.type = LeaveNotify;
  27632. ev.xcrossing.window = pluginWindow;
  27633. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27634. ev.xcrossing.time = CurrentTime;
  27635. ev.xcrossing.x = e.x;
  27636. ev.xcrossing.y = e.y;
  27637. ev.xcrossing.x_root = e.getScreenX();
  27638. ev.xcrossing.y_root = e.getScreenY();
  27639. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27640. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27641. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27642. translateJuceToXCrossingModifiers (e, ev);
  27643. sendEventToChild (&ev);
  27644. }
  27645. }
  27646. void mouseMove (const MouseEvent& e)
  27647. {
  27648. if (pluginWindow != 0)
  27649. {
  27650. XEvent ev;
  27651. zerostruct (ev);
  27652. ev.xmotion.display = display;
  27653. ev.xmotion.type = MotionNotify;
  27654. ev.xmotion.window = pluginWindow;
  27655. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27656. ev.xmotion.time = CurrentTime;
  27657. ev.xmotion.is_hint = NotifyNormal;
  27658. ev.xmotion.x = e.x;
  27659. ev.xmotion.y = e.y;
  27660. ev.xmotion.x_root = e.getScreenX();
  27661. ev.xmotion.y_root = e.getScreenY();
  27662. sendEventToChild (&ev);
  27663. }
  27664. }
  27665. void mouseDrag (const MouseEvent& e)
  27666. {
  27667. if (pluginWindow != 0)
  27668. {
  27669. XEvent ev;
  27670. zerostruct (ev);
  27671. ev.xmotion.display = display;
  27672. ev.xmotion.type = MotionNotify;
  27673. ev.xmotion.window = pluginWindow;
  27674. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27675. ev.xmotion.time = CurrentTime;
  27676. ev.xmotion.x = e.x ;
  27677. ev.xmotion.y = e.y;
  27678. ev.xmotion.x_root = e.getScreenX();
  27679. ev.xmotion.y_root = e.getScreenY();
  27680. ev.xmotion.is_hint = NotifyNormal;
  27681. translateJuceToXMotionModifiers (e, ev);
  27682. sendEventToChild (&ev);
  27683. }
  27684. }
  27685. void mouseUp (const MouseEvent& e)
  27686. {
  27687. if (pluginWindow != 0)
  27688. {
  27689. XEvent ev;
  27690. zerostruct (ev);
  27691. ev.xbutton.display = display;
  27692. ev.xbutton.type = ButtonRelease;
  27693. ev.xbutton.window = pluginWindow;
  27694. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27695. ev.xbutton.time = CurrentTime;
  27696. ev.xbutton.x = e.x;
  27697. ev.xbutton.y = e.y;
  27698. ev.xbutton.x_root = e.getScreenX();
  27699. ev.xbutton.y_root = e.getScreenY();
  27700. translateJuceToXButtonModifiers (e, ev);
  27701. sendEventToChild (&ev);
  27702. }
  27703. }
  27704. void mouseWheelMove (const MouseEvent& e,
  27705. float incrementX,
  27706. float incrementY)
  27707. {
  27708. if (pluginWindow != 0)
  27709. {
  27710. XEvent ev;
  27711. zerostruct (ev);
  27712. ev.xbutton.display = display;
  27713. ev.xbutton.type = ButtonPress;
  27714. ev.xbutton.window = pluginWindow;
  27715. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27716. ev.xbutton.time = CurrentTime;
  27717. ev.xbutton.x = e.x;
  27718. ev.xbutton.y = e.y;
  27719. ev.xbutton.x_root = e.getScreenX();
  27720. ev.xbutton.y_root = e.getScreenY();
  27721. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27722. sendEventToChild (&ev);
  27723. // TODO - put a usleep here ?
  27724. ev.xbutton.type = ButtonRelease;
  27725. sendEventToChild (&ev);
  27726. }
  27727. }
  27728. #endif
  27729. #if JUCE_MAC
  27730. #if ! JUCE_SUPPORT_CARBON
  27731. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27732. #endif
  27733. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27734. {
  27735. public:
  27736. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27737. : owner (owner_),
  27738. alreadyInside (false)
  27739. {
  27740. }
  27741. ~InnerWrapperComponent()
  27742. {
  27743. deleteWindow();
  27744. }
  27745. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27746. {
  27747. owner->openPluginWindow (windowRef);
  27748. return 0;
  27749. }
  27750. void removeView (HIViewRef)
  27751. {
  27752. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27753. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27754. }
  27755. bool getEmbeddedViewSize (int& w, int& h)
  27756. {
  27757. ERect* rect = 0;
  27758. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27759. w = rect->right - rect->left;
  27760. h = rect->bottom - rect->top;
  27761. return true;
  27762. }
  27763. void mouseDown (int x, int y)
  27764. {
  27765. if (! alreadyInside)
  27766. {
  27767. alreadyInside = true;
  27768. getTopLevelComponent()->toFront (true);
  27769. owner->dispatch (effEditMouse, x, y, 0, 0);
  27770. alreadyInside = false;
  27771. }
  27772. else
  27773. {
  27774. PostEvent (::mouseDown, 0);
  27775. }
  27776. }
  27777. void paint()
  27778. {
  27779. ComponentPeer* const peer = getPeer();
  27780. if (peer != 0)
  27781. {
  27782. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27783. ERect r;
  27784. r.left = pos.getX();
  27785. r.right = r.left + getWidth();
  27786. r.top = pos.getY();
  27787. r.bottom = r.top + getHeight();
  27788. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27789. }
  27790. }
  27791. private:
  27792. VSTPluginWindow* const owner;
  27793. bool alreadyInside;
  27794. };
  27795. friend class InnerWrapperComponent;
  27796. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27797. void resized()
  27798. {
  27799. innerWrapper->setSize (getWidth(), getHeight());
  27800. }
  27801. #endif
  27802. };
  27803. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27804. {
  27805. if (hasEditor())
  27806. return new VSTPluginWindow (*this);
  27807. return 0;
  27808. }
  27809. void VSTPluginInstance::handleAsyncUpdate()
  27810. {
  27811. // indicates that something about the plugin has changed..
  27812. updateHostDisplay();
  27813. }
  27814. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27815. {
  27816. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27817. {
  27818. changeProgramName (getCurrentProgram(), prog->prgName);
  27819. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27820. setParameter (i, vst_swapFloat (prog->params[i]));
  27821. return true;
  27822. }
  27823. return false;
  27824. }
  27825. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27826. const int dataSize)
  27827. {
  27828. if (dataSize < 28)
  27829. return false;
  27830. const fxSet* const set = (const fxSet*) data;
  27831. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27832. || vst_swap (set->version) > fxbVersionNum)
  27833. return false;
  27834. if (vst_swap (set->fxMagic) == 'FxBk')
  27835. {
  27836. // bank of programs
  27837. if (vst_swap (set->numPrograms) >= 0)
  27838. {
  27839. const int oldProg = getCurrentProgram();
  27840. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27841. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27842. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27843. {
  27844. if (i != oldProg)
  27845. {
  27846. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27847. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27848. return false;
  27849. if (vst_swap (set->numPrograms) > 0)
  27850. setCurrentProgram (i);
  27851. if (! restoreProgramSettings (prog))
  27852. return false;
  27853. }
  27854. }
  27855. if (vst_swap (set->numPrograms) > 0)
  27856. setCurrentProgram (oldProg);
  27857. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27858. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27859. return false;
  27860. if (! restoreProgramSettings (prog))
  27861. return false;
  27862. }
  27863. }
  27864. else if (vst_swap (set->fxMagic) == 'FxCk')
  27865. {
  27866. // single program
  27867. const fxProgram* const prog = (const fxProgram*) data;
  27868. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27869. return false;
  27870. changeProgramName (getCurrentProgram(), prog->prgName);
  27871. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27872. setParameter (i, vst_swapFloat (prog->params[i]));
  27873. }
  27874. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27875. {
  27876. // non-preset chunk
  27877. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27878. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27879. return false;
  27880. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27881. }
  27882. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27883. {
  27884. // preset chunk
  27885. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27886. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27887. return false;
  27888. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27889. changeProgramName (getCurrentProgram(), cset->name);
  27890. }
  27891. else
  27892. {
  27893. return false;
  27894. }
  27895. return true;
  27896. }
  27897. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27898. {
  27899. const int numParams = getNumParameters();
  27900. prog->chunkMagic = vst_swap ('CcnK');
  27901. prog->byteSize = 0;
  27902. prog->fxMagic = vst_swap ('FxCk');
  27903. prog->version = vst_swap (fxbVersionNum);
  27904. prog->fxID = vst_swap (getUID());
  27905. prog->fxVersion = vst_swap (getVersionNumber());
  27906. prog->numParams = vst_swap (numParams);
  27907. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27908. for (int i = 0; i < numParams; ++i)
  27909. prog->params[i] = vst_swapFloat (getParameter (i));
  27910. }
  27911. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27912. {
  27913. const int numPrograms = getNumPrograms();
  27914. const int numParams = getNumParameters();
  27915. if (usesChunks())
  27916. {
  27917. if (isFXB)
  27918. {
  27919. MemoryBlock chunk;
  27920. getChunkData (chunk, false, maxSizeMB);
  27921. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27922. dest.setSize (totalLen, true);
  27923. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27924. set->chunkMagic = vst_swap ('CcnK');
  27925. set->byteSize = 0;
  27926. set->fxMagic = vst_swap ('FBCh');
  27927. set->version = vst_swap (fxbVersionNum);
  27928. set->fxID = vst_swap (getUID());
  27929. set->fxVersion = vst_swap (getVersionNumber());
  27930. set->numPrograms = vst_swap (numPrograms);
  27931. set->chunkSize = vst_swap ((long) chunk.getSize());
  27932. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27933. }
  27934. else
  27935. {
  27936. MemoryBlock chunk;
  27937. getChunkData (chunk, true, maxSizeMB);
  27938. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27939. dest.setSize (totalLen, true);
  27940. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27941. set->chunkMagic = vst_swap ('CcnK');
  27942. set->byteSize = 0;
  27943. set->fxMagic = vst_swap ('FPCh');
  27944. set->version = vst_swap (fxbVersionNum);
  27945. set->fxID = vst_swap (getUID());
  27946. set->fxVersion = vst_swap (getVersionNumber());
  27947. set->numPrograms = vst_swap (numPrograms);
  27948. set->chunkSize = vst_swap ((long) chunk.getSize());
  27949. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27950. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27951. }
  27952. }
  27953. else
  27954. {
  27955. if (isFXB)
  27956. {
  27957. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27958. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27959. dest.setSize (len, true);
  27960. fxSet* const set = (fxSet*) dest.getData();
  27961. set->chunkMagic = vst_swap ('CcnK');
  27962. set->byteSize = 0;
  27963. set->fxMagic = vst_swap ('FxBk');
  27964. set->version = vst_swap (fxbVersionNum);
  27965. set->fxID = vst_swap (getUID());
  27966. set->fxVersion = vst_swap (getVersionNumber());
  27967. set->numPrograms = vst_swap (numPrograms);
  27968. const int oldProgram = getCurrentProgram();
  27969. MemoryBlock oldSettings;
  27970. createTempParameterStore (oldSettings);
  27971. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27972. for (int i = 0; i < numPrograms; ++i)
  27973. {
  27974. if (i != oldProgram)
  27975. {
  27976. setCurrentProgram (i);
  27977. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27978. }
  27979. }
  27980. setCurrentProgram (oldProgram);
  27981. restoreFromTempParameterStore (oldSettings);
  27982. }
  27983. else
  27984. {
  27985. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27986. dest.setSize (totalLen, true);
  27987. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27988. }
  27989. }
  27990. return true;
  27991. }
  27992. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27993. {
  27994. if (usesChunks())
  27995. {
  27996. void* data = 0;
  27997. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27998. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27999. {
  28000. mb.setSize (bytes);
  28001. mb.copyFrom (data, 0, bytes);
  28002. }
  28003. }
  28004. }
  28005. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28006. {
  28007. if (size > 0 && usesChunks())
  28008. {
  28009. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28010. if (! isPreset)
  28011. updateStoredProgramNames();
  28012. }
  28013. }
  28014. void VSTPluginInstance::timerCallback()
  28015. {
  28016. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28017. stopTimer();
  28018. }
  28019. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28020. {
  28021. const ScopedLock sl (lock);
  28022. ++insideVSTCallback;
  28023. int result = 0;
  28024. try
  28025. {
  28026. if (effect != 0)
  28027. {
  28028. #if JUCE_MAC
  28029. if (module->resFileId != 0)
  28030. UseResFile (module->resFileId);
  28031. #endif
  28032. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28033. #if JUCE_MAC
  28034. module->resFileId = CurResFile();
  28035. #endif
  28036. --insideVSTCallback;
  28037. return result;
  28038. }
  28039. }
  28040. catch (...)
  28041. {
  28042. }
  28043. --insideVSTCallback;
  28044. return result;
  28045. }
  28046. // handles non plugin-specific callbacks..
  28047. static const int defaultVSTSampleRateValue = 16384;
  28048. static const int defaultVSTBlockSizeValue = 512;
  28049. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28050. {
  28051. (void) index;
  28052. (void) value;
  28053. (void) opt;
  28054. switch (opcode)
  28055. {
  28056. case audioMasterCanDo:
  28057. {
  28058. static const char* canDos[] = { "supplyIdle",
  28059. "sendVstEvents",
  28060. "sendVstMidiEvent",
  28061. "sendVstTimeInfo",
  28062. "receiveVstEvents",
  28063. "receiveVstMidiEvent",
  28064. "supportShell",
  28065. "shellCategory" };
  28066. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28067. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28068. return 1;
  28069. return 0;
  28070. }
  28071. case audioMasterVersion: return 0x2400;
  28072. case audioMasterCurrentId: return shellUIDToCreate;
  28073. case audioMasterGetNumAutomatableParameters: return 0;
  28074. case audioMasterGetAutomationState: return 1;
  28075. case audioMasterGetVendorVersion: return 0x0101;
  28076. case audioMasterGetVendorString:
  28077. case audioMasterGetProductString:
  28078. {
  28079. String hostName ("Juce VST Host");
  28080. if (JUCEApplication::getInstance() != 0)
  28081. hostName = JUCEApplication::getInstance()->getApplicationName();
  28082. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28083. break;
  28084. }
  28085. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28086. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28087. case audioMasterSetOutputSampleRate: return 0;
  28088. default:
  28089. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28090. break;
  28091. }
  28092. return 0;
  28093. }
  28094. // handles callbacks for a specific plugin
  28095. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28096. {
  28097. switch (opcode)
  28098. {
  28099. case audioMasterAutomate:
  28100. sendParamChangeMessageToListeners (index, opt);
  28101. break;
  28102. case audioMasterProcessEvents:
  28103. handleMidiFromPlugin ((const VstEvents*) ptr);
  28104. break;
  28105. case audioMasterGetTime:
  28106. #if JUCE_MSVC
  28107. #pragma warning (push)
  28108. #pragma warning (disable: 4311)
  28109. #endif
  28110. return (VstIntPtr) &vstHostTime;
  28111. #if JUCE_MSVC
  28112. #pragma warning (pop)
  28113. #endif
  28114. break;
  28115. case audioMasterIdle:
  28116. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28117. {
  28118. ++insideVSTCallback;
  28119. #if JUCE_MAC
  28120. if (getActiveEditor() != 0)
  28121. dispatch (effEditIdle, 0, 0, 0, 0);
  28122. #endif
  28123. juce_callAnyTimersSynchronously();
  28124. handleUpdateNowIfNeeded();
  28125. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28126. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28127. --insideVSTCallback;
  28128. }
  28129. break;
  28130. case audioMasterUpdateDisplay:
  28131. triggerAsyncUpdate();
  28132. break;
  28133. case audioMasterTempoAt:
  28134. // returns (10000 * bpm)
  28135. break;
  28136. case audioMasterNeedIdle:
  28137. startTimer (50);
  28138. break;
  28139. case audioMasterSizeWindow:
  28140. if (getActiveEditor() != 0)
  28141. getActiveEditor()->setSize (index, value);
  28142. return 1;
  28143. case audioMasterGetSampleRate:
  28144. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28145. case audioMasterGetBlockSize:
  28146. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28147. case audioMasterWantMidi:
  28148. wantsMidiMessages = true;
  28149. break;
  28150. case audioMasterGetDirectory:
  28151. #if JUCE_MAC
  28152. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28153. #else
  28154. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28155. #endif
  28156. case audioMasterGetAutomationState:
  28157. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28158. break;
  28159. // none of these are handled (yet)..
  28160. case audioMasterBeginEdit:
  28161. case audioMasterEndEdit:
  28162. case audioMasterSetTime:
  28163. case audioMasterPinConnected:
  28164. case audioMasterGetParameterQuantization:
  28165. case audioMasterIOChanged:
  28166. case audioMasterGetInputLatency:
  28167. case audioMasterGetOutputLatency:
  28168. case audioMasterGetPreviousPlug:
  28169. case audioMasterGetNextPlug:
  28170. case audioMasterWillReplaceOrAccumulate:
  28171. case audioMasterGetCurrentProcessLevel:
  28172. case audioMasterOfflineStart:
  28173. case audioMasterOfflineRead:
  28174. case audioMasterOfflineWrite:
  28175. case audioMasterOfflineGetCurrentPass:
  28176. case audioMasterOfflineGetCurrentMetaPass:
  28177. case audioMasterVendorSpecific:
  28178. case audioMasterSetIcon:
  28179. case audioMasterGetLanguage:
  28180. case audioMasterOpenWindow:
  28181. case audioMasterCloseWindow:
  28182. break;
  28183. default:
  28184. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28185. }
  28186. return 0;
  28187. }
  28188. // entry point for all callbacks from the plugin
  28189. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28190. {
  28191. try
  28192. {
  28193. if (effect != 0 && effect->resvd2 != 0)
  28194. {
  28195. return ((VSTPluginInstance*)(effect->resvd2))
  28196. ->handleCallback (opcode, index, value, ptr, opt);
  28197. }
  28198. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28199. }
  28200. catch (...)
  28201. {
  28202. return 0;
  28203. }
  28204. }
  28205. const String VSTPluginInstance::getVersion() const
  28206. {
  28207. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28208. String s;
  28209. if (v == 0 || v == -1)
  28210. v = getVersionNumber();
  28211. if (v != 0)
  28212. {
  28213. int versionBits[4];
  28214. int n = 0;
  28215. while (v != 0)
  28216. {
  28217. versionBits [n++] = (v & 0xff);
  28218. v >>= 8;
  28219. }
  28220. s << 'V';
  28221. while (n > 0)
  28222. {
  28223. s << versionBits [--n];
  28224. if (n > 0)
  28225. s << '.';
  28226. }
  28227. }
  28228. return s;
  28229. }
  28230. int VSTPluginInstance::getUID() const
  28231. {
  28232. int uid = effect != 0 ? effect->uniqueID : 0;
  28233. if (uid == 0)
  28234. uid = module->file.hashCode();
  28235. return uid;
  28236. }
  28237. const String VSTPluginInstance::getCategory() const
  28238. {
  28239. const char* result = 0;
  28240. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28241. {
  28242. case kPlugCategEffect: result = "Effect"; break;
  28243. case kPlugCategSynth: result = "Synth"; break;
  28244. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28245. case kPlugCategMastering: result = "Mastering"; break;
  28246. case kPlugCategSpacializer: result = "Spacial"; break;
  28247. case kPlugCategRoomFx: result = "Reverb"; break;
  28248. case kPlugSurroundFx: result = "Surround"; break;
  28249. case kPlugCategRestoration: result = "Restoration"; break;
  28250. case kPlugCategGenerator: result = "Tone generation"; break;
  28251. default: break;
  28252. }
  28253. return result;
  28254. }
  28255. float VSTPluginInstance::getParameter (int index)
  28256. {
  28257. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28258. {
  28259. try
  28260. {
  28261. const ScopedLock sl (lock);
  28262. return effect->getParameter (effect, index);
  28263. }
  28264. catch (...)
  28265. {
  28266. }
  28267. }
  28268. return 0.0f;
  28269. }
  28270. void VSTPluginInstance::setParameter (int index, float newValue)
  28271. {
  28272. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28273. {
  28274. try
  28275. {
  28276. const ScopedLock sl (lock);
  28277. if (effect->getParameter (effect, index) != newValue)
  28278. effect->setParameter (effect, index, newValue);
  28279. }
  28280. catch (...)
  28281. {
  28282. }
  28283. }
  28284. }
  28285. const String VSTPluginInstance::getParameterName (int index)
  28286. {
  28287. if (effect != 0)
  28288. {
  28289. jassert (index >= 0 && index < effect->numParams);
  28290. char nm [256];
  28291. zerostruct (nm);
  28292. dispatch (effGetParamName, index, 0, nm, 0);
  28293. return String (nm).trim();
  28294. }
  28295. return String::empty;
  28296. }
  28297. const String VSTPluginInstance::getParameterLabel (int index) const
  28298. {
  28299. if (effect != 0)
  28300. {
  28301. jassert (index >= 0 && index < effect->numParams);
  28302. char nm [256];
  28303. zerostruct (nm);
  28304. dispatch (effGetParamLabel, index, 0, nm, 0);
  28305. return String (nm).trim();
  28306. }
  28307. return String::empty;
  28308. }
  28309. const String VSTPluginInstance::getParameterText (int index)
  28310. {
  28311. if (effect != 0)
  28312. {
  28313. jassert (index >= 0 && index < effect->numParams);
  28314. char nm [256];
  28315. zerostruct (nm);
  28316. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28317. return String (nm).trim();
  28318. }
  28319. return String::empty;
  28320. }
  28321. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28322. {
  28323. if (effect != 0)
  28324. {
  28325. jassert (index >= 0 && index < effect->numParams);
  28326. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28327. }
  28328. return false;
  28329. }
  28330. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28331. {
  28332. dest.setSize (64 + 4 * getNumParameters());
  28333. dest.fillWith (0);
  28334. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28335. float* const p = (float*) (((char*) dest.getData()) + 64);
  28336. for (int i = 0; i < getNumParameters(); ++i)
  28337. p[i] = getParameter(i);
  28338. }
  28339. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28340. {
  28341. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28342. float* p = (float*) (((char*) m.getData()) + 64);
  28343. for (int i = 0; i < getNumParameters(); ++i)
  28344. setParameter (i, p[i]);
  28345. }
  28346. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28347. {
  28348. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28349. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28350. }
  28351. const String VSTPluginInstance::getProgramName (int index)
  28352. {
  28353. if (index == getCurrentProgram())
  28354. {
  28355. return getCurrentProgramName();
  28356. }
  28357. else if (effect != 0)
  28358. {
  28359. char nm [256];
  28360. zerostruct (nm);
  28361. if (dispatch (effGetProgramNameIndexed,
  28362. jlimit (0, getNumPrograms(), index),
  28363. -1, nm, 0) != 0)
  28364. {
  28365. return String (nm).trim();
  28366. }
  28367. }
  28368. return programNames [index];
  28369. }
  28370. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28371. {
  28372. if (index == getCurrentProgram())
  28373. {
  28374. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28375. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28376. }
  28377. else
  28378. {
  28379. jassertfalse; // xxx not implemented!
  28380. }
  28381. }
  28382. void VSTPluginInstance::updateStoredProgramNames()
  28383. {
  28384. if (effect != 0 && getNumPrograms() > 0)
  28385. {
  28386. char nm [256];
  28387. zerostruct (nm);
  28388. // only do this if the plugin can't use indexed names..
  28389. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28390. {
  28391. const int oldProgram = getCurrentProgram();
  28392. MemoryBlock oldSettings;
  28393. createTempParameterStore (oldSettings);
  28394. for (int i = 0; i < getNumPrograms(); ++i)
  28395. {
  28396. setCurrentProgram (i);
  28397. getCurrentProgramName(); // (this updates the list)
  28398. }
  28399. setCurrentProgram (oldProgram);
  28400. restoreFromTempParameterStore (oldSettings);
  28401. }
  28402. }
  28403. }
  28404. const String VSTPluginInstance::getCurrentProgramName()
  28405. {
  28406. if (effect != 0)
  28407. {
  28408. char nm [256];
  28409. zerostruct (nm);
  28410. dispatch (effGetProgramName, 0, 0, nm, 0);
  28411. const int index = getCurrentProgram();
  28412. if (programNames[index].isEmpty())
  28413. {
  28414. while (programNames.size() < index)
  28415. programNames.add (String::empty);
  28416. programNames.set (index, String (nm).trim());
  28417. }
  28418. return String (nm).trim();
  28419. }
  28420. return String::empty;
  28421. }
  28422. const String VSTPluginInstance::getInputChannelName (int index) const
  28423. {
  28424. if (index >= 0 && index < getNumInputChannels())
  28425. {
  28426. VstPinProperties pinProps;
  28427. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28428. return String (pinProps.label, sizeof (pinProps.label));
  28429. }
  28430. return String::empty;
  28431. }
  28432. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28433. {
  28434. if (index < 0 || index >= getNumInputChannels())
  28435. return false;
  28436. VstPinProperties pinProps;
  28437. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28438. return (pinProps.flags & kVstPinIsStereo) != 0;
  28439. return true;
  28440. }
  28441. const String VSTPluginInstance::getOutputChannelName (int index) const
  28442. {
  28443. if (index >= 0 && index < getNumOutputChannels())
  28444. {
  28445. VstPinProperties pinProps;
  28446. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28447. return String (pinProps.label, sizeof (pinProps.label));
  28448. }
  28449. return String::empty;
  28450. }
  28451. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28452. {
  28453. if (index < 0 || index >= getNumOutputChannels())
  28454. return false;
  28455. VstPinProperties pinProps;
  28456. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28457. return (pinProps.flags & kVstPinIsStereo) != 0;
  28458. return true;
  28459. }
  28460. void VSTPluginInstance::setPower (const bool on)
  28461. {
  28462. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28463. isPowerOn = on;
  28464. }
  28465. const int defaultMaxSizeMB = 64;
  28466. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28467. {
  28468. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28469. }
  28470. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28471. {
  28472. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28473. }
  28474. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28475. {
  28476. loadFromFXBFile (data, sizeInBytes);
  28477. }
  28478. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28479. {
  28480. loadFromFXBFile (data, sizeInBytes);
  28481. }
  28482. VSTPluginFormat::VSTPluginFormat()
  28483. {
  28484. }
  28485. VSTPluginFormat::~VSTPluginFormat()
  28486. {
  28487. }
  28488. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28489. const String& fileOrIdentifier)
  28490. {
  28491. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28492. return;
  28493. PluginDescription desc;
  28494. desc.fileOrIdentifier = fileOrIdentifier;
  28495. desc.uid = 0;
  28496. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28497. if (instance == 0)
  28498. return;
  28499. try
  28500. {
  28501. #if JUCE_MAC
  28502. if (instance->module->resFileId != 0)
  28503. UseResFile (instance->module->resFileId);
  28504. #endif
  28505. instance->fillInPluginDescription (desc);
  28506. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28507. if (category != kPlugCategShell)
  28508. {
  28509. // Normal plugin...
  28510. results.add (new PluginDescription (desc));
  28511. ++insideVSTCallback;
  28512. instance->dispatch (effOpen, 0, 0, 0, 0);
  28513. --insideVSTCallback;
  28514. }
  28515. else
  28516. {
  28517. // It's a shell plugin, so iterate all the subtypes...
  28518. char shellEffectName [64];
  28519. for (;;)
  28520. {
  28521. zerostruct (shellEffectName);
  28522. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28523. if (uid == 0)
  28524. {
  28525. break;
  28526. }
  28527. else
  28528. {
  28529. desc.uid = uid;
  28530. desc.name = shellEffectName;
  28531. bool alreadyThere = false;
  28532. for (int i = results.size(); --i >= 0;)
  28533. {
  28534. PluginDescription* const d = results.getUnchecked(i);
  28535. if (d->isDuplicateOf (desc))
  28536. {
  28537. alreadyThere = true;
  28538. break;
  28539. }
  28540. }
  28541. if (! alreadyThere)
  28542. results.add (new PluginDescription (desc));
  28543. }
  28544. }
  28545. }
  28546. }
  28547. catch (...)
  28548. {
  28549. // crashed while loading...
  28550. }
  28551. }
  28552. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28553. {
  28554. ScopedPointer <VSTPluginInstance> result;
  28555. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28556. {
  28557. File file (desc.fileOrIdentifier);
  28558. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28559. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28560. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28561. if (module != 0)
  28562. {
  28563. shellUIDToCreate = desc.uid;
  28564. result = new VSTPluginInstance (module);
  28565. if (result->effect != 0)
  28566. {
  28567. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28568. result->initialise();
  28569. }
  28570. else
  28571. {
  28572. result = 0;
  28573. }
  28574. }
  28575. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28576. }
  28577. return result.release();
  28578. }
  28579. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28580. {
  28581. const File f (fileOrIdentifier);
  28582. #if JUCE_MAC
  28583. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28584. return true;
  28585. #if JUCE_PPC
  28586. FSRef fileRef;
  28587. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28588. {
  28589. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28590. if (resFileId != -1)
  28591. {
  28592. const int numEffects = Count1Resources ('aEff');
  28593. CloseResFile (resFileId);
  28594. if (numEffects > 0)
  28595. return true;
  28596. }
  28597. }
  28598. #endif
  28599. return false;
  28600. #elif JUCE_WINDOWS
  28601. return f.existsAsFile() && f.hasFileExtension (".dll");
  28602. #elif JUCE_LINUX
  28603. return f.existsAsFile() && f.hasFileExtension (".so");
  28604. #endif
  28605. }
  28606. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28607. {
  28608. return fileOrIdentifier;
  28609. }
  28610. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28611. {
  28612. return File (desc.fileOrIdentifier).exists();
  28613. }
  28614. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28615. {
  28616. StringArray results;
  28617. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28618. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28619. return results;
  28620. }
  28621. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28622. {
  28623. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28624. // .component or .vst directories.
  28625. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28626. while (iter.next())
  28627. {
  28628. const File f (iter.getFile());
  28629. bool isPlugin = false;
  28630. if (fileMightContainThisPluginType (f.getFullPathName()))
  28631. {
  28632. isPlugin = true;
  28633. results.add (f.getFullPathName());
  28634. }
  28635. if (recursive && (! isPlugin) && f.isDirectory())
  28636. recursiveFileSearch (results, f, true);
  28637. }
  28638. }
  28639. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28640. {
  28641. #if JUCE_MAC
  28642. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28643. #elif JUCE_WINDOWS
  28644. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28645. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28646. #elif JUCE_LINUX
  28647. return FileSearchPath ("/usr/lib/vst");
  28648. #endif
  28649. }
  28650. END_JUCE_NAMESPACE
  28651. #endif
  28652. #undef log
  28653. #endif
  28654. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28655. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28656. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28657. BEGIN_JUCE_NAMESPACE
  28658. AudioProcessor::AudioProcessor()
  28659. : playHead (0),
  28660. activeEditor (0),
  28661. sampleRate (0),
  28662. blockSize (0),
  28663. numInputChannels (0),
  28664. numOutputChannels (0),
  28665. latencySamples (0),
  28666. suspended (false),
  28667. nonRealtime (false)
  28668. {
  28669. }
  28670. AudioProcessor::~AudioProcessor()
  28671. {
  28672. // ooh, nasty - the editor should have been deleted before the filter
  28673. // that it refers to is deleted..
  28674. jassert (activeEditor == 0);
  28675. #if JUCE_DEBUG
  28676. // This will fail if you've called beginParameterChangeGesture() for one
  28677. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28678. jassert (changingParams.countNumberOfSetBits() == 0);
  28679. #endif
  28680. }
  28681. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28682. {
  28683. playHead = newPlayHead;
  28684. }
  28685. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28686. {
  28687. const ScopedLock sl (listenerLock);
  28688. listeners.addIfNotAlreadyThere (newListener);
  28689. }
  28690. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28691. {
  28692. const ScopedLock sl (listenerLock);
  28693. listeners.removeValue (listenerToRemove);
  28694. }
  28695. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28696. const int numOuts,
  28697. const double sampleRate_,
  28698. const int blockSize_) throw()
  28699. {
  28700. numInputChannels = numIns;
  28701. numOutputChannels = numOuts;
  28702. sampleRate = sampleRate_;
  28703. blockSize = blockSize_;
  28704. }
  28705. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28706. {
  28707. nonRealtime = nonRealtime_;
  28708. }
  28709. void AudioProcessor::setLatencySamples (const int newLatency)
  28710. {
  28711. if (latencySamples != newLatency)
  28712. {
  28713. latencySamples = newLatency;
  28714. updateHostDisplay();
  28715. }
  28716. }
  28717. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28718. const float newValue)
  28719. {
  28720. setParameter (parameterIndex, newValue);
  28721. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28722. }
  28723. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28724. {
  28725. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28726. for (int i = listeners.size(); --i >= 0;)
  28727. {
  28728. AudioProcessorListener* l;
  28729. {
  28730. const ScopedLock sl (listenerLock);
  28731. l = listeners [i];
  28732. }
  28733. if (l != 0)
  28734. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28735. }
  28736. }
  28737. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28738. {
  28739. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28740. #if JUCE_DEBUG
  28741. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28742. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28743. jassert (! changingParams [parameterIndex]);
  28744. changingParams.setBit (parameterIndex);
  28745. #endif
  28746. for (int i = listeners.size(); --i >= 0;)
  28747. {
  28748. AudioProcessorListener* l;
  28749. {
  28750. const ScopedLock sl (listenerLock);
  28751. l = listeners [i];
  28752. }
  28753. if (l != 0)
  28754. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28755. }
  28756. }
  28757. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28758. {
  28759. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28760. #if JUCE_DEBUG
  28761. // This means you've called endParameterChangeGesture without having previously called
  28762. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28763. // calls matched correctly.
  28764. jassert (changingParams [parameterIndex]);
  28765. changingParams.clearBit (parameterIndex);
  28766. #endif
  28767. for (int i = listeners.size(); --i >= 0;)
  28768. {
  28769. AudioProcessorListener* l;
  28770. {
  28771. const ScopedLock sl (listenerLock);
  28772. l = listeners [i];
  28773. }
  28774. if (l != 0)
  28775. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28776. }
  28777. }
  28778. void AudioProcessor::updateHostDisplay()
  28779. {
  28780. for (int i = listeners.size(); --i >= 0;)
  28781. {
  28782. AudioProcessorListener* l;
  28783. {
  28784. const ScopedLock sl (listenerLock);
  28785. l = listeners [i];
  28786. }
  28787. if (l != 0)
  28788. l->audioProcessorChanged (this);
  28789. }
  28790. }
  28791. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28792. {
  28793. return true;
  28794. }
  28795. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28796. {
  28797. return false;
  28798. }
  28799. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28800. {
  28801. const ScopedLock sl (callbackLock);
  28802. suspended = shouldBeSuspended;
  28803. }
  28804. void AudioProcessor::reset()
  28805. {
  28806. }
  28807. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28808. {
  28809. const ScopedLock sl (callbackLock);
  28810. jassert (activeEditor == editor);
  28811. if (activeEditor == editor)
  28812. activeEditor = 0;
  28813. }
  28814. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28815. {
  28816. if (activeEditor != 0)
  28817. return activeEditor;
  28818. AudioProcessorEditor* const ed = createEditor();
  28819. // You must make your hasEditor() method return a consistent result!
  28820. jassert (hasEditor() == (ed != 0));
  28821. if (ed != 0)
  28822. {
  28823. // you must give your editor comp a size before returning it..
  28824. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28825. const ScopedLock sl (callbackLock);
  28826. activeEditor = ed;
  28827. }
  28828. return ed;
  28829. }
  28830. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28831. {
  28832. getStateInformation (destData);
  28833. }
  28834. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28835. {
  28836. setStateInformation (data, sizeInBytes);
  28837. }
  28838. // magic number to identify memory blocks that we've stored as XML
  28839. const uint32 magicXmlNumber = 0x21324356;
  28840. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28841. JUCE_NAMESPACE::MemoryBlock& destData)
  28842. {
  28843. const String xmlString (xml.createDocument (String::empty, true, false));
  28844. const int stringLength = xmlString.getNumBytesAsUTF8();
  28845. destData.setSize (stringLength + 10);
  28846. char* const d = static_cast<char*> (destData.getData());
  28847. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28848. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28849. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28850. }
  28851. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28852. const int sizeInBytes)
  28853. {
  28854. if (sizeInBytes > 8
  28855. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28856. {
  28857. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28858. if (stringLength > 0)
  28859. {
  28860. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28861. jmin ((sizeInBytes - 8), stringLength)));
  28862. return doc.getDocumentElement();
  28863. }
  28864. }
  28865. return 0;
  28866. }
  28867. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28868. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28869. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28870. {
  28871. return timeInSeconds == other.timeInSeconds
  28872. && ppqPosition == other.ppqPosition
  28873. && editOriginTime == other.editOriginTime
  28874. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28875. && frameRate == other.frameRate
  28876. && isPlaying == other.isPlaying
  28877. && isRecording == other.isRecording
  28878. && bpm == other.bpm
  28879. && timeSigNumerator == other.timeSigNumerator
  28880. && timeSigDenominator == other.timeSigDenominator;
  28881. }
  28882. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28883. {
  28884. return ! operator== (other);
  28885. }
  28886. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28887. {
  28888. zerostruct (*this);
  28889. timeSigNumerator = 4;
  28890. timeSigDenominator = 4;
  28891. bpm = 120;
  28892. }
  28893. END_JUCE_NAMESPACE
  28894. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28895. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28896. BEGIN_JUCE_NAMESPACE
  28897. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28898. : owner (owner_)
  28899. {
  28900. // the filter must be valid..
  28901. jassert (owner != 0);
  28902. }
  28903. AudioProcessorEditor::~AudioProcessorEditor()
  28904. {
  28905. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28906. // filter for some reason..
  28907. jassert (owner->getActiveEditor() != this);
  28908. }
  28909. END_JUCE_NAMESPACE
  28910. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28911. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28912. BEGIN_JUCE_NAMESPACE
  28913. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28914. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28915. : id (id_),
  28916. processor (processor_),
  28917. isPrepared (false)
  28918. {
  28919. jassert (processor_ != 0);
  28920. }
  28921. AudioProcessorGraph::Node::~Node()
  28922. {
  28923. }
  28924. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28925. AudioProcessorGraph* const graph)
  28926. {
  28927. if (! isPrepared)
  28928. {
  28929. isPrepared = true;
  28930. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28931. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28932. if (ioProc != 0)
  28933. ioProc->setParentGraph (graph);
  28934. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28935. processor->getNumOutputChannels(),
  28936. sampleRate, blockSize);
  28937. processor->prepareToPlay (sampleRate, blockSize);
  28938. }
  28939. }
  28940. void AudioProcessorGraph::Node::unprepare()
  28941. {
  28942. if (isPrepared)
  28943. {
  28944. isPrepared = false;
  28945. processor->releaseResources();
  28946. }
  28947. }
  28948. AudioProcessorGraph::AudioProcessorGraph()
  28949. : lastNodeId (0),
  28950. renderingBuffers (1, 1),
  28951. currentAudioOutputBuffer (1, 1)
  28952. {
  28953. }
  28954. AudioProcessorGraph::~AudioProcessorGraph()
  28955. {
  28956. clearRenderingSequence();
  28957. clear();
  28958. }
  28959. const String AudioProcessorGraph::getName() const
  28960. {
  28961. return "Audio Graph";
  28962. }
  28963. void AudioProcessorGraph::clear()
  28964. {
  28965. nodes.clear();
  28966. connections.clear();
  28967. triggerAsyncUpdate();
  28968. }
  28969. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28970. {
  28971. for (int i = nodes.size(); --i >= 0;)
  28972. if (nodes.getUnchecked(i)->id == nodeId)
  28973. return nodes.getUnchecked(i);
  28974. return 0;
  28975. }
  28976. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28977. uint32 nodeId)
  28978. {
  28979. if (newProcessor == 0)
  28980. {
  28981. jassertfalse;
  28982. return 0;
  28983. }
  28984. if (nodeId == 0)
  28985. {
  28986. nodeId = ++lastNodeId;
  28987. }
  28988. else
  28989. {
  28990. // you can't add a node with an id that already exists in the graph..
  28991. jassert (getNodeForId (nodeId) == 0);
  28992. removeNode (nodeId);
  28993. }
  28994. lastNodeId = nodeId;
  28995. Node* const n = new Node (nodeId, newProcessor);
  28996. nodes.add (n);
  28997. triggerAsyncUpdate();
  28998. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28999. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29000. if (ioProc != 0)
  29001. ioProc->setParentGraph (this);
  29002. return n;
  29003. }
  29004. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29005. {
  29006. disconnectNode (nodeId);
  29007. for (int i = nodes.size(); --i >= 0;)
  29008. {
  29009. if (nodes.getUnchecked(i)->id == nodeId)
  29010. {
  29011. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29012. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29013. if (ioProc != 0)
  29014. ioProc->setParentGraph (0);
  29015. nodes.remove (i);
  29016. triggerAsyncUpdate();
  29017. return true;
  29018. }
  29019. }
  29020. return false;
  29021. }
  29022. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29023. const int sourceChannelIndex,
  29024. const uint32 destNodeId,
  29025. const int destChannelIndex) const
  29026. {
  29027. for (int i = connections.size(); --i >= 0;)
  29028. {
  29029. const Connection* const c = connections.getUnchecked(i);
  29030. if (c->sourceNodeId == sourceNodeId
  29031. && c->destNodeId == destNodeId
  29032. && c->sourceChannelIndex == sourceChannelIndex
  29033. && c->destChannelIndex == destChannelIndex)
  29034. {
  29035. return c;
  29036. }
  29037. }
  29038. return 0;
  29039. }
  29040. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29041. const uint32 possibleDestNodeId) const
  29042. {
  29043. for (int i = connections.size(); --i >= 0;)
  29044. {
  29045. const Connection* const c = connections.getUnchecked(i);
  29046. if (c->sourceNodeId == possibleSourceNodeId
  29047. && c->destNodeId == possibleDestNodeId)
  29048. {
  29049. return true;
  29050. }
  29051. }
  29052. return false;
  29053. }
  29054. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29055. const int sourceChannelIndex,
  29056. const uint32 destNodeId,
  29057. const int destChannelIndex) const
  29058. {
  29059. if (sourceChannelIndex < 0
  29060. || destChannelIndex < 0
  29061. || sourceNodeId == destNodeId
  29062. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29063. return false;
  29064. const Node* const source = getNodeForId (sourceNodeId);
  29065. if (source == 0
  29066. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29067. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29068. return false;
  29069. const Node* const dest = getNodeForId (destNodeId);
  29070. if (dest == 0
  29071. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29072. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29073. return false;
  29074. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29075. destNodeId, destChannelIndex) == 0;
  29076. }
  29077. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29078. const int sourceChannelIndex,
  29079. const uint32 destNodeId,
  29080. const int destChannelIndex)
  29081. {
  29082. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29083. return false;
  29084. Connection* const c = new Connection();
  29085. c->sourceNodeId = sourceNodeId;
  29086. c->sourceChannelIndex = sourceChannelIndex;
  29087. c->destNodeId = destNodeId;
  29088. c->destChannelIndex = destChannelIndex;
  29089. connections.add (c);
  29090. triggerAsyncUpdate();
  29091. return true;
  29092. }
  29093. void AudioProcessorGraph::removeConnection (const int index)
  29094. {
  29095. connections.remove (index);
  29096. triggerAsyncUpdate();
  29097. }
  29098. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29099. const uint32 destNodeId, const int destChannelIndex)
  29100. {
  29101. bool doneAnything = false;
  29102. for (int i = connections.size(); --i >= 0;)
  29103. {
  29104. const Connection* const c = connections.getUnchecked(i);
  29105. if (c->sourceNodeId == sourceNodeId
  29106. && c->destNodeId == destNodeId
  29107. && c->sourceChannelIndex == sourceChannelIndex
  29108. && c->destChannelIndex == destChannelIndex)
  29109. {
  29110. removeConnection (i);
  29111. doneAnything = true;
  29112. triggerAsyncUpdate();
  29113. }
  29114. }
  29115. return doneAnything;
  29116. }
  29117. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29118. {
  29119. bool doneAnything = false;
  29120. for (int i = connections.size(); --i >= 0;)
  29121. {
  29122. const Connection* const c = connections.getUnchecked(i);
  29123. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29124. {
  29125. removeConnection (i);
  29126. doneAnything = true;
  29127. triggerAsyncUpdate();
  29128. }
  29129. }
  29130. return doneAnything;
  29131. }
  29132. bool AudioProcessorGraph::removeIllegalConnections()
  29133. {
  29134. bool doneAnything = false;
  29135. for (int i = connections.size(); --i >= 0;)
  29136. {
  29137. const Connection* const c = connections.getUnchecked(i);
  29138. const Node* const source = getNodeForId (c->sourceNodeId);
  29139. const Node* const dest = getNodeForId (c->destNodeId);
  29140. if (source == 0 || dest == 0
  29141. || (c->sourceChannelIndex != midiChannelIndex
  29142. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29143. || (c->sourceChannelIndex == midiChannelIndex
  29144. && ! source->processor->producesMidi())
  29145. || (c->destChannelIndex != midiChannelIndex
  29146. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29147. || (c->destChannelIndex == midiChannelIndex
  29148. && ! dest->processor->acceptsMidi()))
  29149. {
  29150. removeConnection (i);
  29151. doneAnything = true;
  29152. triggerAsyncUpdate();
  29153. }
  29154. }
  29155. return doneAnything;
  29156. }
  29157. namespace GraphRenderingOps
  29158. {
  29159. class AudioGraphRenderingOp
  29160. {
  29161. public:
  29162. AudioGraphRenderingOp() {}
  29163. virtual ~AudioGraphRenderingOp() {}
  29164. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29165. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29166. const int numSamples) = 0;
  29167. juce_UseDebuggingNewOperator
  29168. };
  29169. class ClearChannelOp : public AudioGraphRenderingOp
  29170. {
  29171. public:
  29172. ClearChannelOp (const int channelNum_)
  29173. : channelNum (channelNum_)
  29174. {}
  29175. ~ClearChannelOp() {}
  29176. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29177. {
  29178. sharedBufferChans.clear (channelNum, 0, numSamples);
  29179. }
  29180. private:
  29181. const int channelNum;
  29182. ClearChannelOp (const ClearChannelOp&);
  29183. ClearChannelOp& operator= (const ClearChannelOp&);
  29184. };
  29185. class CopyChannelOp : public AudioGraphRenderingOp
  29186. {
  29187. public:
  29188. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29189. : srcChannelNum (srcChannelNum_),
  29190. dstChannelNum (dstChannelNum_)
  29191. {}
  29192. ~CopyChannelOp() {}
  29193. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29194. {
  29195. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29196. }
  29197. private:
  29198. const int srcChannelNum, dstChannelNum;
  29199. CopyChannelOp (const CopyChannelOp&);
  29200. CopyChannelOp& operator= (const CopyChannelOp&);
  29201. };
  29202. class AddChannelOp : public AudioGraphRenderingOp
  29203. {
  29204. public:
  29205. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29206. : srcChannelNum (srcChannelNum_),
  29207. dstChannelNum (dstChannelNum_)
  29208. {}
  29209. ~AddChannelOp() {}
  29210. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29211. {
  29212. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29213. }
  29214. private:
  29215. const int srcChannelNum, dstChannelNum;
  29216. AddChannelOp (const AddChannelOp&);
  29217. AddChannelOp& operator= (const AddChannelOp&);
  29218. };
  29219. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29220. {
  29221. public:
  29222. ClearMidiBufferOp (const int bufferNum_)
  29223. : bufferNum (bufferNum_)
  29224. {}
  29225. ~ClearMidiBufferOp() {}
  29226. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29227. {
  29228. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29229. }
  29230. private:
  29231. const int bufferNum;
  29232. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29233. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29234. };
  29235. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29236. {
  29237. public:
  29238. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29239. : srcBufferNum (srcBufferNum_),
  29240. dstBufferNum (dstBufferNum_)
  29241. {}
  29242. ~CopyMidiBufferOp() {}
  29243. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29244. {
  29245. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29246. }
  29247. private:
  29248. const int srcBufferNum, dstBufferNum;
  29249. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29250. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29251. };
  29252. class AddMidiBufferOp : public AudioGraphRenderingOp
  29253. {
  29254. public:
  29255. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29256. : srcBufferNum (srcBufferNum_),
  29257. dstBufferNum (dstBufferNum_)
  29258. {}
  29259. ~AddMidiBufferOp() {}
  29260. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29261. {
  29262. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29263. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29264. }
  29265. private:
  29266. const int srcBufferNum, dstBufferNum;
  29267. AddMidiBufferOp (const AddMidiBufferOp&);
  29268. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29269. };
  29270. class ProcessBufferOp : public AudioGraphRenderingOp
  29271. {
  29272. public:
  29273. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29274. const Array <int>& audioChannelsToUse_,
  29275. const int totalChans_,
  29276. const int midiBufferToUse_)
  29277. : node (node_),
  29278. processor (node_->getProcessor()),
  29279. audioChannelsToUse (audioChannelsToUse_),
  29280. totalChans (jmax (1, totalChans_)),
  29281. midiBufferToUse (midiBufferToUse_)
  29282. {
  29283. channels.calloc (totalChans);
  29284. while (audioChannelsToUse.size() < totalChans)
  29285. audioChannelsToUse.add (0);
  29286. }
  29287. ~ProcessBufferOp()
  29288. {
  29289. }
  29290. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29291. {
  29292. for (int i = totalChans; --i >= 0;)
  29293. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29294. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29295. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29296. }
  29297. const AudioProcessorGraph::Node::Ptr node;
  29298. AudioProcessor* const processor;
  29299. private:
  29300. Array <int> audioChannelsToUse;
  29301. HeapBlock <float*> channels;
  29302. int totalChans;
  29303. int midiBufferToUse;
  29304. ProcessBufferOp (const ProcessBufferOp&);
  29305. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29306. };
  29307. /** Used to calculate the correct sequence of rendering ops needed, based on
  29308. the best re-use of shared buffers at each stage.
  29309. */
  29310. class RenderingOpSequenceCalculator
  29311. {
  29312. public:
  29313. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29314. const Array<void*>& orderedNodes_,
  29315. Array<void*>& renderingOps)
  29316. : graph (graph_),
  29317. orderedNodes (orderedNodes_)
  29318. {
  29319. nodeIds.add (-2); // first buffer is read-only zeros
  29320. channels.add (0);
  29321. midiNodeIds.add (-2);
  29322. for (int i = 0; i < orderedNodes.size(); ++i)
  29323. {
  29324. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29325. renderingOps, i);
  29326. markAnyUnusedBuffersAsFree (i);
  29327. }
  29328. }
  29329. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29330. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29331. juce_UseDebuggingNewOperator
  29332. private:
  29333. AudioProcessorGraph& graph;
  29334. const Array<void*>& orderedNodes;
  29335. Array <int> nodeIds, channels, midiNodeIds;
  29336. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29337. Array<void*>& renderingOps,
  29338. const int ourRenderingIndex)
  29339. {
  29340. const int numIns = node->getProcessor()->getNumInputChannels();
  29341. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29342. const int totalChans = jmax (numIns, numOuts);
  29343. Array <int> audioChannelsToUse;
  29344. int midiBufferToUse = -1;
  29345. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29346. {
  29347. // get a list of all the inputs to this node
  29348. Array <int> sourceNodes, sourceOutputChans;
  29349. for (int i = graph.getNumConnections(); --i >= 0;)
  29350. {
  29351. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29352. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29353. {
  29354. sourceNodes.add (c->sourceNodeId);
  29355. sourceOutputChans.add (c->sourceChannelIndex);
  29356. }
  29357. }
  29358. int bufIndex = -1;
  29359. if (sourceNodes.size() == 0)
  29360. {
  29361. // unconnected input channel
  29362. if (inputChan >= numOuts)
  29363. {
  29364. bufIndex = getReadOnlyEmptyBuffer();
  29365. jassert (bufIndex >= 0);
  29366. }
  29367. else
  29368. {
  29369. bufIndex = getFreeBuffer (false);
  29370. renderingOps.add (new ClearChannelOp (bufIndex));
  29371. }
  29372. }
  29373. else if (sourceNodes.size() == 1)
  29374. {
  29375. // channel with a straightforward single input..
  29376. const int srcNode = sourceNodes.getUnchecked(0);
  29377. const int srcChan = sourceOutputChans.getUnchecked(0);
  29378. bufIndex = getBufferContaining (srcNode, srcChan);
  29379. if (bufIndex < 0)
  29380. {
  29381. // if not found, this is probably a feedback loop
  29382. bufIndex = getReadOnlyEmptyBuffer();
  29383. jassert (bufIndex >= 0);
  29384. }
  29385. if (inputChan < numOuts
  29386. && isBufferNeededLater (ourRenderingIndex,
  29387. inputChan,
  29388. srcNode, srcChan))
  29389. {
  29390. // can't mess up this channel because it's needed later by another node, so we
  29391. // need to use a copy of it..
  29392. const int newFreeBuffer = getFreeBuffer (false);
  29393. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29394. bufIndex = newFreeBuffer;
  29395. }
  29396. }
  29397. else
  29398. {
  29399. // channel with a mix of several inputs..
  29400. // try to find a re-usable channel from our inputs..
  29401. int reusableInputIndex = -1;
  29402. for (int i = 0; i < sourceNodes.size(); ++i)
  29403. {
  29404. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29405. sourceOutputChans.getUnchecked(i));
  29406. if (sourceBufIndex >= 0
  29407. && ! isBufferNeededLater (ourRenderingIndex,
  29408. inputChan,
  29409. sourceNodes.getUnchecked(i),
  29410. sourceOutputChans.getUnchecked(i)))
  29411. {
  29412. // we've found one of our input chans that can be re-used..
  29413. reusableInputIndex = i;
  29414. bufIndex = sourceBufIndex;
  29415. break;
  29416. }
  29417. }
  29418. if (reusableInputIndex < 0)
  29419. {
  29420. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29421. bufIndex = getFreeBuffer (false);
  29422. jassert (bufIndex != 0);
  29423. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29424. sourceOutputChans.getUnchecked (0));
  29425. if (srcIndex < 0)
  29426. {
  29427. // if not found, this is probably a feedback loop
  29428. renderingOps.add (new ClearChannelOp (bufIndex));
  29429. }
  29430. else
  29431. {
  29432. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29433. }
  29434. reusableInputIndex = 0;
  29435. }
  29436. for (int j = 0; j < sourceNodes.size(); ++j)
  29437. {
  29438. if (j != reusableInputIndex)
  29439. {
  29440. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29441. sourceOutputChans.getUnchecked(j));
  29442. if (srcIndex >= 0)
  29443. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29444. }
  29445. }
  29446. }
  29447. jassert (bufIndex >= 0);
  29448. audioChannelsToUse.add (bufIndex);
  29449. if (inputChan < numOuts)
  29450. markBufferAsContaining (bufIndex, node->id, inputChan);
  29451. }
  29452. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29453. {
  29454. const int bufIndex = getFreeBuffer (false);
  29455. jassert (bufIndex != 0);
  29456. audioChannelsToUse.add (bufIndex);
  29457. markBufferAsContaining (bufIndex, node->id, outputChan);
  29458. }
  29459. // Now the same thing for midi..
  29460. Array <int> midiSourceNodes;
  29461. for (int i = graph.getNumConnections(); --i >= 0;)
  29462. {
  29463. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29464. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29465. midiSourceNodes.add (c->sourceNodeId);
  29466. }
  29467. if (midiSourceNodes.size() == 0)
  29468. {
  29469. // No midi inputs..
  29470. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29471. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29472. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29473. }
  29474. else if (midiSourceNodes.size() == 1)
  29475. {
  29476. // One midi input..
  29477. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29478. AudioProcessorGraph::midiChannelIndex);
  29479. if (midiBufferToUse >= 0)
  29480. {
  29481. if (isBufferNeededLater (ourRenderingIndex,
  29482. AudioProcessorGraph::midiChannelIndex,
  29483. midiSourceNodes.getUnchecked(0),
  29484. AudioProcessorGraph::midiChannelIndex))
  29485. {
  29486. // can't mess up this channel because it's needed later by another node, so we
  29487. // need to use a copy of it..
  29488. const int newFreeBuffer = getFreeBuffer (true);
  29489. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29490. midiBufferToUse = newFreeBuffer;
  29491. }
  29492. }
  29493. else
  29494. {
  29495. // probably a feedback loop, so just use an empty one..
  29496. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29497. }
  29498. }
  29499. else
  29500. {
  29501. // More than one midi input being mixed..
  29502. int reusableInputIndex = -1;
  29503. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29504. {
  29505. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29506. AudioProcessorGraph::midiChannelIndex);
  29507. if (sourceBufIndex >= 0
  29508. && ! isBufferNeededLater (ourRenderingIndex,
  29509. AudioProcessorGraph::midiChannelIndex,
  29510. midiSourceNodes.getUnchecked(i),
  29511. AudioProcessorGraph::midiChannelIndex))
  29512. {
  29513. // we've found one of our input buffers that can be re-used..
  29514. reusableInputIndex = i;
  29515. midiBufferToUse = sourceBufIndex;
  29516. break;
  29517. }
  29518. }
  29519. if (reusableInputIndex < 0)
  29520. {
  29521. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29522. midiBufferToUse = getFreeBuffer (true);
  29523. jassert (midiBufferToUse >= 0);
  29524. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29525. AudioProcessorGraph::midiChannelIndex);
  29526. if (srcIndex >= 0)
  29527. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29528. else
  29529. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29530. reusableInputIndex = 0;
  29531. }
  29532. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29533. {
  29534. if (j != reusableInputIndex)
  29535. {
  29536. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29537. AudioProcessorGraph::midiChannelIndex);
  29538. if (srcIndex >= 0)
  29539. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29540. }
  29541. }
  29542. }
  29543. if (node->getProcessor()->producesMidi())
  29544. markBufferAsContaining (midiBufferToUse, node->id,
  29545. AudioProcessorGraph::midiChannelIndex);
  29546. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29547. totalChans, midiBufferToUse));
  29548. }
  29549. int getFreeBuffer (const bool forMidi)
  29550. {
  29551. if (forMidi)
  29552. {
  29553. for (int i = 1; i < midiNodeIds.size(); ++i)
  29554. if (midiNodeIds.getUnchecked(i) < 0)
  29555. return i;
  29556. midiNodeIds.add (-1);
  29557. return midiNodeIds.size() - 1;
  29558. }
  29559. else
  29560. {
  29561. for (int i = 1; i < nodeIds.size(); ++i)
  29562. if (nodeIds.getUnchecked(i) < 0)
  29563. return i;
  29564. nodeIds.add (-1);
  29565. channels.add (0);
  29566. return nodeIds.size() - 1;
  29567. }
  29568. }
  29569. int getReadOnlyEmptyBuffer() const
  29570. {
  29571. return 0;
  29572. }
  29573. int getBufferContaining (const int nodeId, const int outputChannel) const
  29574. {
  29575. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29576. {
  29577. for (int i = midiNodeIds.size(); --i >= 0;)
  29578. if (midiNodeIds.getUnchecked(i) == nodeId)
  29579. return i;
  29580. }
  29581. else
  29582. {
  29583. for (int i = nodeIds.size(); --i >= 0;)
  29584. if (nodeIds.getUnchecked(i) == nodeId
  29585. && channels.getUnchecked(i) == outputChannel)
  29586. return i;
  29587. }
  29588. return -1;
  29589. }
  29590. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29591. {
  29592. int i;
  29593. for (i = 0; i < nodeIds.size(); ++i)
  29594. {
  29595. if (nodeIds.getUnchecked(i) >= 0
  29596. && ! isBufferNeededLater (stepIndex, -1,
  29597. nodeIds.getUnchecked(i),
  29598. channels.getUnchecked(i)))
  29599. {
  29600. nodeIds.set (i, -1);
  29601. }
  29602. }
  29603. for (i = 0; i < midiNodeIds.size(); ++i)
  29604. {
  29605. if (midiNodeIds.getUnchecked(i) >= 0
  29606. && ! isBufferNeededLater (stepIndex, -1,
  29607. midiNodeIds.getUnchecked(i),
  29608. AudioProcessorGraph::midiChannelIndex))
  29609. {
  29610. midiNodeIds.set (i, -1);
  29611. }
  29612. }
  29613. }
  29614. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29615. int inputChannelOfIndexToIgnore,
  29616. const int nodeId,
  29617. const int outputChanIndex) const
  29618. {
  29619. while (stepIndexToSearchFrom < orderedNodes.size())
  29620. {
  29621. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29622. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29623. {
  29624. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29625. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29626. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29627. return true;
  29628. }
  29629. else
  29630. {
  29631. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29632. if (i != inputChannelOfIndexToIgnore
  29633. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29634. node->id, i) != 0)
  29635. return true;
  29636. }
  29637. inputChannelOfIndexToIgnore = -1;
  29638. ++stepIndexToSearchFrom;
  29639. }
  29640. return false;
  29641. }
  29642. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29643. {
  29644. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29645. {
  29646. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29647. midiNodeIds.set (bufferNum, nodeId);
  29648. }
  29649. else
  29650. {
  29651. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29652. nodeIds.set (bufferNum, nodeId);
  29653. channels.set (bufferNum, outputIndex);
  29654. }
  29655. }
  29656. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29657. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29658. };
  29659. }
  29660. void AudioProcessorGraph::clearRenderingSequence()
  29661. {
  29662. const ScopedLock sl (renderLock);
  29663. for (int i = renderingOps.size(); --i >= 0;)
  29664. {
  29665. GraphRenderingOps::AudioGraphRenderingOp* const r
  29666. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29667. renderingOps.remove (i);
  29668. delete r;
  29669. }
  29670. }
  29671. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29672. const uint32 possibleDestinationId,
  29673. const int recursionCheck) const
  29674. {
  29675. if (recursionCheck > 0)
  29676. {
  29677. for (int i = connections.size(); --i >= 0;)
  29678. {
  29679. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29680. if (c->destNodeId == possibleDestinationId
  29681. && (c->sourceNodeId == possibleInputId
  29682. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29683. return true;
  29684. }
  29685. }
  29686. return false;
  29687. }
  29688. void AudioProcessorGraph::buildRenderingSequence()
  29689. {
  29690. Array<void*> newRenderingOps;
  29691. int numRenderingBuffersNeeded = 2;
  29692. int numMidiBuffersNeeded = 1;
  29693. {
  29694. MessageManagerLock mml;
  29695. Array<void*> orderedNodes;
  29696. int i;
  29697. for (i = 0; i < nodes.size(); ++i)
  29698. {
  29699. Node* const node = nodes.getUnchecked(i);
  29700. node->prepare (getSampleRate(), getBlockSize(), this);
  29701. int j = 0;
  29702. for (; j < orderedNodes.size(); ++j)
  29703. if (isAnInputTo (node->id,
  29704. ((Node*) orderedNodes.getUnchecked (j))->id,
  29705. nodes.size() + 1))
  29706. break;
  29707. orderedNodes.insert (j, node);
  29708. }
  29709. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29710. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29711. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29712. }
  29713. Array<void*> oldRenderingOps (renderingOps);
  29714. {
  29715. // swap over to the new rendering sequence..
  29716. const ScopedLock sl (renderLock);
  29717. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29718. renderingBuffers.clear();
  29719. for (int i = midiBuffers.size(); --i >= 0;)
  29720. midiBuffers.getUnchecked(i)->clear();
  29721. while (midiBuffers.size() < numMidiBuffersNeeded)
  29722. midiBuffers.add (new MidiBuffer());
  29723. renderingOps = newRenderingOps;
  29724. }
  29725. for (int i = oldRenderingOps.size(); --i >= 0;)
  29726. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29727. }
  29728. void AudioProcessorGraph::handleAsyncUpdate()
  29729. {
  29730. buildRenderingSequence();
  29731. }
  29732. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29733. {
  29734. currentAudioInputBuffer = 0;
  29735. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29736. currentMidiInputBuffer = 0;
  29737. currentMidiOutputBuffer.clear();
  29738. clearRenderingSequence();
  29739. buildRenderingSequence();
  29740. }
  29741. void AudioProcessorGraph::releaseResources()
  29742. {
  29743. for (int i = 0; i < nodes.size(); ++i)
  29744. nodes.getUnchecked(i)->unprepare();
  29745. renderingBuffers.setSize (1, 1);
  29746. midiBuffers.clear();
  29747. currentAudioInputBuffer = 0;
  29748. currentAudioOutputBuffer.setSize (1, 1);
  29749. currentMidiInputBuffer = 0;
  29750. currentMidiOutputBuffer.clear();
  29751. }
  29752. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29753. {
  29754. const int numSamples = buffer.getNumSamples();
  29755. const ScopedLock sl (renderLock);
  29756. currentAudioInputBuffer = &buffer;
  29757. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29758. currentAudioOutputBuffer.clear();
  29759. currentMidiInputBuffer = &midiMessages;
  29760. currentMidiOutputBuffer.clear();
  29761. int i;
  29762. for (i = 0; i < renderingOps.size(); ++i)
  29763. {
  29764. GraphRenderingOps::AudioGraphRenderingOp* const op
  29765. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29766. op->perform (renderingBuffers, midiBuffers, numSamples);
  29767. }
  29768. for (i = 0; i < buffer.getNumChannels(); ++i)
  29769. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29770. midiMessages.clear();
  29771. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29772. }
  29773. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29774. {
  29775. return "Input " + String (channelIndex + 1);
  29776. }
  29777. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29778. {
  29779. return "Output " + String (channelIndex + 1);
  29780. }
  29781. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29782. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29783. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29784. bool AudioProcessorGraph::producesMidi() const { return true; }
  29785. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29786. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29787. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29788. : type (type_),
  29789. graph (0)
  29790. {
  29791. }
  29792. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29793. {
  29794. }
  29795. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29796. {
  29797. switch (type)
  29798. {
  29799. case audioOutputNode: return "Audio Output";
  29800. case audioInputNode: return "Audio Input";
  29801. case midiOutputNode: return "Midi Output";
  29802. case midiInputNode: return "Midi Input";
  29803. default: break;
  29804. }
  29805. return String::empty;
  29806. }
  29807. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29808. {
  29809. d.name = getName();
  29810. d.uid = d.name.hashCode();
  29811. d.category = "I/O devices";
  29812. d.pluginFormatName = "Internal";
  29813. d.manufacturerName = "Raw Material Software";
  29814. d.version = "1.0";
  29815. d.isInstrument = false;
  29816. d.numInputChannels = getNumInputChannels();
  29817. if (type == audioOutputNode && graph != 0)
  29818. d.numInputChannels = graph->getNumInputChannels();
  29819. d.numOutputChannels = getNumOutputChannels();
  29820. if (type == audioInputNode && graph != 0)
  29821. d.numOutputChannels = graph->getNumOutputChannels();
  29822. }
  29823. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29824. {
  29825. jassert (graph != 0);
  29826. }
  29827. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29828. {
  29829. }
  29830. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29831. MidiBuffer& midiMessages)
  29832. {
  29833. jassert (graph != 0);
  29834. switch (type)
  29835. {
  29836. case audioOutputNode:
  29837. {
  29838. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29839. buffer.getNumChannels()); --i >= 0;)
  29840. {
  29841. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29842. }
  29843. break;
  29844. }
  29845. case audioInputNode:
  29846. {
  29847. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29848. buffer.getNumChannels()); --i >= 0;)
  29849. {
  29850. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29851. }
  29852. break;
  29853. }
  29854. case midiOutputNode:
  29855. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29856. break;
  29857. case midiInputNode:
  29858. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29859. break;
  29860. default:
  29861. break;
  29862. }
  29863. }
  29864. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29865. {
  29866. return type == midiOutputNode;
  29867. }
  29868. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29869. {
  29870. return type == midiInputNode;
  29871. }
  29872. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29873. {
  29874. switch (type)
  29875. {
  29876. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29877. case midiOutputNode: return "Midi Output";
  29878. default: break;
  29879. }
  29880. return String::empty;
  29881. }
  29882. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29883. {
  29884. switch (type)
  29885. {
  29886. case audioInputNode: return "Input " + String (channelIndex + 1);
  29887. case midiInputNode: return "Midi Input";
  29888. default: break;
  29889. }
  29890. return String::empty;
  29891. }
  29892. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29893. {
  29894. return type == audioInputNode || type == audioOutputNode;
  29895. }
  29896. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29897. {
  29898. return isInputChannelStereoPair (index);
  29899. }
  29900. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29901. {
  29902. return type == audioInputNode || type == midiInputNode;
  29903. }
  29904. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29905. {
  29906. return type == audioOutputNode || type == midiOutputNode;
  29907. }
  29908. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29909. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29910. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29911. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29912. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29913. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29914. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29915. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29916. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29917. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29918. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29919. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29920. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29921. {
  29922. }
  29923. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29924. {
  29925. }
  29926. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29927. {
  29928. graph = newGraph;
  29929. if (graph != 0)
  29930. {
  29931. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29932. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29933. getSampleRate(),
  29934. getBlockSize());
  29935. updateHostDisplay();
  29936. }
  29937. }
  29938. END_JUCE_NAMESPACE
  29939. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29940. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29941. BEGIN_JUCE_NAMESPACE
  29942. AudioProcessorPlayer::AudioProcessorPlayer()
  29943. : processor (0),
  29944. sampleRate (0),
  29945. blockSize (0),
  29946. isPrepared (false),
  29947. numInputChans (0),
  29948. numOutputChans (0),
  29949. tempBuffer (1, 1)
  29950. {
  29951. }
  29952. AudioProcessorPlayer::~AudioProcessorPlayer()
  29953. {
  29954. setProcessor (0);
  29955. }
  29956. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29957. {
  29958. if (processor != processorToPlay)
  29959. {
  29960. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29961. {
  29962. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29963. sampleRate, blockSize);
  29964. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29965. }
  29966. AudioProcessor* oldOne;
  29967. {
  29968. const ScopedLock sl (lock);
  29969. oldOne = isPrepared ? processor : 0;
  29970. processor = processorToPlay;
  29971. isPrepared = true;
  29972. }
  29973. if (oldOne != 0)
  29974. oldOne->releaseResources();
  29975. }
  29976. }
  29977. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29978. const int numInputChannels,
  29979. float** const outputChannelData,
  29980. const int numOutputChannels,
  29981. const int numSamples)
  29982. {
  29983. // these should have been prepared by audioDeviceAboutToStart()...
  29984. jassert (sampleRate > 0 && blockSize > 0);
  29985. incomingMidi.clear();
  29986. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29987. int i, totalNumChans = 0;
  29988. if (numInputChannels > numOutputChannels)
  29989. {
  29990. // if there aren't enough output channels for the number of
  29991. // inputs, we need to create some temporary extra ones (can't
  29992. // use the input data in case it gets written to)
  29993. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29994. false, false, true);
  29995. for (i = 0; i < numOutputChannels; ++i)
  29996. {
  29997. channels[totalNumChans] = outputChannelData[i];
  29998. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29999. ++totalNumChans;
  30000. }
  30001. for (i = numOutputChannels; i < numInputChannels; ++i)
  30002. {
  30003. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30004. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30005. ++totalNumChans;
  30006. }
  30007. }
  30008. else
  30009. {
  30010. for (i = 0; i < numInputChannels; ++i)
  30011. {
  30012. channels[totalNumChans] = outputChannelData[i];
  30013. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30014. ++totalNumChans;
  30015. }
  30016. for (i = numInputChannels; i < numOutputChannels; ++i)
  30017. {
  30018. channels[totalNumChans] = outputChannelData[i];
  30019. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30020. ++totalNumChans;
  30021. }
  30022. }
  30023. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30024. const ScopedLock sl (lock);
  30025. if (processor != 0)
  30026. {
  30027. const ScopedLock sl (processor->getCallbackLock());
  30028. if (processor->isSuspended())
  30029. {
  30030. for (i = 0; i < numOutputChannels; ++i)
  30031. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30032. }
  30033. else
  30034. {
  30035. processor->processBlock (buffer, incomingMidi);
  30036. }
  30037. }
  30038. }
  30039. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30040. {
  30041. const ScopedLock sl (lock);
  30042. sampleRate = device->getCurrentSampleRate();
  30043. blockSize = device->getCurrentBufferSizeSamples();
  30044. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30045. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30046. messageCollector.reset (sampleRate);
  30047. zeromem (channels, sizeof (channels));
  30048. if (processor != 0)
  30049. {
  30050. if (isPrepared)
  30051. processor->releaseResources();
  30052. AudioProcessor* const oldProcessor = processor;
  30053. setProcessor (0);
  30054. setProcessor (oldProcessor);
  30055. }
  30056. }
  30057. void AudioProcessorPlayer::audioDeviceStopped()
  30058. {
  30059. const ScopedLock sl (lock);
  30060. if (processor != 0 && isPrepared)
  30061. processor->releaseResources();
  30062. sampleRate = 0.0;
  30063. blockSize = 0;
  30064. isPrepared = false;
  30065. tempBuffer.setSize (1, 1);
  30066. }
  30067. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30068. {
  30069. messageCollector.addMessageToQueue (message);
  30070. }
  30071. END_JUCE_NAMESPACE
  30072. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30073. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30074. BEGIN_JUCE_NAMESPACE
  30075. class ProcessorParameterPropertyComp : public PropertyComponent,
  30076. public AudioProcessorListener,
  30077. public AsyncUpdater
  30078. {
  30079. public:
  30080. ProcessorParameterPropertyComp (const String& name,
  30081. AudioProcessor* const owner_,
  30082. const int index_)
  30083. : PropertyComponent (name),
  30084. owner (owner_),
  30085. index (index_)
  30086. {
  30087. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  30088. owner_->addListener (this);
  30089. }
  30090. ~ProcessorParameterPropertyComp()
  30091. {
  30092. owner->removeListener (this);
  30093. deleteAllChildren();
  30094. }
  30095. void refresh()
  30096. {
  30097. slider->setValue (owner->getParameter (index), false);
  30098. }
  30099. void audioProcessorChanged (AudioProcessor*) {}
  30100. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30101. {
  30102. if (parameterIndex == index)
  30103. triggerAsyncUpdate();
  30104. }
  30105. void handleAsyncUpdate()
  30106. {
  30107. refresh();
  30108. }
  30109. juce_UseDebuggingNewOperator
  30110. private:
  30111. AudioProcessor* const owner;
  30112. const int index;
  30113. Slider* slider;
  30114. class ParamSlider : public Slider
  30115. {
  30116. public:
  30117. ParamSlider (AudioProcessor* const owner_, const int index_)
  30118. : Slider (String::empty),
  30119. owner (owner_),
  30120. index (index_)
  30121. {
  30122. setRange (0.0, 1.0, 0.0);
  30123. setSliderStyle (Slider::LinearBar);
  30124. setTextBoxIsEditable (false);
  30125. setScrollWheelEnabled (false);
  30126. }
  30127. ~ParamSlider()
  30128. {
  30129. }
  30130. void valueChanged()
  30131. {
  30132. const float newVal = (float) getValue();
  30133. if (owner->getParameter (index) != newVal)
  30134. owner->setParameter (index, newVal);
  30135. }
  30136. const String getTextFromValue (double /*value*/)
  30137. {
  30138. return owner->getParameterText (index);
  30139. }
  30140. juce_UseDebuggingNewOperator
  30141. private:
  30142. AudioProcessor* const owner;
  30143. const int index;
  30144. ParamSlider (const ParamSlider&);
  30145. ParamSlider& operator= (const ParamSlider&);
  30146. };
  30147. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30148. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30149. };
  30150. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30151. : AudioProcessorEditor (owner_)
  30152. {
  30153. setOpaque (true);
  30154. addAndMakeVisible (panel = new PropertyPanel());
  30155. Array <PropertyComponent*> params;
  30156. const int numParams = owner_->getNumParameters();
  30157. int totalHeight = 0;
  30158. for (int i = 0; i < numParams; ++i)
  30159. {
  30160. String name (owner_->getParameterName (i));
  30161. if (name.trim().isEmpty())
  30162. name = "Unnamed";
  30163. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  30164. params.add (pc);
  30165. totalHeight += pc->getPreferredHeight();
  30166. }
  30167. panel->addProperties (params);
  30168. setSize (400, jlimit (25, 400, totalHeight));
  30169. }
  30170. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30171. {
  30172. deleteAllChildren();
  30173. }
  30174. void GenericAudioProcessorEditor::paint (Graphics& g)
  30175. {
  30176. g.fillAll (Colours::white);
  30177. }
  30178. void GenericAudioProcessorEditor::resized()
  30179. {
  30180. panel->setSize (getWidth(), getHeight());
  30181. }
  30182. END_JUCE_NAMESPACE
  30183. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30184. /*** Start of inlined file: juce_Sampler.cpp ***/
  30185. BEGIN_JUCE_NAMESPACE
  30186. SamplerSound::SamplerSound (const String& name_,
  30187. AudioFormatReader& source,
  30188. const BigInteger& midiNotes_,
  30189. const int midiNoteForNormalPitch,
  30190. const double attackTimeSecs,
  30191. const double releaseTimeSecs,
  30192. const double maxSampleLengthSeconds)
  30193. : name (name_),
  30194. midiNotes (midiNotes_),
  30195. midiRootNote (midiNoteForNormalPitch)
  30196. {
  30197. sourceSampleRate = source.sampleRate;
  30198. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30199. {
  30200. length = 0;
  30201. attackSamples = 0;
  30202. releaseSamples = 0;
  30203. }
  30204. else
  30205. {
  30206. length = jmin ((int) source.lengthInSamples,
  30207. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30208. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30209. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30210. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30211. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30212. }
  30213. }
  30214. SamplerSound::~SamplerSound()
  30215. {
  30216. }
  30217. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30218. {
  30219. return midiNotes [midiNoteNumber];
  30220. }
  30221. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30222. {
  30223. return true;
  30224. }
  30225. SamplerVoice::SamplerVoice()
  30226. : pitchRatio (0.0),
  30227. sourceSamplePosition (0.0),
  30228. lgain (0.0f),
  30229. rgain (0.0f),
  30230. isInAttack (false),
  30231. isInRelease (false)
  30232. {
  30233. }
  30234. SamplerVoice::~SamplerVoice()
  30235. {
  30236. }
  30237. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30238. {
  30239. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30240. }
  30241. void SamplerVoice::startNote (const int midiNoteNumber,
  30242. const float velocity,
  30243. SynthesiserSound* s,
  30244. const int /*currentPitchWheelPosition*/)
  30245. {
  30246. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30247. jassert (sound != 0); // this object can only play SamplerSounds!
  30248. if (sound != 0)
  30249. {
  30250. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30251. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30252. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30253. sourceSamplePosition = 0.0;
  30254. lgain = velocity;
  30255. rgain = velocity;
  30256. isInAttack = (sound->attackSamples > 0);
  30257. isInRelease = false;
  30258. if (isInAttack)
  30259. {
  30260. attackReleaseLevel = 0.0f;
  30261. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30262. }
  30263. else
  30264. {
  30265. attackReleaseLevel = 1.0f;
  30266. attackDelta = 0.0f;
  30267. }
  30268. if (sound->releaseSamples > 0)
  30269. {
  30270. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30271. }
  30272. else
  30273. {
  30274. releaseDelta = 0.0f;
  30275. }
  30276. }
  30277. }
  30278. void SamplerVoice::stopNote (const bool allowTailOff)
  30279. {
  30280. if (allowTailOff)
  30281. {
  30282. isInAttack = false;
  30283. isInRelease = true;
  30284. }
  30285. else
  30286. {
  30287. clearCurrentNote();
  30288. }
  30289. }
  30290. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30291. {
  30292. }
  30293. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30294. const int /*newValue*/)
  30295. {
  30296. }
  30297. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30298. {
  30299. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30300. if (playingSound != 0)
  30301. {
  30302. const float* const inL = playingSound->data->getSampleData (0, 0);
  30303. const float* const inR = playingSound->data->getNumChannels() > 1
  30304. ? playingSound->data->getSampleData (1, 0) : 0;
  30305. float* outL = outputBuffer.getSampleData (0, startSample);
  30306. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30307. while (--numSamples >= 0)
  30308. {
  30309. const int pos = (int) sourceSamplePosition;
  30310. const float alpha = (float) (sourceSamplePosition - pos);
  30311. const float invAlpha = 1.0f - alpha;
  30312. // just using a very simple linear interpolation here..
  30313. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30314. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30315. : l;
  30316. l *= lgain;
  30317. r *= rgain;
  30318. if (isInAttack)
  30319. {
  30320. l *= attackReleaseLevel;
  30321. r *= attackReleaseLevel;
  30322. attackReleaseLevel += attackDelta;
  30323. if (attackReleaseLevel >= 1.0f)
  30324. {
  30325. attackReleaseLevel = 1.0f;
  30326. isInAttack = false;
  30327. }
  30328. }
  30329. else if (isInRelease)
  30330. {
  30331. l *= attackReleaseLevel;
  30332. r *= attackReleaseLevel;
  30333. attackReleaseLevel += releaseDelta;
  30334. if (attackReleaseLevel <= 0.0f)
  30335. {
  30336. stopNote (false);
  30337. break;
  30338. }
  30339. }
  30340. if (outR != 0)
  30341. {
  30342. *outL++ += l;
  30343. *outR++ += r;
  30344. }
  30345. else
  30346. {
  30347. *outL++ += (l + r) * 0.5f;
  30348. }
  30349. sourceSamplePosition += pitchRatio;
  30350. if (sourceSamplePosition > playingSound->length)
  30351. {
  30352. stopNote (false);
  30353. break;
  30354. }
  30355. }
  30356. }
  30357. }
  30358. END_JUCE_NAMESPACE
  30359. /*** End of inlined file: juce_Sampler.cpp ***/
  30360. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30361. BEGIN_JUCE_NAMESPACE
  30362. SynthesiserSound::SynthesiserSound()
  30363. {
  30364. }
  30365. SynthesiserSound::~SynthesiserSound()
  30366. {
  30367. }
  30368. SynthesiserVoice::SynthesiserVoice()
  30369. : currentSampleRate (44100.0),
  30370. currentlyPlayingNote (-1),
  30371. noteOnTime (0),
  30372. currentlyPlayingSound (0)
  30373. {
  30374. }
  30375. SynthesiserVoice::~SynthesiserVoice()
  30376. {
  30377. }
  30378. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30379. {
  30380. return currentlyPlayingSound != 0
  30381. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30382. }
  30383. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30384. {
  30385. currentSampleRate = newRate;
  30386. }
  30387. void SynthesiserVoice::clearCurrentNote()
  30388. {
  30389. currentlyPlayingNote = -1;
  30390. currentlyPlayingSound = 0;
  30391. }
  30392. Synthesiser::Synthesiser()
  30393. : sampleRate (0),
  30394. lastNoteOnCounter (0),
  30395. shouldStealNotes (true)
  30396. {
  30397. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30398. lastPitchWheelValues[i] = 0x2000;
  30399. }
  30400. Synthesiser::~Synthesiser()
  30401. {
  30402. }
  30403. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30404. {
  30405. const ScopedLock sl (lock);
  30406. return voices [index];
  30407. }
  30408. void Synthesiser::clearVoices()
  30409. {
  30410. const ScopedLock sl (lock);
  30411. voices.clear();
  30412. }
  30413. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30414. {
  30415. const ScopedLock sl (lock);
  30416. voices.add (newVoice);
  30417. }
  30418. void Synthesiser::removeVoice (const int index)
  30419. {
  30420. const ScopedLock sl (lock);
  30421. voices.remove (index);
  30422. }
  30423. void Synthesiser::clearSounds()
  30424. {
  30425. const ScopedLock sl (lock);
  30426. sounds.clear();
  30427. }
  30428. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30429. {
  30430. const ScopedLock sl (lock);
  30431. sounds.add (newSound);
  30432. }
  30433. void Synthesiser::removeSound (const int index)
  30434. {
  30435. const ScopedLock sl (lock);
  30436. sounds.remove (index);
  30437. }
  30438. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30439. {
  30440. shouldStealNotes = shouldStealNotes_;
  30441. }
  30442. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30443. {
  30444. if (sampleRate != newRate)
  30445. {
  30446. const ScopedLock sl (lock);
  30447. allNotesOff (0, false);
  30448. sampleRate = newRate;
  30449. for (int i = voices.size(); --i >= 0;)
  30450. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30451. }
  30452. }
  30453. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30454. const MidiBuffer& midiData,
  30455. int startSample,
  30456. int numSamples)
  30457. {
  30458. // must set the sample rate before using this!
  30459. jassert (sampleRate != 0);
  30460. const ScopedLock sl (lock);
  30461. MidiBuffer::Iterator midiIterator (midiData);
  30462. midiIterator.setNextSamplePosition (startSample);
  30463. MidiMessage m (0xf4, 0.0);
  30464. while (numSamples > 0)
  30465. {
  30466. int midiEventPos;
  30467. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30468. && midiEventPos < startSample + numSamples;
  30469. const int numThisTime = useEvent ? midiEventPos - startSample
  30470. : numSamples;
  30471. if (numThisTime > 0)
  30472. {
  30473. for (int i = voices.size(); --i >= 0;)
  30474. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30475. }
  30476. if (useEvent)
  30477. {
  30478. if (m.isNoteOn())
  30479. {
  30480. const int channel = m.getChannel();
  30481. noteOn (channel,
  30482. m.getNoteNumber(),
  30483. m.getFloatVelocity());
  30484. }
  30485. else if (m.isNoteOff())
  30486. {
  30487. noteOff (m.getChannel(),
  30488. m.getNoteNumber(),
  30489. true);
  30490. }
  30491. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30492. {
  30493. allNotesOff (m.getChannel(), true);
  30494. }
  30495. else if (m.isPitchWheel())
  30496. {
  30497. const int channel = m.getChannel();
  30498. const int wheelPos = m.getPitchWheelValue();
  30499. lastPitchWheelValues [channel - 1] = wheelPos;
  30500. handlePitchWheel (channel, wheelPos);
  30501. }
  30502. else if (m.isController())
  30503. {
  30504. handleController (m.getChannel(),
  30505. m.getControllerNumber(),
  30506. m.getControllerValue());
  30507. }
  30508. }
  30509. startSample += numThisTime;
  30510. numSamples -= numThisTime;
  30511. }
  30512. }
  30513. void Synthesiser::noteOn (const int midiChannel,
  30514. const int midiNoteNumber,
  30515. const float velocity)
  30516. {
  30517. const ScopedLock sl (lock);
  30518. for (int i = sounds.size(); --i >= 0;)
  30519. {
  30520. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30521. if (sound->appliesToNote (midiNoteNumber)
  30522. && sound->appliesToChannel (midiChannel))
  30523. {
  30524. startVoice (findFreeVoice (sound, shouldStealNotes),
  30525. sound, midiChannel, midiNoteNumber, velocity);
  30526. }
  30527. }
  30528. }
  30529. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30530. SynthesiserSound* const sound,
  30531. const int midiChannel,
  30532. const int midiNoteNumber,
  30533. const float velocity)
  30534. {
  30535. if (voice != 0 && sound != 0)
  30536. {
  30537. if (voice->currentlyPlayingSound != 0)
  30538. voice->stopNote (false);
  30539. voice->startNote (midiNoteNumber,
  30540. velocity,
  30541. sound,
  30542. lastPitchWheelValues [midiChannel - 1]);
  30543. voice->currentlyPlayingNote = midiNoteNumber;
  30544. voice->noteOnTime = ++lastNoteOnCounter;
  30545. voice->currentlyPlayingSound = sound;
  30546. }
  30547. }
  30548. void Synthesiser::noteOff (const int midiChannel,
  30549. const int midiNoteNumber,
  30550. const bool allowTailOff)
  30551. {
  30552. const ScopedLock sl (lock);
  30553. for (int i = voices.size(); --i >= 0;)
  30554. {
  30555. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30556. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30557. {
  30558. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30559. if (sound != 0
  30560. && sound->appliesToNote (midiNoteNumber)
  30561. && sound->appliesToChannel (midiChannel))
  30562. {
  30563. voice->stopNote (allowTailOff);
  30564. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30565. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30566. }
  30567. }
  30568. }
  30569. }
  30570. void Synthesiser::allNotesOff (const int midiChannel,
  30571. const bool allowTailOff)
  30572. {
  30573. const ScopedLock sl (lock);
  30574. for (int i = voices.size(); --i >= 0;)
  30575. {
  30576. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30577. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30578. voice->stopNote (allowTailOff);
  30579. }
  30580. }
  30581. void Synthesiser::handlePitchWheel (const int midiChannel,
  30582. const int wheelValue)
  30583. {
  30584. const ScopedLock sl (lock);
  30585. for (int i = voices.size(); --i >= 0;)
  30586. {
  30587. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30588. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30589. {
  30590. voice->pitchWheelMoved (wheelValue);
  30591. }
  30592. }
  30593. }
  30594. void Synthesiser::handleController (const int midiChannel,
  30595. const int controllerNumber,
  30596. const int controllerValue)
  30597. {
  30598. const ScopedLock sl (lock);
  30599. for (int i = voices.size(); --i >= 0;)
  30600. {
  30601. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30602. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30603. voice->controllerMoved (controllerNumber, controllerValue);
  30604. }
  30605. }
  30606. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30607. const bool stealIfNoneAvailable) const
  30608. {
  30609. const ScopedLock sl (lock);
  30610. for (int i = voices.size(); --i >= 0;)
  30611. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30612. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30613. return voices.getUnchecked (i);
  30614. if (stealIfNoneAvailable)
  30615. {
  30616. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30617. SynthesiserVoice* oldest = 0;
  30618. for (int i = voices.size(); --i >= 0;)
  30619. {
  30620. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30621. if (voice->canPlaySound (soundToPlay)
  30622. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30623. oldest = voice;
  30624. }
  30625. jassert (oldest != 0);
  30626. return oldest;
  30627. }
  30628. return 0;
  30629. }
  30630. END_JUCE_NAMESPACE
  30631. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30632. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30633. BEGIN_JUCE_NAMESPACE
  30634. ActionBroadcaster::ActionBroadcaster() throw()
  30635. {
  30636. // are you trying to create this object before or after juce has been intialised??
  30637. jassert (MessageManager::instance != 0);
  30638. }
  30639. ActionBroadcaster::~ActionBroadcaster()
  30640. {
  30641. // all event-based objects must be deleted BEFORE juce is shut down!
  30642. jassert (MessageManager::instance != 0);
  30643. }
  30644. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30645. {
  30646. actionListenerList.addActionListener (listener);
  30647. }
  30648. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30649. {
  30650. jassert (actionListenerList.isValidMessageListener());
  30651. if (actionListenerList.isValidMessageListener())
  30652. actionListenerList.removeActionListener (listener);
  30653. }
  30654. void ActionBroadcaster::removeAllActionListeners()
  30655. {
  30656. actionListenerList.removeAllActionListeners();
  30657. }
  30658. void ActionBroadcaster::sendActionMessage (const String& message) const
  30659. {
  30660. actionListenerList.sendActionMessage (message);
  30661. }
  30662. END_JUCE_NAMESPACE
  30663. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30664. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30665. BEGIN_JUCE_NAMESPACE
  30666. // special message of our own with a string in it
  30667. class ActionMessage : public Message
  30668. {
  30669. public:
  30670. const String message;
  30671. ActionMessage (const String& messageText, void* const listener_) throw()
  30672. : message (messageText)
  30673. {
  30674. pointerParameter = listener_;
  30675. }
  30676. ~ActionMessage() throw()
  30677. {
  30678. }
  30679. private:
  30680. ActionMessage (const ActionMessage&);
  30681. ActionMessage& operator= (const ActionMessage&);
  30682. };
  30683. ActionListenerList::ActionListenerList()
  30684. {
  30685. }
  30686. ActionListenerList::~ActionListenerList()
  30687. {
  30688. }
  30689. void ActionListenerList::addActionListener (ActionListener* const listener)
  30690. {
  30691. const ScopedLock sl (actionListenerLock_);
  30692. jassert (listener != 0);
  30693. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30694. if (listener != 0)
  30695. actionListeners_.add (listener);
  30696. }
  30697. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30698. {
  30699. const ScopedLock sl (actionListenerLock_);
  30700. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30701. actionListeners_.removeValue (listener);
  30702. }
  30703. void ActionListenerList::removeAllActionListeners()
  30704. {
  30705. const ScopedLock sl (actionListenerLock_);
  30706. actionListeners_.clear();
  30707. }
  30708. void ActionListenerList::sendActionMessage (const String& message) const
  30709. {
  30710. const ScopedLock sl (actionListenerLock_);
  30711. for (int i = actionListeners_.size(); --i >= 0;)
  30712. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30713. }
  30714. void ActionListenerList::handleMessage (const Message& message)
  30715. {
  30716. const ActionMessage& am = (const ActionMessage&) message;
  30717. if (actionListeners_.contains (am.pointerParameter))
  30718. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30719. }
  30720. END_JUCE_NAMESPACE
  30721. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30722. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30723. BEGIN_JUCE_NAMESPACE
  30724. AsyncUpdater::AsyncUpdater() throw()
  30725. : asyncMessagePending (false)
  30726. {
  30727. internalAsyncHandler.owner = this;
  30728. }
  30729. AsyncUpdater::~AsyncUpdater()
  30730. {
  30731. }
  30732. void AsyncUpdater::triggerAsyncUpdate()
  30733. {
  30734. if (! asyncMessagePending)
  30735. {
  30736. asyncMessagePending = true;
  30737. internalAsyncHandler.postMessage (new Message());
  30738. }
  30739. }
  30740. void AsyncUpdater::cancelPendingUpdate() throw()
  30741. {
  30742. asyncMessagePending = false;
  30743. }
  30744. void AsyncUpdater::handleUpdateNowIfNeeded()
  30745. {
  30746. if (asyncMessagePending)
  30747. {
  30748. asyncMessagePending = false;
  30749. handleAsyncUpdate();
  30750. }
  30751. }
  30752. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30753. {
  30754. owner->handleUpdateNowIfNeeded();
  30755. }
  30756. END_JUCE_NAMESPACE
  30757. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30758. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30759. BEGIN_JUCE_NAMESPACE
  30760. ChangeBroadcaster::ChangeBroadcaster() throw()
  30761. {
  30762. // are you trying to create this object before or after juce has been intialised??
  30763. jassert (MessageManager::instance != 0);
  30764. }
  30765. ChangeBroadcaster::~ChangeBroadcaster()
  30766. {
  30767. // all event-based objects must be deleted BEFORE juce is shut down!
  30768. jassert (MessageManager::instance != 0);
  30769. }
  30770. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30771. {
  30772. changeListenerList.addChangeListener (listener);
  30773. }
  30774. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30775. {
  30776. jassert (changeListenerList.isValidMessageListener());
  30777. if (changeListenerList.isValidMessageListener())
  30778. changeListenerList.removeChangeListener (listener);
  30779. }
  30780. void ChangeBroadcaster::removeAllChangeListeners()
  30781. {
  30782. changeListenerList.removeAllChangeListeners();
  30783. }
  30784. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30785. {
  30786. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30787. }
  30788. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30789. {
  30790. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30791. }
  30792. void ChangeBroadcaster::dispatchPendingMessages()
  30793. {
  30794. changeListenerList.dispatchPendingMessages();
  30795. }
  30796. END_JUCE_NAMESPACE
  30797. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30798. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30799. BEGIN_JUCE_NAMESPACE
  30800. ChangeListenerList::ChangeListenerList()
  30801. : lastChangedObject (0),
  30802. messagePending (false)
  30803. {
  30804. }
  30805. ChangeListenerList::~ChangeListenerList()
  30806. {
  30807. }
  30808. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30809. {
  30810. const ScopedLock sl (lock);
  30811. jassert (listener != 0);
  30812. if (listener != 0)
  30813. listeners.add (listener);
  30814. }
  30815. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30816. {
  30817. const ScopedLock sl (lock);
  30818. listeners.removeValue (listener);
  30819. }
  30820. void ChangeListenerList::removeAllChangeListeners()
  30821. {
  30822. const ScopedLock sl (lock);
  30823. listeners.clear();
  30824. }
  30825. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30826. {
  30827. const ScopedLock sl (lock);
  30828. if ((! messagePending) && (listeners.size() > 0))
  30829. {
  30830. lastChangedObject = objectThatHasChanged;
  30831. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30832. messagePending = true;
  30833. }
  30834. }
  30835. void ChangeListenerList::handleMessage (const Message& message)
  30836. {
  30837. sendSynchronousChangeMessage (message.pointerParameter);
  30838. }
  30839. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30840. {
  30841. const ScopedLock sl (lock);
  30842. messagePending = false;
  30843. for (int i = listeners.size(); --i >= 0;)
  30844. {
  30845. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30846. {
  30847. const ScopedUnlock tempUnlocker (lock);
  30848. l->changeListenerCallback (objectThatHasChanged);
  30849. }
  30850. i = jmin (i, listeners.size());
  30851. }
  30852. }
  30853. void ChangeListenerList::dispatchPendingMessages()
  30854. {
  30855. if (messagePending)
  30856. sendSynchronousChangeMessage (lastChangedObject);
  30857. }
  30858. END_JUCE_NAMESPACE
  30859. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30860. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30861. BEGIN_JUCE_NAMESPACE
  30862. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30863. const uint32 magicMessageHeaderNumber)
  30864. : Thread ("Juce IPC connection"),
  30865. callbackConnectionState (false),
  30866. useMessageThread (callbacksOnMessageThread),
  30867. magicMessageHeader (magicMessageHeaderNumber),
  30868. pipeReceiveMessageTimeout (-1)
  30869. {
  30870. }
  30871. InterprocessConnection::~InterprocessConnection()
  30872. {
  30873. callbackConnectionState = false;
  30874. disconnect();
  30875. }
  30876. bool InterprocessConnection::connectToSocket (const String& hostName,
  30877. const int portNumber,
  30878. const int timeOutMillisecs)
  30879. {
  30880. disconnect();
  30881. const ScopedLock sl (pipeAndSocketLock);
  30882. socket = new StreamingSocket();
  30883. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30884. {
  30885. connectionMadeInt();
  30886. startThread();
  30887. return true;
  30888. }
  30889. else
  30890. {
  30891. socket = 0;
  30892. return false;
  30893. }
  30894. }
  30895. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30896. const int pipeReceiveMessageTimeoutMs)
  30897. {
  30898. disconnect();
  30899. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30900. if (newPipe->openExisting (pipeName))
  30901. {
  30902. const ScopedLock sl (pipeAndSocketLock);
  30903. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30904. initialiseWithPipe (newPipe.release());
  30905. return true;
  30906. }
  30907. return false;
  30908. }
  30909. bool InterprocessConnection::createPipe (const String& pipeName,
  30910. const int pipeReceiveMessageTimeoutMs)
  30911. {
  30912. disconnect();
  30913. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30914. if (newPipe->createNewPipe (pipeName))
  30915. {
  30916. const ScopedLock sl (pipeAndSocketLock);
  30917. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30918. initialiseWithPipe (newPipe.release());
  30919. return true;
  30920. }
  30921. return false;
  30922. }
  30923. void InterprocessConnection::disconnect()
  30924. {
  30925. if (socket != 0)
  30926. socket->close();
  30927. if (pipe != 0)
  30928. {
  30929. pipe->cancelPendingReads();
  30930. pipe->close();
  30931. }
  30932. stopThread (4000);
  30933. {
  30934. const ScopedLock sl (pipeAndSocketLock);
  30935. socket = 0;
  30936. pipe = 0;
  30937. }
  30938. connectionLostInt();
  30939. }
  30940. bool InterprocessConnection::isConnected() const
  30941. {
  30942. const ScopedLock sl (pipeAndSocketLock);
  30943. return ((socket != 0 && socket->isConnected())
  30944. || (pipe != 0 && pipe->isOpen()))
  30945. && isThreadRunning();
  30946. }
  30947. const String InterprocessConnection::getConnectedHostName() const
  30948. {
  30949. if (pipe != 0)
  30950. {
  30951. return "localhost";
  30952. }
  30953. else if (socket != 0)
  30954. {
  30955. if (! socket->isLocal())
  30956. return socket->getHostName();
  30957. return "localhost";
  30958. }
  30959. return String::empty;
  30960. }
  30961. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30962. {
  30963. uint32 messageHeader[2];
  30964. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30965. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30966. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30967. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30968. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30969. size_t bytesWritten = 0;
  30970. const ScopedLock sl (pipeAndSocketLock);
  30971. if (socket != 0)
  30972. {
  30973. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30974. }
  30975. else if (pipe != 0)
  30976. {
  30977. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30978. }
  30979. if (bytesWritten < 0)
  30980. {
  30981. // error..
  30982. return false;
  30983. }
  30984. return (bytesWritten == messageData.getSize());
  30985. }
  30986. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30987. {
  30988. jassert (socket == 0);
  30989. socket = socket_;
  30990. connectionMadeInt();
  30991. startThread();
  30992. }
  30993. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30994. {
  30995. jassert (pipe == 0);
  30996. pipe = pipe_;
  30997. connectionMadeInt();
  30998. startThread();
  30999. }
  31000. const int messageMagicNumber = 0xb734128b;
  31001. void InterprocessConnection::handleMessage (const Message& message)
  31002. {
  31003. if (message.intParameter1 == messageMagicNumber)
  31004. {
  31005. switch (message.intParameter2)
  31006. {
  31007. case 0:
  31008. {
  31009. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31010. messageReceived (*data);
  31011. break;
  31012. }
  31013. case 1:
  31014. connectionMade();
  31015. break;
  31016. case 2:
  31017. connectionLost();
  31018. break;
  31019. }
  31020. }
  31021. }
  31022. void InterprocessConnection::connectionMadeInt()
  31023. {
  31024. if (! callbackConnectionState)
  31025. {
  31026. callbackConnectionState = true;
  31027. if (useMessageThread)
  31028. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31029. else
  31030. connectionMade();
  31031. }
  31032. }
  31033. void InterprocessConnection::connectionLostInt()
  31034. {
  31035. if (callbackConnectionState)
  31036. {
  31037. callbackConnectionState = false;
  31038. if (useMessageThread)
  31039. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31040. else
  31041. connectionLost();
  31042. }
  31043. }
  31044. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31045. {
  31046. jassert (callbackConnectionState);
  31047. if (useMessageThread)
  31048. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31049. else
  31050. messageReceived (data);
  31051. }
  31052. bool InterprocessConnection::readNextMessageInt()
  31053. {
  31054. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31055. uint32 messageHeader[2];
  31056. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31057. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31058. if (bytes == sizeof (messageHeader)
  31059. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31060. {
  31061. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31062. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31063. {
  31064. MemoryBlock messageData (bytesInMessage, true);
  31065. int bytesRead = 0;
  31066. while (bytesInMessage > 0)
  31067. {
  31068. if (threadShouldExit())
  31069. return false;
  31070. const int numThisTime = jmin (bytesInMessage, 65536);
  31071. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31072. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31073. if (bytesIn <= 0)
  31074. break;
  31075. bytesRead += bytesIn;
  31076. bytesInMessage -= bytesIn;
  31077. }
  31078. if (bytesRead >= 0)
  31079. deliverDataInt (messageData);
  31080. }
  31081. }
  31082. else if (bytes < 0)
  31083. {
  31084. {
  31085. const ScopedLock sl (pipeAndSocketLock);
  31086. socket = 0;
  31087. }
  31088. connectionLostInt();
  31089. return false;
  31090. }
  31091. return true;
  31092. }
  31093. void InterprocessConnection::run()
  31094. {
  31095. while (! threadShouldExit())
  31096. {
  31097. if (socket != 0)
  31098. {
  31099. const int ready = socket->waitUntilReady (true, 0);
  31100. if (ready < 0)
  31101. {
  31102. {
  31103. const ScopedLock sl (pipeAndSocketLock);
  31104. socket = 0;
  31105. }
  31106. connectionLostInt();
  31107. break;
  31108. }
  31109. else if (ready > 0)
  31110. {
  31111. if (! readNextMessageInt())
  31112. break;
  31113. }
  31114. else
  31115. {
  31116. Thread::sleep (2);
  31117. }
  31118. }
  31119. else if (pipe != 0)
  31120. {
  31121. if (! pipe->isOpen())
  31122. {
  31123. {
  31124. const ScopedLock sl (pipeAndSocketLock);
  31125. pipe = 0;
  31126. }
  31127. connectionLostInt();
  31128. break;
  31129. }
  31130. else
  31131. {
  31132. if (! readNextMessageInt())
  31133. break;
  31134. }
  31135. }
  31136. else
  31137. {
  31138. break;
  31139. }
  31140. }
  31141. }
  31142. END_JUCE_NAMESPACE
  31143. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31144. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31145. BEGIN_JUCE_NAMESPACE
  31146. InterprocessConnectionServer::InterprocessConnectionServer()
  31147. : Thread ("Juce IPC server")
  31148. {
  31149. }
  31150. InterprocessConnectionServer::~InterprocessConnectionServer()
  31151. {
  31152. stop();
  31153. }
  31154. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31155. {
  31156. stop();
  31157. socket = new StreamingSocket();
  31158. if (socket->createListener (portNumber))
  31159. {
  31160. startThread();
  31161. return true;
  31162. }
  31163. socket = 0;
  31164. return false;
  31165. }
  31166. void InterprocessConnectionServer::stop()
  31167. {
  31168. signalThreadShouldExit();
  31169. if (socket != 0)
  31170. socket->close();
  31171. stopThread (4000);
  31172. socket = 0;
  31173. }
  31174. void InterprocessConnectionServer::run()
  31175. {
  31176. while ((! threadShouldExit()) && socket != 0)
  31177. {
  31178. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31179. if (clientSocket != 0)
  31180. {
  31181. InterprocessConnection* newConnection = createConnectionObject();
  31182. if (newConnection != 0)
  31183. newConnection->initialiseWithSocket (clientSocket.release());
  31184. }
  31185. }
  31186. }
  31187. END_JUCE_NAMESPACE
  31188. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31189. /*** Start of inlined file: juce_Message.cpp ***/
  31190. BEGIN_JUCE_NAMESPACE
  31191. Message::Message() throw()
  31192. : intParameter1 (0),
  31193. intParameter2 (0),
  31194. intParameter3 (0),
  31195. pointerParameter (0)
  31196. {
  31197. }
  31198. Message::Message (const int intParameter1_,
  31199. const int intParameter2_,
  31200. const int intParameter3_,
  31201. void* const pointerParameter_) throw()
  31202. : intParameter1 (intParameter1_),
  31203. intParameter2 (intParameter2_),
  31204. intParameter3 (intParameter3_),
  31205. pointerParameter (pointerParameter_)
  31206. {
  31207. }
  31208. Message::~Message() throw()
  31209. {
  31210. }
  31211. END_JUCE_NAMESPACE
  31212. /*** End of inlined file: juce_Message.cpp ***/
  31213. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31214. BEGIN_JUCE_NAMESPACE
  31215. MessageListener::MessageListener() throw()
  31216. {
  31217. // are you trying to create a messagelistener before or after juce has been intialised??
  31218. jassert (MessageManager::instance != 0);
  31219. if (MessageManager::instance != 0)
  31220. MessageManager::instance->messageListeners.add (this);
  31221. }
  31222. MessageListener::~MessageListener()
  31223. {
  31224. if (MessageManager::instance != 0)
  31225. MessageManager::instance->messageListeners.removeValue (this);
  31226. }
  31227. void MessageListener::postMessage (Message* const message) const throw()
  31228. {
  31229. message->messageRecipient = const_cast <MessageListener*> (this);
  31230. if (MessageManager::instance == 0)
  31231. MessageManager::getInstance();
  31232. MessageManager::instance->postMessageToQueue (message);
  31233. }
  31234. bool MessageListener::isValidMessageListener() const throw()
  31235. {
  31236. return (MessageManager::instance != 0)
  31237. && MessageManager::instance->messageListeners.contains (this);
  31238. }
  31239. END_JUCE_NAMESPACE
  31240. /*** End of inlined file: juce_MessageListener.cpp ***/
  31241. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31242. BEGIN_JUCE_NAMESPACE
  31243. // platform-specific functions..
  31244. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31245. bool juce_postMessageToSystemQueue (Message* message);
  31246. MessageManager* MessageManager::instance = 0;
  31247. static const int quitMessageId = 0xfffff321;
  31248. MessageManager::MessageManager() throw()
  31249. : quitMessagePosted (false),
  31250. quitMessageReceived (false),
  31251. threadWithLock (0)
  31252. {
  31253. messageThreadId = Thread::getCurrentThreadId();
  31254. }
  31255. MessageManager::~MessageManager() throw()
  31256. {
  31257. broadcastListeners = 0;
  31258. doPlatformSpecificShutdown();
  31259. // If you hit this assertion, then you've probably leaked a Component or some other
  31260. // kind of MessageListener object...
  31261. jassert (messageListeners.size() == 0);
  31262. jassert (instance == this);
  31263. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31264. }
  31265. MessageManager* MessageManager::getInstance() throw()
  31266. {
  31267. if (instance == 0)
  31268. {
  31269. instance = new MessageManager();
  31270. doPlatformSpecificInitialisation();
  31271. }
  31272. return instance;
  31273. }
  31274. void MessageManager::postMessageToQueue (Message* const message)
  31275. {
  31276. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31277. delete message;
  31278. }
  31279. CallbackMessage::CallbackMessage() throw() {}
  31280. CallbackMessage::~CallbackMessage() throw() {}
  31281. void CallbackMessage::post()
  31282. {
  31283. if (MessageManager::instance != 0)
  31284. MessageManager::instance->postCallbackMessage (this);
  31285. }
  31286. void MessageManager::postCallbackMessage (Message* const message)
  31287. {
  31288. message->messageRecipient = 0;
  31289. postMessageToQueue (message);
  31290. }
  31291. // not for public use..
  31292. void MessageManager::deliverMessage (Message* const message)
  31293. {
  31294. const ScopedPointer <Message> messageDeleter (message);
  31295. MessageListener* const recipient = message->messageRecipient;
  31296. JUCE_TRY
  31297. {
  31298. if (messageListeners.contains (recipient))
  31299. {
  31300. recipient->handleMessage (*message);
  31301. }
  31302. else if (recipient == 0)
  31303. {
  31304. if (message->intParameter1 == quitMessageId)
  31305. {
  31306. quitMessageReceived = true;
  31307. }
  31308. else
  31309. {
  31310. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31311. if (cm != 0)
  31312. cm->messageCallback();
  31313. }
  31314. }
  31315. }
  31316. JUCE_CATCH_EXCEPTION
  31317. }
  31318. #if ! (JUCE_MAC || JUCE_IOS)
  31319. void MessageManager::runDispatchLoop()
  31320. {
  31321. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31322. runDispatchLoopUntil (-1);
  31323. }
  31324. void MessageManager::stopDispatchLoop()
  31325. {
  31326. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31327. m->messageRecipient = 0;
  31328. postMessageToQueue (m);
  31329. quitMessagePosted = true;
  31330. }
  31331. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31332. {
  31333. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31334. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31335. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31336. && ! quitMessageReceived)
  31337. {
  31338. JUCE_TRY
  31339. {
  31340. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31341. {
  31342. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31343. if (msToWait > 0)
  31344. Thread::sleep (jmin (5, msToWait));
  31345. }
  31346. }
  31347. JUCE_CATCH_EXCEPTION
  31348. }
  31349. return ! quitMessageReceived;
  31350. }
  31351. #endif
  31352. void MessageManager::deliverBroadcastMessage (const String& value)
  31353. {
  31354. if (broadcastListeners != 0)
  31355. broadcastListeners->sendActionMessage (value);
  31356. }
  31357. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31358. {
  31359. if (broadcastListeners == 0)
  31360. broadcastListeners = new ActionListenerList();
  31361. broadcastListeners->addActionListener (listener);
  31362. }
  31363. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31364. {
  31365. if (broadcastListeners != 0)
  31366. broadcastListeners->removeActionListener (listener);
  31367. }
  31368. bool MessageManager::isThisTheMessageThread() const throw()
  31369. {
  31370. return Thread::getCurrentThreadId() == messageThreadId;
  31371. }
  31372. void MessageManager::setCurrentThreadAsMessageThread()
  31373. {
  31374. if (messageThreadId != Thread::getCurrentThreadId())
  31375. {
  31376. messageThreadId = Thread::getCurrentThreadId();
  31377. // This is needed on windows to make sure the message window is created by this thread
  31378. doPlatformSpecificShutdown();
  31379. doPlatformSpecificInitialisation();
  31380. }
  31381. }
  31382. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31383. {
  31384. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31385. return thisThread == messageThreadId || thisThread == threadWithLock;
  31386. }
  31387. /* The only safe way to lock the message thread while another thread does
  31388. some work is by posting a special message, whose purpose is to tie up the event
  31389. loop until the other thread has finished its business.
  31390. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31391. get locked before making an event callback, because if the same OS lock gets indirectly
  31392. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31393. in Cocoa).
  31394. */
  31395. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31396. {
  31397. public:
  31398. SharedEvents() {}
  31399. ~SharedEvents() {}
  31400. /* This class just holds a couple of events to communicate between the BlockingMessage
  31401. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31402. this shared data must be kept in a separate, ref-counted container. */
  31403. WaitableEvent lockedEvent, releaseEvent;
  31404. private:
  31405. SharedEvents (const SharedEvents&);
  31406. SharedEvents& operator= (const SharedEvents&);
  31407. };
  31408. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31409. {
  31410. public:
  31411. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31412. ~BlockingMessage() throw() {}
  31413. void messageCallback()
  31414. {
  31415. events->lockedEvent.signal();
  31416. events->releaseEvent.wait();
  31417. }
  31418. juce_UseDebuggingNewOperator
  31419. private:
  31420. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31421. BlockingMessage (const BlockingMessage&);
  31422. BlockingMessage& operator= (const BlockingMessage&);
  31423. };
  31424. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31425. : sharedEvents (0),
  31426. locked (false)
  31427. {
  31428. init (threadToCheck, 0);
  31429. }
  31430. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31431. : sharedEvents (0),
  31432. locked (false)
  31433. {
  31434. init (0, jobToCheckForExitSignal);
  31435. }
  31436. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31437. {
  31438. if (MessageManager::instance != 0)
  31439. {
  31440. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31441. {
  31442. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31443. }
  31444. else
  31445. {
  31446. if (threadToCheck == 0 && job == 0)
  31447. {
  31448. MessageManager::instance->lockingLock.enter();
  31449. }
  31450. else
  31451. {
  31452. while (! MessageManager::instance->lockingLock.tryEnter())
  31453. {
  31454. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31455. || (job != 0 && job->shouldExit()))
  31456. return;
  31457. Thread::sleep (1);
  31458. }
  31459. }
  31460. sharedEvents = new SharedEvents();
  31461. sharedEvents->incReferenceCount();
  31462. (new BlockingMessage (sharedEvents))->post();
  31463. while (! sharedEvents->lockedEvent.wait (50))
  31464. {
  31465. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31466. || (job != 0 && job->shouldExit()))
  31467. {
  31468. sharedEvents->releaseEvent.signal();
  31469. sharedEvents->decReferenceCount();
  31470. sharedEvents = 0;
  31471. MessageManager::instance->lockingLock.exit();
  31472. return;
  31473. }
  31474. }
  31475. jassert (MessageManager::instance->threadWithLock == 0);
  31476. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31477. locked = true;
  31478. }
  31479. }
  31480. }
  31481. MessageManagerLock::~MessageManagerLock() throw()
  31482. {
  31483. if (sharedEvents != 0)
  31484. {
  31485. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31486. sharedEvents->releaseEvent.signal();
  31487. sharedEvents->decReferenceCount();
  31488. if (MessageManager::instance != 0)
  31489. {
  31490. MessageManager::instance->threadWithLock = 0;
  31491. MessageManager::instance->lockingLock.exit();
  31492. }
  31493. }
  31494. }
  31495. END_JUCE_NAMESPACE
  31496. /*** End of inlined file: juce_MessageManager.cpp ***/
  31497. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31498. BEGIN_JUCE_NAMESPACE
  31499. class MultiTimer::MultiTimerCallback : public Timer
  31500. {
  31501. public:
  31502. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31503. : timerId (timerId_),
  31504. owner (owner_)
  31505. {
  31506. }
  31507. ~MultiTimerCallback()
  31508. {
  31509. }
  31510. void timerCallback()
  31511. {
  31512. owner.timerCallback (timerId);
  31513. }
  31514. const int timerId;
  31515. private:
  31516. MultiTimer& owner;
  31517. };
  31518. MultiTimer::MultiTimer() throw()
  31519. {
  31520. }
  31521. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31522. {
  31523. }
  31524. MultiTimer::~MultiTimer()
  31525. {
  31526. const ScopedLock sl (timerListLock);
  31527. timers.clear();
  31528. }
  31529. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31530. {
  31531. const ScopedLock sl (timerListLock);
  31532. for (int i = timers.size(); --i >= 0;)
  31533. {
  31534. MultiTimerCallback* const t = timers.getUnchecked(i);
  31535. if (t->timerId == timerId)
  31536. {
  31537. t->startTimer (intervalInMilliseconds);
  31538. return;
  31539. }
  31540. }
  31541. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31542. timers.add (newTimer);
  31543. newTimer->startTimer (intervalInMilliseconds);
  31544. }
  31545. void MultiTimer::stopTimer (const int timerId) throw()
  31546. {
  31547. const ScopedLock sl (timerListLock);
  31548. for (int i = timers.size(); --i >= 0;)
  31549. {
  31550. MultiTimerCallback* const t = timers.getUnchecked(i);
  31551. if (t->timerId == timerId)
  31552. t->stopTimer();
  31553. }
  31554. }
  31555. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31556. {
  31557. const ScopedLock sl (timerListLock);
  31558. for (int i = timers.size(); --i >= 0;)
  31559. {
  31560. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31561. if (t->timerId == timerId)
  31562. return t->isTimerRunning();
  31563. }
  31564. return false;
  31565. }
  31566. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31567. {
  31568. const ScopedLock sl (timerListLock);
  31569. for (int i = timers.size(); --i >= 0;)
  31570. {
  31571. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31572. if (t->timerId == timerId)
  31573. return t->getTimerInterval();
  31574. }
  31575. return 0;
  31576. }
  31577. END_JUCE_NAMESPACE
  31578. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31579. /*** Start of inlined file: juce_Timer.cpp ***/
  31580. BEGIN_JUCE_NAMESPACE
  31581. class InternalTimerThread : private Thread,
  31582. private MessageListener,
  31583. private DeletedAtShutdown,
  31584. private AsyncUpdater
  31585. {
  31586. public:
  31587. InternalTimerThread()
  31588. : Thread ("Juce Timer"),
  31589. firstTimer (0),
  31590. callbackNeeded (0)
  31591. {
  31592. triggerAsyncUpdate();
  31593. }
  31594. ~InternalTimerThread() throw()
  31595. {
  31596. stopThread (4000);
  31597. jassert (instance == this || instance == 0);
  31598. if (instance == this)
  31599. instance = 0;
  31600. }
  31601. void run()
  31602. {
  31603. uint32 lastTime = Time::getMillisecondCounter();
  31604. while (! threadShouldExit())
  31605. {
  31606. const uint32 now = Time::getMillisecondCounter();
  31607. if (now <= lastTime)
  31608. {
  31609. wait (2);
  31610. continue;
  31611. }
  31612. const int elapsed = now - lastTime;
  31613. lastTime = now;
  31614. int timeUntilFirstTimer = 1000;
  31615. {
  31616. const ScopedLock sl (lock);
  31617. decrementAllCounters (elapsed);
  31618. if (firstTimer != 0)
  31619. timeUntilFirstTimer = firstTimer->countdownMs;
  31620. }
  31621. if (timeUntilFirstTimer <= 0)
  31622. {
  31623. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31624. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31625. but if it fails it means the message-thread changed the value from under us so at least
  31626. some processing is happenening and we can just loop around and try again
  31627. */
  31628. if (callbackNeeded.compareAndSetBool (1, 0))
  31629. {
  31630. postMessage (new Message());
  31631. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31632. when the app has a modal loop), so this is how long to wait before assuming the
  31633. message has been lost and trying again.
  31634. */
  31635. const uint32 messageDeliveryTimeout = now + 2000;
  31636. while (callbackNeeded.get() != 0)
  31637. {
  31638. wait (4);
  31639. if (threadShouldExit())
  31640. return;
  31641. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31642. break;
  31643. }
  31644. }
  31645. }
  31646. else
  31647. {
  31648. // don't wait for too long because running this loop also helps keep the
  31649. // Time::getApproximateMillisecondTimer value stay up-to-date
  31650. wait (jlimit (1, 50, timeUntilFirstTimer));
  31651. }
  31652. }
  31653. }
  31654. void callTimers()
  31655. {
  31656. const ScopedLock sl (lock);
  31657. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31658. {
  31659. Timer* const t = firstTimer;
  31660. t->countdownMs = t->periodMs;
  31661. removeTimer (t);
  31662. addTimer (t);
  31663. const ScopedUnlock ul (lock);
  31664. JUCE_TRY
  31665. {
  31666. t->timerCallback();
  31667. }
  31668. JUCE_CATCH_EXCEPTION
  31669. }
  31670. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31671. before the boolean is set. This set should never fail since if it was false in the first place,
  31672. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31673. get a message then the value is true and the other thread can only set it to true again and
  31674. we will get another callback to set it to false.
  31675. */
  31676. callbackNeeded.set (0);
  31677. }
  31678. void handleMessage (const Message&)
  31679. {
  31680. callTimers();
  31681. }
  31682. void callTimersSynchronously()
  31683. {
  31684. if (! isThreadRunning())
  31685. {
  31686. // (This is relied on by some plugins in cases where the MM has
  31687. // had to restart and the async callback never started)
  31688. cancelPendingUpdate();
  31689. triggerAsyncUpdate();
  31690. }
  31691. callTimers();
  31692. }
  31693. static void callAnyTimersSynchronously()
  31694. {
  31695. if (InternalTimerThread::instance != 0)
  31696. InternalTimerThread::instance->callTimersSynchronously();
  31697. }
  31698. static inline void add (Timer* const tim) throw()
  31699. {
  31700. if (instance == 0)
  31701. instance = new InternalTimerThread();
  31702. const ScopedLock sl (instance->lock);
  31703. instance->addTimer (tim);
  31704. }
  31705. static inline void remove (Timer* const tim) throw()
  31706. {
  31707. if (instance != 0)
  31708. {
  31709. const ScopedLock sl (instance->lock);
  31710. instance->removeTimer (tim);
  31711. }
  31712. }
  31713. static inline void resetCounter (Timer* const tim,
  31714. const int newCounter) throw()
  31715. {
  31716. if (instance != 0)
  31717. {
  31718. tim->countdownMs = newCounter;
  31719. tim->periodMs = newCounter;
  31720. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31721. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31722. {
  31723. const ScopedLock sl (instance->lock);
  31724. instance->removeTimer (tim);
  31725. instance->addTimer (tim);
  31726. }
  31727. }
  31728. }
  31729. private:
  31730. friend class Timer;
  31731. static InternalTimerThread* instance;
  31732. static CriticalSection lock;
  31733. Timer* volatile firstTimer;
  31734. Atomic <int> callbackNeeded;
  31735. void addTimer (Timer* const t) throw()
  31736. {
  31737. #if JUCE_DEBUG
  31738. Timer* tt = firstTimer;
  31739. while (tt != 0)
  31740. {
  31741. // trying to add a timer that's already here - shouldn't get to this point,
  31742. // so if you get this assertion, let me know!
  31743. jassert (tt != t);
  31744. tt = tt->next;
  31745. }
  31746. jassert (t->previous == 0 && t->next == 0);
  31747. #endif
  31748. Timer* i = firstTimer;
  31749. if (i == 0 || i->countdownMs > t->countdownMs)
  31750. {
  31751. t->next = firstTimer;
  31752. firstTimer = t;
  31753. }
  31754. else
  31755. {
  31756. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31757. i = i->next;
  31758. jassert (i != 0);
  31759. t->next = i->next;
  31760. t->previous = i;
  31761. i->next = t;
  31762. }
  31763. if (t->next != 0)
  31764. t->next->previous = t;
  31765. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31766. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31767. notify();
  31768. }
  31769. void removeTimer (Timer* const t) throw()
  31770. {
  31771. #if JUCE_DEBUG
  31772. Timer* tt = firstTimer;
  31773. bool found = false;
  31774. while (tt != 0)
  31775. {
  31776. if (tt == t)
  31777. {
  31778. found = true;
  31779. break;
  31780. }
  31781. tt = tt->next;
  31782. }
  31783. // trying to remove a timer that's not here - shouldn't get to this point,
  31784. // so if you get this assertion, let me know!
  31785. jassert (found);
  31786. #endif
  31787. if (t->previous != 0)
  31788. {
  31789. jassert (firstTimer != t);
  31790. t->previous->next = t->next;
  31791. }
  31792. else
  31793. {
  31794. jassert (firstTimer == t);
  31795. firstTimer = t->next;
  31796. }
  31797. if (t->next != 0)
  31798. t->next->previous = t->previous;
  31799. t->next = 0;
  31800. t->previous = 0;
  31801. }
  31802. void decrementAllCounters (const int numMillisecs) const
  31803. {
  31804. Timer* t = firstTimer;
  31805. while (t != 0)
  31806. {
  31807. t->countdownMs -= numMillisecs;
  31808. t = t->next;
  31809. }
  31810. }
  31811. void handleAsyncUpdate()
  31812. {
  31813. startThread (7);
  31814. }
  31815. InternalTimerThread (const InternalTimerThread&);
  31816. InternalTimerThread& operator= (const InternalTimerThread&);
  31817. };
  31818. InternalTimerThread* InternalTimerThread::instance = 0;
  31819. CriticalSection InternalTimerThread::lock;
  31820. void juce_callAnyTimersSynchronously()
  31821. {
  31822. InternalTimerThread::callAnyTimersSynchronously();
  31823. }
  31824. #if JUCE_DEBUG
  31825. static SortedSet <Timer*> activeTimers;
  31826. #endif
  31827. Timer::Timer() throw()
  31828. : countdownMs (0),
  31829. periodMs (0),
  31830. previous (0),
  31831. next (0)
  31832. {
  31833. #if JUCE_DEBUG
  31834. activeTimers.add (this);
  31835. #endif
  31836. }
  31837. Timer::Timer (const Timer&) throw()
  31838. : countdownMs (0),
  31839. periodMs (0),
  31840. previous (0),
  31841. next (0)
  31842. {
  31843. #if JUCE_DEBUG
  31844. activeTimers.add (this);
  31845. #endif
  31846. }
  31847. Timer::~Timer()
  31848. {
  31849. stopTimer();
  31850. #if JUCE_DEBUG
  31851. activeTimers.removeValue (this);
  31852. #endif
  31853. }
  31854. void Timer::startTimer (const int interval) throw()
  31855. {
  31856. const ScopedLock sl (InternalTimerThread::lock);
  31857. #if JUCE_DEBUG
  31858. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31859. jassert (activeTimers.contains (this));
  31860. #endif
  31861. if (periodMs == 0)
  31862. {
  31863. countdownMs = interval;
  31864. periodMs = jmax (1, interval);
  31865. InternalTimerThread::add (this);
  31866. }
  31867. else
  31868. {
  31869. InternalTimerThread::resetCounter (this, interval);
  31870. }
  31871. }
  31872. void Timer::stopTimer() throw()
  31873. {
  31874. const ScopedLock sl (InternalTimerThread::lock);
  31875. #if JUCE_DEBUG
  31876. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31877. jassert (activeTimers.contains (this));
  31878. #endif
  31879. if (periodMs > 0)
  31880. {
  31881. InternalTimerThread::remove (this);
  31882. periodMs = 0;
  31883. }
  31884. }
  31885. END_JUCE_NAMESPACE
  31886. /*** End of inlined file: juce_Timer.cpp ***/
  31887. #endif
  31888. #if JUCE_BUILD_GUI
  31889. /*** Start of inlined file: juce_Component.cpp ***/
  31890. BEGIN_JUCE_NAMESPACE
  31891. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31892. enum ComponentMessageNumbers
  31893. {
  31894. customCommandMessage = 0x7fff0001,
  31895. exitModalStateMessage = 0x7fff0002
  31896. };
  31897. static uint32 nextComponentUID = 0;
  31898. Component* Component::currentlyFocusedComponent = 0;
  31899. Component::Component()
  31900. : parentComponent_ (0),
  31901. componentUID (++nextComponentUID),
  31902. numDeepMouseListeners (0),
  31903. lookAndFeel_ (0),
  31904. effect_ (0),
  31905. bufferedImage_ (0),
  31906. mouseListeners_ (0),
  31907. keyListeners_ (0),
  31908. componentFlags_ (0)
  31909. {
  31910. }
  31911. Component::Component (const String& name)
  31912. : componentName_ (name),
  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()
  31925. {
  31926. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31927. if (parentComponent_ != 0)
  31928. {
  31929. parentComponent_->removeChildComponent (this);
  31930. }
  31931. else if ((currentlyFocusedComponent == this)
  31932. || isParentOf (currentlyFocusedComponent))
  31933. {
  31934. giveAwayFocus();
  31935. }
  31936. if (flags.hasHeavyweightPeerFlag)
  31937. removeFromDesktop();
  31938. for (int i = childComponentList_.size(); --i >= 0;)
  31939. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31940. delete mouseListeners_;
  31941. delete keyListeners_;
  31942. }
  31943. void Component::setName (const String& name)
  31944. {
  31945. // if component methods are being called from threads other than the message
  31946. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31947. checkMessageManagerIsLocked
  31948. if (componentName_ != name)
  31949. {
  31950. componentName_ = name;
  31951. if (flags.hasHeavyweightPeerFlag)
  31952. {
  31953. ComponentPeer* const peer = getPeer();
  31954. jassert (peer != 0);
  31955. if (peer != 0)
  31956. peer->setTitle (name);
  31957. }
  31958. BailOutChecker checker (this);
  31959. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31960. }
  31961. }
  31962. void Component::setVisible (bool shouldBeVisible)
  31963. {
  31964. if (flags.visibleFlag != shouldBeVisible)
  31965. {
  31966. // if component methods are being called from threads other than the message
  31967. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31968. checkMessageManagerIsLocked
  31969. SafePointer<Component> safePointer (this);
  31970. flags.visibleFlag = shouldBeVisible;
  31971. internalRepaint (0, 0, getWidth(), getHeight());
  31972. sendFakeMouseMove();
  31973. if (! shouldBeVisible)
  31974. {
  31975. if (currentlyFocusedComponent == this
  31976. || isParentOf (currentlyFocusedComponent))
  31977. {
  31978. if (parentComponent_ != 0)
  31979. parentComponent_->grabKeyboardFocus();
  31980. else
  31981. giveAwayFocus();
  31982. }
  31983. }
  31984. if (safePointer != 0)
  31985. {
  31986. sendVisibilityChangeMessage();
  31987. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31988. {
  31989. ComponentPeer* const peer = getPeer();
  31990. jassert (peer != 0);
  31991. if (peer != 0)
  31992. {
  31993. peer->setVisible (shouldBeVisible);
  31994. internalHierarchyChanged();
  31995. }
  31996. }
  31997. }
  31998. }
  31999. }
  32000. void Component::visibilityChanged()
  32001. {
  32002. }
  32003. void Component::sendVisibilityChangeMessage()
  32004. {
  32005. BailOutChecker checker (this);
  32006. visibilityChanged();
  32007. if (! checker.shouldBailOut())
  32008. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32009. }
  32010. bool Component::isShowing() const
  32011. {
  32012. if (flags.visibleFlag)
  32013. {
  32014. if (parentComponent_ != 0)
  32015. {
  32016. return parentComponent_->isShowing();
  32017. }
  32018. else
  32019. {
  32020. const ComponentPeer* const peer = getPeer();
  32021. return peer != 0 && ! peer->isMinimised();
  32022. }
  32023. }
  32024. return false;
  32025. }
  32026. class FadeOutProxyComponent : public Component,
  32027. public Timer
  32028. {
  32029. public:
  32030. FadeOutProxyComponent (Component* comp,
  32031. const int fadeLengthMs,
  32032. const int deltaXToMove,
  32033. const int deltaYToMove,
  32034. const float scaleFactorAtEnd)
  32035. : lastTime (0),
  32036. alpha (1.0f),
  32037. scale (1.0f)
  32038. {
  32039. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32040. setBounds (comp->getBounds());
  32041. comp->getParentComponent()->addAndMakeVisible (this);
  32042. toBehind (comp);
  32043. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32044. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32045. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32046. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32047. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32048. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32049. setInterceptsMouseClicks (false, false);
  32050. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32051. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32052. }
  32053. ~FadeOutProxyComponent()
  32054. {
  32055. }
  32056. void paint (Graphics& g)
  32057. {
  32058. g.setOpacity (alpha);
  32059. g.drawImage (image,
  32060. 0, 0, getWidth(), getHeight(),
  32061. 0, 0, image.getWidth(), image.getHeight());
  32062. }
  32063. void timerCallback()
  32064. {
  32065. const uint32 now = Time::getMillisecondCounter();
  32066. if (lastTime == 0)
  32067. lastTime = now;
  32068. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32069. lastTime = now;
  32070. alpha += alphaChangePerMs * msPassed;
  32071. if (alpha > 0)
  32072. {
  32073. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32074. {
  32075. centreX += xChangePerMs * msPassed;
  32076. centreY += yChangePerMs * msPassed;
  32077. scale += scaleChangePerMs * msPassed;
  32078. const int w = roundToInt (image.getWidth() * scale);
  32079. const int h = roundToInt (image.getHeight() * scale);
  32080. setBounds (roundToInt (centreX) - w / 2,
  32081. roundToInt (centreY) - h / 2,
  32082. w, h);
  32083. }
  32084. repaint();
  32085. }
  32086. else
  32087. {
  32088. delete this;
  32089. }
  32090. }
  32091. juce_UseDebuggingNewOperator
  32092. private:
  32093. Image image;
  32094. uint32 lastTime;
  32095. float alpha, alphaChangePerMs;
  32096. float centreX, xChangePerMs;
  32097. float centreY, yChangePerMs;
  32098. float scale, scaleChangePerMs;
  32099. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32100. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32101. };
  32102. void Component::fadeOutComponent (const int millisecondsToFade,
  32103. const int deltaXToMove,
  32104. const int deltaYToMove,
  32105. const float scaleFactorAtEnd)
  32106. {
  32107. //xxx won't work for comps without parents
  32108. if (isShowing() && millisecondsToFade > 0)
  32109. new FadeOutProxyComponent (this, millisecondsToFade,
  32110. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32111. setVisible (false);
  32112. }
  32113. bool Component::isValidComponent() const
  32114. {
  32115. return (this != 0) && isValidMessageListener();
  32116. }
  32117. void* Component::getWindowHandle() const
  32118. {
  32119. const ComponentPeer* const peer = getPeer();
  32120. if (peer != 0)
  32121. return peer->getNativeHandle();
  32122. return 0;
  32123. }
  32124. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32125. {
  32126. // if component methods are being called from threads other than the message
  32127. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32128. checkMessageManagerIsLocked
  32129. if (isOpaque())
  32130. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32131. else
  32132. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32133. int currentStyleFlags = 0;
  32134. // don't use getPeer(), so that we only get the peer that's specifically
  32135. // for this comp, and not for one of its parents.
  32136. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32137. if (peer != 0)
  32138. currentStyleFlags = peer->getStyleFlags();
  32139. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32140. {
  32141. SafePointer<Component> safePointer (this);
  32142. #if JUCE_LINUX
  32143. // it's wise to give the component a non-zero size before
  32144. // putting it on the desktop, as X windows get confused by this, and
  32145. // a (1, 1) minimum size is enforced here.
  32146. setSize (jmax (1, getWidth()),
  32147. jmax (1, getHeight()));
  32148. #endif
  32149. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32150. bool wasFullscreen = false;
  32151. bool wasMinimised = false;
  32152. ComponentBoundsConstrainer* currentConstainer = 0;
  32153. Rectangle<int> oldNonFullScreenBounds;
  32154. if (peer != 0)
  32155. {
  32156. wasFullscreen = peer->isFullScreen();
  32157. wasMinimised = peer->isMinimised();
  32158. currentConstainer = peer->getConstrainer();
  32159. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32160. removeFromDesktop();
  32161. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32162. }
  32163. if (parentComponent_ != 0)
  32164. parentComponent_->removeChildComponent (this);
  32165. if (safePointer != 0)
  32166. {
  32167. flags.hasHeavyweightPeerFlag = true;
  32168. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32169. Desktop::getInstance().addDesktopComponent (this);
  32170. bounds_.setPosition (topLeft);
  32171. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32172. peer->setVisible (isVisible());
  32173. if (wasFullscreen)
  32174. {
  32175. peer->setFullScreen (true);
  32176. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32177. }
  32178. if (wasMinimised)
  32179. peer->setMinimised (true);
  32180. if (isAlwaysOnTop())
  32181. peer->setAlwaysOnTop (true);
  32182. peer->setConstrainer (currentConstainer);
  32183. repaint();
  32184. }
  32185. internalHierarchyChanged();
  32186. }
  32187. }
  32188. void Component::removeFromDesktop()
  32189. {
  32190. // if component methods are being called from threads other than the message
  32191. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32192. checkMessageManagerIsLocked
  32193. if (flags.hasHeavyweightPeerFlag)
  32194. {
  32195. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32196. flags.hasHeavyweightPeerFlag = false;
  32197. jassert (peer != 0);
  32198. delete peer;
  32199. Desktop::getInstance().removeDesktopComponent (this);
  32200. }
  32201. }
  32202. bool Component::isOnDesktop() const throw()
  32203. {
  32204. return flags.hasHeavyweightPeerFlag;
  32205. }
  32206. void Component::userTriedToCloseWindow()
  32207. {
  32208. /* This means that the user's trying to get rid of your window with the 'close window' system
  32209. menu option (on windows) or possibly the task manager - you should really handle this
  32210. and delete or hide your component in an appropriate way.
  32211. If you want to ignore the event and don't want to trigger this assertion, just override
  32212. this method and do nothing.
  32213. */
  32214. jassertfalse;
  32215. }
  32216. void Component::minimisationStateChanged (bool)
  32217. {
  32218. }
  32219. void Component::setOpaque (const bool shouldBeOpaque)
  32220. {
  32221. if (shouldBeOpaque != flags.opaqueFlag)
  32222. {
  32223. flags.opaqueFlag = shouldBeOpaque;
  32224. if (flags.hasHeavyweightPeerFlag)
  32225. {
  32226. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32227. if (peer != 0)
  32228. {
  32229. // to make it recreate the heavyweight window
  32230. addToDesktop (peer->getStyleFlags());
  32231. }
  32232. }
  32233. repaint();
  32234. }
  32235. }
  32236. bool Component::isOpaque() const throw()
  32237. {
  32238. return flags.opaqueFlag;
  32239. }
  32240. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32241. {
  32242. if (shouldBeBuffered != flags.bufferToImageFlag)
  32243. {
  32244. bufferedImage_ = Image::null;
  32245. flags.bufferToImageFlag = shouldBeBuffered;
  32246. }
  32247. }
  32248. void Component::toFront (const bool setAsForeground)
  32249. {
  32250. // if component methods are being called from threads other than the message
  32251. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32252. checkMessageManagerIsLocked
  32253. if (flags.hasHeavyweightPeerFlag)
  32254. {
  32255. ComponentPeer* const peer = getPeer();
  32256. if (peer != 0)
  32257. {
  32258. peer->toFront (setAsForeground);
  32259. if (setAsForeground && ! hasKeyboardFocus (true))
  32260. grabKeyboardFocus();
  32261. }
  32262. }
  32263. else if (parentComponent_ != 0)
  32264. {
  32265. Array<Component*>& childList = parentComponent_->childComponentList_;
  32266. if (childList.getLast() != this)
  32267. {
  32268. const int index = childList.indexOf (this);
  32269. if (index >= 0)
  32270. {
  32271. int insertIndex = -1;
  32272. if (! flags.alwaysOnTopFlag)
  32273. {
  32274. insertIndex = childList.size() - 1;
  32275. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32276. --insertIndex;
  32277. }
  32278. if (index != insertIndex)
  32279. {
  32280. childList.move (index, insertIndex);
  32281. sendFakeMouseMove();
  32282. repaintParent();
  32283. }
  32284. }
  32285. }
  32286. if (setAsForeground)
  32287. {
  32288. internalBroughtToFront();
  32289. grabKeyboardFocus();
  32290. }
  32291. }
  32292. }
  32293. void Component::toBehind (Component* const other)
  32294. {
  32295. if (other != 0 && other != this)
  32296. {
  32297. // the two components must belong to the same parent..
  32298. jassert (parentComponent_ == other->parentComponent_);
  32299. if (parentComponent_ != 0)
  32300. {
  32301. Array<Component*>& childList = parentComponent_->childComponentList_;
  32302. const int index = childList.indexOf (this);
  32303. if (index >= 0 && childList [index + 1] != other)
  32304. {
  32305. int otherIndex = childList.indexOf (other);
  32306. if (otherIndex >= 0)
  32307. {
  32308. if (index < otherIndex)
  32309. --otherIndex;
  32310. childList.move (index, otherIndex);
  32311. sendFakeMouseMove();
  32312. repaintParent();
  32313. }
  32314. }
  32315. }
  32316. else if (isOnDesktop())
  32317. {
  32318. jassert (other->isOnDesktop());
  32319. if (other->isOnDesktop())
  32320. {
  32321. ComponentPeer* const us = getPeer();
  32322. ComponentPeer* const them = other->getPeer();
  32323. jassert (us != 0 && them != 0);
  32324. if (us != 0 && them != 0)
  32325. us->toBehind (them);
  32326. }
  32327. }
  32328. }
  32329. }
  32330. void Component::toBack()
  32331. {
  32332. Array<Component*>& childList = parentComponent_->childComponentList_;
  32333. if (isOnDesktop())
  32334. {
  32335. jassertfalse; //xxx need to add this to native window
  32336. }
  32337. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32338. {
  32339. const int index = childList.indexOf (this);
  32340. if (index > 0)
  32341. {
  32342. int insertIndex = 0;
  32343. if (flags.alwaysOnTopFlag)
  32344. {
  32345. while (insertIndex < childList.size()
  32346. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32347. {
  32348. ++insertIndex;
  32349. }
  32350. }
  32351. if (index != insertIndex)
  32352. {
  32353. childList.move (index, insertIndex);
  32354. sendFakeMouseMove();
  32355. repaintParent();
  32356. }
  32357. }
  32358. }
  32359. }
  32360. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32361. {
  32362. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32363. {
  32364. flags.alwaysOnTopFlag = shouldStayOnTop;
  32365. if (isOnDesktop())
  32366. {
  32367. ComponentPeer* const peer = getPeer();
  32368. jassert (peer != 0);
  32369. if (peer != 0)
  32370. {
  32371. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32372. {
  32373. // some kinds of peer can't change their always-on-top status, so
  32374. // for these, we'll need to create a new window
  32375. const int oldFlags = peer->getStyleFlags();
  32376. removeFromDesktop();
  32377. addToDesktop (oldFlags);
  32378. }
  32379. }
  32380. }
  32381. if (shouldStayOnTop)
  32382. toFront (false);
  32383. internalHierarchyChanged();
  32384. }
  32385. }
  32386. bool Component::isAlwaysOnTop() const throw()
  32387. {
  32388. return flags.alwaysOnTopFlag;
  32389. }
  32390. int Component::proportionOfWidth (const float proportion) const throw()
  32391. {
  32392. return roundToInt (proportion * bounds_.getWidth());
  32393. }
  32394. int Component::proportionOfHeight (const float proportion) const throw()
  32395. {
  32396. return roundToInt (proportion * bounds_.getHeight());
  32397. }
  32398. int Component::getParentWidth() const throw()
  32399. {
  32400. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32401. : getParentMonitorArea().getWidth();
  32402. }
  32403. int Component::getParentHeight() const throw()
  32404. {
  32405. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32406. : getParentMonitorArea().getHeight();
  32407. }
  32408. int Component::getScreenX() const
  32409. {
  32410. return getScreenPosition().getX();
  32411. }
  32412. int Component::getScreenY() const
  32413. {
  32414. return getScreenPosition().getY();
  32415. }
  32416. const Point<int> Component::getScreenPosition() const
  32417. {
  32418. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32419. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32420. : getPosition());
  32421. }
  32422. const Rectangle<int> Component::getScreenBounds() const
  32423. {
  32424. return bounds_.withPosition (getScreenPosition());
  32425. }
  32426. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32427. {
  32428. const Component* c = this;
  32429. Point<int> p (relativePosition);
  32430. do
  32431. {
  32432. if (c->flags.hasHeavyweightPeerFlag)
  32433. return c->getPeer()->relativePositionToGlobal (p);
  32434. p += c->getPosition();
  32435. c = c->parentComponent_;
  32436. }
  32437. while (c != 0);
  32438. return p;
  32439. }
  32440. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32441. {
  32442. if (flags.hasHeavyweightPeerFlag)
  32443. {
  32444. return getPeer()->globalPositionToRelative (screenPosition);
  32445. }
  32446. else
  32447. {
  32448. if (parentComponent_ != 0)
  32449. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32450. return screenPosition - getPosition();
  32451. }
  32452. }
  32453. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32454. {
  32455. Point<int> p (positionRelativeToThis);
  32456. if (targetComponent != 0)
  32457. {
  32458. const Component* c = this;
  32459. do
  32460. {
  32461. if (c == targetComponent)
  32462. return p;
  32463. if (c->flags.hasHeavyweightPeerFlag)
  32464. {
  32465. p = c->getPeer()->relativePositionToGlobal (p);
  32466. break;
  32467. }
  32468. p += c->getPosition();
  32469. c = c->parentComponent_;
  32470. }
  32471. while (c != 0);
  32472. p = targetComponent->globalPositionToRelative (p);
  32473. }
  32474. return p;
  32475. }
  32476. void Component::setBounds (const int x, const int y, int w, int h)
  32477. {
  32478. // if component methods are being called from threads other than the message
  32479. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32480. checkMessageManagerIsLocked
  32481. if (w < 0) w = 0;
  32482. if (h < 0) h = 0;
  32483. const bool wasResized = (getWidth() != w || getHeight() != h);
  32484. const bool wasMoved = (getX() != x || getY() != y);
  32485. #if JUCE_DEBUG
  32486. // It's a very bad idea to try to resize a window during its paint() method!
  32487. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32488. #endif
  32489. if (wasMoved || wasResized)
  32490. {
  32491. if (flags.visibleFlag)
  32492. {
  32493. // send a fake mouse move to trigger enter/exit messages if needed..
  32494. sendFakeMouseMove();
  32495. if (! flags.hasHeavyweightPeerFlag)
  32496. repaintParent();
  32497. }
  32498. bounds_.setBounds (x, y, w, h);
  32499. if (wasResized)
  32500. repaint();
  32501. else if (! flags.hasHeavyweightPeerFlag)
  32502. repaintParent();
  32503. if (flags.hasHeavyweightPeerFlag)
  32504. {
  32505. ComponentPeer* const peer = getPeer();
  32506. if (peer != 0)
  32507. {
  32508. if (wasMoved && wasResized)
  32509. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32510. else if (wasMoved)
  32511. peer->setPosition (getX(), getY());
  32512. else if (wasResized)
  32513. peer->setSize (getWidth(), getHeight());
  32514. }
  32515. }
  32516. sendMovedResizedMessages (wasMoved, wasResized);
  32517. }
  32518. }
  32519. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32520. {
  32521. JUCE_TRY
  32522. {
  32523. if (wasMoved)
  32524. moved();
  32525. if (wasResized)
  32526. {
  32527. resized();
  32528. for (int i = childComponentList_.size(); --i >= 0;)
  32529. {
  32530. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32531. i = jmin (i, childComponentList_.size());
  32532. }
  32533. }
  32534. BailOutChecker checker (this);
  32535. if (parentComponent_ != 0)
  32536. parentComponent_->childBoundsChanged (this);
  32537. if (! checker.shouldBailOut())
  32538. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32539. *this, wasMoved, wasResized);
  32540. }
  32541. JUCE_CATCH_EXCEPTION
  32542. }
  32543. void Component::setSize (const int w, const int h)
  32544. {
  32545. setBounds (getX(), getY(), w, h);
  32546. }
  32547. void Component::setTopLeftPosition (const int x, const int y)
  32548. {
  32549. setBounds (x, y, getWidth(), getHeight());
  32550. }
  32551. void Component::setTopRightPosition (const int x, const int y)
  32552. {
  32553. setTopLeftPosition (x - getWidth(), y);
  32554. }
  32555. void Component::setBounds (const Rectangle<int>& r)
  32556. {
  32557. setBounds (r.getX(),
  32558. r.getY(),
  32559. r.getWidth(),
  32560. r.getHeight());
  32561. }
  32562. void Component::setBoundsRelative (const float x, const float y,
  32563. const float w, const float h)
  32564. {
  32565. const int pw = getParentWidth();
  32566. const int ph = getParentHeight();
  32567. setBounds (roundToInt (x * pw),
  32568. roundToInt (y * ph),
  32569. roundToInt (w * pw),
  32570. roundToInt (h * ph));
  32571. }
  32572. void Component::setCentrePosition (const int x, const int y)
  32573. {
  32574. setTopLeftPosition (x - getWidth() / 2,
  32575. y - getHeight() / 2);
  32576. }
  32577. void Component::setCentreRelative (const float x, const float y)
  32578. {
  32579. setCentrePosition (roundToInt (getParentWidth() * x),
  32580. roundToInt (getParentHeight() * y));
  32581. }
  32582. void Component::centreWithSize (const int width, const int height)
  32583. {
  32584. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32585. setBounds (parentArea.getCentreX() - width / 2,
  32586. parentArea.getCentreY() - height / 2,
  32587. width, height);
  32588. }
  32589. void Component::setBoundsInset (const BorderSize& borders)
  32590. {
  32591. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32592. }
  32593. void Component::setBoundsToFit (int x, int y, int width, int height,
  32594. const Justification& justification,
  32595. const bool onlyReduceInSize)
  32596. {
  32597. // it's no good calling this method unless both the component and
  32598. // target rectangle have a finite size.
  32599. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32600. if (getWidth() > 0 && getHeight() > 0
  32601. && width > 0 && height > 0)
  32602. {
  32603. int newW, newH;
  32604. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32605. {
  32606. newW = getWidth();
  32607. newH = getHeight();
  32608. }
  32609. else
  32610. {
  32611. const double imageRatio = getHeight() / (double) getWidth();
  32612. const double targetRatio = height / (double) width;
  32613. if (imageRatio <= targetRatio)
  32614. {
  32615. newW = width;
  32616. newH = jmin (height, roundToInt (newW * imageRatio));
  32617. }
  32618. else
  32619. {
  32620. newH = height;
  32621. newW = jmin (width, roundToInt (newH / imageRatio));
  32622. }
  32623. }
  32624. if (newW > 0 && newH > 0)
  32625. {
  32626. int newX, newY;
  32627. justification.applyToRectangle (newX, newY, newW, newH,
  32628. x, y, width, height);
  32629. setBounds (newX, newY, newW, newH);
  32630. }
  32631. }
  32632. }
  32633. bool Component::hitTest (int x, int y)
  32634. {
  32635. if (! flags.ignoresMouseClicksFlag)
  32636. return true;
  32637. if (flags.allowChildMouseClicksFlag)
  32638. {
  32639. for (int i = getNumChildComponents(); --i >= 0;)
  32640. {
  32641. Component* const c = getChildComponent (i);
  32642. if (c->isVisible()
  32643. && c->bounds_.contains (x, y)
  32644. && c->hitTest (x - c->getX(),
  32645. y - c->getY()))
  32646. {
  32647. return true;
  32648. }
  32649. }
  32650. }
  32651. return false;
  32652. }
  32653. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32654. const bool allowClicksOnChildComponents) throw()
  32655. {
  32656. flags.ignoresMouseClicksFlag = ! allowClicks;
  32657. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32658. }
  32659. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32660. bool& allowsClicksOnChildComponents) const throw()
  32661. {
  32662. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32663. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32664. }
  32665. bool Component::contains (const int x, const int y)
  32666. {
  32667. if (((unsigned int) x) < (unsigned int) getWidth()
  32668. && ((unsigned int) y) < (unsigned int) getHeight()
  32669. && hitTest (x, y))
  32670. {
  32671. if (parentComponent_ != 0)
  32672. {
  32673. return parentComponent_->contains (x + getX(),
  32674. y + getY());
  32675. }
  32676. else if (flags.hasHeavyweightPeerFlag)
  32677. {
  32678. const ComponentPeer* const peer = getPeer();
  32679. if (peer != 0)
  32680. return peer->contains (Point<int> (x, y), true);
  32681. }
  32682. }
  32683. return false;
  32684. }
  32685. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32686. {
  32687. if (! contains (x, y))
  32688. return false;
  32689. Component* p = this;
  32690. while (p->parentComponent_ != 0)
  32691. {
  32692. x += p->getX();
  32693. y += p->getY();
  32694. p = p->parentComponent_;
  32695. }
  32696. const Component* const c = p->getComponentAt (x, y);
  32697. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32698. }
  32699. Component* Component::getComponentAt (const Point<int>& position)
  32700. {
  32701. return getComponentAt (position.getX(), position.getY());
  32702. }
  32703. Component* Component::getComponentAt (const int x, const int y)
  32704. {
  32705. if (flags.visibleFlag
  32706. && ((unsigned int) x) < (unsigned int) getWidth()
  32707. && ((unsigned int) y) < (unsigned int) getHeight()
  32708. && hitTest (x, y))
  32709. {
  32710. for (int i = childComponentList_.size(); --i >= 0;)
  32711. {
  32712. Component* const child = childComponentList_.getUnchecked(i);
  32713. Component* const c = child->getComponentAt (x - child->getX(),
  32714. y - child->getY());
  32715. if (c != 0)
  32716. return c;
  32717. }
  32718. return this;
  32719. }
  32720. return 0;
  32721. }
  32722. void Component::addChildComponent (Component* const child, int zOrder)
  32723. {
  32724. // if component methods are being called from threads other than the message
  32725. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32726. checkMessageManagerIsLocked
  32727. if (child != 0 && child->parentComponent_ != this)
  32728. {
  32729. if (child->parentComponent_ != 0)
  32730. child->parentComponent_->removeChildComponent (child);
  32731. else
  32732. child->removeFromDesktop();
  32733. child->parentComponent_ = this;
  32734. if (child->isVisible())
  32735. child->repaintParent();
  32736. if (! child->isAlwaysOnTop())
  32737. {
  32738. if (zOrder < 0 || zOrder > childComponentList_.size())
  32739. zOrder = childComponentList_.size();
  32740. while (zOrder > 0)
  32741. {
  32742. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32743. break;
  32744. --zOrder;
  32745. }
  32746. }
  32747. childComponentList_.insert (zOrder, child);
  32748. child->internalHierarchyChanged();
  32749. internalChildrenChanged();
  32750. }
  32751. }
  32752. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32753. {
  32754. if (child != 0)
  32755. {
  32756. child->setVisible (true);
  32757. addChildComponent (child, zOrder);
  32758. }
  32759. }
  32760. void Component::removeChildComponent (Component* const child)
  32761. {
  32762. removeChildComponent (childComponentList_.indexOf (child));
  32763. }
  32764. Component* Component::removeChildComponent (const int index)
  32765. {
  32766. // if component methods are being called from threads other than the message
  32767. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32768. checkMessageManagerIsLocked
  32769. Component* const child = childComponentList_ [index];
  32770. if (child != 0)
  32771. {
  32772. sendFakeMouseMove();
  32773. child->repaintParent();
  32774. childComponentList_.remove (index);
  32775. child->parentComponent_ = 0;
  32776. JUCE_TRY
  32777. {
  32778. if ((currentlyFocusedComponent == child)
  32779. || child->isParentOf (currentlyFocusedComponent))
  32780. {
  32781. // get rid first to force the grabKeyboardFocus to change to us.
  32782. giveAwayFocus();
  32783. grabKeyboardFocus();
  32784. }
  32785. }
  32786. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32787. catch (const std::exception& e)
  32788. {
  32789. currentlyFocusedComponent = 0;
  32790. Desktop::getInstance().triggerFocusCallback();
  32791. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32792. }
  32793. catch (...)
  32794. {
  32795. currentlyFocusedComponent = 0;
  32796. Desktop::getInstance().triggerFocusCallback();
  32797. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32798. }
  32799. #endif
  32800. child->internalHierarchyChanged();
  32801. internalChildrenChanged();
  32802. }
  32803. return child;
  32804. }
  32805. void Component::removeAllChildren()
  32806. {
  32807. while (childComponentList_.size() > 0)
  32808. removeChildComponent (childComponentList_.size() - 1);
  32809. }
  32810. void Component::deleteAllChildren()
  32811. {
  32812. while (childComponentList_.size() > 0)
  32813. delete (removeChildComponent (childComponentList_.size() - 1));
  32814. }
  32815. int Component::getNumChildComponents() const throw()
  32816. {
  32817. return childComponentList_.size();
  32818. }
  32819. Component* Component::getChildComponent (const int index) const throw()
  32820. {
  32821. return childComponentList_ [index];
  32822. }
  32823. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32824. {
  32825. return childComponentList_.indexOf (const_cast <Component*> (child));
  32826. }
  32827. Component* Component::getTopLevelComponent() const throw()
  32828. {
  32829. const Component* comp = this;
  32830. while (comp->parentComponent_ != 0)
  32831. comp = comp->parentComponent_;
  32832. return const_cast <Component*> (comp);
  32833. }
  32834. bool Component::isParentOf (const Component* possibleChild) const throw()
  32835. {
  32836. if (! possibleChild->isValidComponent())
  32837. {
  32838. jassert (possibleChild == 0);
  32839. return false;
  32840. }
  32841. while (possibleChild != 0)
  32842. {
  32843. possibleChild = possibleChild->parentComponent_;
  32844. if (possibleChild == this)
  32845. return true;
  32846. }
  32847. return false;
  32848. }
  32849. void Component::parentHierarchyChanged()
  32850. {
  32851. }
  32852. void Component::childrenChanged()
  32853. {
  32854. }
  32855. void Component::internalChildrenChanged()
  32856. {
  32857. if (componentListeners.isEmpty())
  32858. {
  32859. childrenChanged();
  32860. }
  32861. else
  32862. {
  32863. BailOutChecker checker (this);
  32864. childrenChanged();
  32865. if (! checker.shouldBailOut())
  32866. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32867. }
  32868. }
  32869. void Component::internalHierarchyChanged()
  32870. {
  32871. BailOutChecker checker (this);
  32872. parentHierarchyChanged();
  32873. if (checker.shouldBailOut())
  32874. return;
  32875. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32876. if (checker.shouldBailOut())
  32877. return;
  32878. for (int i = childComponentList_.size(); --i >= 0;)
  32879. {
  32880. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32881. if (checker.shouldBailOut())
  32882. {
  32883. // you really shouldn't delete the parent component during a callback telling you
  32884. // that it's changed..
  32885. jassertfalse;
  32886. return;
  32887. }
  32888. i = jmin (i, childComponentList_.size());
  32889. }
  32890. }
  32891. void* Component::runModalLoopCallback (void* userData)
  32892. {
  32893. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32894. }
  32895. int Component::runModalLoop()
  32896. {
  32897. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32898. {
  32899. // use a callback so this can be called from non-gui threads
  32900. return (int) (pointer_sized_int) MessageManager::getInstance()
  32901. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32902. }
  32903. if (! isCurrentlyModal())
  32904. enterModalState (true);
  32905. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32906. }
  32907. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32908. {
  32909. // if component methods are being called from threads other than the message
  32910. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32911. checkMessageManagerIsLocked
  32912. // Check for an attempt to make a component modal when it already is!
  32913. // This can cause nasty problems..
  32914. jassert (! flags.currentlyModalFlag);
  32915. if (! isCurrentlyModal())
  32916. {
  32917. ModalComponentManager::getInstance()->startModal (this, callback);
  32918. flags.currentlyModalFlag = true;
  32919. setVisible (true);
  32920. if (takeKeyboardFocus_)
  32921. grabKeyboardFocus();
  32922. }
  32923. }
  32924. void Component::exitModalState (const int returnValue)
  32925. {
  32926. if (isCurrentlyModal())
  32927. {
  32928. if (MessageManager::getInstance()->isThisTheMessageThread())
  32929. {
  32930. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32931. flags.currentlyModalFlag = false;
  32932. bringModalComponentToFront();
  32933. }
  32934. else
  32935. {
  32936. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32937. }
  32938. }
  32939. }
  32940. bool Component::isCurrentlyModal() const throw()
  32941. {
  32942. return flags.currentlyModalFlag
  32943. && getCurrentlyModalComponent() == this;
  32944. }
  32945. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32946. {
  32947. Component* const mc = getCurrentlyModalComponent();
  32948. return mc != 0
  32949. && mc != this
  32950. && (! mc->isParentOf (this))
  32951. && ! mc->canModalEventBeSentToComponent (this);
  32952. }
  32953. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32954. {
  32955. return ModalComponentManager::getInstance()->getNumModalComponents();
  32956. }
  32957. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32958. {
  32959. return ModalComponentManager::getInstance()->getModalComponent (index);
  32960. }
  32961. void Component::bringModalComponentToFront()
  32962. {
  32963. ComponentPeer* lastOne = 0;
  32964. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32965. {
  32966. Component* const c = getCurrentlyModalComponent (i);
  32967. if (c == 0)
  32968. break;
  32969. ComponentPeer* peer = c->getPeer();
  32970. if (peer != 0 && peer != lastOne)
  32971. {
  32972. if (lastOne == 0)
  32973. {
  32974. peer->toFront (true);
  32975. peer->grabFocus();
  32976. }
  32977. else
  32978. peer->toBehind (lastOne);
  32979. lastOne = peer;
  32980. }
  32981. }
  32982. }
  32983. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32984. {
  32985. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32986. }
  32987. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32988. {
  32989. return flags.bringToFrontOnClickFlag;
  32990. }
  32991. void Component::setMouseCursor (const MouseCursor& cursor)
  32992. {
  32993. if (cursor_ != cursor)
  32994. {
  32995. cursor_ = cursor;
  32996. if (flags.visibleFlag)
  32997. updateMouseCursor();
  32998. }
  32999. }
  33000. const MouseCursor Component::getMouseCursor()
  33001. {
  33002. return cursor_;
  33003. }
  33004. void Component::updateMouseCursor() const
  33005. {
  33006. sendFakeMouseMove();
  33007. }
  33008. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33009. {
  33010. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33011. }
  33012. void Component::repaintParent()
  33013. {
  33014. if (flags.visibleFlag)
  33015. internalRepaint (0, 0, getWidth(), getHeight());
  33016. }
  33017. void Component::repaint()
  33018. {
  33019. repaint (0, 0, getWidth(), getHeight());
  33020. }
  33021. void Component::repaint (const int x, const int y,
  33022. const int w, const int h)
  33023. {
  33024. bufferedImage_ = Image::null;
  33025. if (flags.visibleFlag)
  33026. internalRepaint (x, y, w, h);
  33027. }
  33028. void Component::repaint (const Rectangle<int>& area)
  33029. {
  33030. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33031. }
  33032. void Component::internalRepaint (int x, int y, int w, int h)
  33033. {
  33034. // if component methods are being called from threads other than the message
  33035. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33036. checkMessageManagerIsLocked
  33037. if (x < 0)
  33038. {
  33039. w += x;
  33040. x = 0;
  33041. }
  33042. if (x + w > getWidth())
  33043. w = getWidth() - x;
  33044. if (w > 0)
  33045. {
  33046. if (y < 0)
  33047. {
  33048. h += y;
  33049. y = 0;
  33050. }
  33051. if (y + h > getHeight())
  33052. h = getHeight() - y;
  33053. if (h > 0)
  33054. {
  33055. if (parentComponent_ != 0)
  33056. {
  33057. x += getX();
  33058. y += getY();
  33059. if (parentComponent_->flags.visibleFlag)
  33060. parentComponent_->internalRepaint (x, y, w, h);
  33061. }
  33062. else if (flags.hasHeavyweightPeerFlag)
  33063. {
  33064. ComponentPeer* const peer = getPeer();
  33065. if (peer != 0)
  33066. peer->repaint (Rectangle<int> (x, y, w, h));
  33067. }
  33068. }
  33069. }
  33070. }
  33071. void Component::renderComponent (Graphics& g)
  33072. {
  33073. const Rectangle<int> clipBounds (g.getClipBounds());
  33074. g.saveState();
  33075. clipObscuredRegions (g, clipBounds, 0, 0);
  33076. if (! g.isClipEmpty())
  33077. {
  33078. if (flags.bufferToImageFlag)
  33079. {
  33080. if (bufferedImage_.isNull())
  33081. {
  33082. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33083. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33084. Graphics imG (bufferedImage_);
  33085. paint (imG);
  33086. }
  33087. g.setColour (Colours::black);
  33088. g.drawImageAt (bufferedImage_, 0, 0);
  33089. }
  33090. else
  33091. {
  33092. paint (g);
  33093. }
  33094. }
  33095. g.restoreState();
  33096. for (int i = 0; i < childComponentList_.size(); ++i)
  33097. {
  33098. Component* const child = childComponentList_.getUnchecked (i);
  33099. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33100. {
  33101. g.saveState();
  33102. if (g.reduceClipRegion (child->getX(), child->getY(),
  33103. child->getWidth(), child->getHeight()))
  33104. {
  33105. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33106. {
  33107. const Component* const sibling = childComponentList_.getUnchecked (j);
  33108. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33109. g.excludeClipRegion (sibling->getBounds());
  33110. }
  33111. if (! g.isClipEmpty())
  33112. {
  33113. g.setOrigin (child->getX(), child->getY());
  33114. child->paintEntireComponent (g);
  33115. }
  33116. }
  33117. g.restoreState();
  33118. }
  33119. }
  33120. g.saveState();
  33121. paintOverChildren (g);
  33122. g.restoreState();
  33123. }
  33124. void Component::paintEntireComponent (Graphics& g)
  33125. {
  33126. jassert (! g.isClipEmpty());
  33127. #if JUCE_DEBUG
  33128. flags.isInsidePaintCall = true;
  33129. #endif
  33130. if (effect_ != 0)
  33131. {
  33132. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33133. getWidth(), getHeight(),
  33134. ! flags.opaqueFlag, Image::NativeImage);
  33135. {
  33136. Graphics g2 (effectImage);
  33137. renderComponent (g2);
  33138. }
  33139. effect_->applyEffect (effectImage, g);
  33140. }
  33141. else
  33142. {
  33143. renderComponent (g);
  33144. }
  33145. #if JUCE_DEBUG
  33146. flags.isInsidePaintCall = false;
  33147. #endif
  33148. }
  33149. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33150. const bool clipImageToComponentBounds)
  33151. {
  33152. Rectangle<int> r (areaToGrab);
  33153. if (clipImageToComponentBounds)
  33154. r = r.getIntersection (getLocalBounds());
  33155. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33156. jmax (1, r.getWidth()),
  33157. jmax (1, r.getHeight()),
  33158. true);
  33159. Graphics imageContext (componentImage);
  33160. imageContext.setOrigin (-r.getX(), -r.getY());
  33161. paintEntireComponent (imageContext);
  33162. return componentImage;
  33163. }
  33164. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33165. {
  33166. if (effect_ != effect)
  33167. {
  33168. effect_ = effect;
  33169. repaint();
  33170. }
  33171. }
  33172. LookAndFeel& Component::getLookAndFeel() const throw()
  33173. {
  33174. const Component* c = this;
  33175. do
  33176. {
  33177. if (c->lookAndFeel_ != 0)
  33178. return *(c->lookAndFeel_);
  33179. c = c->parentComponent_;
  33180. }
  33181. while (c != 0);
  33182. return LookAndFeel::getDefaultLookAndFeel();
  33183. }
  33184. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33185. {
  33186. if (lookAndFeel_ != newLookAndFeel)
  33187. {
  33188. lookAndFeel_ = newLookAndFeel;
  33189. sendLookAndFeelChange();
  33190. }
  33191. }
  33192. void Component::lookAndFeelChanged()
  33193. {
  33194. }
  33195. void Component::sendLookAndFeelChange()
  33196. {
  33197. repaint();
  33198. lookAndFeelChanged();
  33199. // (it's not a great idea to do anything that would delete this component
  33200. // during the lookAndFeelChanged() callback)
  33201. jassert (isValidComponent());
  33202. SafePointer<Component> safePointer (this);
  33203. for (int i = childComponentList_.size(); --i >= 0;)
  33204. {
  33205. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33206. if (safePointer == 0)
  33207. return;
  33208. i = jmin (i, childComponentList_.size());
  33209. }
  33210. }
  33211. static const Identifier getColourPropertyId (const int colourId)
  33212. {
  33213. String s;
  33214. s.preallocateStorage (18);
  33215. s << "jcclr_" << String::toHexString (colourId);
  33216. return s;
  33217. }
  33218. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33219. {
  33220. var* v = properties.getItem (getColourPropertyId (colourId));
  33221. if (v != 0)
  33222. return Colour ((int) *v);
  33223. if (inheritFromParent && parentComponent_ != 0)
  33224. return parentComponent_->findColour (colourId, true);
  33225. return getLookAndFeel().findColour (colourId);
  33226. }
  33227. bool Component::isColourSpecified (const int colourId) const
  33228. {
  33229. return properties.contains (getColourPropertyId (colourId));
  33230. }
  33231. void Component::removeColour (const int colourId)
  33232. {
  33233. if (properties.remove (getColourPropertyId (colourId)))
  33234. colourChanged();
  33235. }
  33236. void Component::setColour (const int colourId, const Colour& colour)
  33237. {
  33238. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33239. colourChanged();
  33240. }
  33241. void Component::copyAllExplicitColoursTo (Component& target) const
  33242. {
  33243. bool changed = false;
  33244. for (int i = properties.size(); --i >= 0;)
  33245. {
  33246. const Identifier name (properties.getName(i));
  33247. if (name.toString().startsWith ("jcclr_"))
  33248. if (target.properties.set (name, properties [name]))
  33249. changed = true;
  33250. }
  33251. if (changed)
  33252. target.colourChanged();
  33253. }
  33254. void Component::colourChanged()
  33255. {
  33256. }
  33257. const Rectangle<int> Component::getLocalBounds() const throw()
  33258. {
  33259. return Rectangle<int> (getWidth(), getHeight());
  33260. }
  33261. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33262. {
  33263. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33264. : Desktop::getInstance().getMainMonitorArea();
  33265. }
  33266. const Rectangle<int> Component::getUnclippedArea() const
  33267. {
  33268. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33269. Component* p = parentComponent_;
  33270. int px = getX();
  33271. int py = getY();
  33272. while (p != 0)
  33273. {
  33274. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33275. return Rectangle<int>();
  33276. px += p->getX();
  33277. py += p->getY();
  33278. p = p->parentComponent_;
  33279. }
  33280. return Rectangle<int> (x, y, w, h);
  33281. }
  33282. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33283. const int deltaX, const int deltaY) const
  33284. {
  33285. for (int i = childComponentList_.size(); --i >= 0;)
  33286. {
  33287. const Component* const c = childComponentList_.getUnchecked(i);
  33288. if (c->isVisible())
  33289. {
  33290. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33291. if (! newClip.isEmpty())
  33292. {
  33293. if (c->isOpaque())
  33294. {
  33295. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33296. }
  33297. else
  33298. {
  33299. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33300. c->getX() + deltaX,
  33301. c->getY() + deltaY);
  33302. }
  33303. }
  33304. }
  33305. }
  33306. }
  33307. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33308. {
  33309. result.clear();
  33310. const Rectangle<int> unclipped (getUnclippedArea());
  33311. if (! unclipped.isEmpty())
  33312. {
  33313. result.add (unclipped);
  33314. if (includeSiblings)
  33315. {
  33316. const Component* const c = getTopLevelComponent();
  33317. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33318. c->getLocalBounds(), this);
  33319. }
  33320. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33321. result.consolidate();
  33322. }
  33323. }
  33324. void Component::subtractObscuredRegions (RectangleList& result,
  33325. const Point<int>& delta,
  33326. const Rectangle<int>& clipRect,
  33327. const Component* const compToAvoid) const
  33328. {
  33329. for (int i = childComponentList_.size(); --i >= 0;)
  33330. {
  33331. const Component* const c = childComponentList_.getUnchecked(i);
  33332. if (c != compToAvoid && c->isVisible())
  33333. {
  33334. if (c->isOpaque())
  33335. {
  33336. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33337. childBounds.translate (delta.getX(), delta.getY());
  33338. result.subtract (childBounds);
  33339. }
  33340. else
  33341. {
  33342. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33343. newClip.translate (-c->getX(), -c->getY());
  33344. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33345. newClip, compToAvoid);
  33346. }
  33347. }
  33348. }
  33349. }
  33350. void Component::mouseEnter (const MouseEvent&)
  33351. {
  33352. // base class does nothing
  33353. }
  33354. void Component::mouseExit (const MouseEvent&)
  33355. {
  33356. // base class does nothing
  33357. }
  33358. void Component::mouseDown (const MouseEvent&)
  33359. {
  33360. // base class does nothing
  33361. }
  33362. void Component::mouseUp (const MouseEvent&)
  33363. {
  33364. // base class does nothing
  33365. }
  33366. void Component::mouseDrag (const MouseEvent&)
  33367. {
  33368. // base class does nothing
  33369. }
  33370. void Component::mouseMove (const MouseEvent&)
  33371. {
  33372. // base class does nothing
  33373. }
  33374. void Component::mouseDoubleClick (const MouseEvent&)
  33375. {
  33376. // base class does nothing
  33377. }
  33378. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33379. {
  33380. // the base class just passes this event up to its parent..
  33381. if (parentComponent_ != 0)
  33382. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33383. wheelIncrementX, wheelIncrementY);
  33384. }
  33385. void Component::resized()
  33386. {
  33387. // base class does nothing
  33388. }
  33389. void Component::moved()
  33390. {
  33391. // base class does nothing
  33392. }
  33393. void Component::childBoundsChanged (Component*)
  33394. {
  33395. // base class does nothing
  33396. }
  33397. void Component::parentSizeChanged()
  33398. {
  33399. // base class does nothing
  33400. }
  33401. void Component::addComponentListener (ComponentListener* const newListener)
  33402. {
  33403. jassert (isValidComponent());
  33404. componentListeners.add (newListener);
  33405. }
  33406. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33407. {
  33408. jassert (isValidComponent());
  33409. componentListeners.remove (listenerToRemove);
  33410. }
  33411. void Component::inputAttemptWhenModal()
  33412. {
  33413. bringModalComponentToFront();
  33414. getLookAndFeel().playAlertSound();
  33415. }
  33416. bool Component::canModalEventBeSentToComponent (const Component*)
  33417. {
  33418. return false;
  33419. }
  33420. void Component::internalModalInputAttempt()
  33421. {
  33422. Component* const current = getCurrentlyModalComponent();
  33423. if (current != 0)
  33424. current->inputAttemptWhenModal();
  33425. }
  33426. void Component::paint (Graphics&)
  33427. {
  33428. // all painting is done in the subclasses
  33429. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33430. }
  33431. void Component::paintOverChildren (Graphics&)
  33432. {
  33433. // all painting is done in the subclasses
  33434. }
  33435. void Component::handleMessage (const Message& message)
  33436. {
  33437. if (message.intParameter1 == exitModalStateMessage)
  33438. {
  33439. exitModalState (message.intParameter2);
  33440. }
  33441. else if (message.intParameter1 == customCommandMessage)
  33442. {
  33443. handleCommandMessage (message.intParameter2);
  33444. }
  33445. }
  33446. void Component::postCommandMessage (const int commandId)
  33447. {
  33448. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33449. }
  33450. void Component::handleCommandMessage (int)
  33451. {
  33452. // used by subclasses
  33453. }
  33454. void Component::addMouseListener (MouseListener* const newListener,
  33455. const bool wantsEventsForAllNestedChildComponents)
  33456. {
  33457. // if component methods are being called from threads other than the message
  33458. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33459. checkMessageManagerIsLocked
  33460. // If you register a component as a mouselistener for itself, it'll receive all the events
  33461. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33462. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33463. if (mouseListeners_ == 0)
  33464. mouseListeners_ = new Array<MouseListener*>();
  33465. if (! mouseListeners_->contains (newListener))
  33466. {
  33467. if (wantsEventsForAllNestedChildComponents)
  33468. {
  33469. mouseListeners_->insert (0, newListener);
  33470. ++numDeepMouseListeners;
  33471. }
  33472. else
  33473. {
  33474. mouseListeners_->add (newListener);
  33475. }
  33476. }
  33477. }
  33478. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33479. {
  33480. // if component methods are being called from threads other than the message
  33481. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33482. checkMessageManagerIsLocked
  33483. if (mouseListeners_ != 0)
  33484. {
  33485. const int index = mouseListeners_->indexOf (listenerToRemove);
  33486. if (index >= 0)
  33487. {
  33488. if (index < numDeepMouseListeners)
  33489. --numDeepMouseListeners;
  33490. mouseListeners_->remove (index);
  33491. }
  33492. }
  33493. }
  33494. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33495. {
  33496. if (isCurrentlyBlockedByAnotherModalComponent())
  33497. {
  33498. // if something else is modal, always just show a normal mouse cursor
  33499. source.showMouseCursor (MouseCursor::NormalCursor);
  33500. return;
  33501. }
  33502. if (! flags.mouseInsideFlag)
  33503. {
  33504. flags.mouseInsideFlag = true;
  33505. flags.mouseOverFlag = true;
  33506. flags.draggingFlag = false;
  33507. BailOutChecker checker (this);
  33508. if (flags.repaintOnMouseActivityFlag)
  33509. repaint();
  33510. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33511. this, this, time, relativePos,
  33512. time, 0, false);
  33513. mouseEnter (me);
  33514. if (checker.shouldBailOut())
  33515. return;
  33516. Desktop::getInstance().resetTimer();
  33517. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33518. if (checker.shouldBailOut())
  33519. return;
  33520. if (mouseListeners_ != 0)
  33521. {
  33522. for (int i = mouseListeners_->size(); --i >= 0;)
  33523. {
  33524. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33525. if (checker.shouldBailOut())
  33526. return;
  33527. i = jmin (i, mouseListeners_->size());
  33528. }
  33529. }
  33530. Component* p = parentComponent_;
  33531. while (p != 0)
  33532. {
  33533. if (p->numDeepMouseListeners > 0)
  33534. {
  33535. BailOutChecker checker2 (this, p);
  33536. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33537. {
  33538. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33539. if (checker2.shouldBailOut())
  33540. return;
  33541. i = jmin (i, p->numDeepMouseListeners);
  33542. }
  33543. }
  33544. p = p->parentComponent_;
  33545. }
  33546. }
  33547. }
  33548. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33549. {
  33550. BailOutChecker checker (this);
  33551. if (flags.draggingFlag)
  33552. {
  33553. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33554. if (checker.shouldBailOut())
  33555. return;
  33556. }
  33557. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33558. {
  33559. flags.mouseInsideFlag = false;
  33560. flags.mouseOverFlag = false;
  33561. flags.draggingFlag = false;
  33562. if (flags.repaintOnMouseActivityFlag)
  33563. repaint();
  33564. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33565. this, this, time, relativePos,
  33566. time, 0, false);
  33567. mouseExit (me);
  33568. if (checker.shouldBailOut())
  33569. return;
  33570. Desktop::getInstance().resetTimer();
  33571. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33572. if (checker.shouldBailOut())
  33573. return;
  33574. if (mouseListeners_ != 0)
  33575. {
  33576. for (int i = mouseListeners_->size(); --i >= 0;)
  33577. {
  33578. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33579. if (checker.shouldBailOut())
  33580. return;
  33581. i = jmin (i, mouseListeners_->size());
  33582. }
  33583. }
  33584. Component* p = parentComponent_;
  33585. while (p != 0)
  33586. {
  33587. if (p->numDeepMouseListeners > 0)
  33588. {
  33589. BailOutChecker checker2 (this, p);
  33590. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33591. {
  33592. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33593. if (checker2.shouldBailOut())
  33594. return;
  33595. i = jmin (i, p->numDeepMouseListeners);
  33596. }
  33597. }
  33598. p = p->parentComponent_;
  33599. }
  33600. }
  33601. }
  33602. class InternalDragRepeater : public Timer
  33603. {
  33604. public:
  33605. InternalDragRepeater()
  33606. {}
  33607. ~InternalDragRepeater()
  33608. {
  33609. clearSingletonInstance();
  33610. }
  33611. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33612. void timerCallback()
  33613. {
  33614. Desktop& desktop = Desktop::getInstance();
  33615. int numMiceDown = 0;
  33616. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33617. {
  33618. MouseInputSource* const source = desktop.getMouseSource(i);
  33619. if (source->isDragging())
  33620. {
  33621. source->triggerFakeMove();
  33622. ++numMiceDown;
  33623. }
  33624. }
  33625. if (numMiceDown == 0)
  33626. deleteInstance();
  33627. }
  33628. juce_UseDebuggingNewOperator
  33629. private:
  33630. InternalDragRepeater (const InternalDragRepeater&);
  33631. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33632. };
  33633. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33634. void Component::beginDragAutoRepeat (const int interval)
  33635. {
  33636. if (interval > 0)
  33637. {
  33638. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33639. InternalDragRepeater::getInstance()->startTimer (interval);
  33640. }
  33641. else
  33642. {
  33643. InternalDragRepeater::deleteInstance();
  33644. }
  33645. }
  33646. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33647. {
  33648. Desktop& desktop = Desktop::getInstance();
  33649. BailOutChecker checker (this);
  33650. if (isCurrentlyBlockedByAnotherModalComponent())
  33651. {
  33652. internalModalInputAttempt();
  33653. if (checker.shouldBailOut())
  33654. return;
  33655. // If processing the input attempt has exited the modal loop, we'll allow the event
  33656. // to be delivered..
  33657. if (isCurrentlyBlockedByAnotherModalComponent())
  33658. {
  33659. // allow blocked mouse-events to go to global listeners..
  33660. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33661. this, this, time, relativePos, time,
  33662. source.getNumberOfMultipleClicks(), false);
  33663. desktop.resetTimer();
  33664. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33665. return;
  33666. }
  33667. }
  33668. {
  33669. Component* c = this;
  33670. while (c != 0)
  33671. {
  33672. if (c->isBroughtToFrontOnMouseClick())
  33673. {
  33674. c->toFront (true);
  33675. if (checker.shouldBailOut())
  33676. return;
  33677. }
  33678. c = c->parentComponent_;
  33679. }
  33680. }
  33681. if (! flags.dontFocusOnMouseClickFlag)
  33682. {
  33683. grabFocusInternal (focusChangedByMouseClick);
  33684. if (checker.shouldBailOut())
  33685. return;
  33686. }
  33687. flags.draggingFlag = true;
  33688. flags.mouseOverFlag = true;
  33689. if (flags.repaintOnMouseActivityFlag)
  33690. repaint();
  33691. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33692. this, this, time, relativePos, time,
  33693. source.getNumberOfMultipleClicks(), false);
  33694. mouseDown (me);
  33695. if (checker.shouldBailOut())
  33696. return;
  33697. desktop.resetTimer();
  33698. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33699. if (checker.shouldBailOut())
  33700. return;
  33701. if (mouseListeners_ != 0)
  33702. {
  33703. for (int i = mouseListeners_->size(); --i >= 0;)
  33704. {
  33705. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33706. if (checker.shouldBailOut())
  33707. return;
  33708. i = jmin (i, mouseListeners_->size());
  33709. }
  33710. }
  33711. Component* p = parentComponent_;
  33712. while (p != 0)
  33713. {
  33714. if (p->numDeepMouseListeners > 0)
  33715. {
  33716. BailOutChecker checker2 (this, p);
  33717. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33718. {
  33719. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33720. if (checker2.shouldBailOut())
  33721. return;
  33722. i = jmin (i, p->numDeepMouseListeners);
  33723. }
  33724. }
  33725. p = p->parentComponent_;
  33726. }
  33727. }
  33728. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33729. {
  33730. if (flags.draggingFlag)
  33731. {
  33732. Desktop& desktop = Desktop::getInstance();
  33733. flags.draggingFlag = false;
  33734. BailOutChecker checker (this);
  33735. if (flags.repaintOnMouseActivityFlag)
  33736. repaint();
  33737. const MouseEvent me (source, relativePos,
  33738. oldModifiers, this, this, time,
  33739. globalPositionToRelative (source.getLastMouseDownPosition()),
  33740. source.getLastMouseDownTime(),
  33741. source.getNumberOfMultipleClicks(),
  33742. source.hasMouseMovedSignificantlySincePressed());
  33743. mouseUp (me);
  33744. if (checker.shouldBailOut())
  33745. return;
  33746. desktop.resetTimer();
  33747. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33748. if (checker.shouldBailOut())
  33749. return;
  33750. if (mouseListeners_ != 0)
  33751. {
  33752. for (int i = mouseListeners_->size(); --i >= 0;)
  33753. {
  33754. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33755. if (checker.shouldBailOut())
  33756. return;
  33757. i = jmin (i, mouseListeners_->size());
  33758. }
  33759. }
  33760. {
  33761. Component* p = parentComponent_;
  33762. while (p != 0)
  33763. {
  33764. if (p->numDeepMouseListeners > 0)
  33765. {
  33766. BailOutChecker checker2 (this, p);
  33767. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33768. {
  33769. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33770. if (checker2.shouldBailOut())
  33771. return;
  33772. i = jmin (i, p->numDeepMouseListeners);
  33773. }
  33774. }
  33775. p = p->parentComponent_;
  33776. }
  33777. }
  33778. // check for double-click
  33779. if (me.getNumberOfClicks() >= 2)
  33780. {
  33781. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33782. mouseDoubleClick (me);
  33783. if (checker.shouldBailOut())
  33784. return;
  33785. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33786. if (checker.shouldBailOut())
  33787. return;
  33788. for (int i = numListeners; --i >= 0;)
  33789. {
  33790. if (checker.shouldBailOut())
  33791. return;
  33792. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33793. if (ml != 0)
  33794. ml->mouseDoubleClick (me);
  33795. }
  33796. if (checker.shouldBailOut())
  33797. return;
  33798. Component* p = parentComponent_;
  33799. while (p != 0)
  33800. {
  33801. if (p->numDeepMouseListeners > 0)
  33802. {
  33803. BailOutChecker checker2 (this, p);
  33804. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33805. {
  33806. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33807. if (checker2.shouldBailOut())
  33808. return;
  33809. i = jmin (i, p->numDeepMouseListeners);
  33810. }
  33811. }
  33812. p = p->parentComponent_;
  33813. }
  33814. }
  33815. }
  33816. }
  33817. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33818. {
  33819. if (flags.draggingFlag)
  33820. {
  33821. Desktop& desktop = Desktop::getInstance();
  33822. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33823. BailOutChecker checker (this);
  33824. const MouseEvent me (source, relativePos,
  33825. source.getCurrentModifiers(), this, this, time,
  33826. globalPositionToRelative (source.getLastMouseDownPosition()),
  33827. source.getLastMouseDownTime(),
  33828. source.getNumberOfMultipleClicks(),
  33829. source.hasMouseMovedSignificantlySincePressed());
  33830. mouseDrag (me);
  33831. if (checker.shouldBailOut())
  33832. return;
  33833. desktop.resetTimer();
  33834. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33835. if (checker.shouldBailOut())
  33836. return;
  33837. if (mouseListeners_ != 0)
  33838. {
  33839. for (int i = mouseListeners_->size(); --i >= 0;)
  33840. {
  33841. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33842. if (checker.shouldBailOut())
  33843. return;
  33844. i = jmin (i, mouseListeners_->size());
  33845. }
  33846. }
  33847. Component* p = parentComponent_;
  33848. while (p != 0)
  33849. {
  33850. if (p->numDeepMouseListeners > 0)
  33851. {
  33852. BailOutChecker checker2 (this, p);
  33853. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33854. {
  33855. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33856. if (checker2.shouldBailOut())
  33857. return;
  33858. i = jmin (i, p->numDeepMouseListeners);
  33859. }
  33860. }
  33861. p = p->parentComponent_;
  33862. }
  33863. }
  33864. }
  33865. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33866. {
  33867. Desktop& desktop = Desktop::getInstance();
  33868. BailOutChecker checker (this);
  33869. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33870. this, this, time, relativePos,
  33871. time, 0, false);
  33872. if (isCurrentlyBlockedByAnotherModalComponent())
  33873. {
  33874. // allow blocked mouse-events to go to global listeners..
  33875. desktop.sendMouseMove();
  33876. }
  33877. else
  33878. {
  33879. flags.mouseOverFlag = true;
  33880. mouseMove (me);
  33881. if (checker.shouldBailOut())
  33882. return;
  33883. desktop.resetTimer();
  33884. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33885. if (checker.shouldBailOut())
  33886. return;
  33887. if (mouseListeners_ != 0)
  33888. {
  33889. for (int i = mouseListeners_->size(); --i >= 0;)
  33890. {
  33891. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33892. if (checker.shouldBailOut())
  33893. return;
  33894. i = jmin (i, mouseListeners_->size());
  33895. }
  33896. }
  33897. Component* p = parentComponent_;
  33898. while (p != 0)
  33899. {
  33900. if (p->numDeepMouseListeners > 0)
  33901. {
  33902. BailOutChecker checker2 (this, p);
  33903. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33904. {
  33905. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33906. if (checker2.shouldBailOut())
  33907. return;
  33908. i = jmin (i, p->numDeepMouseListeners);
  33909. }
  33910. }
  33911. p = p->parentComponent_;
  33912. }
  33913. }
  33914. }
  33915. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33916. const Time& time, const float amountX, const float amountY)
  33917. {
  33918. Desktop& desktop = Desktop::getInstance();
  33919. BailOutChecker checker (this);
  33920. const float wheelIncrementX = amountX / 256.0f;
  33921. const float wheelIncrementY = amountY / 256.0f;
  33922. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33923. this, this, time, relativePos, time, 0, false);
  33924. if (isCurrentlyBlockedByAnotherModalComponent())
  33925. {
  33926. // allow blocked mouse-events to go to global listeners..
  33927. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33928. }
  33929. else
  33930. {
  33931. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33932. if (checker.shouldBailOut())
  33933. return;
  33934. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33935. if (checker.shouldBailOut())
  33936. return;
  33937. if (mouseListeners_ != 0)
  33938. {
  33939. for (int i = mouseListeners_->size(); --i >= 0;)
  33940. {
  33941. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33942. if (checker.shouldBailOut())
  33943. return;
  33944. i = jmin (i, mouseListeners_->size());
  33945. }
  33946. }
  33947. Component* p = parentComponent_;
  33948. while (p != 0)
  33949. {
  33950. if (p->numDeepMouseListeners > 0)
  33951. {
  33952. BailOutChecker checker2 (this, p);
  33953. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33954. {
  33955. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33956. if (checker2.shouldBailOut())
  33957. return;
  33958. i = jmin (i, p->numDeepMouseListeners);
  33959. }
  33960. }
  33961. p = p->parentComponent_;
  33962. }
  33963. }
  33964. }
  33965. void Component::sendFakeMouseMove() const
  33966. {
  33967. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33968. }
  33969. void Component::broughtToFront()
  33970. {
  33971. }
  33972. void Component::internalBroughtToFront()
  33973. {
  33974. if (! isValidComponent())
  33975. return;
  33976. if (flags.hasHeavyweightPeerFlag)
  33977. Desktop::getInstance().componentBroughtToFront (this);
  33978. BailOutChecker checker (this);
  33979. broughtToFront();
  33980. if (checker.shouldBailOut())
  33981. return;
  33982. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33983. if (checker.shouldBailOut())
  33984. return;
  33985. // When brought to the front and there's a modal component blocking this one,
  33986. // we need to bring the modal one to the front instead..
  33987. Component* const cm = getCurrentlyModalComponent();
  33988. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33989. bringModalComponentToFront();
  33990. }
  33991. void Component::focusGained (FocusChangeType)
  33992. {
  33993. // base class does nothing
  33994. }
  33995. void Component::internalFocusGain (const FocusChangeType cause)
  33996. {
  33997. SafePointer<Component> safePointer (this);
  33998. focusGained (cause);
  33999. if (safePointer != 0)
  34000. internalChildFocusChange (cause);
  34001. }
  34002. void Component::focusLost (FocusChangeType)
  34003. {
  34004. // base class does nothing
  34005. }
  34006. void Component::internalFocusLoss (const FocusChangeType cause)
  34007. {
  34008. SafePointer<Component> safePointer (this);
  34009. focusLost (focusChangedDirectly);
  34010. if (safePointer != 0)
  34011. internalChildFocusChange (cause);
  34012. }
  34013. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34014. {
  34015. // base class does nothing
  34016. }
  34017. void Component::internalChildFocusChange (FocusChangeType cause)
  34018. {
  34019. const bool childIsNowFocused = hasKeyboardFocus (true);
  34020. if (flags.childCompFocusedFlag != childIsNowFocused)
  34021. {
  34022. flags.childCompFocusedFlag = childIsNowFocused;
  34023. SafePointer<Component> safePointer (this);
  34024. focusOfChildComponentChanged (cause);
  34025. if (safePointer == 0)
  34026. return;
  34027. }
  34028. if (parentComponent_ != 0)
  34029. parentComponent_->internalChildFocusChange (cause);
  34030. }
  34031. bool Component::isEnabled() const throw()
  34032. {
  34033. return (! flags.isDisabledFlag)
  34034. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34035. }
  34036. void Component::setEnabled (const bool shouldBeEnabled)
  34037. {
  34038. if (flags.isDisabledFlag == shouldBeEnabled)
  34039. {
  34040. flags.isDisabledFlag = ! shouldBeEnabled;
  34041. // if any parent components are disabled, setting our flag won't make a difference,
  34042. // so no need to send a change message
  34043. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34044. sendEnablementChangeMessage();
  34045. }
  34046. }
  34047. void Component::sendEnablementChangeMessage()
  34048. {
  34049. SafePointer<Component> safePointer (this);
  34050. enablementChanged();
  34051. if (safePointer == 0)
  34052. return;
  34053. for (int i = getNumChildComponents(); --i >= 0;)
  34054. {
  34055. Component* const c = getChildComponent (i);
  34056. if (c != 0)
  34057. {
  34058. c->sendEnablementChangeMessage();
  34059. if (safePointer == 0)
  34060. return;
  34061. }
  34062. }
  34063. }
  34064. void Component::enablementChanged()
  34065. {
  34066. }
  34067. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34068. {
  34069. flags.wantsFocusFlag = wantsFocus;
  34070. }
  34071. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34072. {
  34073. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34074. }
  34075. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34076. {
  34077. return ! flags.dontFocusOnMouseClickFlag;
  34078. }
  34079. bool Component::getWantsKeyboardFocus() const throw()
  34080. {
  34081. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34082. }
  34083. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34084. {
  34085. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34086. }
  34087. bool Component::isFocusContainer() const throw()
  34088. {
  34089. return flags.isFocusContainerFlag;
  34090. }
  34091. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34092. int Component::getExplicitFocusOrder() const
  34093. {
  34094. return properties [juce_explicitFocusOrderId];
  34095. }
  34096. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34097. {
  34098. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34099. }
  34100. KeyboardFocusTraverser* Component::createFocusTraverser()
  34101. {
  34102. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34103. return new KeyboardFocusTraverser();
  34104. return parentComponent_->createFocusTraverser();
  34105. }
  34106. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34107. {
  34108. // give the focus to this component
  34109. if (currentlyFocusedComponent != this)
  34110. {
  34111. JUCE_TRY
  34112. {
  34113. // get the focus onto our desktop window
  34114. ComponentPeer* const peer = getPeer();
  34115. if (peer != 0)
  34116. {
  34117. SafePointer<Component> safePointer (this);
  34118. peer->grabFocus();
  34119. if (peer->isFocused() && currentlyFocusedComponent != this)
  34120. {
  34121. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34122. currentlyFocusedComponent = this;
  34123. Desktop::getInstance().triggerFocusCallback();
  34124. // call this after setting currentlyFocusedComponent so that the one that's
  34125. // losing it has a chance to see where focus is going
  34126. if (componentLosingFocus != 0)
  34127. componentLosingFocus->internalFocusLoss (cause);
  34128. if (currentlyFocusedComponent == this)
  34129. {
  34130. focusGained (cause);
  34131. if (safePointer != 0)
  34132. internalChildFocusChange (cause);
  34133. }
  34134. }
  34135. }
  34136. }
  34137. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34138. catch (const std::exception& e)
  34139. {
  34140. currentlyFocusedComponent = 0;
  34141. Desktop::getInstance().triggerFocusCallback();
  34142. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34143. }
  34144. catch (...)
  34145. {
  34146. currentlyFocusedComponent = 0;
  34147. Desktop::getInstance().triggerFocusCallback();
  34148. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34149. }
  34150. #endif
  34151. }
  34152. }
  34153. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34154. {
  34155. if (isShowing())
  34156. {
  34157. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34158. {
  34159. takeKeyboardFocus (cause);
  34160. }
  34161. else
  34162. {
  34163. if (isParentOf (currentlyFocusedComponent)
  34164. && currentlyFocusedComponent->isShowing())
  34165. {
  34166. // do nothing if the focused component is actually a child of ours..
  34167. }
  34168. else
  34169. {
  34170. // find the default child component..
  34171. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34172. if (traverser != 0)
  34173. {
  34174. Component* const defaultComp = traverser->getDefaultComponent (this);
  34175. traverser = 0;
  34176. if (defaultComp != 0)
  34177. {
  34178. defaultComp->grabFocusInternal (cause, false);
  34179. return;
  34180. }
  34181. }
  34182. if (canTryParent && parentComponent_ != 0)
  34183. {
  34184. // if no children want it and we're allowed to try our parent comp,
  34185. // then pass up to parent, which will try our siblings.
  34186. parentComponent_->grabFocusInternal (cause, true);
  34187. }
  34188. }
  34189. }
  34190. }
  34191. }
  34192. void Component::grabKeyboardFocus()
  34193. {
  34194. // if component methods are being called from threads other than the message
  34195. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34196. checkMessageManagerIsLocked
  34197. grabFocusInternal (focusChangedDirectly);
  34198. }
  34199. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34200. {
  34201. // if component methods are being called from threads other than the message
  34202. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34203. checkMessageManagerIsLocked
  34204. if (parentComponent_ != 0)
  34205. {
  34206. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34207. if (traverser != 0)
  34208. {
  34209. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34210. : traverser->getPreviousComponent (this);
  34211. traverser = 0;
  34212. if (nextComp != 0)
  34213. {
  34214. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34215. {
  34216. SafePointer<Component> nextCompPointer (nextComp);
  34217. internalModalInputAttempt();
  34218. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34219. return;
  34220. }
  34221. nextComp->grabFocusInternal (focusChangedByTabKey);
  34222. return;
  34223. }
  34224. }
  34225. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34226. }
  34227. }
  34228. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34229. {
  34230. return (currentlyFocusedComponent == this)
  34231. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34232. }
  34233. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34234. {
  34235. return currentlyFocusedComponent;
  34236. }
  34237. void Component::giveAwayFocus()
  34238. {
  34239. // use a copy so we can clear the value before the call
  34240. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34241. currentlyFocusedComponent = 0;
  34242. Desktop::getInstance().triggerFocusCallback();
  34243. if (componentLosingFocus != 0)
  34244. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34245. }
  34246. bool Component::isMouseOver() const throw()
  34247. {
  34248. return flags.mouseOverFlag;
  34249. }
  34250. bool Component::isMouseButtonDown() const throw()
  34251. {
  34252. return flags.draggingFlag;
  34253. }
  34254. bool Component::isMouseOverOrDragging() const throw()
  34255. {
  34256. return flags.mouseOverFlag || flags.draggingFlag;
  34257. }
  34258. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34259. {
  34260. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34261. }
  34262. const Point<int> Component::getMouseXYRelative() const
  34263. {
  34264. return globalPositionToRelative (Desktop::getMousePosition());
  34265. }
  34266. const Rectangle<int> Component::getParentMonitorArea() const
  34267. {
  34268. return Desktop::getInstance()
  34269. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34270. }
  34271. void Component::addKeyListener (KeyListener* const newListener)
  34272. {
  34273. if (keyListeners_ == 0)
  34274. keyListeners_ = new Array <KeyListener*>();
  34275. keyListeners_->addIfNotAlreadyThere (newListener);
  34276. }
  34277. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34278. {
  34279. if (keyListeners_ != 0)
  34280. keyListeners_->removeValue (listenerToRemove);
  34281. }
  34282. bool Component::keyPressed (const KeyPress&)
  34283. {
  34284. return false;
  34285. }
  34286. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34287. {
  34288. return false;
  34289. }
  34290. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34291. {
  34292. if (parentComponent_ != 0)
  34293. parentComponent_->modifierKeysChanged (modifiers);
  34294. }
  34295. void Component::internalModifierKeysChanged()
  34296. {
  34297. sendFakeMouseMove();
  34298. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34299. }
  34300. ComponentPeer* Component::getPeer() const
  34301. {
  34302. if (flags.hasHeavyweightPeerFlag)
  34303. return ComponentPeer::getPeerFor (this);
  34304. else if (parentComponent_ != 0)
  34305. return parentComponent_->getPeer();
  34306. else
  34307. return 0;
  34308. }
  34309. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34310. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34311. {
  34312. jassert (component1 != 0);
  34313. }
  34314. bool Component::BailOutChecker::shouldBailOut() const throw()
  34315. {
  34316. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34317. }
  34318. END_JUCE_NAMESPACE
  34319. /*** End of inlined file: juce_Component.cpp ***/
  34320. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34321. BEGIN_JUCE_NAMESPACE
  34322. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34323. void ComponentListener::componentBroughtToFront (Component&) {}
  34324. void ComponentListener::componentVisibilityChanged (Component&) {}
  34325. void ComponentListener::componentChildrenChanged (Component&) {}
  34326. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34327. void ComponentListener::componentNameChanged (Component&) {}
  34328. void ComponentListener::componentBeingDeleted (Component&) {}
  34329. END_JUCE_NAMESPACE
  34330. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34331. /*** Start of inlined file: juce_Desktop.cpp ***/
  34332. BEGIN_JUCE_NAMESPACE
  34333. Desktop::Desktop()
  34334. : mouseClickCounter (0),
  34335. kioskModeComponent (0)
  34336. {
  34337. createMouseInputSources();
  34338. refreshMonitorSizes();
  34339. }
  34340. Desktop::~Desktop()
  34341. {
  34342. jassert (instance == this);
  34343. instance = 0;
  34344. // doh! If you don't delete all your windows before exiting, you're going to
  34345. // be leaking memory!
  34346. jassert (desktopComponents.size() == 0);
  34347. }
  34348. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34349. {
  34350. if (instance == 0)
  34351. instance = new Desktop();
  34352. return *instance;
  34353. }
  34354. Desktop* Desktop::instance = 0;
  34355. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34356. const bool clipToWorkArea);
  34357. void Desktop::refreshMonitorSizes()
  34358. {
  34359. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34360. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34361. monitorCoordsClipped.clear();
  34362. monitorCoordsUnclipped.clear();
  34363. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34364. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34365. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34366. if (oldClipped != monitorCoordsClipped
  34367. || oldUnclipped != monitorCoordsUnclipped)
  34368. {
  34369. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34370. {
  34371. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34372. if (p != 0)
  34373. p->handleScreenSizeChange();
  34374. }
  34375. }
  34376. }
  34377. int Desktop::getNumDisplayMonitors() const throw()
  34378. {
  34379. return monitorCoordsClipped.size();
  34380. }
  34381. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34382. {
  34383. return clippedToWorkArea ? monitorCoordsClipped [index]
  34384. : monitorCoordsUnclipped [index];
  34385. }
  34386. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34387. {
  34388. RectangleList rl;
  34389. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34390. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34391. return rl;
  34392. }
  34393. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34394. {
  34395. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34396. }
  34397. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34398. {
  34399. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34400. double bestDistance = 1.0e10;
  34401. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34402. {
  34403. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34404. if (rect.contains (position))
  34405. return rect;
  34406. const double distance = rect.getCentre().getDistanceFrom (position);
  34407. if (distance < bestDistance)
  34408. {
  34409. bestDistance = distance;
  34410. best = rect;
  34411. }
  34412. }
  34413. return best;
  34414. }
  34415. int Desktop::getNumComponents() const throw()
  34416. {
  34417. return desktopComponents.size();
  34418. }
  34419. Component* Desktop::getComponent (const int index) const throw()
  34420. {
  34421. return desktopComponents [index];
  34422. }
  34423. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34424. {
  34425. for (int i = desktopComponents.size(); --i >= 0;)
  34426. {
  34427. Component* const c = desktopComponents.getUnchecked(i);
  34428. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34429. if (c->contains (relative.getX(), relative.getY()))
  34430. return c->getComponentAt (relative.getX(), relative.getY());
  34431. }
  34432. return 0;
  34433. }
  34434. void Desktop::addDesktopComponent (Component* const c)
  34435. {
  34436. jassert (c != 0);
  34437. jassert (! desktopComponents.contains (c));
  34438. desktopComponents.addIfNotAlreadyThere (c);
  34439. }
  34440. void Desktop::removeDesktopComponent (Component* const c)
  34441. {
  34442. desktopComponents.removeValue (c);
  34443. }
  34444. void Desktop::componentBroughtToFront (Component* const c)
  34445. {
  34446. const int index = desktopComponents.indexOf (c);
  34447. jassert (index >= 0);
  34448. if (index >= 0)
  34449. {
  34450. int newIndex = -1;
  34451. if (! c->isAlwaysOnTop())
  34452. {
  34453. newIndex = desktopComponents.size();
  34454. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34455. --newIndex;
  34456. --newIndex;
  34457. }
  34458. desktopComponents.move (index, newIndex);
  34459. }
  34460. }
  34461. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34462. {
  34463. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34464. }
  34465. int Desktop::getMouseButtonClickCounter() throw()
  34466. {
  34467. return getInstance().mouseClickCounter;
  34468. }
  34469. void Desktop::incrementMouseClickCounter() throw()
  34470. {
  34471. ++mouseClickCounter;
  34472. }
  34473. int Desktop::getNumDraggingMouseSources() const throw()
  34474. {
  34475. int num = 0;
  34476. for (int i = mouseSources.size(); --i >= 0;)
  34477. if (mouseSources.getUnchecked(i)->isDragging())
  34478. ++num;
  34479. return num;
  34480. }
  34481. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34482. {
  34483. int num = 0;
  34484. for (int i = mouseSources.size(); --i >= 0;)
  34485. {
  34486. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34487. if (mi->isDragging())
  34488. {
  34489. if (index == num)
  34490. return mi;
  34491. ++num;
  34492. }
  34493. }
  34494. return 0;
  34495. }
  34496. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34497. {
  34498. focusListeners.add (listener);
  34499. }
  34500. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34501. {
  34502. focusListeners.remove (listener);
  34503. }
  34504. void Desktop::triggerFocusCallback()
  34505. {
  34506. triggerAsyncUpdate();
  34507. }
  34508. void Desktop::handleAsyncUpdate()
  34509. {
  34510. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34511. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34512. }
  34513. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34514. {
  34515. mouseListeners.add (listener);
  34516. resetTimer();
  34517. }
  34518. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34519. {
  34520. mouseListeners.remove (listener);
  34521. resetTimer();
  34522. }
  34523. void Desktop::timerCallback()
  34524. {
  34525. if (lastFakeMouseMove != getMousePosition())
  34526. sendMouseMove();
  34527. }
  34528. void Desktop::sendMouseMove()
  34529. {
  34530. if (! mouseListeners.isEmpty())
  34531. {
  34532. startTimer (20);
  34533. lastFakeMouseMove = getMousePosition();
  34534. Component* const target = findComponentAt (lastFakeMouseMove);
  34535. if (target != 0)
  34536. {
  34537. Component::BailOutChecker checker (target);
  34538. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34539. const Time now (Time::getCurrentTime());
  34540. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34541. target, target, now, pos, now, 0, false);
  34542. if (me.mods.isAnyMouseButtonDown())
  34543. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34544. else
  34545. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34546. }
  34547. }
  34548. }
  34549. void Desktop::resetTimer()
  34550. {
  34551. if (mouseListeners.size() == 0)
  34552. stopTimer();
  34553. else
  34554. startTimer (100);
  34555. lastFakeMouseMove = getMousePosition();
  34556. }
  34557. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34558. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34559. {
  34560. if (kioskModeComponent != componentToUse)
  34561. {
  34562. // agh! Don't delete a component without first stopping it being the kiosk comp
  34563. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34564. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34565. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34566. if (kioskModeComponent->isValidComponent())
  34567. {
  34568. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34569. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34570. }
  34571. kioskModeComponent = componentToUse;
  34572. if (kioskModeComponent != 0)
  34573. {
  34574. jassert (kioskModeComponent->isValidComponent());
  34575. // Only components that are already on the desktop can be put into kiosk mode!
  34576. jassert (kioskModeComponent->isOnDesktop());
  34577. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34578. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34579. }
  34580. }
  34581. }
  34582. END_JUCE_NAMESPACE
  34583. /*** End of inlined file: juce_Desktop.cpp ***/
  34584. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34585. BEGIN_JUCE_NAMESPACE
  34586. class ModalComponentManager::ModalItem : public ComponentListener
  34587. {
  34588. public:
  34589. ModalItem (Component* const comp, Callback* const callback)
  34590. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34591. {
  34592. if (callback != 0)
  34593. callbacks.add (callback);
  34594. jassert (comp != 0);
  34595. component->addComponentListener (this);
  34596. }
  34597. ~ModalItem()
  34598. {
  34599. if (! isDeleted)
  34600. component->removeComponentListener (this);
  34601. }
  34602. void componentBeingDeleted (Component&)
  34603. {
  34604. isDeleted = true;
  34605. cancel();
  34606. }
  34607. void componentVisibilityChanged (Component&)
  34608. {
  34609. if (! component->isShowing())
  34610. cancel();
  34611. }
  34612. void componentParentHierarchyChanged (Component&)
  34613. {
  34614. if (! component->isShowing())
  34615. cancel();
  34616. }
  34617. void cancel()
  34618. {
  34619. if (isActive)
  34620. {
  34621. isActive = false;
  34622. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34623. }
  34624. }
  34625. Component* component;
  34626. OwnedArray<Callback> callbacks;
  34627. int returnValue;
  34628. bool isActive, isDeleted;
  34629. private:
  34630. ModalItem (const ModalItem&);
  34631. ModalItem& operator= (const ModalItem&);
  34632. };
  34633. ModalComponentManager::ModalComponentManager()
  34634. {
  34635. }
  34636. ModalComponentManager::~ModalComponentManager()
  34637. {
  34638. clearSingletonInstance();
  34639. }
  34640. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34641. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34642. {
  34643. if (component != 0)
  34644. stack.add (new ModalItem (component, callback));
  34645. }
  34646. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34647. {
  34648. if (callback != 0)
  34649. {
  34650. ScopedPointer<Callback> callbackDeleter (callback);
  34651. for (int i = stack.size(); --i >= 0;)
  34652. {
  34653. ModalItem* const item = stack.getUnchecked(i);
  34654. if (item->component == component)
  34655. {
  34656. item->callbacks.add (callback);
  34657. callbackDeleter.release();
  34658. break;
  34659. }
  34660. }
  34661. }
  34662. }
  34663. void ModalComponentManager::endModal (Component* component)
  34664. {
  34665. for (int i = stack.size(); --i >= 0;)
  34666. {
  34667. ModalItem* const item = stack.getUnchecked(i);
  34668. if (item->component == component)
  34669. item->cancel();
  34670. }
  34671. }
  34672. void ModalComponentManager::endModal (Component* component, int returnValue)
  34673. {
  34674. for (int i = stack.size(); --i >= 0;)
  34675. {
  34676. ModalItem* const item = stack.getUnchecked(i);
  34677. if (item->component == component)
  34678. {
  34679. item->returnValue = returnValue;
  34680. item->cancel();
  34681. }
  34682. }
  34683. }
  34684. int ModalComponentManager::getNumModalComponents() const
  34685. {
  34686. int n = 0;
  34687. for (int i = 0; i < stack.size(); ++i)
  34688. if (stack.getUnchecked(i)->isActive)
  34689. ++n;
  34690. return n;
  34691. }
  34692. Component* ModalComponentManager::getModalComponent (const int index) const
  34693. {
  34694. int n = 0;
  34695. for (int i = stack.size(); --i >= 0;)
  34696. {
  34697. const ModalItem* const item = stack.getUnchecked(i);
  34698. if (item->isActive)
  34699. if (n++ == index)
  34700. return item->component;
  34701. }
  34702. return 0;
  34703. }
  34704. bool ModalComponentManager::isModal (Component* const comp) const
  34705. {
  34706. for (int i = stack.size(); --i >= 0;)
  34707. {
  34708. const ModalItem* const item = stack.getUnchecked(i);
  34709. if (item->isActive && item->component == comp)
  34710. return true;
  34711. }
  34712. return false;
  34713. }
  34714. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34715. {
  34716. return comp == getModalComponent (0);
  34717. }
  34718. void ModalComponentManager::handleAsyncUpdate()
  34719. {
  34720. for (int i = stack.size(); --i >= 0;)
  34721. {
  34722. const ModalItem* const item = stack.getUnchecked(i);
  34723. if (! item->isActive)
  34724. {
  34725. for (int j = item->callbacks.size(); --j >= 0;)
  34726. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34727. stack.remove (i);
  34728. }
  34729. }
  34730. }
  34731. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34732. {
  34733. public:
  34734. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34735. ~ReturnValueRetriever() {}
  34736. void modalStateFinished (int returnValue)
  34737. {
  34738. finished = true;
  34739. value = returnValue;
  34740. }
  34741. private:
  34742. int& value;
  34743. bool& finished;
  34744. ReturnValueRetriever (const ReturnValueRetriever&);
  34745. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34746. };
  34747. int ModalComponentManager::runEventLoopForCurrentComponent()
  34748. {
  34749. // This can only be run from the message thread!
  34750. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34751. Component* currentlyModal = getModalComponent (0);
  34752. if (currentlyModal == 0)
  34753. return 0;
  34754. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34755. int returnValue = 0;
  34756. bool finished = false;
  34757. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34758. JUCE_TRY
  34759. {
  34760. while (! finished)
  34761. {
  34762. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34763. break;
  34764. }
  34765. }
  34766. JUCE_CATCH_EXCEPTION
  34767. if (prevFocused != 0)
  34768. prevFocused->grabKeyboardFocus();
  34769. return returnValue;
  34770. }
  34771. END_JUCE_NAMESPACE
  34772. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34773. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34774. BEGIN_JUCE_NAMESPACE
  34775. ArrowButton::ArrowButton (const String& name,
  34776. float arrowDirectionInRadians,
  34777. const Colour& arrowColour)
  34778. : Button (name),
  34779. colour (arrowColour)
  34780. {
  34781. path.lineTo (0.0f, 1.0f);
  34782. path.lineTo (1.0f, 0.5f);
  34783. path.closeSubPath();
  34784. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34785. 0.5f, 0.5f));
  34786. setComponentEffect (&shadow);
  34787. buttonStateChanged();
  34788. }
  34789. ArrowButton::~ArrowButton()
  34790. {
  34791. }
  34792. void ArrowButton::paintButton (Graphics& g,
  34793. bool /*isMouseOverButton*/,
  34794. bool /*isButtonDown*/)
  34795. {
  34796. g.setColour (colour);
  34797. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34798. (float) offset,
  34799. (float) (getWidth() - 3),
  34800. (float) (getHeight() - 3),
  34801. false));
  34802. }
  34803. void ArrowButton::buttonStateChanged()
  34804. {
  34805. offset = (isDown()) ? 1 : 0;
  34806. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34807. 0.3f, -1, 0);
  34808. }
  34809. END_JUCE_NAMESPACE
  34810. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34811. /*** Start of inlined file: juce_Button.cpp ***/
  34812. BEGIN_JUCE_NAMESPACE
  34813. class Button::RepeatTimer : public Timer
  34814. {
  34815. public:
  34816. RepeatTimer (Button& owner_) : owner (owner_) {}
  34817. void timerCallback() { owner.repeatTimerCallback(); }
  34818. juce_UseDebuggingNewOperator
  34819. private:
  34820. Button& owner;
  34821. RepeatTimer (const RepeatTimer&);
  34822. RepeatTimer& operator= (const RepeatTimer&);
  34823. };
  34824. Button::Button (const String& name)
  34825. : Component (name),
  34826. text (name),
  34827. buttonPressTime (0),
  34828. lastTimeCallbackTime (0),
  34829. commandManagerToUse (0),
  34830. autoRepeatDelay (-1),
  34831. autoRepeatSpeed (0),
  34832. autoRepeatMinimumDelay (-1),
  34833. radioGroupId (0),
  34834. commandID (0),
  34835. connectedEdgeFlags (0),
  34836. buttonState (buttonNormal),
  34837. lastToggleState (false),
  34838. clickTogglesState (false),
  34839. needsToRelease (false),
  34840. needsRepainting (false),
  34841. isKeyDown (false),
  34842. triggerOnMouseDown (false),
  34843. generateTooltip (false)
  34844. {
  34845. setWantsKeyboardFocus (true);
  34846. isOn.addListener (this);
  34847. }
  34848. Button::~Button()
  34849. {
  34850. isOn.removeListener (this);
  34851. if (commandManagerToUse != 0)
  34852. commandManagerToUse->removeListener (this);
  34853. repeatTimer = 0;
  34854. clearShortcuts();
  34855. }
  34856. void Button::setButtonText (const String& newText)
  34857. {
  34858. if (text != newText)
  34859. {
  34860. text = newText;
  34861. repaint();
  34862. }
  34863. }
  34864. void Button::setTooltip (const String& newTooltip)
  34865. {
  34866. SettableTooltipClient::setTooltip (newTooltip);
  34867. generateTooltip = false;
  34868. }
  34869. const String Button::getTooltip()
  34870. {
  34871. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34872. {
  34873. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34874. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34875. for (int i = 0; i < keyPresses.size(); ++i)
  34876. {
  34877. const String key (keyPresses.getReference(i).getTextDescription());
  34878. tt << " [";
  34879. if (key.length() == 1)
  34880. tt << TRANS("shortcut") << ": '" << key << "']";
  34881. else
  34882. tt << key << ']';
  34883. }
  34884. return tt;
  34885. }
  34886. return SettableTooltipClient::getTooltip();
  34887. }
  34888. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34889. {
  34890. if (connectedEdgeFlags != connectedEdgeFlags_)
  34891. {
  34892. connectedEdgeFlags = connectedEdgeFlags_;
  34893. repaint();
  34894. }
  34895. }
  34896. void Button::setToggleState (const bool shouldBeOn,
  34897. const bool sendChangeNotification)
  34898. {
  34899. if (shouldBeOn != lastToggleState)
  34900. {
  34901. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34902. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34903. lastToggleState = shouldBeOn;
  34904. repaint();
  34905. if (sendChangeNotification)
  34906. {
  34907. Component::SafePointer<Component> deletionWatcher (this);
  34908. sendClickMessage (ModifierKeys());
  34909. if (deletionWatcher == 0)
  34910. return;
  34911. }
  34912. if (lastToggleState)
  34913. turnOffOtherButtonsInGroup (sendChangeNotification);
  34914. }
  34915. }
  34916. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34917. {
  34918. clickTogglesState = shouldToggle;
  34919. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34920. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34921. // it is that this button represents, and the button will update its state to reflect this
  34922. // in the applicationCommandListChanged() method.
  34923. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34924. }
  34925. bool Button::getClickingTogglesState() const throw()
  34926. {
  34927. return clickTogglesState;
  34928. }
  34929. void Button::valueChanged (Value& value)
  34930. {
  34931. if (value.refersToSameSourceAs (isOn))
  34932. setToggleState (isOn.getValue(), true);
  34933. }
  34934. void Button::setRadioGroupId (const int newGroupId)
  34935. {
  34936. if (radioGroupId != newGroupId)
  34937. {
  34938. radioGroupId = newGroupId;
  34939. if (lastToggleState)
  34940. turnOffOtherButtonsInGroup (true);
  34941. }
  34942. }
  34943. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34944. {
  34945. Component* const p = getParentComponent();
  34946. if (p != 0 && radioGroupId != 0)
  34947. {
  34948. Component::SafePointer<Component> deletionWatcher (this);
  34949. for (int i = p->getNumChildComponents(); --i >= 0;)
  34950. {
  34951. Component* const c = p->getChildComponent (i);
  34952. if (c != this)
  34953. {
  34954. Button* const b = dynamic_cast <Button*> (c);
  34955. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34956. {
  34957. b->setToggleState (false, sendChangeNotification);
  34958. if (deletionWatcher == 0)
  34959. return;
  34960. }
  34961. }
  34962. }
  34963. }
  34964. }
  34965. void Button::enablementChanged()
  34966. {
  34967. updateState (0);
  34968. repaint();
  34969. }
  34970. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34971. {
  34972. ButtonState state = buttonNormal;
  34973. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34974. {
  34975. Point<int> mousePos;
  34976. if (e == 0)
  34977. mousePos = getMouseXYRelative();
  34978. else
  34979. mousePos = e->getEventRelativeTo (this).getPosition();
  34980. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34981. const bool down = isMouseButtonDown();
  34982. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34983. state = buttonDown;
  34984. else if (over)
  34985. state = buttonOver;
  34986. }
  34987. setState (state);
  34988. return state;
  34989. }
  34990. void Button::setState (const ButtonState newState)
  34991. {
  34992. if (buttonState != newState)
  34993. {
  34994. buttonState = newState;
  34995. repaint();
  34996. if (buttonState == buttonDown)
  34997. {
  34998. buttonPressTime = Time::getApproximateMillisecondCounter();
  34999. lastTimeCallbackTime = buttonPressTime;
  35000. }
  35001. sendStateMessage();
  35002. }
  35003. }
  35004. bool Button::isDown() const throw()
  35005. {
  35006. return buttonState == buttonDown;
  35007. }
  35008. bool Button::isOver() const throw()
  35009. {
  35010. return buttonState != buttonNormal;
  35011. }
  35012. void Button::buttonStateChanged()
  35013. {
  35014. }
  35015. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35016. {
  35017. const uint32 now = Time::getApproximateMillisecondCounter();
  35018. return now > buttonPressTime ? now - buttonPressTime : 0;
  35019. }
  35020. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35021. {
  35022. triggerOnMouseDown = isTriggeredOnMouseDown;
  35023. }
  35024. void Button::clicked()
  35025. {
  35026. }
  35027. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35028. {
  35029. clicked();
  35030. }
  35031. static const int clickMessageId = 0x2f3f4f99;
  35032. void Button::triggerClick()
  35033. {
  35034. postCommandMessage (clickMessageId);
  35035. }
  35036. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35037. {
  35038. if (clickTogglesState)
  35039. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35040. sendClickMessage (modifiers);
  35041. }
  35042. void Button::flashButtonState()
  35043. {
  35044. if (isEnabled())
  35045. {
  35046. needsToRelease = true;
  35047. setState (buttonDown);
  35048. getRepeatTimer().startTimer (100);
  35049. }
  35050. }
  35051. void Button::handleCommandMessage (int commandId)
  35052. {
  35053. if (commandId == clickMessageId)
  35054. {
  35055. if (isEnabled())
  35056. {
  35057. flashButtonState();
  35058. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35059. }
  35060. }
  35061. else
  35062. {
  35063. Component::handleCommandMessage (commandId);
  35064. }
  35065. }
  35066. void Button::addButtonListener (Listener* const newListener)
  35067. {
  35068. buttonListeners.add (newListener);
  35069. }
  35070. void Button::removeButtonListener (Listener* const listener)
  35071. {
  35072. buttonListeners.remove (listener);
  35073. }
  35074. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35075. {
  35076. Component::BailOutChecker checker (this);
  35077. if (commandManagerToUse != 0 && commandID != 0)
  35078. {
  35079. ApplicationCommandTarget::InvocationInfo info (commandID);
  35080. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35081. info.originatingComponent = this;
  35082. commandManagerToUse->invoke (info, true);
  35083. }
  35084. clicked (modifiers);
  35085. if (! checker.shouldBailOut())
  35086. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35087. }
  35088. void Button::sendStateMessage()
  35089. {
  35090. Component::BailOutChecker checker (this);
  35091. buttonStateChanged();
  35092. if (! checker.shouldBailOut())
  35093. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35094. }
  35095. void Button::paint (Graphics& g)
  35096. {
  35097. if (needsToRelease && isEnabled())
  35098. {
  35099. needsToRelease = false;
  35100. needsRepainting = true;
  35101. }
  35102. paintButton (g, isOver(), isDown());
  35103. }
  35104. void Button::mouseEnter (const MouseEvent& e)
  35105. {
  35106. updateState (&e);
  35107. }
  35108. void Button::mouseExit (const MouseEvent& e)
  35109. {
  35110. updateState (&e);
  35111. }
  35112. void Button::mouseDown (const MouseEvent& e)
  35113. {
  35114. updateState (&e);
  35115. if (isDown())
  35116. {
  35117. if (autoRepeatDelay >= 0)
  35118. getRepeatTimer().startTimer (autoRepeatDelay);
  35119. if (triggerOnMouseDown)
  35120. internalClickCallback (e.mods);
  35121. }
  35122. }
  35123. void Button::mouseUp (const MouseEvent& e)
  35124. {
  35125. const bool wasDown = isDown();
  35126. updateState (&e);
  35127. if (wasDown && isOver() && ! triggerOnMouseDown)
  35128. internalClickCallback (e.mods);
  35129. }
  35130. void Button::mouseDrag (const MouseEvent& e)
  35131. {
  35132. const ButtonState oldState = buttonState;
  35133. updateState (&e);
  35134. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35135. getRepeatTimer().startTimer (autoRepeatSpeed);
  35136. }
  35137. void Button::focusGained (FocusChangeType)
  35138. {
  35139. updateState (0);
  35140. repaint();
  35141. }
  35142. void Button::focusLost (FocusChangeType)
  35143. {
  35144. updateState (0);
  35145. repaint();
  35146. }
  35147. void Button::setVisible (bool shouldBeVisible)
  35148. {
  35149. if (shouldBeVisible != isVisible())
  35150. {
  35151. Component::setVisible (shouldBeVisible);
  35152. if (! shouldBeVisible)
  35153. needsToRelease = false;
  35154. updateState (0);
  35155. }
  35156. else
  35157. {
  35158. Component::setVisible (shouldBeVisible);
  35159. }
  35160. }
  35161. void Button::parentHierarchyChanged()
  35162. {
  35163. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35164. if (newKeySource != keySource.getComponent())
  35165. {
  35166. if (keySource != 0)
  35167. keySource->removeKeyListener (this);
  35168. keySource = newKeySource;
  35169. if (keySource != 0)
  35170. keySource->addKeyListener (this);
  35171. }
  35172. }
  35173. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35174. const int commandID_,
  35175. const bool generateTooltip_)
  35176. {
  35177. commandID = commandID_;
  35178. generateTooltip = generateTooltip_;
  35179. if (commandManagerToUse != commandManagerToUse_)
  35180. {
  35181. if (commandManagerToUse != 0)
  35182. commandManagerToUse->removeListener (this);
  35183. commandManagerToUse = commandManagerToUse_;
  35184. if (commandManagerToUse != 0)
  35185. commandManagerToUse->addListener (this);
  35186. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35187. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35188. // it is that this button represents, and the button will update its state to reflect this
  35189. // in the applicationCommandListChanged() method.
  35190. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35191. }
  35192. if (commandManagerToUse != 0)
  35193. applicationCommandListChanged();
  35194. else
  35195. setEnabled (true);
  35196. }
  35197. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35198. {
  35199. if (info.commandID == commandID
  35200. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35201. {
  35202. flashButtonState();
  35203. }
  35204. }
  35205. void Button::applicationCommandListChanged()
  35206. {
  35207. if (commandManagerToUse != 0)
  35208. {
  35209. ApplicationCommandInfo info (0);
  35210. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35211. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35212. if (target != 0)
  35213. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35214. }
  35215. }
  35216. void Button::addShortcut (const KeyPress& key)
  35217. {
  35218. if (key.isValid())
  35219. {
  35220. jassert (! isRegisteredForShortcut (key)); // already registered!
  35221. shortcuts.add (key);
  35222. parentHierarchyChanged();
  35223. }
  35224. }
  35225. void Button::clearShortcuts()
  35226. {
  35227. shortcuts.clear();
  35228. parentHierarchyChanged();
  35229. }
  35230. bool Button::isShortcutPressed() const
  35231. {
  35232. if (! isCurrentlyBlockedByAnotherModalComponent())
  35233. {
  35234. for (int i = shortcuts.size(); --i >= 0;)
  35235. if (shortcuts.getReference(i).isCurrentlyDown())
  35236. return true;
  35237. }
  35238. return false;
  35239. }
  35240. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35241. {
  35242. for (int i = shortcuts.size(); --i >= 0;)
  35243. if (key == shortcuts.getReference(i))
  35244. return true;
  35245. return false;
  35246. }
  35247. bool Button::keyStateChanged (const bool, Component*)
  35248. {
  35249. if (! isEnabled())
  35250. return false;
  35251. const bool wasDown = isKeyDown;
  35252. isKeyDown = isShortcutPressed();
  35253. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35254. getRepeatTimer().startTimer (autoRepeatDelay);
  35255. updateState (0);
  35256. if (isEnabled() && wasDown && ! isKeyDown)
  35257. {
  35258. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35259. // (return immediately - this button may now have been deleted)
  35260. return true;
  35261. }
  35262. return wasDown || isKeyDown;
  35263. }
  35264. bool Button::keyPressed (const KeyPress&, Component*)
  35265. {
  35266. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35267. return isShortcutPressed();
  35268. }
  35269. bool Button::keyPressed (const KeyPress& key)
  35270. {
  35271. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35272. {
  35273. triggerClick();
  35274. return true;
  35275. }
  35276. return false;
  35277. }
  35278. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35279. const int repeatMillisecs,
  35280. const int minimumDelayInMillisecs) throw()
  35281. {
  35282. autoRepeatDelay = initialDelayMillisecs;
  35283. autoRepeatSpeed = repeatMillisecs;
  35284. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35285. }
  35286. void Button::repeatTimerCallback()
  35287. {
  35288. if (needsRepainting)
  35289. {
  35290. getRepeatTimer().stopTimer();
  35291. updateState (0);
  35292. needsRepainting = false;
  35293. }
  35294. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35295. {
  35296. int repeatSpeed = autoRepeatSpeed;
  35297. if (autoRepeatMinimumDelay >= 0)
  35298. {
  35299. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35300. timeHeldDown *= timeHeldDown;
  35301. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35302. }
  35303. repeatSpeed = jmax (1, repeatSpeed);
  35304. getRepeatTimer().startTimer (repeatSpeed);
  35305. const uint32 now = Time::getApproximateMillisecondCounter();
  35306. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35307. lastTimeCallbackTime = now;
  35308. Component::SafePointer<Component> deletionWatcher (this);
  35309. for (int i = numTimesToCallback; --i >= 0;)
  35310. {
  35311. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35312. if (deletionWatcher == 0 || ! isDown())
  35313. return;
  35314. }
  35315. }
  35316. else if (! needsToRelease)
  35317. {
  35318. getRepeatTimer().stopTimer();
  35319. }
  35320. }
  35321. Button::RepeatTimer& Button::getRepeatTimer()
  35322. {
  35323. if (repeatTimer == 0)
  35324. repeatTimer = new RepeatTimer (*this);
  35325. return *repeatTimer;
  35326. }
  35327. END_JUCE_NAMESPACE
  35328. /*** End of inlined file: juce_Button.cpp ***/
  35329. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35330. BEGIN_JUCE_NAMESPACE
  35331. DrawableButton::DrawableButton (const String& name,
  35332. const DrawableButton::ButtonStyle buttonStyle)
  35333. : Button (name),
  35334. style (buttonStyle),
  35335. edgeIndent (3)
  35336. {
  35337. if (buttonStyle == ImageOnButtonBackground)
  35338. {
  35339. backgroundOff = Colour (0xffbbbbff);
  35340. backgroundOn = Colour (0xff3333ff);
  35341. }
  35342. else
  35343. {
  35344. backgroundOff = Colours::transparentBlack;
  35345. backgroundOn = Colour (0xaabbbbff);
  35346. }
  35347. }
  35348. DrawableButton::~DrawableButton()
  35349. {
  35350. deleteImages();
  35351. }
  35352. void DrawableButton::deleteImages()
  35353. {
  35354. }
  35355. void DrawableButton::setImages (const Drawable* normal,
  35356. const Drawable* over,
  35357. const Drawable* down,
  35358. const Drawable* disabled,
  35359. const Drawable* normalOn,
  35360. const Drawable* overOn,
  35361. const Drawable* downOn,
  35362. const Drawable* disabledOn)
  35363. {
  35364. deleteImages();
  35365. jassert (normal != 0); // you really need to give it at least a normal image..
  35366. if (normal != 0)
  35367. normalImage = normal->createCopy();
  35368. if (over != 0)
  35369. overImage = over->createCopy();
  35370. if (down != 0)
  35371. downImage = down->createCopy();
  35372. if (disabled != 0)
  35373. disabledImage = disabled->createCopy();
  35374. if (normalOn != 0)
  35375. normalImageOn = normalOn->createCopy();
  35376. if (overOn != 0)
  35377. overImageOn = overOn->createCopy();
  35378. if (downOn != 0)
  35379. downImageOn = downOn->createCopy();
  35380. if (disabledOn != 0)
  35381. disabledImageOn = disabledOn->createCopy();
  35382. repaint();
  35383. }
  35384. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35385. {
  35386. if (style != newStyle)
  35387. {
  35388. style = newStyle;
  35389. repaint();
  35390. }
  35391. }
  35392. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35393. const Colour& toggledOnColour)
  35394. {
  35395. if (backgroundOff != toggledOffColour
  35396. || backgroundOn != toggledOnColour)
  35397. {
  35398. backgroundOff = toggledOffColour;
  35399. backgroundOn = toggledOnColour;
  35400. repaint();
  35401. }
  35402. }
  35403. const Colour& DrawableButton::getBackgroundColour() const throw()
  35404. {
  35405. return getToggleState() ? backgroundOn
  35406. : backgroundOff;
  35407. }
  35408. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35409. {
  35410. edgeIndent = numPixelsIndent;
  35411. repaint();
  35412. }
  35413. void DrawableButton::paintButton (Graphics& g,
  35414. bool isMouseOverButton,
  35415. bool isButtonDown)
  35416. {
  35417. Rectangle<int> imageSpace;
  35418. if (style == ImageOnButtonBackground)
  35419. {
  35420. const int insetX = getWidth() / 4;
  35421. const int insetY = getHeight() / 4;
  35422. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35423. getLookAndFeel().drawButtonBackground (g, *this,
  35424. getBackgroundColour(),
  35425. isMouseOverButton,
  35426. isButtonDown);
  35427. }
  35428. else
  35429. {
  35430. g.fillAll (getBackgroundColour());
  35431. const int textH = (style == ImageAboveTextLabel)
  35432. ? jmin (16, proportionOfHeight (0.25f))
  35433. : 0;
  35434. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35435. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35436. imageSpace.setBounds (indentX, indentY,
  35437. getWidth() - indentX * 2,
  35438. getHeight() - indentY * 2 - textH);
  35439. if (textH > 0)
  35440. {
  35441. g.setFont ((float) textH);
  35442. g.setColour (findColour (DrawableButton::textColourId)
  35443. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35444. g.drawFittedText (getButtonText(),
  35445. 2, getHeight() - textH - 1,
  35446. getWidth() - 4, textH,
  35447. Justification::centred, 1);
  35448. }
  35449. }
  35450. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35451. g.setOpacity (1.0f);
  35452. const Drawable* imageToDraw = 0;
  35453. if (isEnabled())
  35454. {
  35455. imageToDraw = getCurrentImage();
  35456. }
  35457. else
  35458. {
  35459. imageToDraw = getToggleState() ? disabledImageOn
  35460. : disabledImage;
  35461. if (imageToDraw == 0)
  35462. {
  35463. g.setOpacity (0.4f);
  35464. imageToDraw = getNormalImage();
  35465. }
  35466. }
  35467. if (imageToDraw != 0)
  35468. {
  35469. if (style == ImageRaw)
  35470. {
  35471. imageToDraw->draw (g, 1.0f);
  35472. }
  35473. else
  35474. {
  35475. imageToDraw->drawWithin (g,
  35476. imageSpace.getX(),
  35477. imageSpace.getY(),
  35478. imageSpace.getWidth(),
  35479. imageSpace.getHeight(),
  35480. RectanglePlacement::centred,
  35481. 1.0f);
  35482. }
  35483. }
  35484. }
  35485. const Drawable* DrawableButton::getCurrentImage() const throw()
  35486. {
  35487. if (isDown())
  35488. return getDownImage();
  35489. if (isOver())
  35490. return getOverImage();
  35491. return getNormalImage();
  35492. }
  35493. const Drawable* DrawableButton::getNormalImage() const throw()
  35494. {
  35495. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35496. : normalImage;
  35497. }
  35498. const Drawable* DrawableButton::getOverImage() const throw()
  35499. {
  35500. const Drawable* d = normalImage;
  35501. if (getToggleState())
  35502. {
  35503. if (overImageOn != 0)
  35504. d = overImageOn;
  35505. else if (normalImageOn != 0)
  35506. d = normalImageOn;
  35507. else if (overImage != 0)
  35508. d = overImage;
  35509. }
  35510. else
  35511. {
  35512. if (overImage != 0)
  35513. d = overImage;
  35514. }
  35515. return d;
  35516. }
  35517. const Drawable* DrawableButton::getDownImage() const throw()
  35518. {
  35519. const Drawable* d = normalImage;
  35520. if (getToggleState())
  35521. {
  35522. if (downImageOn != 0)
  35523. d = downImageOn;
  35524. else if (overImageOn != 0)
  35525. d = overImageOn;
  35526. else if (normalImageOn != 0)
  35527. d = normalImageOn;
  35528. else if (downImage != 0)
  35529. d = downImage;
  35530. else
  35531. d = getOverImage();
  35532. }
  35533. else
  35534. {
  35535. if (downImage != 0)
  35536. d = downImage;
  35537. else
  35538. d = getOverImage();
  35539. }
  35540. return d;
  35541. }
  35542. END_JUCE_NAMESPACE
  35543. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35544. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35545. BEGIN_JUCE_NAMESPACE
  35546. HyperlinkButton::HyperlinkButton (const String& linkText,
  35547. const URL& linkURL)
  35548. : Button (linkText),
  35549. url (linkURL),
  35550. font (14.0f, Font::underlined),
  35551. resizeFont (true),
  35552. justification (Justification::centred)
  35553. {
  35554. setMouseCursor (MouseCursor::PointingHandCursor);
  35555. setTooltip (linkURL.toString (false));
  35556. }
  35557. HyperlinkButton::~HyperlinkButton()
  35558. {
  35559. }
  35560. void HyperlinkButton::setFont (const Font& newFont,
  35561. const bool resizeToMatchComponentHeight,
  35562. const Justification& justificationType)
  35563. {
  35564. font = newFont;
  35565. resizeFont = resizeToMatchComponentHeight;
  35566. justification = justificationType;
  35567. repaint();
  35568. }
  35569. void HyperlinkButton::setURL (const URL& newURL) throw()
  35570. {
  35571. url = newURL;
  35572. setTooltip (newURL.toString (false));
  35573. }
  35574. const Font HyperlinkButton::getFontToUse() const
  35575. {
  35576. Font f (font);
  35577. if (resizeFont)
  35578. f.setHeight (getHeight() * 0.7f);
  35579. return f;
  35580. }
  35581. void HyperlinkButton::changeWidthToFitText()
  35582. {
  35583. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35584. }
  35585. void HyperlinkButton::colourChanged()
  35586. {
  35587. repaint();
  35588. }
  35589. void HyperlinkButton::clicked()
  35590. {
  35591. if (url.isWellFormed())
  35592. url.launchInDefaultBrowser();
  35593. }
  35594. void HyperlinkButton::paintButton (Graphics& g,
  35595. bool isMouseOverButton,
  35596. bool isButtonDown)
  35597. {
  35598. const Colour textColour (findColour (textColourId));
  35599. if (isEnabled())
  35600. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35601. : textColour);
  35602. else
  35603. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35604. g.setFont (getFontToUse());
  35605. g.drawText (getButtonText(),
  35606. 2, 0, getWidth() - 2, getHeight(),
  35607. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35608. true);
  35609. }
  35610. END_JUCE_NAMESPACE
  35611. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35612. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35613. BEGIN_JUCE_NAMESPACE
  35614. ImageButton::ImageButton (const String& text_)
  35615. : Button (text_),
  35616. scaleImageToFit (true),
  35617. preserveProportions (true),
  35618. alphaThreshold (0),
  35619. imageX (0),
  35620. imageY (0),
  35621. imageW (0),
  35622. imageH (0),
  35623. normalImage (0),
  35624. overImage (0),
  35625. downImage (0)
  35626. {
  35627. }
  35628. ImageButton::~ImageButton()
  35629. {
  35630. }
  35631. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35632. const bool rescaleImagesWhenButtonSizeChanges,
  35633. const bool preserveImageProportions,
  35634. const Image& normalImage_,
  35635. const float imageOpacityWhenNormal,
  35636. const Colour& overlayColourWhenNormal,
  35637. const Image& overImage_,
  35638. const float imageOpacityWhenOver,
  35639. const Colour& overlayColourWhenOver,
  35640. const Image& downImage_,
  35641. const float imageOpacityWhenDown,
  35642. const Colour& overlayColourWhenDown,
  35643. const float hitTestAlphaThreshold)
  35644. {
  35645. normalImage = normalImage_;
  35646. overImage = overImage_;
  35647. downImage = downImage_;
  35648. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35649. {
  35650. imageW = normalImage.getWidth();
  35651. imageH = normalImage.getHeight();
  35652. setSize (imageW, imageH);
  35653. }
  35654. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35655. preserveProportions = preserveImageProportions;
  35656. normalOpacity = imageOpacityWhenNormal;
  35657. normalOverlay = overlayColourWhenNormal;
  35658. overOpacity = imageOpacityWhenOver;
  35659. overOverlay = overlayColourWhenOver;
  35660. downOpacity = imageOpacityWhenDown;
  35661. downOverlay = overlayColourWhenDown;
  35662. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35663. repaint();
  35664. }
  35665. const Image ImageButton::getCurrentImage() const
  35666. {
  35667. if (isDown() || getToggleState())
  35668. return getDownImage();
  35669. if (isOver())
  35670. return getOverImage();
  35671. return getNormalImage();
  35672. }
  35673. const Image ImageButton::getNormalImage() const
  35674. {
  35675. return normalImage;
  35676. }
  35677. const Image ImageButton::getOverImage() const
  35678. {
  35679. return overImage.isValid() ? overImage
  35680. : normalImage;
  35681. }
  35682. const Image ImageButton::getDownImage() const
  35683. {
  35684. return downImage.isValid() ? downImage
  35685. : getOverImage();
  35686. }
  35687. void ImageButton::paintButton (Graphics& g,
  35688. bool isMouseOverButton,
  35689. bool isButtonDown)
  35690. {
  35691. if (! isEnabled())
  35692. {
  35693. isMouseOverButton = false;
  35694. isButtonDown = false;
  35695. }
  35696. Image im (getCurrentImage());
  35697. if (im.isValid())
  35698. {
  35699. const int iw = im.getWidth();
  35700. const int ih = im.getHeight();
  35701. imageW = getWidth();
  35702. imageH = getHeight();
  35703. imageX = (imageW - iw) >> 1;
  35704. imageY = (imageH - ih) >> 1;
  35705. if (scaleImageToFit)
  35706. {
  35707. if (preserveProportions)
  35708. {
  35709. int newW, newH;
  35710. const float imRatio = ih / (float)iw;
  35711. const float destRatio = imageH / (float)imageW;
  35712. if (imRatio > destRatio)
  35713. {
  35714. newW = roundToInt (imageH / imRatio);
  35715. newH = imageH;
  35716. }
  35717. else
  35718. {
  35719. newW = imageW;
  35720. newH = roundToInt (imageW * imRatio);
  35721. }
  35722. imageX = (imageW - newW) / 2;
  35723. imageY = (imageH - newH) / 2;
  35724. imageW = newW;
  35725. imageH = newH;
  35726. }
  35727. else
  35728. {
  35729. imageX = 0;
  35730. imageY = 0;
  35731. }
  35732. }
  35733. if (! scaleImageToFit)
  35734. {
  35735. imageW = iw;
  35736. imageH = ih;
  35737. }
  35738. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35739. isButtonDown ? downOverlay
  35740. : (isMouseOverButton ? overOverlay
  35741. : normalOverlay),
  35742. isButtonDown ? downOpacity
  35743. : (isMouseOverButton ? overOpacity
  35744. : normalOpacity),
  35745. *this);
  35746. }
  35747. }
  35748. bool ImageButton::hitTest (int x, int y)
  35749. {
  35750. if (alphaThreshold == 0)
  35751. return true;
  35752. Image im (getCurrentImage());
  35753. return im.isNull() || (imageW > 0 && imageH > 0
  35754. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35755. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35756. }
  35757. END_JUCE_NAMESPACE
  35758. /*** End of inlined file: juce_ImageButton.cpp ***/
  35759. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35760. BEGIN_JUCE_NAMESPACE
  35761. ShapeButton::ShapeButton (const String& text_,
  35762. const Colour& normalColour_,
  35763. const Colour& overColour_,
  35764. const Colour& downColour_)
  35765. : Button (text_),
  35766. normalColour (normalColour_),
  35767. overColour (overColour_),
  35768. downColour (downColour_),
  35769. maintainShapeProportions (false),
  35770. outlineWidth (0.0f)
  35771. {
  35772. }
  35773. ShapeButton::~ShapeButton()
  35774. {
  35775. }
  35776. void ShapeButton::setColours (const Colour& newNormalColour,
  35777. const Colour& newOverColour,
  35778. const Colour& newDownColour)
  35779. {
  35780. normalColour = newNormalColour;
  35781. overColour = newOverColour;
  35782. downColour = newDownColour;
  35783. }
  35784. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35785. const float newOutlineWidth)
  35786. {
  35787. outlineColour = newOutlineColour;
  35788. outlineWidth = newOutlineWidth;
  35789. }
  35790. void ShapeButton::setShape (const Path& newShape,
  35791. const bool resizeNowToFitThisShape,
  35792. const bool maintainShapeProportions_,
  35793. const bool hasShadow)
  35794. {
  35795. shape = newShape;
  35796. maintainShapeProportions = maintainShapeProportions_;
  35797. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35798. setComponentEffect ((hasShadow) ? &shadow : 0);
  35799. if (resizeNowToFitThisShape)
  35800. {
  35801. Rectangle<float> bounds (shape.getBounds());
  35802. if (hasShadow)
  35803. bounds.expand (4.0f, 4.0f);
  35804. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35805. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35806. 1 + (int) (bounds.getHeight() + outlineWidth));
  35807. }
  35808. }
  35809. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35810. {
  35811. if (! isEnabled())
  35812. {
  35813. isMouseOverButton = false;
  35814. isButtonDown = false;
  35815. }
  35816. g.setColour ((isButtonDown) ? downColour
  35817. : (isMouseOverButton) ? overColour
  35818. : normalColour);
  35819. int w = getWidth();
  35820. int h = getHeight();
  35821. if (getComponentEffect() != 0)
  35822. {
  35823. w -= 4;
  35824. h -= 4;
  35825. }
  35826. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35827. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35828. w - offset - outlineWidth,
  35829. h - offset - outlineWidth,
  35830. maintainShapeProportions));
  35831. g.fillPath (shape, trans);
  35832. if (outlineWidth > 0.0f)
  35833. {
  35834. g.setColour (outlineColour);
  35835. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35836. }
  35837. }
  35838. END_JUCE_NAMESPACE
  35839. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35840. /*** Start of inlined file: juce_TextButton.cpp ***/
  35841. BEGIN_JUCE_NAMESPACE
  35842. TextButton::TextButton (const String& name,
  35843. const String& toolTip)
  35844. : Button (name)
  35845. {
  35846. setTooltip (toolTip);
  35847. }
  35848. TextButton::~TextButton()
  35849. {
  35850. }
  35851. void TextButton::paintButton (Graphics& g,
  35852. bool isMouseOverButton,
  35853. bool isButtonDown)
  35854. {
  35855. getLookAndFeel().drawButtonBackground (g, *this,
  35856. findColour (getToggleState() ? buttonOnColourId
  35857. : buttonColourId),
  35858. isMouseOverButton,
  35859. isButtonDown);
  35860. getLookAndFeel().drawButtonText (g, *this,
  35861. isMouseOverButton,
  35862. isButtonDown);
  35863. }
  35864. void TextButton::colourChanged()
  35865. {
  35866. repaint();
  35867. }
  35868. const Font TextButton::getFont()
  35869. {
  35870. return Font (jmin (15.0f, getHeight() * 0.6f));
  35871. }
  35872. void TextButton::changeWidthToFitText (const int newHeight)
  35873. {
  35874. if (newHeight >= 0)
  35875. setSize (jmax (1, getWidth()), newHeight);
  35876. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35877. getHeight());
  35878. }
  35879. END_JUCE_NAMESPACE
  35880. /*** End of inlined file: juce_TextButton.cpp ***/
  35881. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35882. BEGIN_JUCE_NAMESPACE
  35883. ToggleButton::ToggleButton (const String& buttonText)
  35884. : Button (buttonText)
  35885. {
  35886. setClickingTogglesState (true);
  35887. }
  35888. ToggleButton::~ToggleButton()
  35889. {
  35890. }
  35891. void ToggleButton::paintButton (Graphics& g,
  35892. bool isMouseOverButton,
  35893. bool isButtonDown)
  35894. {
  35895. getLookAndFeel().drawToggleButton (g, *this,
  35896. isMouseOverButton,
  35897. isButtonDown);
  35898. }
  35899. void ToggleButton::changeWidthToFitText()
  35900. {
  35901. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35902. }
  35903. void ToggleButton::colourChanged()
  35904. {
  35905. repaint();
  35906. }
  35907. END_JUCE_NAMESPACE
  35908. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35909. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35910. BEGIN_JUCE_NAMESPACE
  35911. ToolbarButton::ToolbarButton (const int itemId_,
  35912. const String& buttonText,
  35913. Drawable* const normalImage_,
  35914. Drawable* const toggledOnImage_)
  35915. : ToolbarItemComponent (itemId_, buttonText, true),
  35916. normalImage (normalImage_),
  35917. toggledOnImage (toggledOnImage_)
  35918. {
  35919. jassert (normalImage_ != 0);
  35920. }
  35921. ToolbarButton::~ToolbarButton()
  35922. {
  35923. }
  35924. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35925. bool /*isToolbarVertical*/,
  35926. int& preferredSize,
  35927. int& minSize, int& maxSize)
  35928. {
  35929. preferredSize = minSize = maxSize = toolbarDepth;
  35930. return true;
  35931. }
  35932. void ToolbarButton::paintButtonArea (Graphics& g,
  35933. int width, int height,
  35934. bool /*isMouseOver*/,
  35935. bool /*isMouseDown*/)
  35936. {
  35937. Drawable* d = normalImage;
  35938. if (getToggleState() && toggledOnImage != 0)
  35939. d = toggledOnImage;
  35940. if (! isEnabled())
  35941. {
  35942. Image im (Image::ARGB, width, height, true);
  35943. {
  35944. Graphics g2 (im);
  35945. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35946. }
  35947. im.desaturate();
  35948. g.drawImageAt (im, 0, 0);
  35949. }
  35950. else
  35951. {
  35952. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35953. }
  35954. }
  35955. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35956. {
  35957. }
  35958. END_JUCE_NAMESPACE
  35959. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35960. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35961. BEGIN_JUCE_NAMESPACE
  35962. class CodeDocumentLine
  35963. {
  35964. public:
  35965. CodeDocumentLine (const juce_wchar* const line_,
  35966. const int lineLength_,
  35967. const int numNewLineChars,
  35968. const int lineStartInFile_)
  35969. : line (line_, lineLength_),
  35970. lineStartInFile (lineStartInFile_),
  35971. lineLength (lineLength_),
  35972. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35973. {
  35974. }
  35975. ~CodeDocumentLine()
  35976. {
  35977. }
  35978. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35979. {
  35980. const juce_wchar* const t = text;
  35981. int pos = 0;
  35982. while (t [pos] != 0)
  35983. {
  35984. const int startOfLine = pos;
  35985. int numNewLineChars = 0;
  35986. while (t[pos] != 0)
  35987. {
  35988. if (t[pos] == '\r')
  35989. {
  35990. ++numNewLineChars;
  35991. ++pos;
  35992. if (t[pos] == '\n')
  35993. {
  35994. ++numNewLineChars;
  35995. ++pos;
  35996. }
  35997. break;
  35998. }
  35999. if (t[pos] == '\n')
  36000. {
  36001. ++numNewLineChars;
  36002. ++pos;
  36003. break;
  36004. }
  36005. ++pos;
  36006. }
  36007. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36008. numNewLineChars, startOfLine));
  36009. }
  36010. jassert (pos == text.length());
  36011. }
  36012. bool endsWithLineBreak() const throw()
  36013. {
  36014. return lineLengthWithoutNewLines != lineLength;
  36015. }
  36016. void updateLength() throw()
  36017. {
  36018. lineLengthWithoutNewLines = lineLength = line.length();
  36019. while (lineLengthWithoutNewLines > 0
  36020. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36021. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36022. {
  36023. --lineLengthWithoutNewLines;
  36024. }
  36025. }
  36026. String line;
  36027. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36028. };
  36029. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36030. : document (document_),
  36031. currentLine (document_->lines[0]),
  36032. line (0),
  36033. position (0)
  36034. {
  36035. }
  36036. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36037. : document (other.document),
  36038. currentLine (other.currentLine),
  36039. line (other.line),
  36040. position (other.position)
  36041. {
  36042. }
  36043. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36044. {
  36045. document = other.document;
  36046. currentLine = other.currentLine;
  36047. line = other.line;
  36048. position = other.position;
  36049. return *this;
  36050. }
  36051. CodeDocument::Iterator::~Iterator() throw()
  36052. {
  36053. }
  36054. juce_wchar CodeDocument::Iterator::nextChar()
  36055. {
  36056. if (currentLine == 0)
  36057. return 0;
  36058. jassert (currentLine == document->lines.getUnchecked (line));
  36059. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36060. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36061. {
  36062. ++line;
  36063. currentLine = document->lines [line];
  36064. }
  36065. return result;
  36066. }
  36067. void CodeDocument::Iterator::skip()
  36068. {
  36069. if (currentLine != 0)
  36070. {
  36071. jassert (currentLine == document->lines.getUnchecked (line));
  36072. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36073. {
  36074. ++line;
  36075. currentLine = document->lines [line];
  36076. }
  36077. }
  36078. }
  36079. void CodeDocument::Iterator::skipToEndOfLine()
  36080. {
  36081. if (currentLine != 0)
  36082. {
  36083. jassert (currentLine == document->lines.getUnchecked (line));
  36084. ++line;
  36085. currentLine = document->lines [line];
  36086. if (currentLine != 0)
  36087. position = currentLine->lineStartInFile;
  36088. else
  36089. position = document->getNumCharacters();
  36090. }
  36091. }
  36092. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36093. {
  36094. if (currentLine == 0)
  36095. return 0;
  36096. jassert (currentLine == document->lines.getUnchecked (line));
  36097. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36098. }
  36099. void CodeDocument::Iterator::skipWhitespace()
  36100. {
  36101. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36102. skip();
  36103. }
  36104. bool CodeDocument::Iterator::isEOF() const throw()
  36105. {
  36106. return currentLine == 0;
  36107. }
  36108. CodeDocument::Position::Position() throw()
  36109. : owner (0), characterPos (0), line (0),
  36110. indexInLine (0), positionMaintained (false)
  36111. {
  36112. }
  36113. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36114. const int line_, const int indexInLine_) throw()
  36115. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36116. characterPos (0), line (line_),
  36117. indexInLine (indexInLine_), positionMaintained (false)
  36118. {
  36119. setLineAndIndex (line_, indexInLine_);
  36120. }
  36121. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36122. const int characterPos_) throw()
  36123. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36124. positionMaintained (false)
  36125. {
  36126. setPosition (characterPos_);
  36127. }
  36128. CodeDocument::Position::Position (const Position& other) throw()
  36129. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36130. indexInLine (other.indexInLine), positionMaintained (false)
  36131. {
  36132. jassert (*this == other);
  36133. }
  36134. CodeDocument::Position::~Position()
  36135. {
  36136. setPositionMaintained (false);
  36137. }
  36138. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36139. {
  36140. if (this != &other)
  36141. {
  36142. const bool wasPositionMaintained = positionMaintained;
  36143. if (owner != other.owner)
  36144. setPositionMaintained (false);
  36145. owner = other.owner;
  36146. line = other.line;
  36147. indexInLine = other.indexInLine;
  36148. characterPos = other.characterPos;
  36149. setPositionMaintained (wasPositionMaintained);
  36150. jassert (*this == other);
  36151. }
  36152. return *this;
  36153. }
  36154. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36155. {
  36156. jassert ((characterPos == other.characterPos)
  36157. == (line == other.line && indexInLine == other.indexInLine));
  36158. return characterPos == other.characterPos
  36159. && line == other.line
  36160. && indexInLine == other.indexInLine
  36161. && owner == other.owner;
  36162. }
  36163. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36164. {
  36165. return ! operator== (other);
  36166. }
  36167. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36168. {
  36169. jassert (owner != 0);
  36170. if (owner->lines.size() == 0)
  36171. {
  36172. line = 0;
  36173. indexInLine = 0;
  36174. characterPos = 0;
  36175. }
  36176. else
  36177. {
  36178. if (newLine >= owner->lines.size())
  36179. {
  36180. line = owner->lines.size() - 1;
  36181. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36182. jassert (l != 0);
  36183. indexInLine = l->lineLengthWithoutNewLines;
  36184. characterPos = l->lineStartInFile + indexInLine;
  36185. }
  36186. else
  36187. {
  36188. line = jmax (0, newLine);
  36189. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36190. jassert (l != 0);
  36191. if (l->lineLengthWithoutNewLines > 0)
  36192. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36193. else
  36194. indexInLine = 0;
  36195. characterPos = l->lineStartInFile + indexInLine;
  36196. }
  36197. }
  36198. }
  36199. void CodeDocument::Position::setPosition (const int newPosition)
  36200. {
  36201. jassert (owner != 0);
  36202. line = 0;
  36203. indexInLine = 0;
  36204. characterPos = 0;
  36205. if (newPosition > 0)
  36206. {
  36207. int lineStart = 0;
  36208. int lineEnd = owner->lines.size();
  36209. for (;;)
  36210. {
  36211. if (lineEnd - lineStart < 4)
  36212. {
  36213. for (int i = lineStart; i < lineEnd; ++i)
  36214. {
  36215. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36216. int index = newPosition - l->lineStartInFile;
  36217. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36218. {
  36219. line = i;
  36220. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36221. characterPos = l->lineStartInFile + indexInLine;
  36222. }
  36223. }
  36224. break;
  36225. }
  36226. else
  36227. {
  36228. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36229. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36230. if (newPosition >= mid->lineStartInFile)
  36231. lineStart = midIndex;
  36232. else
  36233. lineEnd = midIndex;
  36234. }
  36235. }
  36236. }
  36237. }
  36238. void CodeDocument::Position::moveBy (int characterDelta)
  36239. {
  36240. jassert (owner != 0);
  36241. if (characterDelta == 1)
  36242. {
  36243. setPosition (getPosition());
  36244. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36245. if (line < owner->lines.size())
  36246. {
  36247. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36248. if (indexInLine + characterDelta < l->lineLength
  36249. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36250. ++characterDelta;
  36251. }
  36252. }
  36253. setPosition (characterPos + characterDelta);
  36254. }
  36255. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36256. {
  36257. CodeDocument::Position p (*this);
  36258. p.moveBy (characterDelta);
  36259. return p;
  36260. }
  36261. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36262. {
  36263. CodeDocument::Position p (*this);
  36264. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36265. return p;
  36266. }
  36267. const juce_wchar CodeDocument::Position::getCharacter() const
  36268. {
  36269. const CodeDocumentLine* const l = owner->lines [line];
  36270. return l == 0 ? 0 : l->line [getIndexInLine()];
  36271. }
  36272. const String CodeDocument::Position::getLineText() const
  36273. {
  36274. const CodeDocumentLine* const l = owner->lines [line];
  36275. return l == 0 ? String::empty : l->line;
  36276. }
  36277. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36278. {
  36279. if (isMaintained != positionMaintained)
  36280. {
  36281. positionMaintained = isMaintained;
  36282. if (owner != 0)
  36283. {
  36284. if (isMaintained)
  36285. {
  36286. jassert (! owner->positionsToMaintain.contains (this));
  36287. owner->positionsToMaintain.add (this);
  36288. }
  36289. else
  36290. {
  36291. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36292. jassert (owner->positionsToMaintain.contains (this));
  36293. owner->positionsToMaintain.removeValue (this);
  36294. }
  36295. }
  36296. }
  36297. }
  36298. CodeDocument::CodeDocument()
  36299. : undoManager (std::numeric_limits<int>::max(), 10000),
  36300. currentActionIndex (0),
  36301. indexOfSavedState (-1),
  36302. maximumLineLength (-1),
  36303. newLineChars ("\r\n")
  36304. {
  36305. }
  36306. CodeDocument::~CodeDocument()
  36307. {
  36308. }
  36309. const String CodeDocument::getAllContent() const
  36310. {
  36311. return getTextBetween (Position (this, 0),
  36312. Position (this, lines.size(), 0));
  36313. }
  36314. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36315. {
  36316. if (end.getPosition() <= start.getPosition())
  36317. return String::empty;
  36318. const int startLine = start.getLineNumber();
  36319. const int endLine = end.getLineNumber();
  36320. if (startLine == endLine)
  36321. {
  36322. CodeDocumentLine* const line = lines [startLine];
  36323. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36324. }
  36325. String result;
  36326. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36327. String::Concatenator concatenator (result);
  36328. const int maxLine = jmin (lines.size() - 1, endLine);
  36329. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36330. {
  36331. const CodeDocumentLine* line = lines.getUnchecked(i);
  36332. int len = line->lineLength;
  36333. if (i == startLine)
  36334. {
  36335. const int index = start.getIndexInLine();
  36336. concatenator.append (line->line.substring (index, len));
  36337. }
  36338. else if (i == endLine)
  36339. {
  36340. len = end.getIndexInLine();
  36341. concatenator.append (line->line.substring (0, len));
  36342. }
  36343. else
  36344. {
  36345. concatenator.append (line->line);
  36346. }
  36347. }
  36348. return result;
  36349. }
  36350. int CodeDocument::getNumCharacters() const throw()
  36351. {
  36352. const CodeDocumentLine* const lastLine = lines.getLast();
  36353. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36354. }
  36355. const String CodeDocument::getLine (const int lineIndex) const throw()
  36356. {
  36357. const CodeDocumentLine* const line = lines [lineIndex];
  36358. return (line == 0) ? String::empty : line->line;
  36359. }
  36360. int CodeDocument::getMaximumLineLength() throw()
  36361. {
  36362. if (maximumLineLength < 0)
  36363. {
  36364. maximumLineLength = 0;
  36365. for (int i = lines.size(); --i >= 0;)
  36366. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36367. }
  36368. return maximumLineLength;
  36369. }
  36370. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36371. {
  36372. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36373. }
  36374. void CodeDocument::insertText (const Position& position, const String& text)
  36375. {
  36376. insert (text, position.getPosition(), true);
  36377. }
  36378. void CodeDocument::replaceAllContent (const String& newContent)
  36379. {
  36380. remove (0, getNumCharacters(), true);
  36381. insert (newContent, 0, true);
  36382. }
  36383. bool CodeDocument::loadFromStream (InputStream& stream)
  36384. {
  36385. replaceAllContent (stream.readEntireStreamAsString());
  36386. setSavePoint();
  36387. clearUndoHistory();
  36388. return true;
  36389. }
  36390. bool CodeDocument::writeToStream (OutputStream& stream)
  36391. {
  36392. for (int i = 0; i < lines.size(); ++i)
  36393. {
  36394. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36395. const char* utf8 = temp.toUTF8();
  36396. if (! stream.write (utf8, (int) strlen (utf8)))
  36397. return false;
  36398. }
  36399. return true;
  36400. }
  36401. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36402. {
  36403. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36404. newLineChars = newLine;
  36405. }
  36406. void CodeDocument::newTransaction()
  36407. {
  36408. undoManager.beginNewTransaction (String::empty);
  36409. }
  36410. void CodeDocument::undo()
  36411. {
  36412. newTransaction();
  36413. undoManager.undo();
  36414. }
  36415. void CodeDocument::redo()
  36416. {
  36417. undoManager.redo();
  36418. }
  36419. void CodeDocument::clearUndoHistory()
  36420. {
  36421. undoManager.clearUndoHistory();
  36422. }
  36423. void CodeDocument::setSavePoint() throw()
  36424. {
  36425. indexOfSavedState = currentActionIndex;
  36426. }
  36427. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36428. {
  36429. return currentActionIndex != indexOfSavedState;
  36430. }
  36431. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36432. {
  36433. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36434. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36435. }
  36436. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36437. {
  36438. Position p (position);
  36439. const int maxDistance = 256;
  36440. int i = 0;
  36441. while (i < maxDistance
  36442. && CharacterFunctions::isWhitespace (p.getCharacter())
  36443. && (i == 0 || (p.getCharacter() != '\n'
  36444. && p.getCharacter() != '\r')))
  36445. {
  36446. ++i;
  36447. p.moveBy (1);
  36448. }
  36449. if (i == 0)
  36450. {
  36451. const int type = getCodeCharacterCategory (p.getCharacter());
  36452. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36453. {
  36454. ++i;
  36455. p.moveBy (1);
  36456. }
  36457. while (i < maxDistance
  36458. && CharacterFunctions::isWhitespace (p.getCharacter())
  36459. && (i == 0 || (p.getCharacter() != '\n'
  36460. && p.getCharacter() != '\r')))
  36461. {
  36462. ++i;
  36463. p.moveBy (1);
  36464. }
  36465. }
  36466. return p;
  36467. }
  36468. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36469. {
  36470. Position p (position);
  36471. const int maxDistance = 256;
  36472. int i = 0;
  36473. bool stoppedAtLineStart = false;
  36474. while (i < maxDistance)
  36475. {
  36476. const juce_wchar c = p.movedBy (-1).getCharacter();
  36477. if (c == '\r' || c == '\n')
  36478. {
  36479. stoppedAtLineStart = true;
  36480. if (i > 0)
  36481. break;
  36482. }
  36483. if (! CharacterFunctions::isWhitespace (c))
  36484. break;
  36485. p.moveBy (-1);
  36486. ++i;
  36487. }
  36488. if (i < maxDistance && ! stoppedAtLineStart)
  36489. {
  36490. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36491. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36492. {
  36493. p.moveBy (-1);
  36494. ++i;
  36495. }
  36496. }
  36497. return p;
  36498. }
  36499. void CodeDocument::checkLastLineStatus()
  36500. {
  36501. while (lines.size() > 0
  36502. && lines.getLast()->lineLength == 0
  36503. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36504. {
  36505. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36506. lines.removeLast();
  36507. }
  36508. const CodeDocumentLine* const lastLine = lines.getLast();
  36509. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36510. {
  36511. // check that there's an empty line at the end if the preceding one ends in a newline..
  36512. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36513. }
  36514. }
  36515. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36516. {
  36517. listeners.add (listener);
  36518. }
  36519. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36520. {
  36521. listeners.remove (listener);
  36522. }
  36523. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36524. {
  36525. Position startPos (this, startLine, 0);
  36526. Position endPos (this, endLine, 0);
  36527. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36528. }
  36529. class CodeDocumentInsertAction : public UndoableAction
  36530. {
  36531. CodeDocument& owner;
  36532. const String text;
  36533. int insertPos;
  36534. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36535. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36536. public:
  36537. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36538. : owner (owner_),
  36539. text (text_),
  36540. insertPos (insertPos_)
  36541. {
  36542. }
  36543. ~CodeDocumentInsertAction() {}
  36544. bool perform()
  36545. {
  36546. owner.currentActionIndex++;
  36547. owner.insert (text, insertPos, false);
  36548. return true;
  36549. }
  36550. bool undo()
  36551. {
  36552. owner.currentActionIndex--;
  36553. owner.remove (insertPos, insertPos + text.length(), false);
  36554. return true;
  36555. }
  36556. int getSizeInUnits() { return text.length() + 32; }
  36557. };
  36558. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36559. {
  36560. if (text.isEmpty())
  36561. return;
  36562. if (undoable)
  36563. {
  36564. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36565. }
  36566. else
  36567. {
  36568. Position pos (this, insertPos);
  36569. const int firstAffectedLine = pos.getLineNumber();
  36570. int lastAffectedLine = firstAffectedLine + 1;
  36571. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36572. String textInsideOriginalLine (text);
  36573. if (firstLine != 0)
  36574. {
  36575. const int index = pos.getIndexInLine();
  36576. textInsideOriginalLine = firstLine->line.substring (0, index)
  36577. + textInsideOriginalLine
  36578. + firstLine->line.substring (index);
  36579. }
  36580. maximumLineLength = -1;
  36581. Array <CodeDocumentLine*> newLines;
  36582. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36583. jassert (newLines.size() > 0);
  36584. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36585. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36586. lines.set (firstAffectedLine, newFirstLine);
  36587. if (newLines.size() > 1)
  36588. {
  36589. for (int i = 1; i < newLines.size(); ++i)
  36590. {
  36591. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36592. lines.insert (firstAffectedLine + i, l);
  36593. }
  36594. lastAffectedLine = lines.size();
  36595. }
  36596. int i, lineStart = newFirstLine->lineStartInFile;
  36597. for (i = firstAffectedLine; i < lines.size(); ++i)
  36598. {
  36599. CodeDocumentLine* const l = lines.getUnchecked (i);
  36600. l->lineStartInFile = lineStart;
  36601. lineStart += l->lineLength;
  36602. }
  36603. checkLastLineStatus();
  36604. const int newTextLength = text.length();
  36605. for (i = 0; i < positionsToMaintain.size(); ++i)
  36606. {
  36607. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36608. if (p->getPosition() >= insertPos)
  36609. p->setPosition (p->getPosition() + newTextLength);
  36610. }
  36611. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36612. }
  36613. }
  36614. class CodeDocumentDeleteAction : public UndoableAction
  36615. {
  36616. CodeDocument& owner;
  36617. int startPos, endPos;
  36618. String removedText;
  36619. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36620. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36621. public:
  36622. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36623. : owner (owner_),
  36624. startPos (startPos_),
  36625. endPos (endPos_)
  36626. {
  36627. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36628. CodeDocument::Position (&owner, endPos));
  36629. }
  36630. ~CodeDocumentDeleteAction() {}
  36631. bool perform()
  36632. {
  36633. owner.currentActionIndex++;
  36634. owner.remove (startPos, endPos, false);
  36635. return true;
  36636. }
  36637. bool undo()
  36638. {
  36639. owner.currentActionIndex--;
  36640. owner.insert (removedText, startPos, false);
  36641. return true;
  36642. }
  36643. int getSizeInUnits() { return removedText.length() + 32; }
  36644. };
  36645. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36646. {
  36647. if (endPos <= startPos)
  36648. return;
  36649. if (undoable)
  36650. {
  36651. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36652. }
  36653. else
  36654. {
  36655. Position startPosition (this, startPos);
  36656. Position endPosition (this, endPos);
  36657. maximumLineLength = -1;
  36658. const int firstAffectedLine = startPosition.getLineNumber();
  36659. const int endLine = endPosition.getLineNumber();
  36660. int lastAffectedLine = firstAffectedLine + 1;
  36661. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36662. if (firstAffectedLine == endLine)
  36663. {
  36664. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36665. + firstLine->line.substring (endPosition.getIndexInLine());
  36666. firstLine->updateLength();
  36667. }
  36668. else
  36669. {
  36670. lastAffectedLine = lines.size();
  36671. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36672. jassert (lastLine != 0);
  36673. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36674. + lastLine->line.substring (endPosition.getIndexInLine());
  36675. firstLine->updateLength();
  36676. int numLinesToRemove = endLine - firstAffectedLine;
  36677. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36678. }
  36679. int i;
  36680. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36681. {
  36682. CodeDocumentLine* const l = lines.getUnchecked (i);
  36683. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36684. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36685. }
  36686. checkLastLineStatus();
  36687. const int totalChars = getNumCharacters();
  36688. for (i = 0; i < positionsToMaintain.size(); ++i)
  36689. {
  36690. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36691. if (p->getPosition() > startPosition.getPosition())
  36692. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36693. if (p->getPosition() > totalChars)
  36694. p->setPosition (totalChars);
  36695. }
  36696. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36697. }
  36698. }
  36699. END_JUCE_NAMESPACE
  36700. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36701. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36702. BEGIN_JUCE_NAMESPACE
  36703. class CodeEditorComponent::CaretComponent : public Component,
  36704. public Timer
  36705. {
  36706. public:
  36707. CaretComponent (CodeEditorComponent& owner_)
  36708. : owner (owner_)
  36709. {
  36710. setAlwaysOnTop (true);
  36711. setInterceptsMouseClicks (false, false);
  36712. }
  36713. ~CaretComponent()
  36714. {
  36715. }
  36716. void paint (Graphics& g)
  36717. {
  36718. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36719. }
  36720. void timerCallback()
  36721. {
  36722. setVisible (shouldBeShown() && ! isVisible());
  36723. }
  36724. void updatePosition()
  36725. {
  36726. startTimer (400);
  36727. setVisible (shouldBeShown());
  36728. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36729. }
  36730. private:
  36731. CodeEditorComponent& owner;
  36732. CaretComponent (const CaretComponent&);
  36733. CaretComponent& operator= (const CaretComponent&);
  36734. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36735. };
  36736. class CodeEditorComponent::CodeEditorLine
  36737. {
  36738. public:
  36739. CodeEditorLine() throw()
  36740. : highlightColumnStart (0), highlightColumnEnd (0)
  36741. {
  36742. }
  36743. ~CodeEditorLine() throw()
  36744. {
  36745. }
  36746. bool update (CodeDocument& document, int lineNum,
  36747. CodeDocument::Iterator& source,
  36748. CodeTokeniser* analyser, const int spacesPerTab,
  36749. const CodeDocument::Position& selectionStart,
  36750. const CodeDocument::Position& selectionEnd)
  36751. {
  36752. Array <SyntaxToken> newTokens;
  36753. newTokens.ensureStorageAllocated (8);
  36754. if (analyser == 0)
  36755. {
  36756. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36757. }
  36758. else if (lineNum < document.getNumLines())
  36759. {
  36760. const CodeDocument::Position pos (&document, lineNum, 0);
  36761. createTokens (pos.getPosition(), pos.getLineText(),
  36762. source, analyser, newTokens);
  36763. }
  36764. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36765. int newHighlightStart = 0;
  36766. int newHighlightEnd = 0;
  36767. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36768. {
  36769. const String line (document.getLine (lineNum));
  36770. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36771. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36772. line, spacesPerTab);
  36773. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36774. line, spacesPerTab);
  36775. }
  36776. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36777. {
  36778. highlightColumnStart = newHighlightStart;
  36779. highlightColumnEnd = newHighlightEnd;
  36780. }
  36781. else
  36782. {
  36783. if (tokens.size() == newTokens.size())
  36784. {
  36785. bool allTheSame = true;
  36786. for (int i = newTokens.size(); --i >= 0;)
  36787. {
  36788. if (tokens.getReference(i) != newTokens.getReference(i))
  36789. {
  36790. allTheSame = false;
  36791. break;
  36792. }
  36793. }
  36794. if (allTheSame)
  36795. return false;
  36796. }
  36797. }
  36798. tokens.swapWithArray (newTokens);
  36799. return true;
  36800. }
  36801. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36802. float x, const int y, const int baselineOffset, const int lineHeight,
  36803. const Colour& highlightColour) const
  36804. {
  36805. if (highlightColumnStart < highlightColumnEnd)
  36806. {
  36807. g.setColour (highlightColour);
  36808. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36809. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36810. }
  36811. int lastType = std::numeric_limits<int>::min();
  36812. for (int i = 0; i < tokens.size(); ++i)
  36813. {
  36814. SyntaxToken& token = tokens.getReference(i);
  36815. if (lastType != token.tokenType)
  36816. {
  36817. lastType = token.tokenType;
  36818. g.setColour (owner.getColourForTokenType (lastType));
  36819. }
  36820. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36821. if (i < tokens.size() - 1)
  36822. {
  36823. if (token.width < 0)
  36824. token.width = font.getStringWidthFloat (token.text);
  36825. x += token.width;
  36826. }
  36827. }
  36828. }
  36829. private:
  36830. struct SyntaxToken
  36831. {
  36832. String text;
  36833. int tokenType;
  36834. float width;
  36835. SyntaxToken (const String& text_, const int type) throw()
  36836. : text (text_), tokenType (type), width (-1.0f)
  36837. {
  36838. }
  36839. bool operator!= (const SyntaxToken& other) const throw()
  36840. {
  36841. return text != other.text || tokenType != other.tokenType;
  36842. }
  36843. };
  36844. Array <SyntaxToken> tokens;
  36845. int highlightColumnStart, highlightColumnEnd;
  36846. static void createTokens (int startPosition, const String& lineText,
  36847. CodeDocument::Iterator& source,
  36848. CodeTokeniser* analyser,
  36849. Array <SyntaxToken>& newTokens)
  36850. {
  36851. CodeDocument::Iterator lastIterator (source);
  36852. const int lineLength = lineText.length();
  36853. for (;;)
  36854. {
  36855. int tokenType = analyser->readNextToken (source);
  36856. int tokenStart = lastIterator.getPosition();
  36857. int tokenEnd = source.getPosition();
  36858. if (tokenEnd <= tokenStart)
  36859. break;
  36860. tokenEnd -= startPosition;
  36861. if (tokenEnd > 0)
  36862. {
  36863. tokenStart -= startPosition;
  36864. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36865. tokenType));
  36866. if (tokenEnd >= lineLength)
  36867. break;
  36868. }
  36869. lastIterator = source;
  36870. }
  36871. source = lastIterator;
  36872. }
  36873. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36874. {
  36875. int x = 0;
  36876. for (int i = 0; i < tokens.size(); ++i)
  36877. {
  36878. SyntaxToken& t = tokens.getReference(i);
  36879. for (;;)
  36880. {
  36881. int tabPos = t.text.indexOfChar ('\t');
  36882. if (tabPos < 0)
  36883. break;
  36884. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36885. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36886. }
  36887. x += t.text.length();
  36888. }
  36889. }
  36890. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36891. {
  36892. jassert (index <= line.length());
  36893. int col = 0;
  36894. for (int i = 0; i < index; ++i)
  36895. {
  36896. if (line[i] != '\t')
  36897. ++col;
  36898. else
  36899. col += spacesPerTab - (col % spacesPerTab);
  36900. }
  36901. return col;
  36902. }
  36903. };
  36904. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36905. CodeTokeniser* const codeTokeniser_)
  36906. : document (document_),
  36907. firstLineOnScreen (0),
  36908. gutter (5),
  36909. spacesPerTab (4),
  36910. lineHeight (0),
  36911. linesOnScreen (0),
  36912. columnsOnScreen (0),
  36913. scrollbarThickness (16),
  36914. columnToTryToMaintain (-1),
  36915. useSpacesForTabs (false),
  36916. xOffset (0),
  36917. codeTokeniser (codeTokeniser_)
  36918. {
  36919. caretPos = CodeDocument::Position (&document_, 0, 0);
  36920. caretPos.setPositionMaintained (true);
  36921. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36922. selectionStart.setPositionMaintained (true);
  36923. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36924. selectionEnd.setPositionMaintained (true);
  36925. setOpaque (true);
  36926. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36927. setWantsKeyboardFocus (true);
  36928. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36929. verticalScrollBar->setSingleStepSize (1.0);
  36930. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36931. horizontalScrollBar->setSingleStepSize (1.0);
  36932. addAndMakeVisible (caret = new CaretComponent (*this));
  36933. Font f (12.0f);
  36934. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36935. setFont (f);
  36936. resetToDefaultColours();
  36937. verticalScrollBar->addListener (this);
  36938. horizontalScrollBar->addListener (this);
  36939. document.addListener (this);
  36940. }
  36941. CodeEditorComponent::~CodeEditorComponent()
  36942. {
  36943. document.removeListener (this);
  36944. deleteAllChildren();
  36945. }
  36946. void CodeEditorComponent::loadContent (const String& newContent)
  36947. {
  36948. clearCachedIterators (0);
  36949. document.replaceAllContent (newContent);
  36950. document.clearUndoHistory();
  36951. document.setSavePoint();
  36952. caretPos.setPosition (0);
  36953. selectionStart.setPosition (0);
  36954. selectionEnd.setPosition (0);
  36955. scrollToLine (0);
  36956. }
  36957. bool CodeEditorComponent::isTextInputActive() const
  36958. {
  36959. return true;
  36960. }
  36961. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36962. const CodeDocument::Position& affectedTextEnd)
  36963. {
  36964. clearCachedIterators (affectedTextStart.getLineNumber());
  36965. triggerAsyncUpdate();
  36966. caret->updatePosition();
  36967. columnToTryToMaintain = -1;
  36968. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36969. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36970. deselectAll();
  36971. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36972. || caretPos.getPosition() < affectedTextStart.getPosition())
  36973. moveCaretTo (affectedTextStart, false);
  36974. updateScrollBars();
  36975. }
  36976. void CodeEditorComponent::resized()
  36977. {
  36978. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36979. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36980. lines.clear();
  36981. rebuildLineTokens();
  36982. caret->updatePosition();
  36983. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36984. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36985. updateScrollBars();
  36986. }
  36987. void CodeEditorComponent::paint (Graphics& g)
  36988. {
  36989. handleUpdateNowIfNeeded();
  36990. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36991. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36992. g.setFont (font);
  36993. const int baselineOffset = (int) font.getAscent();
  36994. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36995. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36996. const Rectangle<int> clip (g.getClipBounds());
  36997. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36998. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36999. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37000. {
  37001. lines.getUnchecked(j)->draw (*this, g, font,
  37002. (float) (gutter - xOffset * charWidth),
  37003. lineHeight * j, baselineOffset, lineHeight,
  37004. highlightColour);
  37005. }
  37006. }
  37007. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37008. {
  37009. if (scrollbarThickness != thickness)
  37010. {
  37011. scrollbarThickness = thickness;
  37012. resized();
  37013. }
  37014. }
  37015. void CodeEditorComponent::handleAsyncUpdate()
  37016. {
  37017. rebuildLineTokens();
  37018. }
  37019. void CodeEditorComponent::rebuildLineTokens()
  37020. {
  37021. cancelPendingUpdate();
  37022. const int numNeeded = linesOnScreen + 1;
  37023. int minLineToRepaint = numNeeded;
  37024. int maxLineToRepaint = 0;
  37025. if (numNeeded != lines.size())
  37026. {
  37027. lines.clear();
  37028. for (int i = numNeeded; --i >= 0;)
  37029. lines.add (new CodeEditorLine());
  37030. minLineToRepaint = 0;
  37031. maxLineToRepaint = numNeeded;
  37032. }
  37033. jassert (numNeeded == lines.size());
  37034. CodeDocument::Iterator source (&document);
  37035. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37036. for (int i = 0; i < numNeeded; ++i)
  37037. {
  37038. CodeEditorLine* const line = lines.getUnchecked(i);
  37039. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37040. selectionStart, selectionEnd))
  37041. {
  37042. minLineToRepaint = jmin (minLineToRepaint, i);
  37043. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37044. }
  37045. }
  37046. if (minLineToRepaint <= maxLineToRepaint)
  37047. {
  37048. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37049. verticalScrollBar->getX() - gutter,
  37050. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37051. }
  37052. }
  37053. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37054. {
  37055. caretPos = newPos;
  37056. columnToTryToMaintain = -1;
  37057. if (highlighting)
  37058. {
  37059. if (dragType == notDragging)
  37060. {
  37061. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37062. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37063. dragType = draggingSelectionStart;
  37064. else
  37065. dragType = draggingSelectionEnd;
  37066. }
  37067. if (dragType == draggingSelectionStart)
  37068. {
  37069. selectionStart = caretPos;
  37070. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37071. {
  37072. const CodeDocument::Position temp (selectionStart);
  37073. selectionStart = selectionEnd;
  37074. selectionEnd = temp;
  37075. dragType = draggingSelectionEnd;
  37076. }
  37077. }
  37078. else
  37079. {
  37080. selectionEnd = caretPos;
  37081. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37082. {
  37083. const CodeDocument::Position temp (selectionStart);
  37084. selectionStart = selectionEnd;
  37085. selectionEnd = temp;
  37086. dragType = draggingSelectionStart;
  37087. }
  37088. }
  37089. triggerAsyncUpdate();
  37090. }
  37091. else
  37092. {
  37093. deselectAll();
  37094. }
  37095. caret->updatePosition();
  37096. scrollToKeepCaretOnScreen();
  37097. updateScrollBars();
  37098. }
  37099. void CodeEditorComponent::deselectAll()
  37100. {
  37101. if (selectionStart != selectionEnd)
  37102. triggerAsyncUpdate();
  37103. selectionStart = caretPos;
  37104. selectionEnd = caretPos;
  37105. }
  37106. void CodeEditorComponent::updateScrollBars()
  37107. {
  37108. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37109. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37110. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37111. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37112. }
  37113. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37114. {
  37115. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37116. newFirstLineOnScreen);
  37117. if (newFirstLineOnScreen != firstLineOnScreen)
  37118. {
  37119. firstLineOnScreen = newFirstLineOnScreen;
  37120. caret->updatePosition();
  37121. updateCachedIterators (firstLineOnScreen);
  37122. triggerAsyncUpdate();
  37123. }
  37124. }
  37125. void CodeEditorComponent::scrollToColumnInternal (double column)
  37126. {
  37127. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37128. if (xOffset != newOffset)
  37129. {
  37130. xOffset = newOffset;
  37131. caret->updatePosition();
  37132. repaint();
  37133. }
  37134. }
  37135. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37136. {
  37137. scrollToLineInternal (newFirstLineOnScreen);
  37138. updateScrollBars();
  37139. }
  37140. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37141. {
  37142. scrollToColumnInternal (newFirstColumnOnScreen);
  37143. updateScrollBars();
  37144. }
  37145. void CodeEditorComponent::scrollBy (int deltaLines)
  37146. {
  37147. scrollToLine (firstLineOnScreen + deltaLines);
  37148. }
  37149. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37150. {
  37151. if (caretPos.getLineNumber() < firstLineOnScreen)
  37152. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37153. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37154. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37155. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37156. if (column >= xOffset + columnsOnScreen - 1)
  37157. scrollToColumn (column + 1 - columnsOnScreen);
  37158. else if (column < xOffset)
  37159. scrollToColumn (column);
  37160. }
  37161. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37162. {
  37163. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37164. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37165. roundToInt (charWidth),
  37166. lineHeight);
  37167. }
  37168. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37169. {
  37170. const int line = y / lineHeight + firstLineOnScreen;
  37171. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37172. const int index = columnToIndex (line, column);
  37173. return CodeDocument::Position (&document, line, index);
  37174. }
  37175. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37176. {
  37177. document.deleteSection (selectionStart, selectionEnd);
  37178. if (newText.isNotEmpty())
  37179. document.insertText (caretPos, newText);
  37180. scrollToKeepCaretOnScreen();
  37181. }
  37182. void CodeEditorComponent::insertTabAtCaret()
  37183. {
  37184. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37185. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37186. {
  37187. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37188. }
  37189. if (useSpacesForTabs)
  37190. {
  37191. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37192. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37193. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37194. }
  37195. else
  37196. {
  37197. insertTextAtCaret ("\t");
  37198. }
  37199. }
  37200. void CodeEditorComponent::cut()
  37201. {
  37202. insertTextAtCaret (String::empty);
  37203. }
  37204. void CodeEditorComponent::copy()
  37205. {
  37206. newTransaction();
  37207. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37208. if (selection.isNotEmpty())
  37209. SystemClipboard::copyTextToClipboard (selection);
  37210. }
  37211. void CodeEditorComponent::copyThenCut()
  37212. {
  37213. copy();
  37214. cut();
  37215. newTransaction();
  37216. }
  37217. void CodeEditorComponent::paste()
  37218. {
  37219. newTransaction();
  37220. const String clip (SystemClipboard::getTextFromClipboard());
  37221. if (clip.isNotEmpty())
  37222. insertTextAtCaret (clip);
  37223. newTransaction();
  37224. }
  37225. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37226. {
  37227. newTransaction();
  37228. if (moveInWholeWordSteps)
  37229. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37230. else
  37231. moveCaretTo (caretPos.movedBy (-1), selecting);
  37232. }
  37233. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37234. {
  37235. newTransaction();
  37236. if (moveInWholeWordSteps)
  37237. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37238. else
  37239. moveCaretTo (caretPos.movedBy (1), selecting);
  37240. }
  37241. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37242. {
  37243. CodeDocument::Position pos (caretPos);
  37244. const int newLineNum = pos.getLineNumber() + delta;
  37245. if (columnToTryToMaintain < 0)
  37246. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37247. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37248. const int colToMaintain = columnToTryToMaintain;
  37249. moveCaretTo (pos, selecting);
  37250. columnToTryToMaintain = colToMaintain;
  37251. }
  37252. void CodeEditorComponent::cursorDown (const bool selecting)
  37253. {
  37254. newTransaction();
  37255. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37256. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37257. else
  37258. moveLineDelta (1, selecting);
  37259. }
  37260. void CodeEditorComponent::cursorUp (const bool selecting)
  37261. {
  37262. newTransaction();
  37263. if (caretPos.getLineNumber() == 0)
  37264. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37265. else
  37266. moveLineDelta (-1, selecting);
  37267. }
  37268. void CodeEditorComponent::pageDown (const bool selecting)
  37269. {
  37270. newTransaction();
  37271. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37272. moveLineDelta (linesOnScreen, selecting);
  37273. }
  37274. void CodeEditorComponent::pageUp (const bool selecting)
  37275. {
  37276. newTransaction();
  37277. scrollBy (-linesOnScreen);
  37278. moveLineDelta (-linesOnScreen, selecting);
  37279. }
  37280. void CodeEditorComponent::scrollUp()
  37281. {
  37282. newTransaction();
  37283. scrollBy (1);
  37284. if (caretPos.getLineNumber() < firstLineOnScreen)
  37285. moveLineDelta (1, false);
  37286. }
  37287. void CodeEditorComponent::scrollDown()
  37288. {
  37289. newTransaction();
  37290. scrollBy (-1);
  37291. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37292. moveLineDelta (-1, false);
  37293. }
  37294. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37295. {
  37296. newTransaction();
  37297. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37298. }
  37299. static int findFirstNonWhitespaceChar (const String& line) throw()
  37300. {
  37301. const int len = line.length();
  37302. for (int i = 0; i < len; ++i)
  37303. if (! CharacterFunctions::isWhitespace (line [i]))
  37304. return i;
  37305. return 0;
  37306. }
  37307. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37308. {
  37309. newTransaction();
  37310. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37311. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37312. index = 0;
  37313. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37314. }
  37315. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37316. {
  37317. newTransaction();
  37318. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37319. }
  37320. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37321. {
  37322. newTransaction();
  37323. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37324. }
  37325. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37326. {
  37327. if (moveInWholeWordSteps)
  37328. {
  37329. cut(); // in case something is already highlighted
  37330. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37331. }
  37332. else
  37333. {
  37334. if (selectionStart == selectionEnd)
  37335. selectionStart.moveBy (-1);
  37336. }
  37337. cut();
  37338. }
  37339. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37340. {
  37341. if (moveInWholeWordSteps)
  37342. {
  37343. cut(); // in case something is already highlighted
  37344. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37345. }
  37346. else
  37347. {
  37348. if (selectionStart == selectionEnd)
  37349. selectionEnd.moveBy (1);
  37350. else
  37351. newTransaction();
  37352. }
  37353. cut();
  37354. }
  37355. void CodeEditorComponent::selectAll()
  37356. {
  37357. newTransaction();
  37358. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37359. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37360. }
  37361. void CodeEditorComponent::undo()
  37362. {
  37363. document.undo();
  37364. scrollToKeepCaretOnScreen();
  37365. }
  37366. void CodeEditorComponent::redo()
  37367. {
  37368. document.redo();
  37369. scrollToKeepCaretOnScreen();
  37370. }
  37371. void CodeEditorComponent::newTransaction()
  37372. {
  37373. document.newTransaction();
  37374. startTimer (600);
  37375. }
  37376. void CodeEditorComponent::timerCallback()
  37377. {
  37378. newTransaction();
  37379. }
  37380. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37381. {
  37382. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37383. }
  37384. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37385. {
  37386. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37387. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37388. }
  37389. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37390. {
  37391. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37392. CodeDocument::Position (&document, range.getEnd()));
  37393. }
  37394. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37395. {
  37396. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37397. const bool shiftDown = key.getModifiers().isShiftDown();
  37398. if (key.isKeyCode (KeyPress::leftKey))
  37399. {
  37400. cursorLeft (moveInWholeWordSteps, shiftDown);
  37401. }
  37402. else if (key.isKeyCode (KeyPress::rightKey))
  37403. {
  37404. cursorRight (moveInWholeWordSteps, shiftDown);
  37405. }
  37406. else if (key.isKeyCode (KeyPress::upKey))
  37407. {
  37408. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37409. scrollDown();
  37410. #if JUCE_MAC
  37411. else if (key.getModifiers().isCommandDown())
  37412. goToStartOfDocument (shiftDown);
  37413. #endif
  37414. else
  37415. cursorUp (shiftDown);
  37416. }
  37417. else if (key.isKeyCode (KeyPress::downKey))
  37418. {
  37419. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37420. scrollUp();
  37421. #if JUCE_MAC
  37422. else if (key.getModifiers().isCommandDown())
  37423. goToEndOfDocument (shiftDown);
  37424. #endif
  37425. else
  37426. cursorDown (shiftDown);
  37427. }
  37428. else if (key.isKeyCode (KeyPress::pageDownKey))
  37429. {
  37430. pageDown (shiftDown);
  37431. }
  37432. else if (key.isKeyCode (KeyPress::pageUpKey))
  37433. {
  37434. pageUp (shiftDown);
  37435. }
  37436. else if (key.isKeyCode (KeyPress::homeKey))
  37437. {
  37438. if (moveInWholeWordSteps)
  37439. goToStartOfDocument (shiftDown);
  37440. else
  37441. goToStartOfLine (shiftDown);
  37442. }
  37443. else if (key.isKeyCode (KeyPress::endKey))
  37444. {
  37445. if (moveInWholeWordSteps)
  37446. goToEndOfDocument (shiftDown);
  37447. else
  37448. goToEndOfLine (shiftDown);
  37449. }
  37450. else if (key.isKeyCode (KeyPress::backspaceKey))
  37451. {
  37452. backspace (moveInWholeWordSteps);
  37453. }
  37454. else if (key.isKeyCode (KeyPress::deleteKey))
  37455. {
  37456. deleteForward (moveInWholeWordSteps);
  37457. }
  37458. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37459. {
  37460. copy();
  37461. }
  37462. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37463. {
  37464. copyThenCut();
  37465. }
  37466. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37467. {
  37468. paste();
  37469. }
  37470. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37471. {
  37472. undo();
  37473. }
  37474. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37475. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37476. {
  37477. redo();
  37478. }
  37479. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37480. {
  37481. selectAll();
  37482. }
  37483. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37484. {
  37485. insertTabAtCaret();
  37486. }
  37487. else if (key == KeyPress::returnKey)
  37488. {
  37489. newTransaction();
  37490. insertTextAtCaret (document.getNewLineCharacters());
  37491. }
  37492. else if (key.isKeyCode (KeyPress::escapeKey))
  37493. {
  37494. newTransaction();
  37495. }
  37496. else if (key.getTextCharacter() >= ' ')
  37497. {
  37498. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37499. }
  37500. else
  37501. {
  37502. return false;
  37503. }
  37504. return true;
  37505. }
  37506. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37507. {
  37508. newTransaction();
  37509. dragType = notDragging;
  37510. if (! e.mods.isPopupMenu())
  37511. {
  37512. beginDragAutoRepeat (100);
  37513. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37514. }
  37515. else
  37516. {
  37517. /*PopupMenu m;
  37518. addPopupMenuItems (m, &e);
  37519. const int result = m.show();
  37520. if (result != 0)
  37521. performPopupMenuAction (result);
  37522. */
  37523. }
  37524. }
  37525. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37526. {
  37527. if (! e.mods.isPopupMenu())
  37528. moveCaretTo (getPositionAt (e.x, e.y), true);
  37529. }
  37530. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37531. {
  37532. newTransaction();
  37533. beginDragAutoRepeat (0);
  37534. dragType = notDragging;
  37535. }
  37536. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37537. {
  37538. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37539. CodeDocument::Position tokenEnd (tokenStart);
  37540. if (e.getNumberOfClicks() > 2)
  37541. {
  37542. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37543. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37544. }
  37545. else
  37546. {
  37547. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37548. tokenEnd.moveBy (1);
  37549. tokenStart = tokenEnd;
  37550. while (tokenStart.getIndexInLine() > 0
  37551. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37552. tokenStart.moveBy (-1);
  37553. }
  37554. moveCaretTo (tokenEnd, false);
  37555. moveCaretTo (tokenStart, true);
  37556. }
  37557. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37558. {
  37559. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37560. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37561. {
  37562. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37563. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37564. }
  37565. else
  37566. {
  37567. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37568. }
  37569. }
  37570. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37571. {
  37572. if (scrollBarThatHasMoved == verticalScrollBar)
  37573. scrollToLineInternal ((int) newRangeStart);
  37574. else
  37575. scrollToColumnInternal (newRangeStart);
  37576. }
  37577. void CodeEditorComponent::focusGained (FocusChangeType)
  37578. {
  37579. caret->updatePosition();
  37580. }
  37581. void CodeEditorComponent::focusLost (FocusChangeType)
  37582. {
  37583. caret->updatePosition();
  37584. }
  37585. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37586. {
  37587. useSpacesForTabs = insertSpaces;
  37588. if (spacesPerTab != numSpaces)
  37589. {
  37590. spacesPerTab = numSpaces;
  37591. triggerAsyncUpdate();
  37592. }
  37593. }
  37594. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37595. {
  37596. const String line (document.getLine (lineNum));
  37597. jassert (index <= line.length());
  37598. int col = 0;
  37599. for (int i = 0; i < index; ++i)
  37600. {
  37601. if (line[i] != '\t')
  37602. ++col;
  37603. else
  37604. col += getTabSize() - (col % getTabSize());
  37605. }
  37606. return col;
  37607. }
  37608. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37609. {
  37610. const String line (document.getLine (lineNum));
  37611. const int lineLength = line.length();
  37612. int i, col = 0;
  37613. for (i = 0; i < lineLength; ++i)
  37614. {
  37615. if (line[i] != '\t')
  37616. ++col;
  37617. else
  37618. col += getTabSize() - (col % getTabSize());
  37619. if (col > column)
  37620. break;
  37621. }
  37622. return i;
  37623. }
  37624. void CodeEditorComponent::setFont (const Font& newFont)
  37625. {
  37626. font = newFont;
  37627. charWidth = font.getStringWidthFloat ("0");
  37628. lineHeight = roundToInt (font.getHeight());
  37629. resized();
  37630. }
  37631. void CodeEditorComponent::resetToDefaultColours()
  37632. {
  37633. coloursForTokenCategories.clear();
  37634. if (codeTokeniser != 0)
  37635. {
  37636. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37637. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37638. }
  37639. }
  37640. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37641. {
  37642. jassert (tokenType < 256);
  37643. while (coloursForTokenCategories.size() < tokenType)
  37644. coloursForTokenCategories.add (Colours::black);
  37645. coloursForTokenCategories.set (tokenType, colour);
  37646. repaint();
  37647. }
  37648. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37649. {
  37650. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37651. return findColour (CodeEditorComponent::defaultTextColourId);
  37652. return coloursForTokenCategories.getReference (tokenType);
  37653. }
  37654. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37655. {
  37656. int i;
  37657. for (i = cachedIterators.size(); --i >= 0;)
  37658. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37659. break;
  37660. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37661. }
  37662. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37663. {
  37664. const int maxNumCachedPositions = 5000;
  37665. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37666. if (cachedIterators.size() == 0)
  37667. cachedIterators.add (new CodeDocument::Iterator (&document));
  37668. if (codeTokeniser == 0)
  37669. return;
  37670. for (;;)
  37671. {
  37672. CodeDocument::Iterator* last = cachedIterators.getLast();
  37673. if (last->getLine() >= maxLineNum)
  37674. break;
  37675. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37676. cachedIterators.add (t);
  37677. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37678. for (;;)
  37679. {
  37680. codeTokeniser->readNextToken (*t);
  37681. if (t->getLine() >= targetLine)
  37682. break;
  37683. if (t->isEOF())
  37684. return;
  37685. }
  37686. }
  37687. }
  37688. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37689. {
  37690. if (codeTokeniser == 0)
  37691. return;
  37692. for (int i = cachedIterators.size(); --i >= 0;)
  37693. {
  37694. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37695. if (t->getPosition() <= position)
  37696. {
  37697. source = *t;
  37698. break;
  37699. }
  37700. }
  37701. while (source.getPosition() < position)
  37702. {
  37703. const CodeDocument::Iterator original (source);
  37704. codeTokeniser->readNextToken (source);
  37705. if (source.getPosition() > position || source.isEOF())
  37706. {
  37707. source = original;
  37708. break;
  37709. }
  37710. }
  37711. }
  37712. END_JUCE_NAMESPACE
  37713. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37714. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37715. BEGIN_JUCE_NAMESPACE
  37716. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37717. {
  37718. }
  37719. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37720. {
  37721. }
  37722. namespace CppTokeniser
  37723. {
  37724. static bool isIdentifierStart (const juce_wchar c) throw()
  37725. {
  37726. return CharacterFunctions::isLetter (c)
  37727. || c == '_' || c == '@';
  37728. }
  37729. static bool isIdentifierBody (const juce_wchar c) throw()
  37730. {
  37731. return CharacterFunctions::isLetterOrDigit (c)
  37732. || c == '_' || c == '@';
  37733. }
  37734. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37735. {
  37736. static const juce_wchar* const keywords2Char[] =
  37737. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37738. static const juce_wchar* const keywords3Char[] =
  37739. { 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 };
  37740. static const juce_wchar* const keywords4Char[] =
  37741. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37742. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37743. static const juce_wchar* const keywords5Char[] =
  37744. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37745. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37746. static const juce_wchar* const keywords6Char[] =
  37747. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37748. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37749. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37750. static const juce_wchar* const keywordsOther[] =
  37751. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37752. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37753. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37754. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37755. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37756. const juce_wchar* const* k;
  37757. switch (tokenLength)
  37758. {
  37759. case 2: k = keywords2Char; break;
  37760. case 3: k = keywords3Char; break;
  37761. case 4: k = keywords4Char; break;
  37762. case 5: k = keywords5Char; break;
  37763. case 6: k = keywords6Char; break;
  37764. default:
  37765. if (tokenLength < 2 || tokenLength > 16)
  37766. return false;
  37767. k = keywordsOther;
  37768. break;
  37769. }
  37770. int i = 0;
  37771. while (k[i] != 0)
  37772. {
  37773. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37774. return true;
  37775. ++i;
  37776. }
  37777. return false;
  37778. }
  37779. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37780. {
  37781. int tokenLength = 0;
  37782. juce_wchar possibleIdentifier [19];
  37783. while (isIdentifierBody (source.peekNextChar()))
  37784. {
  37785. const juce_wchar c = source.nextChar();
  37786. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37787. possibleIdentifier [tokenLength] = c;
  37788. ++tokenLength;
  37789. }
  37790. if (tokenLength > 1 && tokenLength <= 16)
  37791. {
  37792. possibleIdentifier [tokenLength] = 0;
  37793. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37794. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37795. }
  37796. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37797. }
  37798. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37799. {
  37800. const juce_wchar c = source.peekNextChar();
  37801. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37802. source.skip();
  37803. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37804. return false;
  37805. return true;
  37806. }
  37807. static bool isHexDigit (const juce_wchar c) throw()
  37808. {
  37809. return (c >= '0' && c <= '9')
  37810. || (c >= 'a' && c <= 'f')
  37811. || (c >= 'A' && c <= 'F');
  37812. }
  37813. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37814. {
  37815. if (source.nextChar() != '0')
  37816. return false;
  37817. juce_wchar c = source.nextChar();
  37818. if (c != 'x' && c != 'X')
  37819. return false;
  37820. int numDigits = 0;
  37821. while (isHexDigit (source.peekNextChar()))
  37822. {
  37823. ++numDigits;
  37824. source.skip();
  37825. }
  37826. if (numDigits == 0)
  37827. return false;
  37828. return skipNumberSuffix (source);
  37829. }
  37830. static bool isOctalDigit (const juce_wchar c) throw()
  37831. {
  37832. return c >= '0' && c <= '7';
  37833. }
  37834. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37835. {
  37836. if (source.nextChar() != '0')
  37837. return false;
  37838. if (! isOctalDigit (source.nextChar()))
  37839. return false;
  37840. while (isOctalDigit (source.peekNextChar()))
  37841. source.skip();
  37842. return skipNumberSuffix (source);
  37843. }
  37844. static bool isDecimalDigit (const juce_wchar c) throw()
  37845. {
  37846. return c >= '0' && c <= '9';
  37847. }
  37848. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37849. {
  37850. int numChars = 0;
  37851. while (isDecimalDigit (source.peekNextChar()))
  37852. {
  37853. ++numChars;
  37854. source.skip();
  37855. }
  37856. if (numChars == 0)
  37857. return false;
  37858. return skipNumberSuffix (source);
  37859. }
  37860. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37861. {
  37862. int numDigits = 0;
  37863. while (isDecimalDigit (source.peekNextChar()))
  37864. {
  37865. source.skip();
  37866. ++numDigits;
  37867. }
  37868. const bool hasPoint = (source.peekNextChar() == '.');
  37869. if (hasPoint)
  37870. {
  37871. source.skip();
  37872. while (isDecimalDigit (source.peekNextChar()))
  37873. {
  37874. source.skip();
  37875. ++numDigits;
  37876. }
  37877. }
  37878. if (numDigits == 0)
  37879. return false;
  37880. juce_wchar c = source.peekNextChar();
  37881. const bool hasExponent = (c == 'e' || c == 'E');
  37882. if (hasExponent)
  37883. {
  37884. source.skip();
  37885. c = source.peekNextChar();
  37886. if (c == '+' || c == '-')
  37887. source.skip();
  37888. int numExpDigits = 0;
  37889. while (isDecimalDigit (source.peekNextChar()))
  37890. {
  37891. source.skip();
  37892. ++numExpDigits;
  37893. }
  37894. if (numExpDigits == 0)
  37895. return false;
  37896. }
  37897. c = source.peekNextChar();
  37898. if (c == 'f' || c == 'F')
  37899. source.skip();
  37900. else if (! (hasExponent || hasPoint))
  37901. return false;
  37902. return true;
  37903. }
  37904. static int parseNumber (CodeDocument::Iterator& source)
  37905. {
  37906. const CodeDocument::Iterator original (source);
  37907. if (parseFloatLiteral (source))
  37908. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37909. source = original;
  37910. if (parseHexLiteral (source))
  37911. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37912. source = original;
  37913. if (parseOctalLiteral (source))
  37914. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37915. source = original;
  37916. if (parseDecimalLiteral (source))
  37917. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37918. source = original;
  37919. source.skip();
  37920. return CPlusPlusCodeTokeniser::tokenType_error;
  37921. }
  37922. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37923. {
  37924. const juce_wchar quote = source.nextChar();
  37925. for (;;)
  37926. {
  37927. const juce_wchar c = source.nextChar();
  37928. if (c == quote || c == 0)
  37929. break;
  37930. if (c == '\\')
  37931. source.skip();
  37932. }
  37933. }
  37934. static void skipComment (CodeDocument::Iterator& source) throw()
  37935. {
  37936. bool lastWasStar = false;
  37937. for (;;)
  37938. {
  37939. const juce_wchar c = source.nextChar();
  37940. if (c == 0 || (c == '/' && lastWasStar))
  37941. break;
  37942. lastWasStar = (c == '*');
  37943. }
  37944. }
  37945. }
  37946. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37947. {
  37948. int result = tokenType_error;
  37949. source.skipWhitespace();
  37950. juce_wchar firstChar = source.peekNextChar();
  37951. switch (firstChar)
  37952. {
  37953. case 0:
  37954. source.skip();
  37955. break;
  37956. case '0':
  37957. case '1':
  37958. case '2':
  37959. case '3':
  37960. case '4':
  37961. case '5':
  37962. case '6':
  37963. case '7':
  37964. case '8':
  37965. case '9':
  37966. result = CppTokeniser::parseNumber (source);
  37967. break;
  37968. case '.':
  37969. result = CppTokeniser::parseNumber (source);
  37970. if (result == tokenType_error)
  37971. result = tokenType_punctuation;
  37972. break;
  37973. case ',':
  37974. case ';':
  37975. case ':':
  37976. source.skip();
  37977. result = tokenType_punctuation;
  37978. break;
  37979. case '(':
  37980. case ')':
  37981. case '{':
  37982. case '}':
  37983. case '[':
  37984. case ']':
  37985. source.skip();
  37986. result = tokenType_bracket;
  37987. break;
  37988. case '"':
  37989. case '\'':
  37990. CppTokeniser::skipQuotedString (source);
  37991. result = tokenType_stringLiteral;
  37992. break;
  37993. case '+':
  37994. result = tokenType_operator;
  37995. source.skip();
  37996. if (source.peekNextChar() == '+')
  37997. source.skip();
  37998. else if (source.peekNextChar() == '=')
  37999. source.skip();
  38000. break;
  38001. case '-':
  38002. source.skip();
  38003. result = CppTokeniser::parseNumber (source);
  38004. if (result == tokenType_error)
  38005. {
  38006. result = tokenType_operator;
  38007. if (source.peekNextChar() == '-')
  38008. source.skip();
  38009. else if (source.peekNextChar() == '=')
  38010. source.skip();
  38011. }
  38012. break;
  38013. case '*':
  38014. case '%':
  38015. case '=':
  38016. case '!':
  38017. result = tokenType_operator;
  38018. source.skip();
  38019. if (source.peekNextChar() == '=')
  38020. source.skip();
  38021. break;
  38022. case '/':
  38023. result = tokenType_operator;
  38024. source.skip();
  38025. if (source.peekNextChar() == '=')
  38026. {
  38027. source.skip();
  38028. }
  38029. else if (source.peekNextChar() == '/')
  38030. {
  38031. result = tokenType_comment;
  38032. source.skipToEndOfLine();
  38033. }
  38034. else if (source.peekNextChar() == '*')
  38035. {
  38036. source.skip();
  38037. result = tokenType_comment;
  38038. CppTokeniser::skipComment (source);
  38039. }
  38040. break;
  38041. case '?':
  38042. case '~':
  38043. source.skip();
  38044. result = tokenType_operator;
  38045. break;
  38046. case '<':
  38047. source.skip();
  38048. result = tokenType_operator;
  38049. if (source.peekNextChar() == '=')
  38050. {
  38051. source.skip();
  38052. }
  38053. else if (source.peekNextChar() == '<')
  38054. {
  38055. source.skip();
  38056. if (source.peekNextChar() == '=')
  38057. source.skip();
  38058. }
  38059. break;
  38060. case '>':
  38061. source.skip();
  38062. result = tokenType_operator;
  38063. if (source.peekNextChar() == '=')
  38064. {
  38065. source.skip();
  38066. }
  38067. else if (source.peekNextChar() == '<')
  38068. {
  38069. source.skip();
  38070. if (source.peekNextChar() == '=')
  38071. source.skip();
  38072. }
  38073. break;
  38074. case '|':
  38075. source.skip();
  38076. result = tokenType_operator;
  38077. if (source.peekNextChar() == '=')
  38078. {
  38079. source.skip();
  38080. }
  38081. else if (source.peekNextChar() == '|')
  38082. {
  38083. source.skip();
  38084. if (source.peekNextChar() == '=')
  38085. source.skip();
  38086. }
  38087. break;
  38088. case '&':
  38089. source.skip();
  38090. result = tokenType_operator;
  38091. if (source.peekNextChar() == '=')
  38092. {
  38093. source.skip();
  38094. }
  38095. else if (source.peekNextChar() == '&')
  38096. {
  38097. source.skip();
  38098. if (source.peekNextChar() == '=')
  38099. source.skip();
  38100. }
  38101. break;
  38102. case '^':
  38103. source.skip();
  38104. result = tokenType_operator;
  38105. if (source.peekNextChar() == '=')
  38106. {
  38107. source.skip();
  38108. }
  38109. else if (source.peekNextChar() == '^')
  38110. {
  38111. source.skip();
  38112. if (source.peekNextChar() == '=')
  38113. source.skip();
  38114. }
  38115. break;
  38116. case '#':
  38117. result = tokenType_preprocessor;
  38118. source.skipToEndOfLine();
  38119. break;
  38120. default:
  38121. if (CppTokeniser::isIdentifierStart (firstChar))
  38122. result = CppTokeniser::parseIdentifier (source);
  38123. else
  38124. source.skip();
  38125. break;
  38126. }
  38127. return result;
  38128. }
  38129. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38130. {
  38131. const char* const types[] =
  38132. {
  38133. "Error",
  38134. "Comment",
  38135. "C++ keyword",
  38136. "Identifier",
  38137. "Integer literal",
  38138. "Float literal",
  38139. "String literal",
  38140. "Operator",
  38141. "Bracket",
  38142. "Punctuation",
  38143. "Preprocessor line",
  38144. 0
  38145. };
  38146. return StringArray (types);
  38147. }
  38148. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38149. {
  38150. const uint32 colours[] =
  38151. {
  38152. 0xffcc0000, // error
  38153. 0xff00aa00, // comment
  38154. 0xff0000cc, // keyword
  38155. 0xff000000, // identifier
  38156. 0xff880000, // int literal
  38157. 0xff885500, // float literal
  38158. 0xff990099, // string literal
  38159. 0xff225500, // operator
  38160. 0xff000055, // bracket
  38161. 0xff004400, // punctuation
  38162. 0xff660000 // preprocessor
  38163. };
  38164. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38165. return Colour (colours [tokenType]);
  38166. return Colours::black;
  38167. }
  38168. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38169. {
  38170. return CppTokeniser::isReservedKeyword (token, token.length());
  38171. }
  38172. END_JUCE_NAMESPACE
  38173. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38174. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38175. BEGIN_JUCE_NAMESPACE
  38176. ComboBox::ComboBox (const String& name)
  38177. : Component (name),
  38178. lastCurrentId (0),
  38179. isButtonDown (false),
  38180. separatorPending (false),
  38181. menuActive (false),
  38182. label (0)
  38183. {
  38184. noChoicesMessage = TRANS("(no choices)");
  38185. setRepaintsOnMouseActivity (true);
  38186. lookAndFeelChanged();
  38187. currentId.addListener (this);
  38188. }
  38189. ComboBox::~ComboBox()
  38190. {
  38191. currentId.removeListener (this);
  38192. if (menuActive)
  38193. PopupMenu::dismissAllActiveMenus();
  38194. label = 0;
  38195. deleteAllChildren();
  38196. }
  38197. void ComboBox::setEditableText (const bool isEditable)
  38198. {
  38199. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38200. {
  38201. label->setEditable (isEditable, isEditable, false);
  38202. setWantsKeyboardFocus (! isEditable);
  38203. resized();
  38204. }
  38205. }
  38206. bool ComboBox::isTextEditable() const throw()
  38207. {
  38208. return label->isEditable();
  38209. }
  38210. void ComboBox::setJustificationType (const Justification& justification)
  38211. {
  38212. label->setJustificationType (justification);
  38213. }
  38214. const Justification ComboBox::getJustificationType() const throw()
  38215. {
  38216. return label->getJustificationType();
  38217. }
  38218. void ComboBox::setTooltip (const String& newTooltip)
  38219. {
  38220. SettableTooltipClient::setTooltip (newTooltip);
  38221. label->setTooltip (newTooltip);
  38222. }
  38223. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38224. {
  38225. // you can't add empty strings to the list..
  38226. jassert (newItemText.isNotEmpty());
  38227. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38228. jassert (newItemId != 0);
  38229. // you shouldn't use duplicate item IDs!
  38230. jassert (getItemForId (newItemId) == 0);
  38231. if (newItemText.isNotEmpty() && newItemId != 0)
  38232. {
  38233. if (separatorPending)
  38234. {
  38235. separatorPending = false;
  38236. ItemInfo* const item = new ItemInfo();
  38237. item->itemId = 0;
  38238. item->isEnabled = false;
  38239. item->isHeading = false;
  38240. items.add (item);
  38241. }
  38242. ItemInfo* const item = new ItemInfo();
  38243. item->name = newItemText;
  38244. item->itemId = newItemId;
  38245. item->isEnabled = true;
  38246. item->isHeading = false;
  38247. items.add (item);
  38248. }
  38249. }
  38250. void ComboBox::addSeparator()
  38251. {
  38252. separatorPending = (items.size() > 0);
  38253. }
  38254. void ComboBox::addSectionHeading (const String& headingName)
  38255. {
  38256. // you can't add empty strings to the list..
  38257. jassert (headingName.isNotEmpty());
  38258. if (headingName.isNotEmpty())
  38259. {
  38260. if (separatorPending)
  38261. {
  38262. separatorPending = false;
  38263. ItemInfo* const item = new ItemInfo();
  38264. item->itemId = 0;
  38265. item->isEnabled = false;
  38266. item->isHeading = false;
  38267. items.add (item);
  38268. }
  38269. ItemInfo* const item = new ItemInfo();
  38270. item->name = headingName;
  38271. item->itemId = 0;
  38272. item->isEnabled = true;
  38273. item->isHeading = true;
  38274. items.add (item);
  38275. }
  38276. }
  38277. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38278. {
  38279. ItemInfo* const item = getItemForId (itemId);
  38280. if (item != 0)
  38281. item->isEnabled = shouldBeEnabled;
  38282. }
  38283. void ComboBox::changeItemText (const int itemId, const String& newText)
  38284. {
  38285. ItemInfo* const item = getItemForId (itemId);
  38286. jassert (item != 0);
  38287. if (item != 0)
  38288. item->name = newText;
  38289. }
  38290. void ComboBox::clear (const bool dontSendChangeMessage)
  38291. {
  38292. items.clear();
  38293. separatorPending = false;
  38294. if (! label->isEditable())
  38295. setSelectedItemIndex (-1, dontSendChangeMessage);
  38296. }
  38297. bool ComboBox::ItemInfo::isSeparator() const throw()
  38298. {
  38299. return name.isEmpty();
  38300. }
  38301. bool ComboBox::ItemInfo::isRealItem() const throw()
  38302. {
  38303. return ! (isHeading || name.isEmpty());
  38304. }
  38305. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38306. {
  38307. if (itemId != 0)
  38308. {
  38309. for (int i = items.size(); --i >= 0;)
  38310. if (items.getUnchecked(i)->itemId == itemId)
  38311. return items.getUnchecked(i);
  38312. }
  38313. return 0;
  38314. }
  38315. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38316. {
  38317. int n = 0;
  38318. for (int i = 0; i < items.size(); ++i)
  38319. {
  38320. ItemInfo* const item = items.getUnchecked(i);
  38321. if (item->isRealItem())
  38322. if (n++ == index)
  38323. return item;
  38324. }
  38325. return 0;
  38326. }
  38327. int ComboBox::getNumItems() const throw()
  38328. {
  38329. int n = 0;
  38330. for (int i = items.size(); --i >= 0;)
  38331. if (items.getUnchecked(i)->isRealItem())
  38332. ++n;
  38333. return n;
  38334. }
  38335. const String ComboBox::getItemText (const int index) const
  38336. {
  38337. const ItemInfo* const item = getItemForIndex (index);
  38338. if (item != 0)
  38339. return item->name;
  38340. return String::empty;
  38341. }
  38342. int ComboBox::getItemId (const int index) const throw()
  38343. {
  38344. const ItemInfo* const item = getItemForIndex (index);
  38345. return (item != 0) ? item->itemId : 0;
  38346. }
  38347. int ComboBox::indexOfItemId (const int itemId) const throw()
  38348. {
  38349. int n = 0;
  38350. for (int i = 0; i < items.size(); ++i)
  38351. {
  38352. const ItemInfo* const item = items.getUnchecked(i);
  38353. if (item->isRealItem())
  38354. {
  38355. if (item->itemId == itemId)
  38356. return n;
  38357. ++n;
  38358. }
  38359. }
  38360. return -1;
  38361. }
  38362. int ComboBox::getSelectedItemIndex() const
  38363. {
  38364. int index = indexOfItemId (currentId.getValue());
  38365. if (getText() != getItemText (index))
  38366. index = -1;
  38367. return index;
  38368. }
  38369. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38370. {
  38371. setSelectedId (getItemId (index), dontSendChangeMessage);
  38372. }
  38373. int ComboBox::getSelectedId() const throw()
  38374. {
  38375. const ItemInfo* const item = getItemForId (currentId.getValue());
  38376. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38377. }
  38378. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38379. {
  38380. const ItemInfo* const item = getItemForId (newItemId);
  38381. const String newItemText (item != 0 ? item->name : String::empty);
  38382. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38383. {
  38384. if (! dontSendChangeMessage)
  38385. triggerAsyncUpdate();
  38386. label->setText (newItemText, false);
  38387. lastCurrentId = newItemId;
  38388. currentId = newItemId;
  38389. repaint(); // for the benefit of the 'none selected' text
  38390. }
  38391. }
  38392. void ComboBox::valueChanged (Value&)
  38393. {
  38394. if (lastCurrentId != (int) currentId.getValue())
  38395. setSelectedId (currentId.getValue(), false);
  38396. }
  38397. const String ComboBox::getText() const
  38398. {
  38399. return label->getText();
  38400. }
  38401. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38402. {
  38403. for (int i = items.size(); --i >= 0;)
  38404. {
  38405. const ItemInfo* const item = items.getUnchecked(i);
  38406. if (item->isRealItem()
  38407. && item->name == newText)
  38408. {
  38409. setSelectedId (item->itemId, dontSendChangeMessage);
  38410. return;
  38411. }
  38412. }
  38413. lastCurrentId = 0;
  38414. currentId = 0;
  38415. if (label->getText() != newText)
  38416. {
  38417. label->setText (newText, false);
  38418. if (! dontSendChangeMessage)
  38419. triggerAsyncUpdate();
  38420. }
  38421. repaint();
  38422. }
  38423. void ComboBox::showEditor()
  38424. {
  38425. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38426. label->showEditor();
  38427. }
  38428. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38429. {
  38430. if (textWhenNothingSelected != newMessage)
  38431. {
  38432. textWhenNothingSelected = newMessage;
  38433. repaint();
  38434. }
  38435. }
  38436. const String ComboBox::getTextWhenNothingSelected() const
  38437. {
  38438. return textWhenNothingSelected;
  38439. }
  38440. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38441. {
  38442. noChoicesMessage = newMessage;
  38443. }
  38444. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38445. {
  38446. return noChoicesMessage;
  38447. }
  38448. void ComboBox::paint (Graphics& g)
  38449. {
  38450. getLookAndFeel().drawComboBox (g,
  38451. getWidth(),
  38452. getHeight(),
  38453. isButtonDown,
  38454. label->getRight(),
  38455. 0,
  38456. getWidth() - label->getRight(),
  38457. getHeight(),
  38458. *this);
  38459. if (textWhenNothingSelected.isNotEmpty()
  38460. && label->getText().isEmpty()
  38461. && ! label->isBeingEdited())
  38462. {
  38463. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38464. g.setFont (label->getFont());
  38465. g.drawFittedText (textWhenNothingSelected,
  38466. label->getX() + 2, label->getY() + 1,
  38467. label->getWidth() - 4, label->getHeight() - 2,
  38468. label->getJustificationType(),
  38469. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38470. }
  38471. }
  38472. void ComboBox::resized()
  38473. {
  38474. if (getHeight() > 0 && getWidth() > 0)
  38475. getLookAndFeel().positionComboBoxText (*this, *label);
  38476. }
  38477. void ComboBox::enablementChanged()
  38478. {
  38479. repaint();
  38480. }
  38481. void ComboBox::lookAndFeelChanged()
  38482. {
  38483. repaint();
  38484. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38485. if (label != 0)
  38486. {
  38487. newLabel->setEditable (label->isEditable());
  38488. newLabel->setJustificationType (label->getJustificationType());
  38489. newLabel->setTooltip (label->getTooltip());
  38490. newLabel->setText (label->getText(), false);
  38491. }
  38492. label = newLabel;
  38493. addAndMakeVisible (newLabel);
  38494. newLabel->addListener (this);
  38495. newLabel->addMouseListener (this, false);
  38496. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38497. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38498. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38499. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38500. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38501. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38502. resized();
  38503. }
  38504. void ComboBox::colourChanged()
  38505. {
  38506. lookAndFeelChanged();
  38507. }
  38508. bool ComboBox::keyPressed (const KeyPress& key)
  38509. {
  38510. bool used = false;
  38511. if (key.isKeyCode (KeyPress::upKey)
  38512. || key.isKeyCode (KeyPress::leftKey))
  38513. {
  38514. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38515. used = true;
  38516. }
  38517. else if (key.isKeyCode (KeyPress::downKey)
  38518. || key.isKeyCode (KeyPress::rightKey))
  38519. {
  38520. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38521. used = true;
  38522. }
  38523. else if (key.isKeyCode (KeyPress::returnKey))
  38524. {
  38525. showPopup();
  38526. used = true;
  38527. }
  38528. return used;
  38529. }
  38530. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38531. {
  38532. // only forward key events that aren't used by this component
  38533. return isKeyDown
  38534. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38535. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38536. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38537. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38538. }
  38539. void ComboBox::focusGained (FocusChangeType)
  38540. {
  38541. repaint();
  38542. }
  38543. void ComboBox::focusLost (FocusChangeType)
  38544. {
  38545. repaint();
  38546. }
  38547. void ComboBox::labelTextChanged (Label*)
  38548. {
  38549. triggerAsyncUpdate();
  38550. }
  38551. class ComboBox::Callback : public ModalComponentManager::Callback
  38552. {
  38553. public:
  38554. Callback (ComboBox* const box_)
  38555. : box (box_)
  38556. {
  38557. }
  38558. void modalStateFinished (int returnValue)
  38559. {
  38560. if (box != 0)
  38561. {
  38562. box->menuActive = false;
  38563. if (returnValue != 0)
  38564. box->setSelectedId (returnValue);
  38565. }
  38566. }
  38567. private:
  38568. Component::SafePointer<ComboBox> box;
  38569. Callback (const Callback&);
  38570. Callback& operator= (const Callback&);
  38571. };
  38572. void ComboBox::showPopup()
  38573. {
  38574. if (! menuActive)
  38575. {
  38576. const int selectedId = getSelectedId();
  38577. PopupMenu menu;
  38578. menu.setLookAndFeel (&getLookAndFeel());
  38579. for (int i = 0; i < items.size(); ++i)
  38580. {
  38581. const ItemInfo* const item = items.getUnchecked(i);
  38582. if (item->isSeparator())
  38583. menu.addSeparator();
  38584. else if (item->isHeading)
  38585. menu.addSectionHeader (item->name);
  38586. else
  38587. menu.addItem (item->itemId, item->name,
  38588. item->isEnabled, item->itemId == selectedId);
  38589. }
  38590. if (items.size() == 0)
  38591. menu.addItem (1, noChoicesMessage, false);
  38592. menuActive = true;
  38593. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38594. new Callback (this));
  38595. }
  38596. }
  38597. void ComboBox::mouseDown (const MouseEvent& e)
  38598. {
  38599. beginDragAutoRepeat (300);
  38600. isButtonDown = isEnabled();
  38601. if (isButtonDown
  38602. && (e.eventComponent == this || ! label->isEditable()))
  38603. {
  38604. showPopup();
  38605. }
  38606. }
  38607. void ComboBox::mouseDrag (const MouseEvent& e)
  38608. {
  38609. beginDragAutoRepeat (50);
  38610. if (isButtonDown && ! e.mouseWasClicked())
  38611. showPopup();
  38612. }
  38613. void ComboBox::mouseUp (const MouseEvent& e2)
  38614. {
  38615. if (isButtonDown)
  38616. {
  38617. isButtonDown = false;
  38618. repaint();
  38619. const MouseEvent e (e2.getEventRelativeTo (this));
  38620. if (reallyContains (e.x, e.y, true)
  38621. && (e2.eventComponent == this || ! label->isEditable()))
  38622. {
  38623. showPopup();
  38624. }
  38625. }
  38626. }
  38627. void ComboBox::addListener (Listener* const listener)
  38628. {
  38629. listeners.add (listener);
  38630. }
  38631. void ComboBox::removeListener (Listener* const listener)
  38632. {
  38633. listeners.remove (listener);
  38634. }
  38635. void ComboBox::handleAsyncUpdate()
  38636. {
  38637. Component::BailOutChecker checker (this);
  38638. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38639. }
  38640. END_JUCE_NAMESPACE
  38641. /*** End of inlined file: juce_ComboBox.cpp ***/
  38642. /*** Start of inlined file: juce_Label.cpp ***/
  38643. BEGIN_JUCE_NAMESPACE
  38644. Label::Label (const String& componentName,
  38645. const String& labelText)
  38646. : Component (componentName),
  38647. textValue (labelText),
  38648. lastTextValue (labelText),
  38649. font (15.0f),
  38650. justification (Justification::centredLeft),
  38651. ownerComponent (0),
  38652. horizontalBorderSize (5),
  38653. verticalBorderSize (1),
  38654. minimumHorizontalScale (0.7f),
  38655. editSingleClick (false),
  38656. editDoubleClick (false),
  38657. lossOfFocusDiscardsChanges (false)
  38658. {
  38659. setColour (TextEditor::textColourId, Colours::black);
  38660. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38661. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38662. textValue.addListener (this);
  38663. }
  38664. Label::~Label()
  38665. {
  38666. textValue.removeListener (this);
  38667. if (ownerComponent != 0)
  38668. ownerComponent->removeComponentListener (this);
  38669. editor = 0;
  38670. }
  38671. void Label::setText (const String& newText,
  38672. const bool broadcastChangeMessage)
  38673. {
  38674. hideEditor (true);
  38675. if (lastTextValue != newText)
  38676. {
  38677. lastTextValue = newText;
  38678. textValue = newText;
  38679. repaint();
  38680. textWasChanged();
  38681. if (ownerComponent != 0)
  38682. componentMovedOrResized (*ownerComponent, true, true);
  38683. if (broadcastChangeMessage)
  38684. callChangeListeners();
  38685. }
  38686. }
  38687. const String Label::getText (const bool returnActiveEditorContents) const
  38688. {
  38689. return (returnActiveEditorContents && isBeingEdited())
  38690. ? editor->getText()
  38691. : textValue.toString();
  38692. }
  38693. void Label::valueChanged (Value&)
  38694. {
  38695. if (lastTextValue != textValue.toString())
  38696. setText (textValue.toString(), true);
  38697. }
  38698. void Label::setFont (const Font& newFont)
  38699. {
  38700. if (font != newFont)
  38701. {
  38702. font = newFont;
  38703. repaint();
  38704. }
  38705. }
  38706. const Font& Label::getFont() const throw()
  38707. {
  38708. return font;
  38709. }
  38710. void Label::setEditable (const bool editOnSingleClick,
  38711. const bool editOnDoubleClick,
  38712. const bool lossOfFocusDiscardsChanges_)
  38713. {
  38714. editSingleClick = editOnSingleClick;
  38715. editDoubleClick = editOnDoubleClick;
  38716. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38717. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38718. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38719. }
  38720. void Label::setJustificationType (const Justification& newJustification)
  38721. {
  38722. if (justification != newJustification)
  38723. {
  38724. justification = newJustification;
  38725. repaint();
  38726. }
  38727. }
  38728. void Label::setBorderSize (int h, int v)
  38729. {
  38730. if (horizontalBorderSize != h || verticalBorderSize != v)
  38731. {
  38732. horizontalBorderSize = h;
  38733. verticalBorderSize = v;
  38734. repaint();
  38735. }
  38736. }
  38737. Component* Label::getAttachedComponent() const
  38738. {
  38739. return static_cast<Component*> (ownerComponent);
  38740. }
  38741. void Label::attachToComponent (Component* owner,
  38742. const bool onLeft)
  38743. {
  38744. if (ownerComponent != 0)
  38745. ownerComponent->removeComponentListener (this);
  38746. ownerComponent = owner;
  38747. leftOfOwnerComp = onLeft;
  38748. if (ownerComponent != 0)
  38749. {
  38750. setVisible (owner->isVisible());
  38751. ownerComponent->addComponentListener (this);
  38752. componentParentHierarchyChanged (*ownerComponent);
  38753. componentMovedOrResized (*ownerComponent, true, true);
  38754. }
  38755. }
  38756. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38757. {
  38758. if (leftOfOwnerComp)
  38759. {
  38760. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38761. component.getHeight());
  38762. setTopRightPosition (component.getX(), component.getY());
  38763. }
  38764. else
  38765. {
  38766. setSize (component.getWidth(),
  38767. 8 + roundToInt (getFont().getHeight()));
  38768. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38769. }
  38770. }
  38771. void Label::componentParentHierarchyChanged (Component& component)
  38772. {
  38773. if (component.getParentComponent() != 0)
  38774. component.getParentComponent()->addChildComponent (this);
  38775. }
  38776. void Label::componentVisibilityChanged (Component& component)
  38777. {
  38778. setVisible (component.isVisible());
  38779. }
  38780. void Label::textWasEdited()
  38781. {
  38782. }
  38783. void Label::textWasChanged()
  38784. {
  38785. }
  38786. void Label::showEditor()
  38787. {
  38788. if (editor == 0)
  38789. {
  38790. addAndMakeVisible (editor = createEditorComponent());
  38791. editor->setText (getText(), false);
  38792. editor->addListener (this);
  38793. editor->grabKeyboardFocus();
  38794. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38795. editor->addListener (this);
  38796. resized();
  38797. repaint();
  38798. editorShown (editor);
  38799. enterModalState (false);
  38800. editor->grabKeyboardFocus();
  38801. }
  38802. }
  38803. void Label::editorShown (TextEditor* /*editorComponent*/)
  38804. {
  38805. }
  38806. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38807. {
  38808. }
  38809. bool Label::updateFromTextEditorContents()
  38810. {
  38811. jassert (editor != 0);
  38812. const String newText (editor->getText());
  38813. if (textValue.toString() != newText)
  38814. {
  38815. lastTextValue = newText;
  38816. textValue = newText;
  38817. repaint();
  38818. textWasChanged();
  38819. if (ownerComponent != 0)
  38820. componentMovedOrResized (*ownerComponent, true, true);
  38821. return true;
  38822. }
  38823. return false;
  38824. }
  38825. void Label::hideEditor (const bool discardCurrentEditorContents)
  38826. {
  38827. if (editor != 0)
  38828. {
  38829. Component::SafePointer<Component> deletionChecker (this);
  38830. editorAboutToBeHidden (editor);
  38831. const bool changed = (! discardCurrentEditorContents)
  38832. && updateFromTextEditorContents();
  38833. editor = 0;
  38834. repaint();
  38835. if (changed)
  38836. textWasEdited();
  38837. if (deletionChecker != 0)
  38838. exitModalState (0);
  38839. if (changed && deletionChecker != 0)
  38840. callChangeListeners();
  38841. }
  38842. }
  38843. void Label::inputAttemptWhenModal()
  38844. {
  38845. if (editor != 0)
  38846. {
  38847. if (lossOfFocusDiscardsChanges)
  38848. textEditorEscapeKeyPressed (*editor);
  38849. else
  38850. textEditorReturnKeyPressed (*editor);
  38851. }
  38852. }
  38853. bool Label::isBeingEdited() const throw()
  38854. {
  38855. return editor != 0;
  38856. }
  38857. TextEditor* Label::createEditorComponent()
  38858. {
  38859. TextEditor* const ed = new TextEditor (getName());
  38860. ed->setFont (font);
  38861. // copy these colours from our own settings..
  38862. const int cols[] = { TextEditor::backgroundColourId,
  38863. TextEditor::textColourId,
  38864. TextEditor::highlightColourId,
  38865. TextEditor::highlightedTextColourId,
  38866. TextEditor::caretColourId,
  38867. TextEditor::outlineColourId,
  38868. TextEditor::focusedOutlineColourId,
  38869. TextEditor::shadowColourId };
  38870. for (int i = 0; i < numElementsInArray (cols); ++i)
  38871. ed->setColour (cols[i], findColour (cols[i]));
  38872. return ed;
  38873. }
  38874. void Label::paint (Graphics& g)
  38875. {
  38876. getLookAndFeel().drawLabel (g, *this);
  38877. }
  38878. void Label::mouseUp (const MouseEvent& e)
  38879. {
  38880. if (editSingleClick
  38881. && e.mouseWasClicked()
  38882. && contains (e.x, e.y)
  38883. && ! e.mods.isPopupMenu())
  38884. {
  38885. showEditor();
  38886. }
  38887. }
  38888. void Label::mouseDoubleClick (const MouseEvent& e)
  38889. {
  38890. if (editDoubleClick && ! e.mods.isPopupMenu())
  38891. showEditor();
  38892. }
  38893. void Label::resized()
  38894. {
  38895. if (editor != 0)
  38896. editor->setBoundsInset (BorderSize (0));
  38897. }
  38898. void Label::focusGained (FocusChangeType cause)
  38899. {
  38900. if (editSingleClick && cause == focusChangedByTabKey)
  38901. showEditor();
  38902. }
  38903. void Label::enablementChanged()
  38904. {
  38905. repaint();
  38906. }
  38907. void Label::colourChanged()
  38908. {
  38909. repaint();
  38910. }
  38911. void Label::setMinimumHorizontalScale (const float newScale)
  38912. {
  38913. if (minimumHorizontalScale != newScale)
  38914. {
  38915. minimumHorizontalScale = newScale;
  38916. repaint();
  38917. }
  38918. }
  38919. // We'll use a custom focus traverser here to make sure focus goes from the
  38920. // text editor to another component rather than back to the label itself.
  38921. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38922. {
  38923. public:
  38924. LabelKeyboardFocusTraverser() {}
  38925. Component* getNextComponent (Component* current)
  38926. {
  38927. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38928. ? current->getParentComponent() : current);
  38929. }
  38930. Component* getPreviousComponent (Component* current)
  38931. {
  38932. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38933. ? current->getParentComponent() : current);
  38934. }
  38935. };
  38936. KeyboardFocusTraverser* Label::createFocusTraverser()
  38937. {
  38938. return new LabelKeyboardFocusTraverser();
  38939. }
  38940. void Label::addListener (Listener* const listener)
  38941. {
  38942. listeners.add (listener);
  38943. }
  38944. void Label::removeListener (Listener* const listener)
  38945. {
  38946. listeners.remove (listener);
  38947. }
  38948. void Label::callChangeListeners()
  38949. {
  38950. Component::BailOutChecker checker (this);
  38951. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38952. }
  38953. void Label::textEditorTextChanged (TextEditor& ed)
  38954. {
  38955. if (editor != 0)
  38956. {
  38957. jassert (&ed == editor);
  38958. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38959. {
  38960. if (lossOfFocusDiscardsChanges)
  38961. textEditorEscapeKeyPressed (ed);
  38962. else
  38963. textEditorReturnKeyPressed (ed);
  38964. }
  38965. }
  38966. }
  38967. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38968. {
  38969. if (editor != 0)
  38970. {
  38971. jassert (&ed == editor);
  38972. (void) ed;
  38973. const bool changed = updateFromTextEditorContents();
  38974. hideEditor (true);
  38975. if (changed)
  38976. {
  38977. Component::SafePointer<Component> deletionChecker (this);
  38978. textWasEdited();
  38979. if (deletionChecker != 0)
  38980. callChangeListeners();
  38981. }
  38982. }
  38983. }
  38984. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38985. {
  38986. if (editor != 0)
  38987. {
  38988. jassert (&ed == editor);
  38989. (void) ed;
  38990. editor->setText (textValue.toString(), false);
  38991. hideEditor (true);
  38992. }
  38993. }
  38994. void Label::textEditorFocusLost (TextEditor& ed)
  38995. {
  38996. textEditorTextChanged (ed);
  38997. }
  38998. END_JUCE_NAMESPACE
  38999. /*** End of inlined file: juce_Label.cpp ***/
  39000. /*** Start of inlined file: juce_ListBox.cpp ***/
  39001. BEGIN_JUCE_NAMESPACE
  39002. class ListBoxRowComponent : public Component,
  39003. public TooltipClient
  39004. {
  39005. public:
  39006. ListBoxRowComponent (ListBox& owner_)
  39007. : owner (owner_),
  39008. row (-1),
  39009. selected (false),
  39010. isDragging (false)
  39011. {
  39012. }
  39013. ~ListBoxRowComponent()
  39014. {
  39015. deleteAllChildren();
  39016. }
  39017. void paint (Graphics& g)
  39018. {
  39019. if (owner.getModel() != 0)
  39020. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39021. }
  39022. void update (const int row_, const bool selected_)
  39023. {
  39024. if (row != row_ || selected != selected_)
  39025. {
  39026. repaint();
  39027. row = row_;
  39028. selected = selected_;
  39029. }
  39030. if (owner.getModel() != 0)
  39031. {
  39032. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39033. if (customComp != 0)
  39034. {
  39035. addAndMakeVisible (customComp);
  39036. customComp->setBounds (getLocalBounds());
  39037. for (int i = getNumChildComponents(); --i >= 0;)
  39038. if (getChildComponent (i) != customComp)
  39039. delete getChildComponent (i);
  39040. }
  39041. else
  39042. {
  39043. deleteAllChildren();
  39044. }
  39045. }
  39046. }
  39047. void mouseDown (const MouseEvent& e)
  39048. {
  39049. isDragging = false;
  39050. selectRowOnMouseUp = false;
  39051. if (isEnabled())
  39052. {
  39053. if (! selected)
  39054. {
  39055. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39056. if (owner.getModel() != 0)
  39057. owner.getModel()->listBoxItemClicked (row, e);
  39058. }
  39059. else
  39060. {
  39061. selectRowOnMouseUp = true;
  39062. }
  39063. }
  39064. }
  39065. void mouseUp (const MouseEvent& e)
  39066. {
  39067. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39068. {
  39069. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39070. if (owner.getModel() != 0)
  39071. owner.getModel()->listBoxItemClicked (row, e);
  39072. }
  39073. }
  39074. void mouseDoubleClick (const MouseEvent& e)
  39075. {
  39076. if (owner.getModel() != 0 && isEnabled())
  39077. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39078. }
  39079. void mouseDrag (const MouseEvent& e)
  39080. {
  39081. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39082. {
  39083. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39084. if (selectedRows.size() > 0)
  39085. {
  39086. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39087. if (dragDescription.isNotEmpty())
  39088. {
  39089. isDragging = true;
  39090. owner.startDragAndDrop (e, dragDescription);
  39091. }
  39092. }
  39093. }
  39094. }
  39095. void resized()
  39096. {
  39097. if (getNumChildComponents() > 0)
  39098. getChildComponent(0)->setBounds (getLocalBounds());
  39099. }
  39100. const String getTooltip()
  39101. {
  39102. if (owner.getModel() != 0)
  39103. return owner.getModel()->getTooltipForRow (row);
  39104. return String::empty;
  39105. }
  39106. juce_UseDebuggingNewOperator
  39107. bool neededFlag;
  39108. private:
  39109. ListBox& owner;
  39110. int row;
  39111. bool selected, isDragging, selectRowOnMouseUp;
  39112. ListBoxRowComponent (const ListBoxRowComponent&);
  39113. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39114. };
  39115. class ListViewport : public Viewport
  39116. {
  39117. public:
  39118. int firstIndex, firstWholeIndex, lastWholeIndex;
  39119. bool hasUpdated;
  39120. ListViewport (ListBox& owner_)
  39121. : owner (owner_)
  39122. {
  39123. setWantsKeyboardFocus (false);
  39124. setViewedComponent (new Component());
  39125. getViewedComponent()->addMouseListener (this, false);
  39126. getViewedComponent()->setWantsKeyboardFocus (false);
  39127. }
  39128. ~ListViewport()
  39129. {
  39130. getViewedComponent()->removeMouseListener (this);
  39131. getViewedComponent()->deleteAllChildren();
  39132. }
  39133. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39134. {
  39135. return static_cast <ListBoxRowComponent*>
  39136. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39137. }
  39138. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39139. {
  39140. const int index = getIndexOfChildComponent (rowComponent);
  39141. const int num = getViewedComponent()->getNumChildComponents();
  39142. for (int i = num; --i >= 0;)
  39143. if (((firstIndex + i) % jmax (1, num)) == index)
  39144. return firstIndex + i;
  39145. return -1;
  39146. }
  39147. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39148. {
  39149. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39150. ? getComponentForRow (row) : 0;
  39151. }
  39152. void visibleAreaChanged (int, int, int, int)
  39153. {
  39154. updateVisibleArea (true);
  39155. if (owner.getModel() != 0)
  39156. owner.getModel()->listWasScrolled();
  39157. }
  39158. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39159. {
  39160. hasUpdated = false;
  39161. const int newX = getViewedComponent()->getX();
  39162. int newY = getViewedComponent()->getY();
  39163. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39164. const int newH = owner.totalItems * owner.getRowHeight();
  39165. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39166. newY = getMaximumVisibleHeight() - newH;
  39167. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39168. if (makeSureItUpdatesContent && ! hasUpdated)
  39169. updateContents();
  39170. }
  39171. void updateContents()
  39172. {
  39173. hasUpdated = true;
  39174. const int rowHeight = owner.getRowHeight();
  39175. if (rowHeight > 0)
  39176. {
  39177. const int y = getViewPositionY();
  39178. const int w = getViewedComponent()->getWidth();
  39179. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39180. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39181. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39182. jassert (numNeeded >= 0);
  39183. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39184. {
  39185. Component* const rowToRemove
  39186. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39187. delete rowToRemove;
  39188. }
  39189. firstIndex = y / rowHeight;
  39190. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39191. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39192. for (int i = 0; i < numNeeded; ++i)
  39193. {
  39194. const int row = i + firstIndex;
  39195. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39196. if (rowComp != 0)
  39197. {
  39198. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39199. rowComp->update (row, owner.isRowSelected (row));
  39200. }
  39201. }
  39202. }
  39203. if (owner.headerComponent != 0)
  39204. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39205. owner.outlineThickness,
  39206. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39207. getViewedComponent()->getWidth()),
  39208. owner.headerComponent->getHeight());
  39209. }
  39210. void paint (Graphics& g)
  39211. {
  39212. if (isOpaque())
  39213. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39214. }
  39215. bool keyPressed (const KeyPress& key)
  39216. {
  39217. if (key.isKeyCode (KeyPress::upKey)
  39218. || key.isKeyCode (KeyPress::downKey)
  39219. || key.isKeyCode (KeyPress::pageUpKey)
  39220. || key.isKeyCode (KeyPress::pageDownKey)
  39221. || key.isKeyCode (KeyPress::homeKey)
  39222. || key.isKeyCode (KeyPress::endKey))
  39223. {
  39224. // we want to avoid these keypresses going to the viewport, and instead allow
  39225. // them to pass up to our listbox..
  39226. return false;
  39227. }
  39228. return Viewport::keyPressed (key);
  39229. }
  39230. juce_UseDebuggingNewOperator
  39231. private:
  39232. ListBox& owner;
  39233. ListViewport (const ListViewport&);
  39234. ListViewport& operator= (const ListViewport&);
  39235. };
  39236. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39237. : Component (name),
  39238. model (model_),
  39239. totalItems (0),
  39240. rowHeight (22),
  39241. minimumRowWidth (0),
  39242. outlineThickness (0),
  39243. lastRowSelected (-1),
  39244. mouseMoveSelects (false),
  39245. multipleSelection (false),
  39246. hasDoneInitialUpdate (false)
  39247. {
  39248. addAndMakeVisible (viewport = new ListViewport (*this));
  39249. setWantsKeyboardFocus (true);
  39250. colourChanged();
  39251. }
  39252. ListBox::~ListBox()
  39253. {
  39254. headerComponent = 0;
  39255. viewport = 0;
  39256. }
  39257. void ListBox::setModel (ListBoxModel* const newModel)
  39258. {
  39259. if (model != newModel)
  39260. {
  39261. model = newModel;
  39262. updateContent();
  39263. }
  39264. }
  39265. void ListBox::setMultipleSelectionEnabled (bool b)
  39266. {
  39267. multipleSelection = b;
  39268. }
  39269. void ListBox::setMouseMoveSelectsRows (bool b)
  39270. {
  39271. mouseMoveSelects = b;
  39272. if (b)
  39273. addMouseListener (this, true);
  39274. }
  39275. void ListBox::paint (Graphics& g)
  39276. {
  39277. if (! hasDoneInitialUpdate)
  39278. updateContent();
  39279. g.fillAll (findColour (backgroundColourId));
  39280. }
  39281. void ListBox::paintOverChildren (Graphics& g)
  39282. {
  39283. if (outlineThickness > 0)
  39284. {
  39285. g.setColour (findColour (outlineColourId));
  39286. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39287. }
  39288. }
  39289. void ListBox::resized()
  39290. {
  39291. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39292. outlineThickness,
  39293. outlineThickness,
  39294. outlineThickness));
  39295. viewport->setSingleStepSizes (20, getRowHeight());
  39296. viewport->updateVisibleArea (false);
  39297. }
  39298. void ListBox::visibilityChanged()
  39299. {
  39300. viewport->updateVisibleArea (true);
  39301. }
  39302. Viewport* ListBox::getViewport() const throw()
  39303. {
  39304. return viewport;
  39305. }
  39306. void ListBox::updateContent()
  39307. {
  39308. hasDoneInitialUpdate = true;
  39309. totalItems = (model != 0) ? model->getNumRows() : 0;
  39310. bool selectionChanged = false;
  39311. if (selected [selected.size() - 1] >= totalItems)
  39312. {
  39313. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39314. lastRowSelected = getSelectedRow (0);
  39315. selectionChanged = true;
  39316. }
  39317. viewport->updateVisibleArea (isVisible());
  39318. viewport->resized();
  39319. if (selectionChanged && model != 0)
  39320. model->selectedRowsChanged (lastRowSelected);
  39321. }
  39322. void ListBox::selectRow (const int row,
  39323. bool dontScroll,
  39324. bool deselectOthersFirst)
  39325. {
  39326. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39327. }
  39328. void ListBox::selectRowInternal (const int row,
  39329. bool dontScroll,
  39330. bool deselectOthersFirst,
  39331. bool isMouseClick)
  39332. {
  39333. if (! multipleSelection)
  39334. deselectOthersFirst = true;
  39335. if ((! isRowSelected (row))
  39336. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39337. {
  39338. if (((unsigned int) row) < (unsigned int) totalItems)
  39339. {
  39340. if (deselectOthersFirst)
  39341. selected.clear();
  39342. selected.addRange (Range<int> (row, row + 1));
  39343. if (getHeight() == 0 || getWidth() == 0)
  39344. dontScroll = true;
  39345. viewport->hasUpdated = false;
  39346. if (row < viewport->firstWholeIndex && ! dontScroll)
  39347. {
  39348. viewport->setViewPosition (viewport->getViewPositionX(),
  39349. row * getRowHeight());
  39350. }
  39351. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39352. {
  39353. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39354. if (row >= lastRowSelected + rowsOnScreen
  39355. && rowsOnScreen < totalItems - 1
  39356. && ! isMouseClick)
  39357. {
  39358. viewport->setViewPosition (viewport->getViewPositionX(),
  39359. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39360. * getRowHeight());
  39361. }
  39362. else
  39363. {
  39364. viewport->setViewPosition (viewport->getViewPositionX(),
  39365. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39366. }
  39367. }
  39368. if (! viewport->hasUpdated)
  39369. viewport->updateContents();
  39370. lastRowSelected = row;
  39371. model->selectedRowsChanged (row);
  39372. }
  39373. else
  39374. {
  39375. if (deselectOthersFirst)
  39376. deselectAllRows();
  39377. }
  39378. }
  39379. }
  39380. void ListBox::deselectRow (const int row)
  39381. {
  39382. if (selected.contains (row))
  39383. {
  39384. selected.removeRange (Range <int> (row, row + 1));
  39385. if (row == lastRowSelected)
  39386. lastRowSelected = getSelectedRow (0);
  39387. viewport->updateContents();
  39388. model->selectedRowsChanged (lastRowSelected);
  39389. }
  39390. }
  39391. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39392. const bool sendNotificationEventToModel)
  39393. {
  39394. selected = setOfRowsToBeSelected;
  39395. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39396. if (! isRowSelected (lastRowSelected))
  39397. lastRowSelected = getSelectedRow (0);
  39398. viewport->updateContents();
  39399. if ((model != 0) && sendNotificationEventToModel)
  39400. model->selectedRowsChanged (lastRowSelected);
  39401. }
  39402. const SparseSet<int> ListBox::getSelectedRows() const
  39403. {
  39404. return selected;
  39405. }
  39406. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39407. {
  39408. if (multipleSelection && (firstRow != lastRow))
  39409. {
  39410. const int numRows = totalItems - 1;
  39411. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39412. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39413. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39414. jmax (firstRow, lastRow) + 1));
  39415. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39416. }
  39417. selectRowInternal (lastRow, false, false, true);
  39418. }
  39419. void ListBox::flipRowSelection (const int row)
  39420. {
  39421. if (isRowSelected (row))
  39422. deselectRow (row);
  39423. else
  39424. selectRowInternal (row, false, false, true);
  39425. }
  39426. void ListBox::deselectAllRows()
  39427. {
  39428. if (! selected.isEmpty())
  39429. {
  39430. selected.clear();
  39431. lastRowSelected = -1;
  39432. viewport->updateContents();
  39433. if (model != 0)
  39434. model->selectedRowsChanged (lastRowSelected);
  39435. }
  39436. }
  39437. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39438. const ModifierKeys& mods)
  39439. {
  39440. if (multipleSelection && mods.isCommandDown())
  39441. {
  39442. flipRowSelection (row);
  39443. }
  39444. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39445. {
  39446. selectRangeOfRows (lastRowSelected, row);
  39447. }
  39448. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39449. {
  39450. selectRowInternal (row, false, true, true);
  39451. }
  39452. }
  39453. int ListBox::getNumSelectedRows() const
  39454. {
  39455. return selected.size();
  39456. }
  39457. int ListBox::getSelectedRow (const int index) const
  39458. {
  39459. return (((unsigned int) index) < (unsigned int) selected.size())
  39460. ? selected [index] : -1;
  39461. }
  39462. bool ListBox::isRowSelected (const int row) const
  39463. {
  39464. return selected.contains (row);
  39465. }
  39466. int ListBox::getLastRowSelected() const
  39467. {
  39468. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39469. }
  39470. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39471. {
  39472. if (((unsigned int) x) < (unsigned int) getWidth())
  39473. {
  39474. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39475. if (((unsigned int) row) < (unsigned int) totalItems)
  39476. return row;
  39477. }
  39478. return -1;
  39479. }
  39480. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39481. {
  39482. if (((unsigned int) x) < (unsigned int) getWidth())
  39483. {
  39484. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39485. return jlimit (0, totalItems, row);
  39486. }
  39487. return -1;
  39488. }
  39489. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39490. {
  39491. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39492. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39493. }
  39494. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39495. {
  39496. return viewport->getRowNumberOfComponent (rowComponent);
  39497. }
  39498. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39499. const bool relativeToComponentTopLeft) const throw()
  39500. {
  39501. int y = viewport->getY() + rowHeight * rowNumber;
  39502. if (relativeToComponentTopLeft)
  39503. y -= viewport->getViewPositionY();
  39504. return Rectangle<int> (viewport->getX(), y,
  39505. viewport->getViewedComponent()->getWidth(), rowHeight);
  39506. }
  39507. void ListBox::setVerticalPosition (const double proportion)
  39508. {
  39509. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39510. viewport->setViewPosition (viewport->getViewPositionX(),
  39511. jmax (0, roundToInt (proportion * offscreen)));
  39512. }
  39513. double ListBox::getVerticalPosition() const
  39514. {
  39515. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39516. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39517. : 0;
  39518. }
  39519. int ListBox::getVisibleRowWidth() const throw()
  39520. {
  39521. return viewport->getViewWidth();
  39522. }
  39523. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39524. {
  39525. if (row < viewport->firstWholeIndex)
  39526. {
  39527. viewport->setViewPosition (viewport->getViewPositionX(),
  39528. row * getRowHeight());
  39529. }
  39530. else if (row >= viewport->lastWholeIndex)
  39531. {
  39532. viewport->setViewPosition (viewport->getViewPositionX(),
  39533. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39534. }
  39535. }
  39536. bool ListBox::keyPressed (const KeyPress& key)
  39537. {
  39538. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39539. const bool multiple = multipleSelection
  39540. && (lastRowSelected >= 0)
  39541. && (key.getModifiers().isShiftDown()
  39542. || key.getModifiers().isCtrlDown()
  39543. || key.getModifiers().isCommandDown());
  39544. if (key.isKeyCode (KeyPress::upKey))
  39545. {
  39546. if (multiple)
  39547. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39548. else
  39549. selectRow (jmax (0, lastRowSelected - 1));
  39550. }
  39551. else if (key.isKeyCode (KeyPress::returnKey)
  39552. && isRowSelected (lastRowSelected))
  39553. {
  39554. if (model != 0)
  39555. model->returnKeyPressed (lastRowSelected);
  39556. }
  39557. else if (key.isKeyCode (KeyPress::pageUpKey))
  39558. {
  39559. if (multiple)
  39560. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39561. else
  39562. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39563. }
  39564. else if (key.isKeyCode (KeyPress::pageDownKey))
  39565. {
  39566. if (multiple)
  39567. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39568. else
  39569. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39570. }
  39571. else if (key.isKeyCode (KeyPress::homeKey))
  39572. {
  39573. if (multiple && key.getModifiers().isShiftDown())
  39574. selectRangeOfRows (lastRowSelected, 0);
  39575. else
  39576. selectRow (0);
  39577. }
  39578. else if (key.isKeyCode (KeyPress::endKey))
  39579. {
  39580. if (multiple && key.getModifiers().isShiftDown())
  39581. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39582. else
  39583. selectRow (totalItems - 1);
  39584. }
  39585. else if (key.isKeyCode (KeyPress::downKey))
  39586. {
  39587. if (multiple)
  39588. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39589. else
  39590. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39591. }
  39592. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39593. && isRowSelected (lastRowSelected))
  39594. {
  39595. if (model != 0)
  39596. model->deleteKeyPressed (lastRowSelected);
  39597. }
  39598. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39599. {
  39600. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39601. }
  39602. else
  39603. {
  39604. return false;
  39605. }
  39606. return true;
  39607. }
  39608. bool ListBox::keyStateChanged (const bool isKeyDown)
  39609. {
  39610. return isKeyDown
  39611. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39612. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39613. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39614. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39615. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39616. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39617. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39618. }
  39619. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39620. {
  39621. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39622. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39623. }
  39624. void ListBox::mouseMove (const MouseEvent& e)
  39625. {
  39626. if (mouseMoveSelects)
  39627. {
  39628. const MouseEvent e2 (e.getEventRelativeTo (this));
  39629. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39630. }
  39631. }
  39632. void ListBox::mouseExit (const MouseEvent& e)
  39633. {
  39634. mouseMove (e);
  39635. }
  39636. void ListBox::mouseUp (const MouseEvent& e)
  39637. {
  39638. if (e.mouseWasClicked() && model != 0)
  39639. model->backgroundClicked();
  39640. }
  39641. void ListBox::setRowHeight (const int newHeight)
  39642. {
  39643. rowHeight = jmax (1, newHeight);
  39644. viewport->setSingleStepSizes (20, rowHeight);
  39645. updateContent();
  39646. }
  39647. int ListBox::getNumRowsOnScreen() const throw()
  39648. {
  39649. return viewport->getMaximumVisibleHeight() / rowHeight;
  39650. }
  39651. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39652. {
  39653. minimumRowWidth = newMinimumWidth;
  39654. updateContent();
  39655. }
  39656. int ListBox::getVisibleContentWidth() const throw()
  39657. {
  39658. return viewport->getMaximumVisibleWidth();
  39659. }
  39660. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39661. {
  39662. return viewport->getVerticalScrollBar();
  39663. }
  39664. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39665. {
  39666. return viewport->getHorizontalScrollBar();
  39667. }
  39668. void ListBox::colourChanged()
  39669. {
  39670. setOpaque (findColour (backgroundColourId).isOpaque());
  39671. viewport->setOpaque (isOpaque());
  39672. repaint();
  39673. }
  39674. void ListBox::setOutlineThickness (const int outlineThickness_)
  39675. {
  39676. outlineThickness = outlineThickness_;
  39677. resized();
  39678. }
  39679. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39680. {
  39681. if (newHeaderComponent != headerComponent)
  39682. {
  39683. headerComponent = newHeaderComponent;
  39684. addAndMakeVisible (newHeaderComponent);
  39685. ListBox::resized();
  39686. }
  39687. }
  39688. void ListBox::repaintRow (const int rowNumber) throw()
  39689. {
  39690. repaint (getRowPosition (rowNumber, true));
  39691. }
  39692. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39693. {
  39694. Rectangle<int> imageArea;
  39695. const int firstRow = getRowContainingPosition (0, 0);
  39696. int i;
  39697. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39698. {
  39699. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39700. if (rowComp != 0 && isRowSelected (firstRow + i))
  39701. {
  39702. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39703. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39704. imageArea = imageArea.getUnion (rowRect);
  39705. }
  39706. }
  39707. imageArea = imageArea.getIntersection (getLocalBounds());
  39708. imageX = imageArea.getX();
  39709. imageY = imageArea.getY();
  39710. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39711. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39712. {
  39713. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39714. if (rowComp != 0 && isRowSelected (firstRow + i))
  39715. {
  39716. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39717. Graphics g (snapshot);
  39718. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39719. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39720. rowComp->paintEntireComponent (g);
  39721. }
  39722. }
  39723. return snapshot;
  39724. }
  39725. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39726. {
  39727. DragAndDropContainer* const dragContainer
  39728. = DragAndDropContainer::findParentDragContainerFor (this);
  39729. if (dragContainer != 0)
  39730. {
  39731. int x, y;
  39732. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39733. dragImage.multiplyAllAlphas (0.6f);
  39734. MouseEvent e2 (e.getEventRelativeTo (this));
  39735. const Point<int> p (x - e2.x, y - e2.y);
  39736. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39737. }
  39738. else
  39739. {
  39740. // to be able to do a drag-and-drop operation, the listbox needs to
  39741. // be inside a component which is also a DragAndDropContainer.
  39742. jassertfalse;
  39743. }
  39744. }
  39745. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39746. {
  39747. (void) existingComponentToUpdate;
  39748. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39749. return 0;
  39750. }
  39751. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39752. {
  39753. }
  39754. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39755. {
  39756. }
  39757. void ListBoxModel::backgroundClicked()
  39758. {
  39759. }
  39760. void ListBoxModel::selectedRowsChanged (int)
  39761. {
  39762. }
  39763. void ListBoxModel::deleteKeyPressed (int)
  39764. {
  39765. }
  39766. void ListBoxModel::returnKeyPressed (int)
  39767. {
  39768. }
  39769. void ListBoxModel::listWasScrolled()
  39770. {
  39771. }
  39772. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39773. {
  39774. return String::empty;
  39775. }
  39776. const String ListBoxModel::getTooltipForRow (int)
  39777. {
  39778. return String::empty;
  39779. }
  39780. END_JUCE_NAMESPACE
  39781. /*** End of inlined file: juce_ListBox.cpp ***/
  39782. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39783. BEGIN_JUCE_NAMESPACE
  39784. ProgressBar::ProgressBar (double& progress_)
  39785. : progress (progress_),
  39786. displayPercentage (true),
  39787. lastCallbackTime (0)
  39788. {
  39789. currentValue = jlimit (0.0, 1.0, progress);
  39790. }
  39791. ProgressBar::~ProgressBar()
  39792. {
  39793. }
  39794. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39795. {
  39796. displayPercentage = shouldDisplayPercentage;
  39797. repaint();
  39798. }
  39799. void ProgressBar::setTextToDisplay (const String& text)
  39800. {
  39801. displayPercentage = false;
  39802. displayedMessage = text;
  39803. }
  39804. void ProgressBar::lookAndFeelChanged()
  39805. {
  39806. setOpaque (findColour (backgroundColourId).isOpaque());
  39807. }
  39808. void ProgressBar::colourChanged()
  39809. {
  39810. lookAndFeelChanged();
  39811. }
  39812. void ProgressBar::paint (Graphics& g)
  39813. {
  39814. String text;
  39815. if (displayPercentage)
  39816. {
  39817. if (currentValue >= 0 && currentValue <= 1.0)
  39818. text << roundToInt (currentValue * 100.0) << '%';
  39819. }
  39820. else
  39821. {
  39822. text = displayedMessage;
  39823. }
  39824. getLookAndFeel().drawProgressBar (g, *this,
  39825. getWidth(), getHeight(),
  39826. currentValue, text);
  39827. }
  39828. void ProgressBar::visibilityChanged()
  39829. {
  39830. if (isVisible())
  39831. startTimer (30);
  39832. else
  39833. stopTimer();
  39834. }
  39835. void ProgressBar::timerCallback()
  39836. {
  39837. double newProgress = progress;
  39838. const uint32 now = Time::getMillisecondCounter();
  39839. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39840. lastCallbackTime = now;
  39841. if (currentValue != newProgress
  39842. || newProgress < 0 || newProgress >= 1.0
  39843. || currentMessage != displayedMessage)
  39844. {
  39845. if (currentValue < newProgress
  39846. && newProgress >= 0 && newProgress < 1.0
  39847. && currentValue >= 0 && currentValue < 1.0)
  39848. {
  39849. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39850. newProgress);
  39851. }
  39852. currentValue = newProgress;
  39853. currentMessage = displayedMessage;
  39854. repaint();
  39855. }
  39856. }
  39857. END_JUCE_NAMESPACE
  39858. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39859. /*** Start of inlined file: juce_Slider.cpp ***/
  39860. BEGIN_JUCE_NAMESPACE
  39861. class SliderPopupDisplayComponent : public BubbleComponent
  39862. {
  39863. public:
  39864. SliderPopupDisplayComponent (Slider* const owner_)
  39865. : owner (owner_),
  39866. font (15.0f, Font::bold)
  39867. {
  39868. setAlwaysOnTop (true);
  39869. }
  39870. ~SliderPopupDisplayComponent()
  39871. {
  39872. }
  39873. void paintContent (Graphics& g, int w, int h)
  39874. {
  39875. g.setFont (font);
  39876. g.setColour (Colours::black);
  39877. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39878. }
  39879. void getContentSize (int& w, int& h)
  39880. {
  39881. w = font.getStringWidth (text) + 18;
  39882. h = (int) (font.getHeight() * 1.6f);
  39883. }
  39884. void updatePosition (const String& newText)
  39885. {
  39886. if (text != newText)
  39887. {
  39888. text = newText;
  39889. repaint();
  39890. }
  39891. BubbleComponent::setPosition (owner);
  39892. }
  39893. juce_UseDebuggingNewOperator
  39894. private:
  39895. Slider* owner;
  39896. Font font;
  39897. String text;
  39898. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39899. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39900. };
  39901. Slider::Slider (const String& name)
  39902. : Component (name),
  39903. lastCurrentValue (0),
  39904. lastValueMin (0),
  39905. lastValueMax (0),
  39906. minimum (0),
  39907. maximum (10),
  39908. interval (0),
  39909. skewFactor (1.0),
  39910. velocityModeSensitivity (1.0),
  39911. velocityModeOffset (0.0),
  39912. velocityModeThreshold (1),
  39913. rotaryStart (float_Pi * 1.2f),
  39914. rotaryEnd (float_Pi * 2.8f),
  39915. numDecimalPlaces (7),
  39916. sliderRegionStart (0),
  39917. sliderRegionSize (1),
  39918. sliderBeingDragged (-1),
  39919. pixelsForFullDragExtent (250),
  39920. style (LinearHorizontal),
  39921. textBoxPos (TextBoxLeft),
  39922. textBoxWidth (80),
  39923. textBoxHeight (20),
  39924. incDecButtonMode (incDecButtonsNotDraggable),
  39925. editableText (true),
  39926. doubleClickToValue (false),
  39927. isVelocityBased (false),
  39928. userKeyOverridesVelocity (true),
  39929. rotaryStop (true),
  39930. incDecButtonsSideBySide (false),
  39931. sendChangeOnlyOnRelease (false),
  39932. popupDisplayEnabled (false),
  39933. menuEnabled (false),
  39934. menuShown (false),
  39935. scrollWheelEnabled (true),
  39936. snapsToMousePos (true),
  39937. valueBox (0),
  39938. incButton (0),
  39939. decButton (0),
  39940. popupDisplay (0),
  39941. parentForPopupDisplay (0)
  39942. {
  39943. setWantsKeyboardFocus (false);
  39944. setRepaintsOnMouseActivity (true);
  39945. lookAndFeelChanged();
  39946. updateText();
  39947. currentValue.addListener (this);
  39948. valueMin.addListener (this);
  39949. valueMax.addListener (this);
  39950. }
  39951. Slider::~Slider()
  39952. {
  39953. currentValue.removeListener (this);
  39954. valueMin.removeListener (this);
  39955. valueMax.removeListener (this);
  39956. popupDisplay = 0;
  39957. deleteAllChildren();
  39958. }
  39959. void Slider::handleAsyncUpdate()
  39960. {
  39961. cancelPendingUpdate();
  39962. Component::BailOutChecker checker (this);
  39963. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39964. }
  39965. void Slider::sendDragStart()
  39966. {
  39967. startedDragging();
  39968. Component::BailOutChecker checker (this);
  39969. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39970. }
  39971. void Slider::sendDragEnd()
  39972. {
  39973. stoppedDragging();
  39974. sliderBeingDragged = -1;
  39975. Component::BailOutChecker checker (this);
  39976. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39977. }
  39978. void Slider::addListener (Listener* const listener)
  39979. {
  39980. listeners.add (listener);
  39981. }
  39982. void Slider::removeListener (Listener* const listener)
  39983. {
  39984. listeners.remove (listener);
  39985. }
  39986. void Slider::setSliderStyle (const SliderStyle newStyle)
  39987. {
  39988. if (style != newStyle)
  39989. {
  39990. style = newStyle;
  39991. repaint();
  39992. lookAndFeelChanged();
  39993. }
  39994. }
  39995. void Slider::setRotaryParameters (const float startAngleRadians,
  39996. const float endAngleRadians,
  39997. const bool stopAtEnd)
  39998. {
  39999. // make sure the values are sensible..
  40000. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40001. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40002. jassert (rotaryStart < rotaryEnd);
  40003. rotaryStart = startAngleRadians;
  40004. rotaryEnd = endAngleRadians;
  40005. rotaryStop = stopAtEnd;
  40006. }
  40007. void Slider::setVelocityBasedMode (const bool velBased)
  40008. {
  40009. isVelocityBased = velBased;
  40010. }
  40011. void Slider::setVelocityModeParameters (const double sensitivity,
  40012. const int threshold,
  40013. const double offset,
  40014. const bool userCanPressKeyToSwapMode)
  40015. {
  40016. jassert (threshold >= 0);
  40017. jassert (sensitivity > 0);
  40018. jassert (offset >= 0);
  40019. velocityModeSensitivity = sensitivity;
  40020. velocityModeOffset = offset;
  40021. velocityModeThreshold = threshold;
  40022. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40023. }
  40024. void Slider::setSkewFactor (const double factor)
  40025. {
  40026. skewFactor = factor;
  40027. }
  40028. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40029. {
  40030. if (maximum > minimum)
  40031. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40032. / (maximum - minimum));
  40033. }
  40034. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40035. {
  40036. jassert (distanceForFullScaleDrag > 0);
  40037. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40038. }
  40039. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40040. {
  40041. if (incDecButtonMode != mode)
  40042. {
  40043. incDecButtonMode = mode;
  40044. lookAndFeelChanged();
  40045. }
  40046. }
  40047. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40048. const bool isReadOnly,
  40049. const int textEntryBoxWidth,
  40050. const int textEntryBoxHeight)
  40051. {
  40052. if (textBoxPos != newPosition
  40053. || editableText != (! isReadOnly)
  40054. || textBoxWidth != textEntryBoxWidth
  40055. || textBoxHeight != textEntryBoxHeight)
  40056. {
  40057. textBoxPos = newPosition;
  40058. editableText = ! isReadOnly;
  40059. textBoxWidth = textEntryBoxWidth;
  40060. textBoxHeight = textEntryBoxHeight;
  40061. repaint();
  40062. lookAndFeelChanged();
  40063. }
  40064. }
  40065. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40066. {
  40067. editableText = shouldBeEditable;
  40068. if (valueBox != 0)
  40069. valueBox->setEditable (shouldBeEditable && isEnabled());
  40070. }
  40071. void Slider::showTextBox()
  40072. {
  40073. jassert (editableText); // this should probably be avoided in read-only sliders.
  40074. if (valueBox != 0)
  40075. valueBox->showEditor();
  40076. }
  40077. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40078. {
  40079. if (valueBox != 0)
  40080. {
  40081. valueBox->hideEditor (discardCurrentEditorContents);
  40082. if (discardCurrentEditorContents)
  40083. updateText();
  40084. }
  40085. }
  40086. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40087. {
  40088. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40089. }
  40090. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40091. {
  40092. snapsToMousePos = shouldSnapToMouse;
  40093. }
  40094. void Slider::setPopupDisplayEnabled (const bool enabled,
  40095. Component* const parentComponentToUse)
  40096. {
  40097. popupDisplayEnabled = enabled;
  40098. parentForPopupDisplay = parentComponentToUse;
  40099. }
  40100. void Slider::colourChanged()
  40101. {
  40102. lookAndFeelChanged();
  40103. }
  40104. void Slider::lookAndFeelChanged()
  40105. {
  40106. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40107. : getTextFromValue (currentValue.getValue()));
  40108. deleteAllChildren();
  40109. valueBox = 0;
  40110. LookAndFeel& lf = getLookAndFeel();
  40111. if (textBoxPos != NoTextBox)
  40112. {
  40113. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40114. valueBox->setWantsKeyboardFocus (false);
  40115. valueBox->setText (previousTextBoxContent, false);
  40116. valueBox->setEditable (editableText && isEnabled());
  40117. valueBox->addListener (this);
  40118. if (style == LinearBar)
  40119. valueBox->addMouseListener (this, false);
  40120. valueBox->setTooltip (getTooltip());
  40121. }
  40122. if (style == IncDecButtons)
  40123. {
  40124. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40125. incButton->addButtonListener (this);
  40126. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40127. decButton->addButtonListener (this);
  40128. if (incDecButtonMode != incDecButtonsNotDraggable)
  40129. {
  40130. incButton->addMouseListener (this, false);
  40131. decButton->addMouseListener (this, false);
  40132. }
  40133. else
  40134. {
  40135. incButton->setRepeatSpeed (300, 100, 20);
  40136. incButton->addMouseListener (decButton, false);
  40137. decButton->setRepeatSpeed (300, 100, 20);
  40138. decButton->addMouseListener (incButton, false);
  40139. }
  40140. incButton->setTooltip (getTooltip());
  40141. decButton->setTooltip (getTooltip());
  40142. }
  40143. setComponentEffect (lf.getSliderEffect());
  40144. resized();
  40145. repaint();
  40146. }
  40147. void Slider::setRange (const double newMin,
  40148. const double newMax,
  40149. const double newInt)
  40150. {
  40151. if (minimum != newMin
  40152. || maximum != newMax
  40153. || interval != newInt)
  40154. {
  40155. minimum = newMin;
  40156. maximum = newMax;
  40157. interval = newInt;
  40158. // figure out the number of DPs needed to display all values at this
  40159. // interval setting.
  40160. numDecimalPlaces = 7;
  40161. if (newInt != 0)
  40162. {
  40163. int v = abs ((int) (newInt * 10000000));
  40164. while ((v % 10) == 0)
  40165. {
  40166. --numDecimalPlaces;
  40167. v /= 10;
  40168. }
  40169. }
  40170. // keep the current values inside the new range..
  40171. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40172. {
  40173. setValue (getValue(), false, false);
  40174. }
  40175. else
  40176. {
  40177. setMinValue (getMinValue(), false, false);
  40178. setMaxValue (getMaxValue(), false, false);
  40179. }
  40180. updateText();
  40181. }
  40182. }
  40183. void Slider::triggerChangeMessage (const bool synchronous)
  40184. {
  40185. if (synchronous)
  40186. handleAsyncUpdate();
  40187. else
  40188. triggerAsyncUpdate();
  40189. valueChanged();
  40190. }
  40191. void Slider::valueChanged (Value& value)
  40192. {
  40193. if (value.refersToSameSourceAs (currentValue))
  40194. {
  40195. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40196. setValue (currentValue.getValue(), false, false);
  40197. }
  40198. else if (value.refersToSameSourceAs (valueMin))
  40199. setMinValue (valueMin.getValue(), false, false, true);
  40200. else if (value.refersToSameSourceAs (valueMax))
  40201. setMaxValue (valueMax.getValue(), false, false, true);
  40202. }
  40203. double Slider::getValue() const
  40204. {
  40205. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40206. // methods to get the two values.
  40207. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40208. return currentValue.getValue();
  40209. }
  40210. void Slider::setValue (double newValue,
  40211. const bool sendUpdateMessage,
  40212. const bool sendMessageSynchronously)
  40213. {
  40214. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40215. // methods to set the two values.
  40216. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40217. newValue = constrainedValue (newValue);
  40218. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40219. {
  40220. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40221. newValue = jlimit ((double) valueMin.getValue(),
  40222. (double) valueMax.getValue(),
  40223. newValue);
  40224. }
  40225. if (newValue != lastCurrentValue)
  40226. {
  40227. if (valueBox != 0)
  40228. valueBox->hideEditor (true);
  40229. lastCurrentValue = newValue;
  40230. currentValue = newValue;
  40231. updateText();
  40232. repaint();
  40233. if (popupDisplay != 0)
  40234. {
  40235. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40236. ->updatePosition (getTextFromValue (newValue));
  40237. popupDisplay->repaint();
  40238. }
  40239. if (sendUpdateMessage)
  40240. triggerChangeMessage (sendMessageSynchronously);
  40241. }
  40242. }
  40243. double Slider::getMinValue() const
  40244. {
  40245. // The minimum value only applies to sliders that are in two- or three-value mode.
  40246. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40247. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40248. return valueMin.getValue();
  40249. }
  40250. double Slider::getMaxValue() const
  40251. {
  40252. // The maximum value only applies to sliders that are in two- or three-value mode.
  40253. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40254. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40255. return valueMax.getValue();
  40256. }
  40257. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40258. {
  40259. // The minimum value only applies to sliders that are in two- or three-value mode.
  40260. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40261. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40262. newValue = constrainedValue (newValue);
  40263. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40264. {
  40265. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40266. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40267. newValue = jmin ((double) valueMax.getValue(), newValue);
  40268. }
  40269. else
  40270. {
  40271. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40272. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40273. newValue = jmin (lastCurrentValue, newValue);
  40274. }
  40275. if (lastValueMin != newValue)
  40276. {
  40277. lastValueMin = newValue;
  40278. valueMin = newValue;
  40279. repaint();
  40280. if (popupDisplay != 0)
  40281. {
  40282. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40283. ->updatePosition (getTextFromValue (newValue));
  40284. popupDisplay->repaint();
  40285. }
  40286. if (sendUpdateMessage)
  40287. triggerChangeMessage (sendMessageSynchronously);
  40288. }
  40289. }
  40290. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40291. {
  40292. // The maximum value only applies to sliders that are in two- or three-value mode.
  40293. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40294. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40295. newValue = constrainedValue (newValue);
  40296. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40297. {
  40298. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40299. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40300. newValue = jmax ((double) valueMin.getValue(), newValue);
  40301. }
  40302. else
  40303. {
  40304. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40305. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40306. newValue = jmax (lastCurrentValue, newValue);
  40307. }
  40308. if (lastValueMax != newValue)
  40309. {
  40310. lastValueMax = newValue;
  40311. valueMax = newValue;
  40312. repaint();
  40313. if (popupDisplay != 0)
  40314. {
  40315. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40316. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40317. popupDisplay->repaint();
  40318. }
  40319. if (sendUpdateMessage)
  40320. triggerChangeMessage (sendMessageSynchronously);
  40321. }
  40322. }
  40323. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40324. const double valueToSetOnDoubleClick)
  40325. {
  40326. doubleClickToValue = isDoubleClickEnabled;
  40327. doubleClickReturnValue = valueToSetOnDoubleClick;
  40328. }
  40329. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40330. {
  40331. isEnabled_ = doubleClickToValue;
  40332. return doubleClickReturnValue;
  40333. }
  40334. void Slider::updateText()
  40335. {
  40336. if (valueBox != 0)
  40337. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40338. }
  40339. void Slider::setTextValueSuffix (const String& suffix)
  40340. {
  40341. if (textSuffix != suffix)
  40342. {
  40343. textSuffix = suffix;
  40344. updateText();
  40345. }
  40346. }
  40347. const String Slider::getTextValueSuffix() const
  40348. {
  40349. return textSuffix;
  40350. }
  40351. const String Slider::getTextFromValue (double v)
  40352. {
  40353. if (getNumDecimalPlacesToDisplay() > 0)
  40354. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40355. else
  40356. return String (roundToInt (v)) + getTextValueSuffix();
  40357. }
  40358. double Slider::getValueFromText (const String& text)
  40359. {
  40360. String t (text.trimStart());
  40361. if (t.endsWith (textSuffix))
  40362. t = t.substring (0, t.length() - textSuffix.length());
  40363. while (t.startsWithChar ('+'))
  40364. t = t.substring (1).trimStart();
  40365. return t.initialSectionContainingOnly ("0123456789.,-")
  40366. .getDoubleValue();
  40367. }
  40368. double Slider::proportionOfLengthToValue (double proportion)
  40369. {
  40370. if (skewFactor != 1.0 && proportion > 0.0)
  40371. proportion = exp (log (proportion) / skewFactor);
  40372. return minimum + (maximum - minimum) * proportion;
  40373. }
  40374. double Slider::valueToProportionOfLength (double value)
  40375. {
  40376. const double n = (value - minimum) / (maximum - minimum);
  40377. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40378. }
  40379. double Slider::snapValue (double attemptedValue, const bool)
  40380. {
  40381. return attemptedValue;
  40382. }
  40383. void Slider::startedDragging()
  40384. {
  40385. }
  40386. void Slider::stoppedDragging()
  40387. {
  40388. }
  40389. void Slider::valueChanged()
  40390. {
  40391. }
  40392. void Slider::enablementChanged()
  40393. {
  40394. repaint();
  40395. }
  40396. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40397. {
  40398. menuEnabled = menuEnabled_;
  40399. }
  40400. void Slider::setScrollWheelEnabled (const bool enabled)
  40401. {
  40402. scrollWheelEnabled = enabled;
  40403. }
  40404. void Slider::labelTextChanged (Label* label)
  40405. {
  40406. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40407. if (newValue != (double) currentValue.getValue())
  40408. {
  40409. sendDragStart();
  40410. setValue (newValue, true, true);
  40411. sendDragEnd();
  40412. }
  40413. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40414. }
  40415. void Slider::buttonClicked (Button* button)
  40416. {
  40417. if (style == IncDecButtons)
  40418. {
  40419. sendDragStart();
  40420. if (button == incButton)
  40421. setValue (snapValue (getValue() + interval, false), true, true);
  40422. else if (button == decButton)
  40423. setValue (snapValue (getValue() - interval, false), true, true);
  40424. sendDragEnd();
  40425. }
  40426. }
  40427. double Slider::constrainedValue (double value) const
  40428. {
  40429. if (interval > 0)
  40430. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40431. if (value <= minimum || maximum <= minimum)
  40432. value = minimum;
  40433. else if (value >= maximum)
  40434. value = maximum;
  40435. return value;
  40436. }
  40437. float Slider::getLinearSliderPos (const double value)
  40438. {
  40439. double sliderPosProportional;
  40440. if (maximum > minimum)
  40441. {
  40442. if (value < minimum)
  40443. {
  40444. sliderPosProportional = 0.0;
  40445. }
  40446. else if (value > maximum)
  40447. {
  40448. sliderPosProportional = 1.0;
  40449. }
  40450. else
  40451. {
  40452. sliderPosProportional = valueToProportionOfLength (value);
  40453. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40454. }
  40455. }
  40456. else
  40457. {
  40458. sliderPosProportional = 0.5;
  40459. }
  40460. if (isVertical() || style == IncDecButtons)
  40461. sliderPosProportional = 1.0 - sliderPosProportional;
  40462. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40463. }
  40464. bool Slider::isHorizontal() const
  40465. {
  40466. return style == LinearHorizontal
  40467. || style == LinearBar
  40468. || style == TwoValueHorizontal
  40469. || style == ThreeValueHorizontal;
  40470. }
  40471. bool Slider::isVertical() const
  40472. {
  40473. return style == LinearVertical
  40474. || style == TwoValueVertical
  40475. || style == ThreeValueVertical;
  40476. }
  40477. bool Slider::incDecDragDirectionIsHorizontal() const
  40478. {
  40479. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40480. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40481. }
  40482. float Slider::getPositionOfValue (const double value)
  40483. {
  40484. if (isHorizontal() || isVertical())
  40485. {
  40486. return getLinearSliderPos (value);
  40487. }
  40488. else
  40489. {
  40490. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40491. return 0.0f;
  40492. }
  40493. }
  40494. void Slider::paint (Graphics& g)
  40495. {
  40496. if (style != IncDecButtons)
  40497. {
  40498. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40499. {
  40500. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40501. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40502. getLookAndFeel().drawRotarySlider (g,
  40503. sliderRect.getX(),
  40504. sliderRect.getY(),
  40505. sliderRect.getWidth(),
  40506. sliderRect.getHeight(),
  40507. sliderPos,
  40508. rotaryStart, rotaryEnd,
  40509. *this);
  40510. }
  40511. else
  40512. {
  40513. getLookAndFeel().drawLinearSlider (g,
  40514. sliderRect.getX(),
  40515. sliderRect.getY(),
  40516. sliderRect.getWidth(),
  40517. sliderRect.getHeight(),
  40518. getLinearSliderPos (lastCurrentValue),
  40519. getLinearSliderPos (lastValueMin),
  40520. getLinearSliderPos (lastValueMax),
  40521. style,
  40522. *this);
  40523. }
  40524. if (style == LinearBar && valueBox == 0)
  40525. {
  40526. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40527. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40528. }
  40529. }
  40530. }
  40531. void Slider::resized()
  40532. {
  40533. int minXSpace = 0;
  40534. int minYSpace = 0;
  40535. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40536. minXSpace = 30;
  40537. else
  40538. minYSpace = 15;
  40539. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40540. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40541. if (style == LinearBar)
  40542. {
  40543. if (valueBox != 0)
  40544. valueBox->setBounds (getLocalBounds());
  40545. }
  40546. else
  40547. {
  40548. if (textBoxPos == NoTextBox)
  40549. {
  40550. sliderRect = getLocalBounds();
  40551. }
  40552. else if (textBoxPos == TextBoxLeft)
  40553. {
  40554. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40555. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40556. }
  40557. else if (textBoxPos == TextBoxRight)
  40558. {
  40559. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40560. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40561. }
  40562. else if (textBoxPos == TextBoxAbove)
  40563. {
  40564. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40565. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40566. }
  40567. else if (textBoxPos == TextBoxBelow)
  40568. {
  40569. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40570. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40571. }
  40572. }
  40573. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40574. if (style == LinearBar)
  40575. {
  40576. const int barIndent = 1;
  40577. sliderRegionStart = barIndent;
  40578. sliderRegionSize = getWidth() - barIndent * 2;
  40579. sliderRect.setBounds (sliderRegionStart, barIndent,
  40580. sliderRegionSize, getHeight() - barIndent * 2);
  40581. }
  40582. else if (isHorizontal())
  40583. {
  40584. sliderRegionStart = sliderRect.getX() + indent;
  40585. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40586. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40587. sliderRegionSize, sliderRect.getHeight());
  40588. }
  40589. else if (isVertical())
  40590. {
  40591. sliderRegionStart = sliderRect.getY() + indent;
  40592. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40593. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40594. sliderRect.getWidth(), sliderRegionSize);
  40595. }
  40596. else
  40597. {
  40598. sliderRegionStart = 0;
  40599. sliderRegionSize = 100;
  40600. }
  40601. if (style == IncDecButtons)
  40602. {
  40603. Rectangle<int> buttonRect (sliderRect);
  40604. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40605. buttonRect.expand (-2, 0);
  40606. else
  40607. buttonRect.expand (0, -2);
  40608. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40609. if (incDecButtonsSideBySide)
  40610. {
  40611. decButton->setBounds (buttonRect.getX(),
  40612. buttonRect.getY(),
  40613. buttonRect.getWidth() / 2,
  40614. buttonRect.getHeight());
  40615. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40616. incButton->setBounds (buttonRect.getCentreX(),
  40617. buttonRect.getY(),
  40618. buttonRect.getWidth() / 2,
  40619. buttonRect.getHeight());
  40620. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40621. }
  40622. else
  40623. {
  40624. incButton->setBounds (buttonRect.getX(),
  40625. buttonRect.getY(),
  40626. buttonRect.getWidth(),
  40627. buttonRect.getHeight() / 2);
  40628. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40629. decButton->setBounds (buttonRect.getX(),
  40630. buttonRect.getCentreY(),
  40631. buttonRect.getWidth(),
  40632. buttonRect.getHeight() / 2);
  40633. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40634. }
  40635. }
  40636. }
  40637. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40638. {
  40639. repaint();
  40640. }
  40641. void Slider::mouseDown (const MouseEvent& e)
  40642. {
  40643. mouseWasHidden = false;
  40644. incDecDragged = false;
  40645. mouseXWhenLastDragged = e.x;
  40646. mouseYWhenLastDragged = e.y;
  40647. mouseDragStartX = e.getMouseDownX();
  40648. mouseDragStartY = e.getMouseDownY();
  40649. if (isEnabled())
  40650. {
  40651. if (e.mods.isPopupMenu() && menuEnabled)
  40652. {
  40653. menuShown = true;
  40654. PopupMenu m;
  40655. m.setLookAndFeel (&getLookAndFeel());
  40656. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40657. m.addSeparator();
  40658. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40659. {
  40660. PopupMenu rotaryMenu;
  40661. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40662. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40663. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40664. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40665. }
  40666. const int r = m.show();
  40667. if (r == 1)
  40668. {
  40669. setVelocityBasedMode (! isVelocityBased);
  40670. }
  40671. else if (r == 2)
  40672. {
  40673. setSliderStyle (Rotary);
  40674. }
  40675. else if (r == 3)
  40676. {
  40677. setSliderStyle (RotaryHorizontalDrag);
  40678. }
  40679. else if (r == 4)
  40680. {
  40681. setSliderStyle (RotaryVerticalDrag);
  40682. }
  40683. }
  40684. else if (maximum > minimum)
  40685. {
  40686. menuShown = false;
  40687. if (valueBox != 0)
  40688. valueBox->hideEditor (true);
  40689. sliderBeingDragged = 0;
  40690. if (style == TwoValueHorizontal
  40691. || style == TwoValueVertical
  40692. || style == ThreeValueHorizontal
  40693. || style == ThreeValueVertical)
  40694. {
  40695. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40696. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40697. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40698. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40699. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40700. {
  40701. if (maxPosDistance <= minPosDistance)
  40702. sliderBeingDragged = 2;
  40703. else
  40704. sliderBeingDragged = 1;
  40705. }
  40706. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40707. {
  40708. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40709. sliderBeingDragged = 1;
  40710. else if (normalPosDistance >= maxPosDistance)
  40711. sliderBeingDragged = 2;
  40712. }
  40713. }
  40714. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40715. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40716. * valueToProportionOfLength (currentValue.getValue());
  40717. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40718. : ((sliderBeingDragged == 1) ? valueMin
  40719. : currentValue)).getValue();
  40720. valueOnMouseDown = valueWhenLastDragged;
  40721. if (popupDisplayEnabled)
  40722. {
  40723. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40724. popupDisplay = popup;
  40725. if (parentForPopupDisplay != 0)
  40726. {
  40727. parentForPopupDisplay->addChildComponent (popup);
  40728. }
  40729. else
  40730. {
  40731. popup->addToDesktop (0);
  40732. }
  40733. popup->setVisible (true);
  40734. }
  40735. sendDragStart();
  40736. mouseDrag (e);
  40737. }
  40738. }
  40739. }
  40740. void Slider::mouseUp (const MouseEvent&)
  40741. {
  40742. if (isEnabled()
  40743. && (! menuShown)
  40744. && (maximum > minimum)
  40745. && (style != IncDecButtons || incDecDragged))
  40746. {
  40747. restoreMouseIfHidden();
  40748. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40749. triggerChangeMessage (false);
  40750. sendDragEnd();
  40751. popupDisplay = 0;
  40752. if (style == IncDecButtons)
  40753. {
  40754. incButton->setState (Button::buttonNormal);
  40755. decButton->setState (Button::buttonNormal);
  40756. }
  40757. }
  40758. }
  40759. void Slider::restoreMouseIfHidden()
  40760. {
  40761. if (mouseWasHidden)
  40762. {
  40763. mouseWasHidden = false;
  40764. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40765. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40766. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40767. : ((sliderBeingDragged == 1) ? getMinValue()
  40768. : (double) currentValue.getValue());
  40769. Point<int> mousePos;
  40770. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40771. {
  40772. mousePos = Desktop::getLastMouseDownPosition();
  40773. if (style == RotaryHorizontalDrag)
  40774. {
  40775. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40776. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40777. }
  40778. else
  40779. {
  40780. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40781. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40782. }
  40783. }
  40784. else
  40785. {
  40786. const int pixelPos = (int) getLinearSliderPos (pos);
  40787. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40788. isVertical() ? pixelPos : (getHeight() / 2)));
  40789. }
  40790. Desktop::setMousePosition (mousePos);
  40791. }
  40792. }
  40793. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40794. {
  40795. if (isEnabled()
  40796. && style != IncDecButtons
  40797. && style != Rotary
  40798. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40799. {
  40800. restoreMouseIfHidden();
  40801. }
  40802. }
  40803. static double smallestAngleBetween (double a1, double a2)
  40804. {
  40805. return jmin (std::abs (a1 - a2),
  40806. std::abs (a1 + double_Pi * 2.0 - a2),
  40807. std::abs (a2 + double_Pi * 2.0 - a1));
  40808. }
  40809. void Slider::mouseDrag (const MouseEvent& e)
  40810. {
  40811. if (isEnabled()
  40812. && (! menuShown)
  40813. && (maximum > minimum))
  40814. {
  40815. if (style == Rotary)
  40816. {
  40817. int dx = e.x - sliderRect.getCentreX();
  40818. int dy = e.y - sliderRect.getCentreY();
  40819. if (dx * dx + dy * dy > 25)
  40820. {
  40821. double angle = std::atan2 ((double) dx, (double) -dy);
  40822. while (angle < 0.0)
  40823. angle += double_Pi * 2.0;
  40824. if (rotaryStop && ! e.mouseWasClicked())
  40825. {
  40826. if (std::abs (angle - lastAngle) > double_Pi)
  40827. {
  40828. if (angle >= lastAngle)
  40829. angle -= double_Pi * 2.0;
  40830. else
  40831. angle += double_Pi * 2.0;
  40832. }
  40833. if (angle >= lastAngle)
  40834. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40835. else
  40836. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40837. }
  40838. else
  40839. {
  40840. while (angle < rotaryStart)
  40841. angle += double_Pi * 2.0;
  40842. if (angle > rotaryEnd)
  40843. {
  40844. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40845. angle = rotaryStart;
  40846. else
  40847. angle = rotaryEnd;
  40848. }
  40849. }
  40850. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40851. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40852. lastAngle = angle;
  40853. }
  40854. }
  40855. else
  40856. {
  40857. if (style == LinearBar && e.mouseWasClicked()
  40858. && valueBox != 0 && valueBox->isEditable())
  40859. return;
  40860. if (style == IncDecButtons && ! incDecDragged)
  40861. {
  40862. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40863. return;
  40864. incDecDragged = true;
  40865. mouseDragStartX = e.x;
  40866. mouseDragStartY = e.y;
  40867. }
  40868. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40869. : false))
  40870. || ((maximum - minimum) / sliderRegionSize < interval))
  40871. {
  40872. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40873. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40874. if (style == RotaryHorizontalDrag
  40875. || style == RotaryVerticalDrag
  40876. || style == IncDecButtons
  40877. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40878. && ! snapsToMousePos))
  40879. {
  40880. const int mouseDiff = (style == RotaryHorizontalDrag
  40881. || style == LinearHorizontal
  40882. || style == LinearBar
  40883. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40884. ? e.x - mouseDragStartX
  40885. : mouseDragStartY - e.y;
  40886. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40887. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40888. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40889. if (style == IncDecButtons)
  40890. {
  40891. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40892. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40893. }
  40894. }
  40895. else
  40896. {
  40897. if (isVertical())
  40898. scaledMousePos = 1.0 - scaledMousePos;
  40899. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40900. }
  40901. }
  40902. else
  40903. {
  40904. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40905. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40906. ? e.x - mouseXWhenLastDragged
  40907. : e.y - mouseYWhenLastDragged;
  40908. const double maxSpeed = jmax (200, sliderRegionSize);
  40909. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40910. if (speed != 0)
  40911. {
  40912. speed = 0.2 * velocityModeSensitivity
  40913. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40914. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40915. / maxSpeed))));
  40916. if (mouseDiff < 0)
  40917. speed = -speed;
  40918. if (isVertical() || style == RotaryVerticalDrag
  40919. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40920. speed = -speed;
  40921. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40922. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40923. e.source.enableUnboundedMouseMovement (true, false);
  40924. mouseWasHidden = true;
  40925. }
  40926. }
  40927. }
  40928. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40929. if (sliderBeingDragged == 0)
  40930. {
  40931. setValue (snapValue (valueWhenLastDragged, true),
  40932. ! sendChangeOnlyOnRelease, true);
  40933. }
  40934. else if (sliderBeingDragged == 1)
  40935. {
  40936. setMinValue (snapValue (valueWhenLastDragged, true),
  40937. ! sendChangeOnlyOnRelease, false, true);
  40938. if (e.mods.isShiftDown())
  40939. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40940. else
  40941. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40942. }
  40943. else
  40944. {
  40945. jassert (sliderBeingDragged == 2);
  40946. setMaxValue (snapValue (valueWhenLastDragged, true),
  40947. ! sendChangeOnlyOnRelease, false, true);
  40948. if (e.mods.isShiftDown())
  40949. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40950. else
  40951. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40952. }
  40953. mouseXWhenLastDragged = e.x;
  40954. mouseYWhenLastDragged = e.y;
  40955. }
  40956. }
  40957. void Slider::mouseDoubleClick (const MouseEvent&)
  40958. {
  40959. if (doubleClickToValue
  40960. && isEnabled()
  40961. && style != IncDecButtons
  40962. && minimum <= doubleClickReturnValue
  40963. && maximum >= doubleClickReturnValue)
  40964. {
  40965. sendDragStart();
  40966. setValue (doubleClickReturnValue, true, true);
  40967. sendDragEnd();
  40968. }
  40969. }
  40970. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40971. {
  40972. if (scrollWheelEnabled && isEnabled()
  40973. && style != TwoValueHorizontal
  40974. && style != TwoValueVertical)
  40975. {
  40976. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40977. {
  40978. if (valueBox != 0)
  40979. valueBox->hideEditor (false);
  40980. const double value = (double) currentValue.getValue();
  40981. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40982. const double currentPos = valueToProportionOfLength (value);
  40983. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40984. double delta = (newValue != value)
  40985. ? jmax (std::abs (newValue - value), interval) : 0;
  40986. if (value > newValue)
  40987. delta = -delta;
  40988. sendDragStart();
  40989. setValue (snapValue (value + delta, false), true, true);
  40990. sendDragEnd();
  40991. }
  40992. }
  40993. else
  40994. {
  40995. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40996. }
  40997. }
  40998. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40999. {
  41000. }
  41001. void SliderListener::sliderDragEnded (Slider*)
  41002. {
  41003. }
  41004. END_JUCE_NAMESPACE
  41005. /*** End of inlined file: juce_Slider.cpp ***/
  41006. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41007. BEGIN_JUCE_NAMESPACE
  41008. class DragOverlayComp : public Component
  41009. {
  41010. public:
  41011. DragOverlayComp (const Image& image_)
  41012. : image (image_)
  41013. {
  41014. image.duplicateIfShared();
  41015. image.multiplyAllAlphas (0.8f);
  41016. setAlwaysOnTop (true);
  41017. }
  41018. ~DragOverlayComp()
  41019. {
  41020. }
  41021. void paint (Graphics& g)
  41022. {
  41023. g.drawImageAt (image, 0, 0);
  41024. }
  41025. private:
  41026. Image image;
  41027. DragOverlayComp (const DragOverlayComp&);
  41028. DragOverlayComp& operator= (const DragOverlayComp&);
  41029. };
  41030. TableHeaderComponent::TableHeaderComponent()
  41031. : columnsChanged (false),
  41032. columnsResized (false),
  41033. sortChanged (false),
  41034. menuActive (true),
  41035. stretchToFit (false),
  41036. columnIdBeingResized (0),
  41037. columnIdBeingDragged (0),
  41038. columnIdUnderMouse (0),
  41039. lastDeliberateWidth (0)
  41040. {
  41041. }
  41042. TableHeaderComponent::~TableHeaderComponent()
  41043. {
  41044. dragOverlayComp = 0;
  41045. }
  41046. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41047. {
  41048. menuActive = hasMenu;
  41049. }
  41050. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41051. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41052. {
  41053. if (onlyCountVisibleColumns)
  41054. {
  41055. int num = 0;
  41056. for (int i = columns.size(); --i >= 0;)
  41057. if (columns.getUnchecked(i)->isVisible())
  41058. ++num;
  41059. return num;
  41060. }
  41061. else
  41062. {
  41063. return columns.size();
  41064. }
  41065. }
  41066. const String TableHeaderComponent::getColumnName (const int columnId) const
  41067. {
  41068. const ColumnInfo* const ci = getInfoForId (columnId);
  41069. return ci != 0 ? ci->name : String::empty;
  41070. }
  41071. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41072. {
  41073. ColumnInfo* const ci = getInfoForId (columnId);
  41074. if (ci != 0 && ci->name != newName)
  41075. {
  41076. ci->name = newName;
  41077. sendColumnsChanged();
  41078. }
  41079. }
  41080. void TableHeaderComponent::addColumn (const String& columnName,
  41081. const int columnId,
  41082. const int width,
  41083. const int minimumWidth,
  41084. const int maximumWidth,
  41085. const int propertyFlags,
  41086. const int insertIndex)
  41087. {
  41088. // can't have a duplicate or null ID!
  41089. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41090. jassert (width > 0);
  41091. ColumnInfo* const ci = new ColumnInfo();
  41092. ci->name = columnName;
  41093. ci->id = columnId;
  41094. ci->width = width;
  41095. ci->lastDeliberateWidth = width;
  41096. ci->minimumWidth = minimumWidth;
  41097. ci->maximumWidth = maximumWidth;
  41098. if (ci->maximumWidth < 0)
  41099. ci->maximumWidth = std::numeric_limits<int>::max();
  41100. jassert (ci->maximumWidth >= ci->minimumWidth);
  41101. ci->propertyFlags = propertyFlags;
  41102. columns.insert (insertIndex, ci);
  41103. sendColumnsChanged();
  41104. }
  41105. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41106. {
  41107. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41108. if (index >= 0)
  41109. {
  41110. columns.remove (index);
  41111. sortChanged = true;
  41112. sendColumnsChanged();
  41113. }
  41114. }
  41115. void TableHeaderComponent::removeAllColumns()
  41116. {
  41117. if (columns.size() > 0)
  41118. {
  41119. columns.clear();
  41120. sendColumnsChanged();
  41121. }
  41122. }
  41123. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41124. {
  41125. const int currentIndex = getIndexOfColumnId (columnId, false);
  41126. newIndex = visibleIndexToTotalIndex (newIndex);
  41127. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41128. {
  41129. columns.move (currentIndex, newIndex);
  41130. sendColumnsChanged();
  41131. }
  41132. }
  41133. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41134. {
  41135. const ColumnInfo* const ci = getInfoForId (columnId);
  41136. return ci != 0 ? ci->width : 0;
  41137. }
  41138. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41139. {
  41140. ColumnInfo* const ci = getInfoForId (columnId);
  41141. if (ci != 0 && ci->width != newWidth)
  41142. {
  41143. const int numColumns = getNumColumns (true);
  41144. ci->lastDeliberateWidth = ci->width
  41145. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41146. if (stretchToFit)
  41147. {
  41148. const int index = getIndexOfColumnId (columnId, true) + 1;
  41149. if (((unsigned int) index) < (unsigned int) numColumns)
  41150. {
  41151. const int x = getColumnPosition (index).getX();
  41152. if (lastDeliberateWidth == 0)
  41153. lastDeliberateWidth = getTotalWidth();
  41154. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41155. }
  41156. }
  41157. repaint();
  41158. columnsResized = true;
  41159. triggerAsyncUpdate();
  41160. }
  41161. }
  41162. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41163. {
  41164. int n = 0;
  41165. for (int i = 0; i < columns.size(); ++i)
  41166. {
  41167. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41168. {
  41169. if (columns.getUnchecked(i)->id == columnId)
  41170. return n;
  41171. ++n;
  41172. }
  41173. }
  41174. return -1;
  41175. }
  41176. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41177. {
  41178. if (onlyCountVisibleColumns)
  41179. index = visibleIndexToTotalIndex (index);
  41180. const ColumnInfo* const ci = columns [index];
  41181. return (ci != 0) ? ci->id : 0;
  41182. }
  41183. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41184. {
  41185. int x = 0, width = 0, n = 0;
  41186. for (int i = 0; i < columns.size(); ++i)
  41187. {
  41188. x += width;
  41189. if (columns.getUnchecked(i)->isVisible())
  41190. {
  41191. width = columns.getUnchecked(i)->width;
  41192. if (n++ == index)
  41193. break;
  41194. }
  41195. else
  41196. {
  41197. width = 0;
  41198. }
  41199. }
  41200. return Rectangle<int> (x, 0, width, getHeight());
  41201. }
  41202. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41203. {
  41204. if (xToFind >= 0)
  41205. {
  41206. int x = 0;
  41207. for (int i = 0; i < columns.size(); ++i)
  41208. {
  41209. const ColumnInfo* const ci = columns.getUnchecked(i);
  41210. if (ci->isVisible())
  41211. {
  41212. x += ci->width;
  41213. if (xToFind < x)
  41214. return ci->id;
  41215. }
  41216. }
  41217. }
  41218. return 0;
  41219. }
  41220. int TableHeaderComponent::getTotalWidth() const
  41221. {
  41222. int w = 0;
  41223. for (int i = columns.size(); --i >= 0;)
  41224. if (columns.getUnchecked(i)->isVisible())
  41225. w += columns.getUnchecked(i)->width;
  41226. return w;
  41227. }
  41228. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41229. {
  41230. stretchToFit = shouldStretchToFit;
  41231. lastDeliberateWidth = getTotalWidth();
  41232. resized();
  41233. }
  41234. bool TableHeaderComponent::isStretchToFitActive() const
  41235. {
  41236. return stretchToFit;
  41237. }
  41238. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41239. {
  41240. if (stretchToFit && getWidth() > 0
  41241. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41242. {
  41243. lastDeliberateWidth = targetTotalWidth;
  41244. resizeColumnsToFit (0, targetTotalWidth);
  41245. }
  41246. }
  41247. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41248. {
  41249. targetTotalWidth = jmax (targetTotalWidth, 0);
  41250. StretchableObjectResizer sor;
  41251. int i;
  41252. for (i = firstColumnIndex; i < columns.size(); ++i)
  41253. {
  41254. ColumnInfo* const ci = columns.getUnchecked(i);
  41255. if (ci->isVisible())
  41256. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41257. }
  41258. sor.resizeToFit (targetTotalWidth);
  41259. int visIndex = 0;
  41260. for (i = firstColumnIndex; i < columns.size(); ++i)
  41261. {
  41262. ColumnInfo* const ci = columns.getUnchecked(i);
  41263. if (ci->isVisible())
  41264. {
  41265. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41266. (int) std::floor (sor.getItemSize (visIndex++)));
  41267. if (newWidth != ci->width)
  41268. {
  41269. ci->width = newWidth;
  41270. repaint();
  41271. columnsResized = true;
  41272. triggerAsyncUpdate();
  41273. }
  41274. }
  41275. }
  41276. }
  41277. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41278. {
  41279. ColumnInfo* const ci = getInfoForId (columnId);
  41280. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41281. {
  41282. if (shouldBeVisible)
  41283. ci->propertyFlags |= visible;
  41284. else
  41285. ci->propertyFlags &= ~visible;
  41286. sendColumnsChanged();
  41287. resized();
  41288. }
  41289. }
  41290. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41291. {
  41292. const ColumnInfo* const ci = getInfoForId (columnId);
  41293. return ci != 0 && ci->isVisible();
  41294. }
  41295. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41296. {
  41297. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41298. {
  41299. for (int i = columns.size(); --i >= 0;)
  41300. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41301. ColumnInfo* const ci = getInfoForId (columnId);
  41302. if (ci != 0)
  41303. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41304. reSortTable();
  41305. }
  41306. }
  41307. int TableHeaderComponent::getSortColumnId() const
  41308. {
  41309. for (int i = columns.size(); --i >= 0;)
  41310. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41311. return columns.getUnchecked(i)->id;
  41312. return 0;
  41313. }
  41314. bool TableHeaderComponent::isSortedForwards() const
  41315. {
  41316. for (int i = columns.size(); --i >= 0;)
  41317. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41318. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41319. return true;
  41320. }
  41321. void TableHeaderComponent::reSortTable()
  41322. {
  41323. sortChanged = true;
  41324. repaint();
  41325. triggerAsyncUpdate();
  41326. }
  41327. const String TableHeaderComponent::toString() const
  41328. {
  41329. String s;
  41330. XmlElement doc ("TABLELAYOUT");
  41331. doc.setAttribute ("sortedCol", getSortColumnId());
  41332. doc.setAttribute ("sortForwards", isSortedForwards());
  41333. for (int i = 0; i < columns.size(); ++i)
  41334. {
  41335. const ColumnInfo* const ci = columns.getUnchecked (i);
  41336. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41337. e->setAttribute ("id", ci->id);
  41338. e->setAttribute ("visible", ci->isVisible());
  41339. e->setAttribute ("width", ci->width);
  41340. }
  41341. return doc.createDocument (String::empty, true, false);
  41342. }
  41343. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41344. {
  41345. XmlDocument doc (storedVersion);
  41346. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41347. int index = 0;
  41348. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41349. {
  41350. forEachXmlChildElement (*storedXml, col)
  41351. {
  41352. const int tabId = col->getIntAttribute ("id");
  41353. ColumnInfo* const ci = getInfoForId (tabId);
  41354. if (ci != 0)
  41355. {
  41356. columns.move (columns.indexOf (ci), index);
  41357. ci->width = col->getIntAttribute ("width");
  41358. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41359. }
  41360. ++index;
  41361. }
  41362. columnsResized = true;
  41363. sendColumnsChanged();
  41364. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41365. storedXml->getBoolAttribute ("sortForwards", true));
  41366. }
  41367. }
  41368. void TableHeaderComponent::addListener (Listener* const newListener)
  41369. {
  41370. listeners.addIfNotAlreadyThere (newListener);
  41371. }
  41372. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41373. {
  41374. listeners.removeValue (listenerToRemove);
  41375. }
  41376. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41377. {
  41378. const ColumnInfo* const ci = getInfoForId (columnId);
  41379. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41380. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41381. }
  41382. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41383. {
  41384. for (int i = 0; i < columns.size(); ++i)
  41385. {
  41386. const ColumnInfo* const ci = columns.getUnchecked(i);
  41387. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41388. menu.addItem (ci->id, ci->name,
  41389. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41390. isColumnVisible (ci->id));
  41391. }
  41392. }
  41393. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41394. {
  41395. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41396. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41397. }
  41398. void TableHeaderComponent::paint (Graphics& g)
  41399. {
  41400. LookAndFeel& lf = getLookAndFeel();
  41401. lf.drawTableHeaderBackground (g, *this);
  41402. const Rectangle<int> clip (g.getClipBounds());
  41403. int x = 0;
  41404. for (int i = 0; i < columns.size(); ++i)
  41405. {
  41406. const ColumnInfo* const ci = columns.getUnchecked(i);
  41407. if (ci->isVisible())
  41408. {
  41409. if (x + ci->width > clip.getX()
  41410. && (ci->id != columnIdBeingDragged
  41411. || dragOverlayComp == 0
  41412. || ! dragOverlayComp->isVisible()))
  41413. {
  41414. g.saveState();
  41415. g.setOrigin (x, 0);
  41416. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41417. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41418. ci->id == columnIdUnderMouse,
  41419. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41420. ci->propertyFlags);
  41421. g.restoreState();
  41422. }
  41423. x += ci->width;
  41424. if (x >= clip.getRight())
  41425. break;
  41426. }
  41427. }
  41428. }
  41429. void TableHeaderComponent::resized()
  41430. {
  41431. }
  41432. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41433. {
  41434. updateColumnUnderMouse (e.x, e.y);
  41435. }
  41436. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41437. {
  41438. updateColumnUnderMouse (e.x, e.y);
  41439. }
  41440. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41441. {
  41442. updateColumnUnderMouse (e.x, e.y);
  41443. }
  41444. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41445. {
  41446. repaint();
  41447. columnIdBeingResized = 0;
  41448. columnIdBeingDragged = 0;
  41449. if (columnIdUnderMouse != 0)
  41450. {
  41451. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41452. if (e.mods.isPopupMenu())
  41453. columnClicked (columnIdUnderMouse, e.mods);
  41454. }
  41455. if (menuActive && e.mods.isPopupMenu())
  41456. showColumnChooserMenu (columnIdUnderMouse);
  41457. }
  41458. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41459. {
  41460. if (columnIdBeingResized == 0
  41461. && columnIdBeingDragged == 0
  41462. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41463. {
  41464. dragOverlayComp = 0;
  41465. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41466. if (columnIdBeingResized != 0)
  41467. {
  41468. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41469. initialColumnWidth = ci->width;
  41470. }
  41471. else
  41472. {
  41473. beginDrag (e);
  41474. }
  41475. }
  41476. if (columnIdBeingResized != 0)
  41477. {
  41478. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41479. if (ci != 0)
  41480. {
  41481. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41482. initialColumnWidth + e.getDistanceFromDragStartX());
  41483. if (stretchToFit)
  41484. {
  41485. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41486. int minWidthOnRight = 0;
  41487. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41488. if (columns.getUnchecked (i)->isVisible())
  41489. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41490. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41491. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41492. }
  41493. setColumnWidth (columnIdBeingResized, w);
  41494. }
  41495. }
  41496. else if (columnIdBeingDragged != 0)
  41497. {
  41498. if (e.y >= -50 && e.y < getHeight() + 50)
  41499. {
  41500. if (dragOverlayComp != 0)
  41501. {
  41502. dragOverlayComp->setVisible (true);
  41503. dragOverlayComp->setBounds (jlimit (0,
  41504. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41505. e.x - draggingColumnOffset),
  41506. 0,
  41507. dragOverlayComp->getWidth(),
  41508. getHeight());
  41509. for (int i = columns.size(); --i >= 0;)
  41510. {
  41511. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41512. int newIndex = currentIndex;
  41513. if (newIndex > 0)
  41514. {
  41515. // if the previous column isn't draggable, we can't move our column
  41516. // past it, because that'd change the undraggable column's position..
  41517. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41518. if ((previous->propertyFlags & draggable) != 0)
  41519. {
  41520. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41521. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41522. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41523. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41524. {
  41525. --newIndex;
  41526. }
  41527. }
  41528. }
  41529. if (newIndex < columns.size() - 1)
  41530. {
  41531. // if the next column isn't draggable, we can't move our column
  41532. // past it, because that'd change the undraggable column's position..
  41533. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41534. if ((nextCol->propertyFlags & draggable) != 0)
  41535. {
  41536. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41537. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41538. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41539. > abs (dragOverlayComp->getRight() - rightOfNext))
  41540. {
  41541. ++newIndex;
  41542. }
  41543. }
  41544. }
  41545. if (newIndex != currentIndex)
  41546. moveColumn (columnIdBeingDragged, newIndex);
  41547. else
  41548. break;
  41549. }
  41550. }
  41551. }
  41552. else
  41553. {
  41554. endDrag (draggingColumnOriginalIndex);
  41555. }
  41556. }
  41557. }
  41558. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41559. {
  41560. if (columnIdBeingDragged == 0)
  41561. {
  41562. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41563. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41564. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41565. {
  41566. columnIdBeingDragged = 0;
  41567. }
  41568. else
  41569. {
  41570. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41571. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41572. const int temp = columnIdBeingDragged;
  41573. columnIdBeingDragged = 0;
  41574. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41575. columnIdBeingDragged = temp;
  41576. dragOverlayComp->setBounds (columnRect);
  41577. for (int i = listeners.size(); --i >= 0;)
  41578. {
  41579. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41580. i = jmin (i, listeners.size() - 1);
  41581. }
  41582. }
  41583. }
  41584. }
  41585. void TableHeaderComponent::endDrag (const int finalIndex)
  41586. {
  41587. if (columnIdBeingDragged != 0)
  41588. {
  41589. moveColumn (columnIdBeingDragged, finalIndex);
  41590. columnIdBeingDragged = 0;
  41591. repaint();
  41592. for (int i = listeners.size(); --i >= 0;)
  41593. {
  41594. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41595. i = jmin (i, listeners.size() - 1);
  41596. }
  41597. }
  41598. }
  41599. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41600. {
  41601. mouseDrag (e);
  41602. for (int i = columns.size(); --i >= 0;)
  41603. if (columns.getUnchecked (i)->isVisible())
  41604. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41605. columnIdBeingResized = 0;
  41606. repaint();
  41607. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41608. updateColumnUnderMouse (e.x, e.y);
  41609. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41610. columnClicked (columnIdUnderMouse, e.mods);
  41611. dragOverlayComp = 0;
  41612. }
  41613. const MouseCursor TableHeaderComponent::getMouseCursor()
  41614. {
  41615. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41616. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41617. return Component::getMouseCursor();
  41618. }
  41619. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41620. {
  41621. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41622. }
  41623. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41624. {
  41625. for (int i = columns.size(); --i >= 0;)
  41626. if (columns.getUnchecked(i)->id == id)
  41627. return columns.getUnchecked(i);
  41628. return 0;
  41629. }
  41630. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41631. {
  41632. int n = 0;
  41633. for (int i = 0; i < columns.size(); ++i)
  41634. {
  41635. if (columns.getUnchecked(i)->isVisible())
  41636. {
  41637. if (n == visibleIndex)
  41638. return i;
  41639. ++n;
  41640. }
  41641. }
  41642. return -1;
  41643. }
  41644. void TableHeaderComponent::sendColumnsChanged()
  41645. {
  41646. if (stretchToFit && lastDeliberateWidth > 0)
  41647. resizeAllColumnsToFit (lastDeliberateWidth);
  41648. repaint();
  41649. columnsChanged = true;
  41650. triggerAsyncUpdate();
  41651. }
  41652. void TableHeaderComponent::handleAsyncUpdate()
  41653. {
  41654. const bool changed = columnsChanged || sortChanged;
  41655. const bool sized = columnsResized || changed;
  41656. const bool sorted = sortChanged;
  41657. columnsChanged = false;
  41658. columnsResized = false;
  41659. sortChanged = false;
  41660. if (sorted)
  41661. {
  41662. for (int i = listeners.size(); --i >= 0;)
  41663. {
  41664. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41665. i = jmin (i, listeners.size() - 1);
  41666. }
  41667. }
  41668. if (changed)
  41669. {
  41670. for (int i = listeners.size(); --i >= 0;)
  41671. {
  41672. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41673. i = jmin (i, listeners.size() - 1);
  41674. }
  41675. }
  41676. if (sized)
  41677. {
  41678. for (int i = listeners.size(); --i >= 0;)
  41679. {
  41680. listeners.getUnchecked(i)->tableColumnsResized (this);
  41681. i = jmin (i, listeners.size() - 1);
  41682. }
  41683. }
  41684. }
  41685. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41686. {
  41687. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41688. {
  41689. const int draggableDistance = 3;
  41690. int x = 0;
  41691. for (int i = 0; i < columns.size(); ++i)
  41692. {
  41693. const ColumnInfo* const ci = columns.getUnchecked(i);
  41694. if (ci->isVisible())
  41695. {
  41696. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41697. && (ci->propertyFlags & resizable) != 0)
  41698. return ci->id;
  41699. x += ci->width;
  41700. }
  41701. }
  41702. }
  41703. return 0;
  41704. }
  41705. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41706. {
  41707. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41708. ? getColumnIdAtX (x) : 0;
  41709. if (newCol != columnIdUnderMouse)
  41710. {
  41711. columnIdUnderMouse = newCol;
  41712. repaint();
  41713. }
  41714. }
  41715. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41716. {
  41717. PopupMenu m;
  41718. addMenuItems (m, columnIdClicked);
  41719. if (m.getNumItems() > 0)
  41720. {
  41721. m.setLookAndFeel (&getLookAndFeel());
  41722. const int result = m.show();
  41723. if (result != 0)
  41724. reactToMenuItem (result, columnIdClicked);
  41725. }
  41726. }
  41727. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41728. {
  41729. }
  41730. END_JUCE_NAMESPACE
  41731. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41732. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41733. BEGIN_JUCE_NAMESPACE
  41734. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41735. class TableListRowComp : public Component,
  41736. public TooltipClient
  41737. {
  41738. public:
  41739. TableListRowComp (TableListBox& owner_)
  41740. : owner (owner_),
  41741. row (-1),
  41742. isSelected (false)
  41743. {
  41744. }
  41745. ~TableListRowComp()
  41746. {
  41747. deleteAllChildren();
  41748. }
  41749. void paint (Graphics& g)
  41750. {
  41751. TableListBoxModel* const model = owner.getModel();
  41752. if (model != 0)
  41753. {
  41754. const TableHeaderComponent* const header = owner.getHeader();
  41755. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41756. const int numColumns = header->getNumColumns (true);
  41757. for (int i = 0; i < numColumns; ++i)
  41758. {
  41759. if (! columnsWithComponents [i])
  41760. {
  41761. const int columnId = header->getColumnIdOfIndex (i, true);
  41762. Rectangle<int> columnRect (header->getColumnPosition (i));
  41763. columnRect.setSize (columnRect.getWidth(), getHeight());
  41764. g.saveState();
  41765. g.reduceClipRegion (columnRect);
  41766. g.setOrigin (columnRect.getX(), 0);
  41767. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41768. g.restoreState();
  41769. }
  41770. }
  41771. }
  41772. }
  41773. void update (const int newRow, const bool isNowSelected)
  41774. {
  41775. if (newRow != row || isNowSelected != isSelected)
  41776. {
  41777. row = newRow;
  41778. isSelected = isNowSelected;
  41779. repaint();
  41780. deleteAllChildren();
  41781. }
  41782. if (row < owner.getNumRows())
  41783. {
  41784. jassert (row >= 0);
  41785. const Identifier tagPropertyName ("_tableLastUseNum");
  41786. const int newTag = Random::getSystemRandom().nextInt();
  41787. const TableHeaderComponent* const header = owner.getHeader();
  41788. const int numColumns = header->getNumColumns (true);
  41789. columnsWithComponents.clear();
  41790. if (owner.getModel() != 0)
  41791. {
  41792. for (int i = 0; i < numColumns; ++i)
  41793. {
  41794. const int columnId = header->getColumnIdOfIndex (i, true);
  41795. Component* const newComp
  41796. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41797. findChildComponentForColumn (columnId));
  41798. if (newComp != 0)
  41799. {
  41800. addAndMakeVisible (newComp);
  41801. newComp->getProperties().set (tagPropertyName, newTag);
  41802. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41803. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41804. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41805. columnsWithComponents.setBit (i);
  41806. }
  41807. }
  41808. }
  41809. for (int i = getNumChildComponents(); --i >= 0;)
  41810. {
  41811. Component* const c = getChildComponent (i);
  41812. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41813. delete c;
  41814. }
  41815. }
  41816. else
  41817. {
  41818. columnsWithComponents.clear();
  41819. deleteAllChildren();
  41820. }
  41821. }
  41822. void resized()
  41823. {
  41824. for (int i = getNumChildComponents(); --i >= 0;)
  41825. {
  41826. Component* const c = getChildComponent (i);
  41827. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41828. if (columnId != 0)
  41829. {
  41830. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41831. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41832. }
  41833. }
  41834. }
  41835. void mouseDown (const MouseEvent& e)
  41836. {
  41837. isDragging = false;
  41838. selectRowOnMouseUp = false;
  41839. if (isEnabled())
  41840. {
  41841. if (! isSelected)
  41842. {
  41843. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41844. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41845. if (columnId != 0 && owner.getModel() != 0)
  41846. owner.getModel()->cellClicked (row, columnId, e);
  41847. }
  41848. else
  41849. {
  41850. selectRowOnMouseUp = true;
  41851. }
  41852. }
  41853. }
  41854. void mouseDrag (const MouseEvent& e)
  41855. {
  41856. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41857. {
  41858. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41859. if (selectedRows.size() > 0)
  41860. {
  41861. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41862. if (dragDescription.isNotEmpty())
  41863. {
  41864. isDragging = true;
  41865. owner.startDragAndDrop (e, dragDescription);
  41866. }
  41867. }
  41868. }
  41869. }
  41870. void mouseUp (const MouseEvent& e)
  41871. {
  41872. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41873. {
  41874. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41875. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41876. if (columnId != 0 && owner.getModel() != 0)
  41877. owner.getModel()->cellClicked (row, columnId, e);
  41878. }
  41879. }
  41880. void mouseDoubleClick (const MouseEvent& e)
  41881. {
  41882. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41883. if (columnId != 0 && owner.getModel() != 0)
  41884. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41885. }
  41886. const String getTooltip()
  41887. {
  41888. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41889. if (columnId != 0 && owner.getModel() != 0)
  41890. return owner.getModel()->getCellTooltip (row, columnId);
  41891. return String::empty;
  41892. }
  41893. Component* findChildComponentForColumn (const int columnId) const
  41894. {
  41895. for (int i = getNumChildComponents(); --i >= 0;)
  41896. {
  41897. Component* const c = getChildComponent (i);
  41898. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41899. return c;
  41900. }
  41901. return 0;
  41902. }
  41903. juce_UseDebuggingNewOperator
  41904. private:
  41905. TableListBox& owner;
  41906. int row;
  41907. bool isSelected, isDragging, selectRowOnMouseUp;
  41908. BigInteger columnsWithComponents;
  41909. TableListRowComp (const TableListRowComp&);
  41910. TableListRowComp& operator= (const TableListRowComp&);
  41911. };
  41912. class TableListBoxHeader : public TableHeaderComponent
  41913. {
  41914. public:
  41915. TableListBoxHeader (TableListBox& owner_)
  41916. : owner (owner_)
  41917. {
  41918. }
  41919. ~TableListBoxHeader()
  41920. {
  41921. }
  41922. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41923. {
  41924. if (owner.isAutoSizeMenuOptionShown())
  41925. {
  41926. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41927. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41928. menu.addSeparator();
  41929. }
  41930. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41931. }
  41932. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41933. {
  41934. if (menuReturnId == 0xf836743)
  41935. {
  41936. owner.autoSizeColumn (columnIdClicked);
  41937. }
  41938. else if (menuReturnId == 0xf836744)
  41939. {
  41940. owner.autoSizeAllColumns();
  41941. }
  41942. else
  41943. {
  41944. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41945. }
  41946. }
  41947. juce_UseDebuggingNewOperator
  41948. private:
  41949. TableListBox& owner;
  41950. TableListBoxHeader (const TableListBoxHeader&);
  41951. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41952. };
  41953. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41954. : ListBox (name, 0),
  41955. model (model_),
  41956. autoSizeOptionsShown (true)
  41957. {
  41958. ListBox::model = this;
  41959. header = new TableListBoxHeader (*this);
  41960. header->setSize (100, 28);
  41961. header->addListener (this);
  41962. setHeaderComponent (header);
  41963. }
  41964. TableListBox::~TableListBox()
  41965. {
  41966. header = 0;
  41967. }
  41968. void TableListBox::setModel (TableListBoxModel* const newModel)
  41969. {
  41970. if (model != newModel)
  41971. {
  41972. model = newModel;
  41973. updateContent();
  41974. }
  41975. }
  41976. int TableListBox::getHeaderHeight() const
  41977. {
  41978. return header->getHeight();
  41979. }
  41980. void TableListBox::setHeaderHeight (const int newHeight)
  41981. {
  41982. header->setSize (header->getWidth(), newHeight);
  41983. resized();
  41984. }
  41985. void TableListBox::autoSizeColumn (const int columnId)
  41986. {
  41987. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41988. if (width > 0)
  41989. header->setColumnWidth (columnId, width);
  41990. }
  41991. void TableListBox::autoSizeAllColumns()
  41992. {
  41993. for (int i = 0; i < header->getNumColumns (true); ++i)
  41994. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41995. }
  41996. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41997. {
  41998. autoSizeOptionsShown = shouldBeShown;
  41999. }
  42000. bool TableListBox::isAutoSizeMenuOptionShown() const
  42001. {
  42002. return autoSizeOptionsShown;
  42003. }
  42004. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42005. const int rowNumber,
  42006. const bool relativeToComponentTopLeft) const
  42007. {
  42008. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42009. if (relativeToComponentTopLeft)
  42010. headerCell.translate (header->getX(), 0);
  42011. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42012. return Rectangle<int> (headerCell.getX(), row.getY(),
  42013. headerCell.getWidth(), row.getHeight());
  42014. }
  42015. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42016. {
  42017. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42018. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42019. }
  42020. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42021. {
  42022. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42023. if (scrollbar != 0)
  42024. {
  42025. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42026. double x = scrollbar->getCurrentRangeStart();
  42027. const double w = scrollbar->getCurrentRangeSize();
  42028. if (pos.getX() < x)
  42029. x = pos.getX();
  42030. else if (pos.getRight() > x + w)
  42031. x += jmax (0.0, pos.getRight() - (x + w));
  42032. scrollbar->setCurrentRangeStart (x);
  42033. }
  42034. }
  42035. int TableListBox::getNumRows()
  42036. {
  42037. return model != 0 ? model->getNumRows() : 0;
  42038. }
  42039. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42040. {
  42041. }
  42042. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42043. {
  42044. if (existingComponentToUpdate == 0)
  42045. existingComponentToUpdate = new TableListRowComp (*this);
  42046. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42047. return existingComponentToUpdate;
  42048. }
  42049. void TableListBox::selectedRowsChanged (int row)
  42050. {
  42051. if (model != 0)
  42052. model->selectedRowsChanged (row);
  42053. }
  42054. void TableListBox::deleteKeyPressed (int row)
  42055. {
  42056. if (model != 0)
  42057. model->deleteKeyPressed (row);
  42058. }
  42059. void TableListBox::returnKeyPressed (int row)
  42060. {
  42061. if (model != 0)
  42062. model->returnKeyPressed (row);
  42063. }
  42064. void TableListBox::backgroundClicked()
  42065. {
  42066. if (model != 0)
  42067. model->backgroundClicked();
  42068. }
  42069. void TableListBox::listWasScrolled()
  42070. {
  42071. if (model != 0)
  42072. model->listWasScrolled();
  42073. }
  42074. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42075. {
  42076. setMinimumContentWidth (header->getTotalWidth());
  42077. repaint();
  42078. updateColumnComponents();
  42079. }
  42080. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42081. {
  42082. setMinimumContentWidth (header->getTotalWidth());
  42083. repaint();
  42084. updateColumnComponents();
  42085. }
  42086. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42087. {
  42088. if (model != 0)
  42089. model->sortOrderChanged (header->getSortColumnId(),
  42090. header->isSortedForwards());
  42091. }
  42092. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42093. {
  42094. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42095. repaint();
  42096. }
  42097. void TableListBox::resized()
  42098. {
  42099. ListBox::resized();
  42100. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42101. setMinimumContentWidth (header->getTotalWidth());
  42102. }
  42103. void TableListBox::updateColumnComponents() const
  42104. {
  42105. const int firstRow = getRowContainingPosition (0, 0);
  42106. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42107. {
  42108. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42109. if (rowComp != 0)
  42110. rowComp->resized();
  42111. }
  42112. }
  42113. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42114. {
  42115. }
  42116. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42117. {
  42118. }
  42119. void TableListBoxModel::backgroundClicked()
  42120. {
  42121. }
  42122. void TableListBoxModel::sortOrderChanged (int, const bool)
  42123. {
  42124. }
  42125. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42126. {
  42127. return 0;
  42128. }
  42129. void TableListBoxModel::selectedRowsChanged (int)
  42130. {
  42131. }
  42132. void TableListBoxModel::deleteKeyPressed (int)
  42133. {
  42134. }
  42135. void TableListBoxModel::returnKeyPressed (int)
  42136. {
  42137. }
  42138. void TableListBoxModel::listWasScrolled()
  42139. {
  42140. }
  42141. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42142. {
  42143. return String::empty;
  42144. }
  42145. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42146. {
  42147. return String::empty;
  42148. }
  42149. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42150. {
  42151. (void) existingComponentToUpdate;
  42152. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42153. return 0;
  42154. }
  42155. END_JUCE_NAMESPACE
  42156. /*** End of inlined file: juce_TableListBox.cpp ***/
  42157. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42158. BEGIN_JUCE_NAMESPACE
  42159. // a word or space that can't be broken down any further
  42160. struct TextAtom
  42161. {
  42162. String atomText;
  42163. float width;
  42164. int numChars;
  42165. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42166. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42167. const String getText (const juce_wchar passwordCharacter) const
  42168. {
  42169. if (passwordCharacter == 0)
  42170. return atomText;
  42171. else
  42172. return String::repeatedString (String::charToString (passwordCharacter),
  42173. atomText.length());
  42174. }
  42175. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42176. {
  42177. if (passwordCharacter == 0)
  42178. return atomText.substring (0, numChars);
  42179. else if (isNewLine())
  42180. return String::empty;
  42181. else
  42182. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42183. }
  42184. };
  42185. // a run of text with a single font and colour
  42186. class TextEditor::UniformTextSection
  42187. {
  42188. public:
  42189. UniformTextSection (const String& text,
  42190. const Font& font_,
  42191. const Colour& colour_,
  42192. const juce_wchar passwordCharacter)
  42193. : font (font_),
  42194. colour (colour_)
  42195. {
  42196. initialiseAtoms (text, passwordCharacter);
  42197. }
  42198. UniformTextSection (const UniformTextSection& other)
  42199. : font (other.font),
  42200. colour (other.colour)
  42201. {
  42202. atoms.ensureStorageAllocated (other.atoms.size());
  42203. for (int i = 0; i < other.atoms.size(); ++i)
  42204. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42205. }
  42206. ~UniformTextSection()
  42207. {
  42208. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42209. }
  42210. void clear()
  42211. {
  42212. for (int i = atoms.size(); --i >= 0;)
  42213. delete getAtom(i);
  42214. atoms.clear();
  42215. }
  42216. int getNumAtoms() const
  42217. {
  42218. return atoms.size();
  42219. }
  42220. TextAtom* getAtom (const int index) const throw()
  42221. {
  42222. return atoms.getUnchecked (index);
  42223. }
  42224. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42225. {
  42226. if (other.atoms.size() > 0)
  42227. {
  42228. TextAtom* const lastAtom = atoms.getLast();
  42229. int i = 0;
  42230. if (lastAtom != 0)
  42231. {
  42232. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42233. {
  42234. TextAtom* const first = other.getAtom(0);
  42235. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42236. {
  42237. lastAtom->atomText += first->atomText;
  42238. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42239. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42240. delete first;
  42241. ++i;
  42242. }
  42243. }
  42244. }
  42245. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42246. while (i < other.atoms.size())
  42247. {
  42248. atoms.add (other.getAtom(i));
  42249. ++i;
  42250. }
  42251. }
  42252. }
  42253. UniformTextSection* split (const int indexToBreakAt,
  42254. const juce_wchar passwordCharacter)
  42255. {
  42256. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42257. font, colour,
  42258. passwordCharacter);
  42259. int index = 0;
  42260. for (int i = 0; i < atoms.size(); ++i)
  42261. {
  42262. TextAtom* const atom = getAtom(i);
  42263. const int nextIndex = index + atom->numChars;
  42264. if (index == indexToBreakAt)
  42265. {
  42266. int j;
  42267. for (j = i; j < atoms.size(); ++j)
  42268. section2->atoms.add (getAtom (j));
  42269. for (j = atoms.size(); --j >= i;)
  42270. atoms.remove (j);
  42271. break;
  42272. }
  42273. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42274. {
  42275. TextAtom* const secondAtom = new TextAtom();
  42276. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42277. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42278. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42279. section2->atoms.add (secondAtom);
  42280. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42281. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42282. atom->numChars = (uint16) (indexToBreakAt - index);
  42283. int j;
  42284. for (j = i + 1; j < atoms.size(); ++j)
  42285. section2->atoms.add (getAtom (j));
  42286. for (j = atoms.size(); --j > i;)
  42287. atoms.remove (j);
  42288. break;
  42289. }
  42290. index = nextIndex;
  42291. }
  42292. return section2;
  42293. }
  42294. void appendAllText (String::Concatenator& concatenator) const
  42295. {
  42296. for (int i = 0; i < atoms.size(); ++i)
  42297. concatenator.append (getAtom(i)->atomText);
  42298. }
  42299. void appendSubstring (String::Concatenator& concatenator,
  42300. const Range<int>& range) const
  42301. {
  42302. int index = 0;
  42303. for (int i = 0; i < atoms.size(); ++i)
  42304. {
  42305. const TextAtom* const atom = getAtom (i);
  42306. const int nextIndex = index + atom->numChars;
  42307. if (range.getStart() < nextIndex)
  42308. {
  42309. if (range.getEnd() <= index)
  42310. break;
  42311. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42312. if (! r.isEmpty())
  42313. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42314. }
  42315. index = nextIndex;
  42316. }
  42317. }
  42318. int getTotalLength() const
  42319. {
  42320. int total = 0;
  42321. for (int i = atoms.size(); --i >= 0;)
  42322. total += getAtom(i)->numChars;
  42323. return total;
  42324. }
  42325. void setFont (const Font& newFont,
  42326. const juce_wchar passwordCharacter)
  42327. {
  42328. if (font != newFont)
  42329. {
  42330. font = newFont;
  42331. for (int i = atoms.size(); --i >= 0;)
  42332. {
  42333. TextAtom* const atom = atoms.getUnchecked(i);
  42334. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42335. }
  42336. }
  42337. }
  42338. juce_UseDebuggingNewOperator
  42339. Font font;
  42340. Colour colour;
  42341. private:
  42342. Array <TextAtom*> atoms;
  42343. void initialiseAtoms (const String& textToParse,
  42344. const juce_wchar passwordCharacter)
  42345. {
  42346. int i = 0;
  42347. const int len = textToParse.length();
  42348. const juce_wchar* const text = textToParse;
  42349. while (i < len)
  42350. {
  42351. int start = i;
  42352. // create a whitespace atom unless it starts with non-ws
  42353. if (CharacterFunctions::isWhitespace (text[i])
  42354. && text[i] != '\r'
  42355. && text[i] != '\n')
  42356. {
  42357. while (i < len
  42358. && CharacterFunctions::isWhitespace (text[i])
  42359. && text[i] != '\r'
  42360. && text[i] != '\n')
  42361. {
  42362. ++i;
  42363. }
  42364. }
  42365. else
  42366. {
  42367. if (text[i] == '\r')
  42368. {
  42369. ++i;
  42370. if ((i < len) && (text[i] == '\n'))
  42371. {
  42372. ++start;
  42373. ++i;
  42374. }
  42375. }
  42376. else if (text[i] == '\n')
  42377. {
  42378. ++i;
  42379. }
  42380. else
  42381. {
  42382. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42383. ++i;
  42384. }
  42385. }
  42386. TextAtom* const atom = new TextAtom();
  42387. atom->atomText = String (text + start, i - start);
  42388. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42389. atom->numChars = (uint16) (i - start);
  42390. atoms.add (atom);
  42391. }
  42392. }
  42393. UniformTextSection& operator= (const UniformTextSection& other);
  42394. };
  42395. class TextEditor::Iterator
  42396. {
  42397. public:
  42398. Iterator (const Array <UniformTextSection*>& sections_,
  42399. const float wordWrapWidth_,
  42400. const juce_wchar passwordCharacter_)
  42401. : indexInText (0),
  42402. lineY (0),
  42403. lineHeight (0),
  42404. maxDescent (0),
  42405. atomX (0),
  42406. atomRight (0),
  42407. atom (0),
  42408. currentSection (0),
  42409. sections (sections_),
  42410. sectionIndex (0),
  42411. atomIndex (0),
  42412. wordWrapWidth (wordWrapWidth_),
  42413. passwordCharacter (passwordCharacter_)
  42414. {
  42415. jassert (wordWrapWidth_ > 0);
  42416. if (sections.size() > 0)
  42417. {
  42418. currentSection = sections.getUnchecked (sectionIndex);
  42419. if (currentSection != 0)
  42420. beginNewLine();
  42421. }
  42422. }
  42423. Iterator (const Iterator& other)
  42424. : indexInText (other.indexInText),
  42425. lineY (other.lineY),
  42426. lineHeight (other.lineHeight),
  42427. maxDescent (other.maxDescent),
  42428. atomX (other.atomX),
  42429. atomRight (other.atomRight),
  42430. atom (other.atom),
  42431. currentSection (other.currentSection),
  42432. sections (other.sections),
  42433. sectionIndex (other.sectionIndex),
  42434. atomIndex (other.atomIndex),
  42435. wordWrapWidth (other.wordWrapWidth),
  42436. passwordCharacter (other.passwordCharacter),
  42437. tempAtom (other.tempAtom)
  42438. {
  42439. }
  42440. ~Iterator()
  42441. {
  42442. }
  42443. bool next()
  42444. {
  42445. if (atom == &tempAtom)
  42446. {
  42447. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42448. if (numRemaining > 0)
  42449. {
  42450. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42451. atomX = 0;
  42452. if (tempAtom.numChars > 0)
  42453. lineY += lineHeight;
  42454. indexInText += tempAtom.numChars;
  42455. GlyphArrangement g;
  42456. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42457. int split;
  42458. for (split = 0; split < g.getNumGlyphs(); ++split)
  42459. if (shouldWrap (g.getGlyph (split).getRight()))
  42460. break;
  42461. if (split > 0 && split <= numRemaining)
  42462. {
  42463. tempAtom.numChars = (uint16) split;
  42464. tempAtom.width = g.getGlyph (split - 1).getRight();
  42465. atomRight = atomX + tempAtom.width;
  42466. return true;
  42467. }
  42468. }
  42469. }
  42470. bool forceNewLine = false;
  42471. if (sectionIndex >= sections.size())
  42472. {
  42473. moveToEndOfLastAtom();
  42474. return false;
  42475. }
  42476. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42477. {
  42478. if (atomIndex >= currentSection->getNumAtoms())
  42479. {
  42480. if (++sectionIndex >= sections.size())
  42481. {
  42482. moveToEndOfLastAtom();
  42483. return false;
  42484. }
  42485. atomIndex = 0;
  42486. currentSection = sections.getUnchecked (sectionIndex);
  42487. }
  42488. else
  42489. {
  42490. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42491. if (! lastAtom->isWhitespace())
  42492. {
  42493. // handle the case where the last atom in a section is actually part of the same
  42494. // word as the first atom of the next section...
  42495. float right = atomRight + lastAtom->width;
  42496. float lineHeight2 = lineHeight;
  42497. float maxDescent2 = maxDescent;
  42498. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42499. {
  42500. const UniformTextSection* const s = sections.getUnchecked (section);
  42501. if (s->getNumAtoms() == 0)
  42502. break;
  42503. const TextAtom* const nextAtom = s->getAtom (0);
  42504. if (nextAtom->isWhitespace())
  42505. break;
  42506. right += nextAtom->width;
  42507. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42508. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42509. if (shouldWrap (right))
  42510. {
  42511. lineHeight = lineHeight2;
  42512. maxDescent = maxDescent2;
  42513. forceNewLine = true;
  42514. break;
  42515. }
  42516. if (s->getNumAtoms() > 1)
  42517. break;
  42518. }
  42519. }
  42520. }
  42521. }
  42522. if (atom != 0)
  42523. {
  42524. atomX = atomRight;
  42525. indexInText += atom->numChars;
  42526. if (atom->isNewLine())
  42527. beginNewLine();
  42528. }
  42529. atom = currentSection->getAtom (atomIndex);
  42530. atomRight = atomX + atom->width;
  42531. ++atomIndex;
  42532. if (shouldWrap (atomRight) || forceNewLine)
  42533. {
  42534. if (atom->isWhitespace())
  42535. {
  42536. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42537. atomRight = jmin (atomRight, wordWrapWidth);
  42538. }
  42539. else
  42540. {
  42541. atomRight = atom->width;
  42542. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42543. {
  42544. tempAtom = *atom;
  42545. tempAtom.width = 0;
  42546. tempAtom.numChars = 0;
  42547. atom = &tempAtom;
  42548. if (atomX > 0)
  42549. beginNewLine();
  42550. return next();
  42551. }
  42552. beginNewLine();
  42553. return true;
  42554. }
  42555. }
  42556. return true;
  42557. }
  42558. void beginNewLine()
  42559. {
  42560. atomX = 0;
  42561. lineY += lineHeight;
  42562. int tempSectionIndex = sectionIndex;
  42563. int tempAtomIndex = atomIndex;
  42564. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42565. lineHeight = section->font.getHeight();
  42566. maxDescent = section->font.getDescent();
  42567. float x = (atom != 0) ? atom->width : 0;
  42568. while (! shouldWrap (x))
  42569. {
  42570. if (tempSectionIndex >= sections.size())
  42571. break;
  42572. bool checkSize = false;
  42573. if (tempAtomIndex >= section->getNumAtoms())
  42574. {
  42575. if (++tempSectionIndex >= sections.size())
  42576. break;
  42577. tempAtomIndex = 0;
  42578. section = sections.getUnchecked (tempSectionIndex);
  42579. checkSize = true;
  42580. }
  42581. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42582. if (nextAtom == 0)
  42583. break;
  42584. x += nextAtom->width;
  42585. if (shouldWrap (x) || nextAtom->isNewLine())
  42586. break;
  42587. if (checkSize)
  42588. {
  42589. lineHeight = jmax (lineHeight, section->font.getHeight());
  42590. maxDescent = jmax (maxDescent, section->font.getDescent());
  42591. }
  42592. ++tempAtomIndex;
  42593. }
  42594. }
  42595. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42596. {
  42597. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42598. {
  42599. if (lastSection != currentSection)
  42600. {
  42601. lastSection = currentSection;
  42602. g.setColour (currentSection->colour);
  42603. g.setFont (currentSection->font);
  42604. }
  42605. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42606. GlyphArrangement ga;
  42607. ga.addLineOfText (currentSection->font,
  42608. atom->getTrimmedText (passwordCharacter),
  42609. atomX,
  42610. (float) roundToInt (lineY + lineHeight - maxDescent));
  42611. ga.draw (g);
  42612. }
  42613. }
  42614. void drawSelection (Graphics& g,
  42615. const Range<int>& selection) const
  42616. {
  42617. const int startX = roundToInt (indexToX (selection.getStart()));
  42618. const int endX = roundToInt (indexToX (selection.getEnd()));
  42619. const int y = roundToInt (lineY);
  42620. const int nextY = roundToInt (lineY + lineHeight);
  42621. g.fillRect (startX, y, endX - startX, nextY - y);
  42622. }
  42623. void drawSelectedText (Graphics& g,
  42624. const Range<int>& selection,
  42625. const Colour& selectedTextColour) const
  42626. {
  42627. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42628. {
  42629. GlyphArrangement ga;
  42630. ga.addLineOfText (currentSection->font,
  42631. atom->getTrimmedText (passwordCharacter),
  42632. atomX,
  42633. (float) roundToInt (lineY + lineHeight - maxDescent));
  42634. if (selection.getEnd() < indexInText + atom->numChars)
  42635. {
  42636. GlyphArrangement ga2 (ga);
  42637. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42638. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42639. g.setColour (currentSection->colour);
  42640. ga2.draw (g);
  42641. }
  42642. if (selection.getStart() > indexInText)
  42643. {
  42644. GlyphArrangement ga2 (ga);
  42645. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42646. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42647. g.setColour (currentSection->colour);
  42648. ga2.draw (g);
  42649. }
  42650. g.setColour (selectedTextColour);
  42651. ga.draw (g);
  42652. }
  42653. }
  42654. float indexToX (const int indexToFind) const
  42655. {
  42656. if (indexToFind <= indexInText)
  42657. return atomX;
  42658. if (indexToFind >= indexInText + atom->numChars)
  42659. return atomRight;
  42660. GlyphArrangement g;
  42661. g.addLineOfText (currentSection->font,
  42662. atom->getText (passwordCharacter),
  42663. atomX, 0.0f);
  42664. if (indexToFind - indexInText >= g.getNumGlyphs())
  42665. return atomRight;
  42666. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42667. }
  42668. int xToIndex (const float xToFind) const
  42669. {
  42670. if (xToFind <= atomX || atom->isNewLine())
  42671. return indexInText;
  42672. if (xToFind >= atomRight)
  42673. return indexInText + atom->numChars;
  42674. GlyphArrangement g;
  42675. g.addLineOfText (currentSection->font,
  42676. atom->getText (passwordCharacter),
  42677. atomX, 0.0f);
  42678. int j;
  42679. for (j = 0; j < g.getNumGlyphs(); ++j)
  42680. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42681. break;
  42682. return indexInText + j;
  42683. }
  42684. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42685. {
  42686. while (next())
  42687. {
  42688. if (indexInText + atom->numChars > index)
  42689. {
  42690. cx = indexToX (index);
  42691. cy = lineY;
  42692. lineHeight_ = lineHeight;
  42693. return true;
  42694. }
  42695. }
  42696. cx = atomX;
  42697. cy = lineY;
  42698. lineHeight_ = lineHeight;
  42699. return false;
  42700. }
  42701. juce_UseDebuggingNewOperator
  42702. int indexInText;
  42703. float lineY, lineHeight, maxDescent;
  42704. float atomX, atomRight;
  42705. const TextAtom* atom;
  42706. const UniformTextSection* currentSection;
  42707. private:
  42708. const Array <UniformTextSection*>& sections;
  42709. int sectionIndex, atomIndex;
  42710. const float wordWrapWidth;
  42711. const juce_wchar passwordCharacter;
  42712. TextAtom tempAtom;
  42713. Iterator& operator= (const Iterator&);
  42714. void moveToEndOfLastAtom()
  42715. {
  42716. if (atom != 0)
  42717. {
  42718. atomX = atomRight;
  42719. if (atom->isNewLine())
  42720. {
  42721. atomX = 0.0f;
  42722. lineY += lineHeight;
  42723. }
  42724. }
  42725. }
  42726. bool shouldWrap (const float x) const
  42727. {
  42728. return (x - 0.0001f) >= wordWrapWidth;
  42729. }
  42730. };
  42731. class TextEditor::InsertAction : public UndoableAction
  42732. {
  42733. TextEditor& owner;
  42734. const String text;
  42735. const int insertIndex, oldCaretPos, newCaretPos;
  42736. const Font font;
  42737. const Colour colour;
  42738. InsertAction (const InsertAction&);
  42739. InsertAction& operator= (const InsertAction&);
  42740. public:
  42741. InsertAction (TextEditor& owner_,
  42742. const String& text_,
  42743. const int insertIndex_,
  42744. const Font& font_,
  42745. const Colour& colour_,
  42746. const int oldCaretPos_,
  42747. const int newCaretPos_)
  42748. : owner (owner_),
  42749. text (text_),
  42750. insertIndex (insertIndex_),
  42751. oldCaretPos (oldCaretPos_),
  42752. newCaretPos (newCaretPos_),
  42753. font (font_),
  42754. colour (colour_)
  42755. {
  42756. }
  42757. ~InsertAction()
  42758. {
  42759. }
  42760. bool perform()
  42761. {
  42762. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42763. return true;
  42764. }
  42765. bool undo()
  42766. {
  42767. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42768. return true;
  42769. }
  42770. int getSizeInUnits()
  42771. {
  42772. return text.length() + 16;
  42773. }
  42774. };
  42775. class TextEditor::RemoveAction : public UndoableAction
  42776. {
  42777. TextEditor& owner;
  42778. const Range<int> range;
  42779. const int oldCaretPos, newCaretPos;
  42780. Array <UniformTextSection*> removedSections;
  42781. RemoveAction (const RemoveAction&);
  42782. RemoveAction& operator= (const RemoveAction&);
  42783. public:
  42784. RemoveAction (TextEditor& owner_,
  42785. const Range<int> range_,
  42786. const int oldCaretPos_,
  42787. const int newCaretPos_,
  42788. const Array <UniformTextSection*>& removedSections_)
  42789. : owner (owner_),
  42790. range (range_),
  42791. oldCaretPos (oldCaretPos_),
  42792. newCaretPos (newCaretPos_),
  42793. removedSections (removedSections_)
  42794. {
  42795. }
  42796. ~RemoveAction()
  42797. {
  42798. for (int i = removedSections.size(); --i >= 0;)
  42799. {
  42800. UniformTextSection* const section = removedSections.getUnchecked (i);
  42801. section->clear();
  42802. delete section;
  42803. }
  42804. }
  42805. bool perform()
  42806. {
  42807. owner.remove (range, 0, newCaretPos);
  42808. return true;
  42809. }
  42810. bool undo()
  42811. {
  42812. owner.reinsert (range.getStart(), removedSections);
  42813. owner.moveCursorTo (oldCaretPos, false);
  42814. return true;
  42815. }
  42816. int getSizeInUnits()
  42817. {
  42818. int n = 0;
  42819. for (int i = removedSections.size(); --i >= 0;)
  42820. n += removedSections.getUnchecked (i)->getTotalLength();
  42821. return n + 16;
  42822. }
  42823. };
  42824. class TextEditor::TextHolderComponent : public Component,
  42825. public Timer,
  42826. public Value::Listener
  42827. {
  42828. public:
  42829. TextHolderComponent (TextEditor& owner_)
  42830. : owner (owner_)
  42831. {
  42832. setWantsKeyboardFocus (false);
  42833. setInterceptsMouseClicks (false, true);
  42834. owner.getTextValue().addListener (this);
  42835. }
  42836. ~TextHolderComponent()
  42837. {
  42838. owner.getTextValue().removeListener (this);
  42839. }
  42840. void paint (Graphics& g)
  42841. {
  42842. owner.drawContent (g);
  42843. }
  42844. void timerCallback()
  42845. {
  42846. owner.timerCallbackInt();
  42847. }
  42848. const MouseCursor getMouseCursor()
  42849. {
  42850. return owner.getMouseCursor();
  42851. }
  42852. void valueChanged (Value&)
  42853. {
  42854. owner.textWasChangedByValue();
  42855. }
  42856. private:
  42857. TextEditor& owner;
  42858. TextHolderComponent (const TextHolderComponent&);
  42859. TextHolderComponent& operator= (const TextHolderComponent&);
  42860. };
  42861. class TextEditorViewport : public Viewport
  42862. {
  42863. public:
  42864. TextEditorViewport (TextEditor* const owner_)
  42865. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42866. {
  42867. }
  42868. ~TextEditorViewport()
  42869. {
  42870. }
  42871. void visibleAreaChanged (int, int, int, int)
  42872. {
  42873. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42874. // appear and disappear, causing the wrap width to change.
  42875. {
  42876. const float wordWrapWidth = owner->getWordWrapWidth();
  42877. if (wordWrapWidth != lastWordWrapWidth)
  42878. {
  42879. lastWordWrapWidth = wordWrapWidth;
  42880. rentrant = true;
  42881. owner->updateTextHolderSize();
  42882. rentrant = false;
  42883. }
  42884. }
  42885. }
  42886. private:
  42887. TextEditor* const owner;
  42888. float lastWordWrapWidth;
  42889. bool rentrant;
  42890. TextEditorViewport (const TextEditorViewport&);
  42891. TextEditorViewport& operator= (const TextEditorViewport&);
  42892. };
  42893. namespace TextEditorDefs
  42894. {
  42895. const int flashSpeedIntervalMs = 380;
  42896. const int textChangeMessageId = 0x10003001;
  42897. const int returnKeyMessageId = 0x10003002;
  42898. const int escapeKeyMessageId = 0x10003003;
  42899. const int focusLossMessageId = 0x10003004;
  42900. const int maxActionsPerTransaction = 100;
  42901. static int getCharacterCategory (const juce_wchar character)
  42902. {
  42903. return CharacterFunctions::isLetterOrDigit (character)
  42904. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42905. }
  42906. }
  42907. TextEditor::TextEditor (const String& name,
  42908. const juce_wchar passwordCharacter_)
  42909. : Component (name),
  42910. borderSize (1, 1, 1, 3),
  42911. readOnly (false),
  42912. multiline (false),
  42913. wordWrap (false),
  42914. returnKeyStartsNewLine (false),
  42915. caretVisible (true),
  42916. popupMenuEnabled (true),
  42917. selectAllTextWhenFocused (false),
  42918. scrollbarVisible (true),
  42919. wasFocused (false),
  42920. caretFlashState (true),
  42921. keepCursorOnScreen (true),
  42922. tabKeyUsed (false),
  42923. menuActive (false),
  42924. valueTextNeedsUpdating (false),
  42925. cursorX (0),
  42926. cursorY (0),
  42927. cursorHeight (0),
  42928. maxTextLength (0),
  42929. leftIndent (4),
  42930. topIndent (4),
  42931. lastTransactionTime (0),
  42932. currentFont (14.0f),
  42933. totalNumChars (0),
  42934. caretPosition (0),
  42935. passwordCharacter (passwordCharacter_),
  42936. dragType (notDragging)
  42937. {
  42938. setOpaque (true);
  42939. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42940. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42941. viewport->setWantsKeyboardFocus (false);
  42942. viewport->setScrollBarsShown (false, false);
  42943. setMouseCursor (MouseCursor::IBeamCursor);
  42944. setWantsKeyboardFocus (true);
  42945. }
  42946. TextEditor::~TextEditor()
  42947. {
  42948. textValue.referTo (Value());
  42949. clearInternal (0);
  42950. viewport = 0;
  42951. textHolder = 0;
  42952. }
  42953. void TextEditor::newTransaction()
  42954. {
  42955. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42956. undoManager.beginNewTransaction();
  42957. }
  42958. void TextEditor::doUndoRedo (const bool isRedo)
  42959. {
  42960. if (! isReadOnly())
  42961. {
  42962. if (isRedo ? undoManager.redo()
  42963. : undoManager.undo())
  42964. {
  42965. scrollToMakeSureCursorIsVisible();
  42966. repaint();
  42967. textChanged();
  42968. }
  42969. }
  42970. }
  42971. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42972. const bool shouldWordWrap)
  42973. {
  42974. if (multiline != shouldBeMultiLine
  42975. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42976. {
  42977. multiline = shouldBeMultiLine;
  42978. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42979. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42980. scrollbarVisible && multiline);
  42981. viewport->setViewPosition (0, 0);
  42982. resized();
  42983. scrollToMakeSureCursorIsVisible();
  42984. }
  42985. }
  42986. bool TextEditor::isMultiLine() const
  42987. {
  42988. return multiline;
  42989. }
  42990. void TextEditor::setScrollbarsShown (bool shown)
  42991. {
  42992. if (scrollbarVisible != shown)
  42993. {
  42994. scrollbarVisible = shown;
  42995. shown = shown && isMultiLine();
  42996. viewport->setScrollBarsShown (shown, shown);
  42997. }
  42998. }
  42999. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43000. {
  43001. if (readOnly != shouldBeReadOnly)
  43002. {
  43003. readOnly = shouldBeReadOnly;
  43004. enablementChanged();
  43005. }
  43006. }
  43007. bool TextEditor::isReadOnly() const
  43008. {
  43009. return readOnly || ! isEnabled();
  43010. }
  43011. bool TextEditor::isTextInputActive() const
  43012. {
  43013. return ! isReadOnly();
  43014. }
  43015. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43016. {
  43017. returnKeyStartsNewLine = shouldStartNewLine;
  43018. }
  43019. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43020. {
  43021. tabKeyUsed = shouldTabKeyBeUsed;
  43022. }
  43023. void TextEditor::setPopupMenuEnabled (const bool b)
  43024. {
  43025. popupMenuEnabled = b;
  43026. }
  43027. void TextEditor::setSelectAllWhenFocused (const bool b)
  43028. {
  43029. selectAllTextWhenFocused = b;
  43030. }
  43031. const Font TextEditor::getFont() const
  43032. {
  43033. return currentFont;
  43034. }
  43035. void TextEditor::setFont (const Font& newFont)
  43036. {
  43037. currentFont = newFont;
  43038. scrollToMakeSureCursorIsVisible();
  43039. }
  43040. void TextEditor::applyFontToAllText (const Font& newFont)
  43041. {
  43042. currentFont = newFont;
  43043. const Colour overallColour (findColour (textColourId));
  43044. for (int i = sections.size(); --i >= 0;)
  43045. {
  43046. UniformTextSection* const uts = sections.getUnchecked (i);
  43047. uts->setFont (newFont, passwordCharacter);
  43048. uts->colour = overallColour;
  43049. }
  43050. coalesceSimilarSections();
  43051. updateTextHolderSize();
  43052. scrollToMakeSureCursorIsVisible();
  43053. repaint();
  43054. }
  43055. void TextEditor::colourChanged()
  43056. {
  43057. setOpaque (findColour (backgroundColourId).isOpaque());
  43058. repaint();
  43059. }
  43060. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43061. {
  43062. caretVisible = shouldCaretBeVisible;
  43063. if (shouldCaretBeVisible)
  43064. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43065. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43066. : MouseCursor::NormalCursor);
  43067. }
  43068. void TextEditor::setInputRestrictions (const int maxLen,
  43069. const String& chars)
  43070. {
  43071. maxTextLength = jmax (0, maxLen);
  43072. allowedCharacters = chars;
  43073. }
  43074. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43075. {
  43076. textToShowWhenEmpty = text;
  43077. colourForTextWhenEmpty = colourToUse;
  43078. }
  43079. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43080. {
  43081. if (passwordCharacter != newPasswordCharacter)
  43082. {
  43083. passwordCharacter = newPasswordCharacter;
  43084. resized();
  43085. repaint();
  43086. }
  43087. }
  43088. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43089. {
  43090. viewport->setScrollBarThickness (newThicknessPixels);
  43091. }
  43092. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43093. {
  43094. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43095. }
  43096. void TextEditor::clear()
  43097. {
  43098. clearInternal (0);
  43099. updateTextHolderSize();
  43100. undoManager.clearUndoHistory();
  43101. }
  43102. void TextEditor::setText (const String& newText,
  43103. const bool sendTextChangeMessage)
  43104. {
  43105. const int newLength = newText.length();
  43106. if (newLength != getTotalNumChars() || getText() != newText)
  43107. {
  43108. const int oldCursorPos = caretPosition;
  43109. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43110. clearInternal (0);
  43111. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43112. // if you're adding text with line-feeds to a single-line text editor, it
  43113. // ain't gonna look right!
  43114. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43115. if (cursorWasAtEnd && ! isMultiLine())
  43116. moveCursorTo (getTotalNumChars(), false);
  43117. else
  43118. moveCursorTo (oldCursorPos, false);
  43119. if (sendTextChangeMessage)
  43120. textChanged();
  43121. updateTextHolderSize();
  43122. scrollToMakeSureCursorIsVisible();
  43123. undoManager.clearUndoHistory();
  43124. repaint();
  43125. }
  43126. }
  43127. Value& TextEditor::getTextValue()
  43128. {
  43129. if (valueTextNeedsUpdating)
  43130. {
  43131. valueTextNeedsUpdating = false;
  43132. textValue = getText();
  43133. }
  43134. return textValue;
  43135. }
  43136. void TextEditor::textWasChangedByValue()
  43137. {
  43138. if (textValue.getValueSource().getReferenceCount() > 1)
  43139. setText (textValue.getValue());
  43140. }
  43141. void TextEditor::textChanged()
  43142. {
  43143. updateTextHolderSize();
  43144. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43145. if (textValue.getValueSource().getReferenceCount() > 1)
  43146. {
  43147. valueTextNeedsUpdating = false;
  43148. textValue = getText();
  43149. }
  43150. }
  43151. void TextEditor::returnPressed()
  43152. {
  43153. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43154. }
  43155. void TextEditor::escapePressed()
  43156. {
  43157. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43158. }
  43159. void TextEditor::addListener (Listener* const newListener)
  43160. {
  43161. listeners.add (newListener);
  43162. }
  43163. void TextEditor::removeListener (Listener* const listenerToRemove)
  43164. {
  43165. listeners.remove (listenerToRemove);
  43166. }
  43167. void TextEditor::timerCallbackInt()
  43168. {
  43169. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43170. if (caretFlashState != newState)
  43171. {
  43172. caretFlashState = newState;
  43173. if (caretFlashState)
  43174. wasFocused = true;
  43175. if (caretVisible
  43176. && hasKeyboardFocus (false)
  43177. && ! isReadOnly())
  43178. {
  43179. repaintCaret();
  43180. }
  43181. }
  43182. const unsigned int now = Time::getApproximateMillisecondCounter();
  43183. if (now > lastTransactionTime + 200)
  43184. newTransaction();
  43185. }
  43186. void TextEditor::repaintCaret()
  43187. {
  43188. if (! findColour (caretColourId).isTransparent())
  43189. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43190. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43191. 4,
  43192. roundToInt (cursorHeight) + 2);
  43193. }
  43194. void TextEditor::repaintText (const Range<int>& range)
  43195. {
  43196. if (! range.isEmpty())
  43197. {
  43198. float x = 0, y = 0, lh = currentFont.getHeight();
  43199. const float wordWrapWidth = getWordWrapWidth();
  43200. if (wordWrapWidth > 0)
  43201. {
  43202. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43203. i.getCharPosition (range.getStart(), x, y, lh);
  43204. const int y1 = (int) y;
  43205. int y2;
  43206. if (range.getEnd() >= getTotalNumChars())
  43207. {
  43208. y2 = textHolder->getHeight();
  43209. }
  43210. else
  43211. {
  43212. i.getCharPosition (range.getEnd(), x, y, lh);
  43213. y2 = (int) (y + lh * 2.0f);
  43214. }
  43215. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43216. }
  43217. }
  43218. }
  43219. void TextEditor::moveCaret (int newCaretPos)
  43220. {
  43221. if (newCaretPos < 0)
  43222. newCaretPos = 0;
  43223. else if (newCaretPos > getTotalNumChars())
  43224. newCaretPos = getTotalNumChars();
  43225. if (newCaretPos != getCaretPosition())
  43226. {
  43227. repaintCaret();
  43228. caretFlashState = true;
  43229. caretPosition = newCaretPos;
  43230. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43231. scrollToMakeSureCursorIsVisible();
  43232. repaintCaret();
  43233. }
  43234. }
  43235. void TextEditor::setCaretPosition (const int newIndex)
  43236. {
  43237. moveCursorTo (newIndex, false);
  43238. }
  43239. int TextEditor::getCaretPosition() const
  43240. {
  43241. return caretPosition;
  43242. }
  43243. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43244. const int desiredCaretY)
  43245. {
  43246. updateCaretPosition();
  43247. int vx = roundToInt (cursorX) - desiredCaretX;
  43248. int vy = roundToInt (cursorY) - desiredCaretY;
  43249. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43250. {
  43251. vx += desiredCaretX - proportionOfWidth (0.2f);
  43252. }
  43253. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43254. {
  43255. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43256. }
  43257. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43258. if (! isMultiLine())
  43259. {
  43260. vy = viewport->getViewPositionY();
  43261. }
  43262. else
  43263. {
  43264. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43265. const int curH = roundToInt (cursorHeight);
  43266. if (desiredCaretY < 0)
  43267. {
  43268. vy = jmax (0, desiredCaretY + vy);
  43269. }
  43270. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43271. {
  43272. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43273. }
  43274. }
  43275. viewport->setViewPosition (vx, vy);
  43276. }
  43277. const Rectangle<int> TextEditor::getCaretRectangle()
  43278. {
  43279. updateCaretPosition();
  43280. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43281. roundToInt (cursorY) - viewport->getY(),
  43282. 1, roundToInt (cursorHeight));
  43283. }
  43284. float TextEditor::getWordWrapWidth() const
  43285. {
  43286. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43287. : 1.0e10f;
  43288. }
  43289. void TextEditor::updateTextHolderSize()
  43290. {
  43291. const float wordWrapWidth = getWordWrapWidth();
  43292. if (wordWrapWidth > 0)
  43293. {
  43294. float maxWidth = 0.0f;
  43295. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43296. while (i.next())
  43297. maxWidth = jmax (maxWidth, i.atomRight);
  43298. const int w = leftIndent + roundToInt (maxWidth);
  43299. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43300. currentFont.getHeight()));
  43301. textHolder->setSize (w + 1, h + 1);
  43302. }
  43303. }
  43304. int TextEditor::getTextWidth() const
  43305. {
  43306. return textHolder->getWidth();
  43307. }
  43308. int TextEditor::getTextHeight() const
  43309. {
  43310. return textHolder->getHeight();
  43311. }
  43312. void TextEditor::setIndents (const int newLeftIndent,
  43313. const int newTopIndent)
  43314. {
  43315. leftIndent = newLeftIndent;
  43316. topIndent = newTopIndent;
  43317. }
  43318. void TextEditor::setBorder (const BorderSize& border)
  43319. {
  43320. borderSize = border;
  43321. resized();
  43322. }
  43323. const BorderSize TextEditor::getBorder() const
  43324. {
  43325. return borderSize;
  43326. }
  43327. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43328. {
  43329. keepCursorOnScreen = shouldScrollToShowCursor;
  43330. }
  43331. void TextEditor::updateCaretPosition()
  43332. {
  43333. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43334. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43335. }
  43336. void TextEditor::scrollToMakeSureCursorIsVisible()
  43337. {
  43338. updateCaretPosition();
  43339. if (keepCursorOnScreen)
  43340. {
  43341. int x = viewport->getViewPositionX();
  43342. int y = viewport->getViewPositionY();
  43343. const int relativeCursorX = roundToInt (cursorX) - x;
  43344. const int relativeCursorY = roundToInt (cursorY) - y;
  43345. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43346. {
  43347. x += relativeCursorX - proportionOfWidth (0.2f);
  43348. }
  43349. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43350. {
  43351. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43352. }
  43353. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43354. if (! isMultiLine())
  43355. {
  43356. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43357. }
  43358. else
  43359. {
  43360. const int curH = roundToInt (cursorHeight);
  43361. if (relativeCursorY < 0)
  43362. {
  43363. y = jmax (0, relativeCursorY + y);
  43364. }
  43365. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43366. {
  43367. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43368. }
  43369. }
  43370. viewport->setViewPosition (x, y);
  43371. }
  43372. }
  43373. void TextEditor::moveCursorTo (const int newPosition,
  43374. const bool isSelecting)
  43375. {
  43376. if (isSelecting)
  43377. {
  43378. moveCaret (newPosition);
  43379. const Range<int> oldSelection (selection);
  43380. if (dragType == notDragging)
  43381. {
  43382. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43383. dragType = draggingSelectionStart;
  43384. else
  43385. dragType = draggingSelectionEnd;
  43386. }
  43387. if (dragType == draggingSelectionStart)
  43388. {
  43389. if (getCaretPosition() >= selection.getEnd())
  43390. dragType = draggingSelectionEnd;
  43391. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43392. }
  43393. else
  43394. {
  43395. if (getCaretPosition() < selection.getStart())
  43396. dragType = draggingSelectionStart;
  43397. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43398. }
  43399. repaintText (selection.getUnionWith (oldSelection));
  43400. }
  43401. else
  43402. {
  43403. dragType = notDragging;
  43404. repaintText (selection);
  43405. moveCaret (newPosition);
  43406. selection = Range<int>::emptyRange (getCaretPosition());
  43407. }
  43408. }
  43409. int TextEditor::getTextIndexAt (const int x,
  43410. const int y)
  43411. {
  43412. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43413. (float) (y + viewport->getViewPositionY() - topIndent));
  43414. }
  43415. void TextEditor::insertTextAtCaret (const String& newText_)
  43416. {
  43417. String newText (newText_);
  43418. if (allowedCharacters.isNotEmpty())
  43419. newText = newText.retainCharacters (allowedCharacters);
  43420. if ((! returnKeyStartsNewLine) && newText == "\n")
  43421. {
  43422. returnPressed();
  43423. return;
  43424. }
  43425. if (! isMultiLine())
  43426. newText = newText.replaceCharacters ("\r\n", " ");
  43427. else
  43428. newText = newText.replace ("\r\n", "\n");
  43429. const int newCaretPos = selection.getStart() + newText.length();
  43430. const int insertIndex = selection.getStart();
  43431. remove (selection, getUndoManager(),
  43432. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43433. if (maxTextLength > 0)
  43434. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43435. if (newText.isNotEmpty())
  43436. insert (newText,
  43437. insertIndex,
  43438. currentFont,
  43439. findColour (textColourId),
  43440. getUndoManager(),
  43441. newCaretPos);
  43442. textChanged();
  43443. }
  43444. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43445. {
  43446. moveCursorTo (newSelection.getStart(), false);
  43447. moveCursorTo (newSelection.getEnd(), true);
  43448. }
  43449. void TextEditor::copy()
  43450. {
  43451. if (passwordCharacter == 0)
  43452. {
  43453. const String selectedText (getHighlightedText());
  43454. if (selectedText.isNotEmpty())
  43455. SystemClipboard::copyTextToClipboard (selectedText);
  43456. }
  43457. }
  43458. void TextEditor::paste()
  43459. {
  43460. if (! isReadOnly())
  43461. {
  43462. const String clip (SystemClipboard::getTextFromClipboard());
  43463. if (clip.isNotEmpty())
  43464. insertTextAtCaret (clip);
  43465. }
  43466. }
  43467. void TextEditor::cut()
  43468. {
  43469. if (! isReadOnly())
  43470. {
  43471. moveCaret (selection.getEnd());
  43472. insertTextAtCaret (String::empty);
  43473. }
  43474. }
  43475. void TextEditor::drawContent (Graphics& g)
  43476. {
  43477. const float wordWrapWidth = getWordWrapWidth();
  43478. if (wordWrapWidth > 0)
  43479. {
  43480. g.setOrigin (leftIndent, topIndent);
  43481. const Rectangle<int> clip (g.getClipBounds());
  43482. Colour selectedTextColour;
  43483. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43484. while (i.lineY + 200.0 < clip.getY() && i.next())
  43485. {}
  43486. if (! selection.isEmpty())
  43487. {
  43488. g.setColour (findColour (highlightColourId)
  43489. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43490. selectedTextColour = findColour (highlightedTextColourId);
  43491. Iterator i2 (i);
  43492. while (i2.next() && i2.lineY < clip.getBottom())
  43493. {
  43494. if (i2.lineY + i2.lineHeight >= clip.getY()
  43495. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43496. {
  43497. i2.drawSelection (g, selection);
  43498. }
  43499. }
  43500. }
  43501. const UniformTextSection* lastSection = 0;
  43502. while (i.next() && i.lineY < clip.getBottom())
  43503. {
  43504. if (i.lineY + i.lineHeight >= clip.getY())
  43505. {
  43506. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43507. {
  43508. i.drawSelectedText (g, selection, selectedTextColour);
  43509. lastSection = 0;
  43510. }
  43511. else
  43512. {
  43513. i.draw (g, lastSection);
  43514. }
  43515. }
  43516. }
  43517. }
  43518. }
  43519. void TextEditor::paint (Graphics& g)
  43520. {
  43521. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43522. }
  43523. void TextEditor::paintOverChildren (Graphics& g)
  43524. {
  43525. if (caretFlashState
  43526. && hasKeyboardFocus (false)
  43527. && caretVisible
  43528. && ! isReadOnly())
  43529. {
  43530. g.setColour (findColour (caretColourId));
  43531. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43532. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43533. 2.0f, cursorHeight);
  43534. }
  43535. if (textToShowWhenEmpty.isNotEmpty()
  43536. && (! hasKeyboardFocus (false))
  43537. && getTotalNumChars() == 0)
  43538. {
  43539. g.setColour (colourForTextWhenEmpty);
  43540. g.setFont (getFont());
  43541. if (isMultiLine())
  43542. {
  43543. g.drawText (textToShowWhenEmpty,
  43544. 0, 0, getWidth(), getHeight(),
  43545. Justification::centred, true);
  43546. }
  43547. else
  43548. {
  43549. g.drawText (textToShowWhenEmpty,
  43550. leftIndent, topIndent,
  43551. viewport->getWidth() - leftIndent,
  43552. viewport->getHeight() - topIndent,
  43553. Justification::centredLeft, true);
  43554. }
  43555. }
  43556. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43557. }
  43558. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43559. {
  43560. public:
  43561. TextEditorMenuPerformer (TextEditor* const editor_)
  43562. : editor (editor_)
  43563. {
  43564. }
  43565. void modalStateFinished (int returnValue)
  43566. {
  43567. if (editor != 0 && returnValue != 0)
  43568. editor->performPopupMenuAction (returnValue);
  43569. }
  43570. private:
  43571. Component::SafePointer<TextEditor> editor;
  43572. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43573. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43574. };
  43575. void TextEditor::mouseDown (const MouseEvent& e)
  43576. {
  43577. beginDragAutoRepeat (100);
  43578. newTransaction();
  43579. if (wasFocused || ! selectAllTextWhenFocused)
  43580. {
  43581. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43582. {
  43583. moveCursorTo (getTextIndexAt (e.x, e.y),
  43584. e.mods.isShiftDown());
  43585. }
  43586. else
  43587. {
  43588. PopupMenu m;
  43589. m.setLookAndFeel (&getLookAndFeel());
  43590. addPopupMenuItems (m, &e);
  43591. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43592. }
  43593. }
  43594. }
  43595. void TextEditor::mouseDrag (const MouseEvent& e)
  43596. {
  43597. if (wasFocused || ! selectAllTextWhenFocused)
  43598. {
  43599. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43600. {
  43601. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43602. }
  43603. }
  43604. }
  43605. void TextEditor::mouseUp (const MouseEvent& e)
  43606. {
  43607. newTransaction();
  43608. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43609. if (wasFocused || ! selectAllTextWhenFocused)
  43610. {
  43611. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43612. {
  43613. moveCaret (getTextIndexAt (e.x, e.y));
  43614. }
  43615. }
  43616. wasFocused = true;
  43617. }
  43618. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43619. {
  43620. int tokenEnd = getTextIndexAt (e.x, e.y);
  43621. int tokenStart = tokenEnd;
  43622. if (e.getNumberOfClicks() > 3)
  43623. {
  43624. tokenStart = 0;
  43625. tokenEnd = getTotalNumChars();
  43626. }
  43627. else
  43628. {
  43629. const String t (getText());
  43630. const int totalLength = getTotalNumChars();
  43631. while (tokenEnd < totalLength)
  43632. {
  43633. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43634. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43635. ++tokenEnd;
  43636. else
  43637. break;
  43638. }
  43639. tokenStart = tokenEnd;
  43640. while (tokenStart > 0)
  43641. {
  43642. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43643. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43644. --tokenStart;
  43645. else
  43646. break;
  43647. }
  43648. if (e.getNumberOfClicks() > 2)
  43649. {
  43650. while (tokenEnd < totalLength)
  43651. {
  43652. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43653. ++tokenEnd;
  43654. else
  43655. break;
  43656. }
  43657. while (tokenStart > 0)
  43658. {
  43659. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43660. --tokenStart;
  43661. else
  43662. break;
  43663. }
  43664. }
  43665. }
  43666. moveCursorTo (tokenEnd, false);
  43667. moveCursorTo (tokenStart, true);
  43668. }
  43669. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43670. {
  43671. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43672. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43673. }
  43674. bool TextEditor::keyPressed (const KeyPress& key)
  43675. {
  43676. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43677. return false;
  43678. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43679. if (key.isKeyCode (KeyPress::leftKey)
  43680. || key.isKeyCode (KeyPress::upKey))
  43681. {
  43682. newTransaction();
  43683. int newPos;
  43684. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43685. newPos = indexAtPosition (cursorX, cursorY - 1);
  43686. else if (moveInWholeWordSteps)
  43687. newPos = findWordBreakBefore (getCaretPosition());
  43688. else
  43689. newPos = getCaretPosition() - 1;
  43690. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43691. }
  43692. else if (key.isKeyCode (KeyPress::rightKey)
  43693. || key.isKeyCode (KeyPress::downKey))
  43694. {
  43695. newTransaction();
  43696. int newPos;
  43697. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43698. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43699. else if (moveInWholeWordSteps)
  43700. newPos = findWordBreakAfter (getCaretPosition());
  43701. else
  43702. newPos = getCaretPosition() + 1;
  43703. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43704. }
  43705. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43706. {
  43707. newTransaction();
  43708. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43709. key.getModifiers().isShiftDown());
  43710. }
  43711. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43712. {
  43713. newTransaction();
  43714. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43715. key.getModifiers().isShiftDown());
  43716. }
  43717. else if (key.isKeyCode (KeyPress::homeKey))
  43718. {
  43719. newTransaction();
  43720. if (isMultiLine() && ! moveInWholeWordSteps)
  43721. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43722. key.getModifiers().isShiftDown());
  43723. else
  43724. moveCursorTo (0, key.getModifiers().isShiftDown());
  43725. }
  43726. else if (key.isKeyCode (KeyPress::endKey))
  43727. {
  43728. newTransaction();
  43729. if (isMultiLine() && ! moveInWholeWordSteps)
  43730. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43731. key.getModifiers().isShiftDown());
  43732. else
  43733. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43734. }
  43735. else if (key.isKeyCode (KeyPress::backspaceKey))
  43736. {
  43737. if (moveInWholeWordSteps)
  43738. {
  43739. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43740. }
  43741. else
  43742. {
  43743. if (selection.isEmpty() && selection.getStart() > 0)
  43744. selection.setStart (selection.getEnd() - 1);
  43745. }
  43746. cut();
  43747. }
  43748. else if (key.isKeyCode (KeyPress::deleteKey))
  43749. {
  43750. if (key.getModifiers().isShiftDown())
  43751. copy();
  43752. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43753. selection.setEnd (selection.getStart() + 1);
  43754. cut();
  43755. }
  43756. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43757. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43758. {
  43759. newTransaction();
  43760. copy();
  43761. }
  43762. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43763. {
  43764. newTransaction();
  43765. copy();
  43766. cut();
  43767. }
  43768. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43769. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43770. {
  43771. newTransaction();
  43772. paste();
  43773. }
  43774. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43775. {
  43776. newTransaction();
  43777. doUndoRedo (false);
  43778. }
  43779. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43780. {
  43781. newTransaction();
  43782. doUndoRedo (true);
  43783. }
  43784. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43785. {
  43786. newTransaction();
  43787. moveCursorTo (getTotalNumChars(), false);
  43788. moveCursorTo (0, true);
  43789. }
  43790. else if (key == KeyPress::returnKey)
  43791. {
  43792. newTransaction();
  43793. insertTextAtCaret ("\n");
  43794. }
  43795. else if (key.isKeyCode (KeyPress::escapeKey))
  43796. {
  43797. newTransaction();
  43798. moveCursorTo (getCaretPosition(), false);
  43799. escapePressed();
  43800. }
  43801. else if (key.getTextCharacter() >= ' '
  43802. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43803. {
  43804. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43805. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43806. }
  43807. else
  43808. {
  43809. return false;
  43810. }
  43811. return true;
  43812. }
  43813. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43814. {
  43815. if (! isKeyDown)
  43816. return false;
  43817. #if JUCE_WINDOWS
  43818. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43819. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43820. #endif
  43821. // (overridden to avoid forwarding key events to the parent)
  43822. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43823. }
  43824. const int baseMenuItemID = 0x7fff0000;
  43825. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43826. {
  43827. const bool writable = ! isReadOnly();
  43828. if (passwordCharacter == 0)
  43829. {
  43830. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43831. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43832. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43833. }
  43834. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43835. m.addSeparator();
  43836. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43837. m.addSeparator();
  43838. if (getUndoManager() != 0)
  43839. {
  43840. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43841. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43842. }
  43843. }
  43844. void TextEditor::performPopupMenuAction (const int menuItemID)
  43845. {
  43846. switch (menuItemID)
  43847. {
  43848. case baseMenuItemID + 1:
  43849. copy();
  43850. cut();
  43851. break;
  43852. case baseMenuItemID + 2:
  43853. copy();
  43854. break;
  43855. case baseMenuItemID + 3:
  43856. paste();
  43857. break;
  43858. case baseMenuItemID + 4:
  43859. cut();
  43860. break;
  43861. case baseMenuItemID + 5:
  43862. moveCursorTo (getTotalNumChars(), false);
  43863. moveCursorTo (0, true);
  43864. break;
  43865. case baseMenuItemID + 6:
  43866. doUndoRedo (false);
  43867. break;
  43868. case baseMenuItemID + 7:
  43869. doUndoRedo (true);
  43870. break;
  43871. default:
  43872. break;
  43873. }
  43874. }
  43875. void TextEditor::focusGained (FocusChangeType)
  43876. {
  43877. newTransaction();
  43878. caretFlashState = true;
  43879. if (selectAllTextWhenFocused)
  43880. {
  43881. moveCursorTo (0, false);
  43882. moveCursorTo (getTotalNumChars(), true);
  43883. }
  43884. repaint();
  43885. if (caretVisible)
  43886. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43887. ComponentPeer* const peer = getPeer();
  43888. if (peer != 0 && ! isReadOnly())
  43889. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43890. }
  43891. void TextEditor::focusLost (FocusChangeType)
  43892. {
  43893. newTransaction();
  43894. wasFocused = false;
  43895. textHolder->stopTimer();
  43896. caretFlashState = false;
  43897. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43898. repaint();
  43899. }
  43900. void TextEditor::resized()
  43901. {
  43902. viewport->setBoundsInset (borderSize);
  43903. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43904. updateTextHolderSize();
  43905. if (! isMultiLine())
  43906. {
  43907. scrollToMakeSureCursorIsVisible();
  43908. }
  43909. else
  43910. {
  43911. updateCaretPosition();
  43912. }
  43913. }
  43914. void TextEditor::handleCommandMessage (const int commandId)
  43915. {
  43916. Component::BailOutChecker checker (this);
  43917. switch (commandId)
  43918. {
  43919. case TextEditorDefs::textChangeMessageId:
  43920. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43921. break;
  43922. case TextEditorDefs::returnKeyMessageId:
  43923. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43924. break;
  43925. case TextEditorDefs::escapeKeyMessageId:
  43926. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43927. break;
  43928. case TextEditorDefs::focusLossMessageId:
  43929. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43930. break;
  43931. default:
  43932. jassertfalse;
  43933. break;
  43934. }
  43935. }
  43936. void TextEditor::enablementChanged()
  43937. {
  43938. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43939. : MouseCursor::IBeamCursor);
  43940. repaint();
  43941. }
  43942. UndoManager* TextEditor::getUndoManager() throw()
  43943. {
  43944. return isReadOnly() ? 0 : &undoManager;
  43945. }
  43946. void TextEditor::clearInternal (UndoManager* const um)
  43947. {
  43948. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43949. }
  43950. void TextEditor::insert (const String& text,
  43951. const int insertIndex,
  43952. const Font& font,
  43953. const Colour& colour,
  43954. UndoManager* const um,
  43955. const int caretPositionToMoveTo)
  43956. {
  43957. if (text.isNotEmpty())
  43958. {
  43959. if (um != 0)
  43960. {
  43961. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43962. newTransaction();
  43963. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43964. caretPosition, caretPositionToMoveTo));
  43965. }
  43966. else
  43967. {
  43968. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43969. // a line gets moved due to word wrap
  43970. int index = 0;
  43971. int nextIndex = 0;
  43972. for (int i = 0; i < sections.size(); ++i)
  43973. {
  43974. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43975. if (insertIndex == index)
  43976. {
  43977. sections.insert (i, new UniformTextSection (text,
  43978. font, colour,
  43979. passwordCharacter));
  43980. break;
  43981. }
  43982. else if (insertIndex > index && insertIndex < nextIndex)
  43983. {
  43984. splitSection (i, insertIndex - index);
  43985. sections.insert (i + 1, new UniformTextSection (text,
  43986. font, colour,
  43987. passwordCharacter));
  43988. break;
  43989. }
  43990. index = nextIndex;
  43991. }
  43992. if (nextIndex == insertIndex)
  43993. sections.add (new UniformTextSection (text,
  43994. font, colour,
  43995. passwordCharacter));
  43996. coalesceSimilarSections();
  43997. totalNumChars = -1;
  43998. valueTextNeedsUpdating = true;
  43999. moveCursorTo (caretPositionToMoveTo, false);
  44000. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44001. }
  44002. }
  44003. }
  44004. void TextEditor::reinsert (const int insertIndex,
  44005. const Array <UniformTextSection*>& sectionsToInsert)
  44006. {
  44007. int index = 0;
  44008. int nextIndex = 0;
  44009. for (int i = 0; i < sections.size(); ++i)
  44010. {
  44011. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44012. if (insertIndex == index)
  44013. {
  44014. for (int j = sectionsToInsert.size(); --j >= 0;)
  44015. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44016. break;
  44017. }
  44018. else if (insertIndex > index && insertIndex < nextIndex)
  44019. {
  44020. splitSection (i, insertIndex - index);
  44021. for (int j = sectionsToInsert.size(); --j >= 0;)
  44022. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44023. break;
  44024. }
  44025. index = nextIndex;
  44026. }
  44027. if (nextIndex == insertIndex)
  44028. {
  44029. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44030. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44031. }
  44032. coalesceSimilarSections();
  44033. totalNumChars = -1;
  44034. valueTextNeedsUpdating = true;
  44035. }
  44036. void TextEditor::remove (const Range<int>& range,
  44037. UndoManager* const um,
  44038. const int caretPositionToMoveTo)
  44039. {
  44040. if (! range.isEmpty())
  44041. {
  44042. int index = 0;
  44043. for (int i = 0; i < sections.size(); ++i)
  44044. {
  44045. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44046. if (range.getStart() > index && range.getStart() < nextIndex)
  44047. {
  44048. splitSection (i, range.getStart() - index);
  44049. --i;
  44050. }
  44051. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44052. {
  44053. splitSection (i, range.getEnd() - index);
  44054. --i;
  44055. }
  44056. else
  44057. {
  44058. index = nextIndex;
  44059. if (index > range.getEnd())
  44060. break;
  44061. }
  44062. }
  44063. index = 0;
  44064. if (um != 0)
  44065. {
  44066. Array <UniformTextSection*> removedSections;
  44067. for (int i = 0; i < sections.size(); ++i)
  44068. {
  44069. if (range.getEnd() <= range.getStart())
  44070. break;
  44071. UniformTextSection* const section = sections.getUnchecked (i);
  44072. const int nextIndex = index + section->getTotalLength();
  44073. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44074. removedSections.add (new UniformTextSection (*section));
  44075. index = nextIndex;
  44076. }
  44077. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44078. newTransaction();
  44079. um->perform (new RemoveAction (*this, range, caretPosition,
  44080. caretPositionToMoveTo, removedSections));
  44081. }
  44082. else
  44083. {
  44084. Range<int> remainingRange (range);
  44085. for (int i = 0; i < sections.size(); ++i)
  44086. {
  44087. UniformTextSection* const section = sections.getUnchecked (i);
  44088. const int nextIndex = index + section->getTotalLength();
  44089. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44090. {
  44091. sections.remove(i);
  44092. section->clear();
  44093. delete section;
  44094. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44095. if (remainingRange.isEmpty())
  44096. break;
  44097. --i;
  44098. }
  44099. else
  44100. {
  44101. index = nextIndex;
  44102. }
  44103. }
  44104. coalesceSimilarSections();
  44105. totalNumChars = -1;
  44106. valueTextNeedsUpdating = true;
  44107. moveCursorTo (caretPositionToMoveTo, false);
  44108. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44109. }
  44110. }
  44111. }
  44112. const String TextEditor::getText() const
  44113. {
  44114. String t;
  44115. t.preallocateStorage (getTotalNumChars());
  44116. String::Concatenator concatenator (t);
  44117. for (int i = 0; i < sections.size(); ++i)
  44118. sections.getUnchecked (i)->appendAllText (concatenator);
  44119. return t;
  44120. }
  44121. const String TextEditor::getTextInRange (const Range<int>& range) const
  44122. {
  44123. String t;
  44124. if (! range.isEmpty())
  44125. {
  44126. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44127. String::Concatenator concatenator (t);
  44128. int index = 0;
  44129. for (int i = 0; i < sections.size(); ++i)
  44130. {
  44131. const UniformTextSection* const s = sections.getUnchecked (i);
  44132. const int nextIndex = index + s->getTotalLength();
  44133. if (range.getStart() < nextIndex)
  44134. {
  44135. if (range.getEnd() <= index)
  44136. break;
  44137. s->appendSubstring (concatenator, range - index);
  44138. }
  44139. index = nextIndex;
  44140. }
  44141. }
  44142. return t;
  44143. }
  44144. const String TextEditor::getHighlightedText() const
  44145. {
  44146. return getTextInRange (selection);
  44147. }
  44148. int TextEditor::getTotalNumChars() const
  44149. {
  44150. if (totalNumChars < 0)
  44151. {
  44152. totalNumChars = 0;
  44153. for (int i = sections.size(); --i >= 0;)
  44154. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44155. }
  44156. return totalNumChars;
  44157. }
  44158. bool TextEditor::isEmpty() const
  44159. {
  44160. return getTotalNumChars() == 0;
  44161. }
  44162. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44163. {
  44164. const float wordWrapWidth = getWordWrapWidth();
  44165. if (wordWrapWidth > 0 && sections.size() > 0)
  44166. {
  44167. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44168. i.getCharPosition (index, cx, cy, lineHeight);
  44169. }
  44170. else
  44171. {
  44172. cx = cy = 0;
  44173. lineHeight = currentFont.getHeight();
  44174. }
  44175. }
  44176. int TextEditor::indexAtPosition (const float x, const float y)
  44177. {
  44178. const float wordWrapWidth = getWordWrapWidth();
  44179. if (wordWrapWidth > 0)
  44180. {
  44181. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44182. while (i.next())
  44183. {
  44184. if (i.lineY + i.lineHeight > y)
  44185. {
  44186. if (i.lineY > y)
  44187. return jmax (0, i.indexInText - 1);
  44188. if (i.atomX >= x)
  44189. return i.indexInText;
  44190. if (x < i.atomRight)
  44191. return i.xToIndex (x);
  44192. }
  44193. }
  44194. }
  44195. return getTotalNumChars();
  44196. }
  44197. int TextEditor::findWordBreakAfter (const int position) const
  44198. {
  44199. const String t (getTextInRange (Range<int> (position, position + 512)));
  44200. const int totalLength = t.length();
  44201. int i = 0;
  44202. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44203. ++i;
  44204. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44205. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44206. ++i;
  44207. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44208. ++i;
  44209. return position + i;
  44210. }
  44211. int TextEditor::findWordBreakBefore (const int position) const
  44212. {
  44213. if (position <= 0)
  44214. return 0;
  44215. const int startOfBuffer = jmax (0, position - 512);
  44216. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44217. int i = position - startOfBuffer;
  44218. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44219. --i;
  44220. if (i > 0)
  44221. {
  44222. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44223. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44224. --i;
  44225. }
  44226. jassert (startOfBuffer + i >= 0);
  44227. return startOfBuffer + i;
  44228. }
  44229. void TextEditor::splitSection (const int sectionIndex,
  44230. const int charToSplitAt)
  44231. {
  44232. jassert (sections[sectionIndex] != 0);
  44233. sections.insert (sectionIndex + 1,
  44234. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44235. }
  44236. void TextEditor::coalesceSimilarSections()
  44237. {
  44238. for (int i = 0; i < sections.size() - 1; ++i)
  44239. {
  44240. UniformTextSection* const s1 = sections.getUnchecked (i);
  44241. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44242. if (s1->font == s2->font
  44243. && s1->colour == s2->colour)
  44244. {
  44245. s1->append (*s2, passwordCharacter);
  44246. sections.remove (i + 1);
  44247. delete s2;
  44248. --i;
  44249. }
  44250. }
  44251. }
  44252. END_JUCE_NAMESPACE
  44253. /*** End of inlined file: juce_TextEditor.cpp ***/
  44254. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44255. BEGIN_JUCE_NAMESPACE
  44256. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44257. class ToolbarSpacerComp : public ToolbarItemComponent
  44258. {
  44259. public:
  44260. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44261. : ToolbarItemComponent (itemId_, String::empty, false),
  44262. fixedSize (fixedSize_),
  44263. drawBar (drawBar_)
  44264. {
  44265. }
  44266. ~ToolbarSpacerComp()
  44267. {
  44268. }
  44269. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44270. int& preferredSize, int& minSize, int& maxSize)
  44271. {
  44272. if (fixedSize <= 0)
  44273. {
  44274. preferredSize = toolbarThickness * 2;
  44275. minSize = 4;
  44276. maxSize = 32768;
  44277. }
  44278. else
  44279. {
  44280. maxSize = roundToInt (toolbarThickness * fixedSize);
  44281. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44282. preferredSize = maxSize;
  44283. if (getEditingMode() == editableOnPalette)
  44284. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44285. }
  44286. return true;
  44287. }
  44288. void paintButtonArea (Graphics&, int, int, bool, bool)
  44289. {
  44290. }
  44291. void contentAreaChanged (const Rectangle<int>&)
  44292. {
  44293. }
  44294. int getResizeOrder() const throw()
  44295. {
  44296. return fixedSize <= 0 ? 0 : 1;
  44297. }
  44298. void paint (Graphics& g)
  44299. {
  44300. const int w = getWidth();
  44301. const int h = getHeight();
  44302. if (drawBar)
  44303. {
  44304. g.setColour (findColour (Toolbar::separatorColourId, true));
  44305. const float thickness = 0.2f;
  44306. if (isToolbarVertical())
  44307. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44308. else
  44309. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44310. }
  44311. if (getEditingMode() != normalMode && ! drawBar)
  44312. {
  44313. g.setColour (findColour (Toolbar::separatorColourId, true));
  44314. const int indentX = jmin (2, (w - 3) / 2);
  44315. const int indentY = jmin (2, (h - 3) / 2);
  44316. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44317. if (fixedSize <= 0)
  44318. {
  44319. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44320. if (isToolbarVertical())
  44321. {
  44322. x1 = w * 0.5f;
  44323. y1 = h * 0.4f;
  44324. x2 = x1;
  44325. y2 = indentX * 2.0f;
  44326. x3 = x1;
  44327. y3 = h * 0.6f;
  44328. x4 = x1;
  44329. y4 = h - y2;
  44330. hw = w * 0.15f;
  44331. hl = w * 0.2f;
  44332. }
  44333. else
  44334. {
  44335. x1 = w * 0.4f;
  44336. y1 = h * 0.5f;
  44337. x2 = indentX * 2.0f;
  44338. y2 = y1;
  44339. x3 = w * 0.6f;
  44340. y3 = y1;
  44341. x4 = w - x2;
  44342. y4 = y1;
  44343. hw = h * 0.15f;
  44344. hl = h * 0.2f;
  44345. }
  44346. Path p;
  44347. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44348. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44349. g.fillPath (p);
  44350. }
  44351. }
  44352. }
  44353. juce_UseDebuggingNewOperator
  44354. private:
  44355. const float fixedSize;
  44356. const bool drawBar;
  44357. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44358. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44359. };
  44360. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44361. {
  44362. public:
  44363. MissingItemsComponent (Toolbar& owner_, const int height_)
  44364. : PopupMenuCustomComponent (true),
  44365. owner (owner_),
  44366. height (height_)
  44367. {
  44368. for (int i = owner_.items.size(); --i >= 0;)
  44369. {
  44370. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44371. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44372. {
  44373. oldIndexes.insert (0, i);
  44374. addAndMakeVisible (tc, 0);
  44375. }
  44376. }
  44377. layout (400);
  44378. }
  44379. ~MissingItemsComponent()
  44380. {
  44381. // deleting the toolbar while its menu it open??
  44382. jassert (owner.isValidComponent());
  44383. for (int i = 0; i < getNumChildComponents(); ++i)
  44384. {
  44385. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44386. if (tc != 0)
  44387. {
  44388. tc->setVisible (false);
  44389. const int index = oldIndexes.remove (i);
  44390. owner.addChildComponent (tc, index);
  44391. --i;
  44392. }
  44393. }
  44394. owner.resized();
  44395. }
  44396. void layout (const int preferredWidth)
  44397. {
  44398. const int indent = 8;
  44399. int x = indent;
  44400. int y = indent;
  44401. int maxX = 0;
  44402. for (int i = 0; i < getNumChildComponents(); ++i)
  44403. {
  44404. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44405. if (tc != 0)
  44406. {
  44407. int preferredSize = 1, minSize = 1, maxSize = 1;
  44408. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44409. {
  44410. if (x + preferredSize > preferredWidth && x > indent)
  44411. {
  44412. x = indent;
  44413. y += height;
  44414. }
  44415. tc->setBounds (x, y, preferredSize, height);
  44416. x += preferredSize;
  44417. maxX = jmax (maxX, x);
  44418. }
  44419. }
  44420. }
  44421. setSize (maxX + 8, y + height + 8);
  44422. }
  44423. void getIdealSize (int& idealWidth, int& idealHeight)
  44424. {
  44425. idealWidth = getWidth();
  44426. idealHeight = getHeight();
  44427. }
  44428. juce_UseDebuggingNewOperator
  44429. private:
  44430. Toolbar& owner;
  44431. const int height;
  44432. Array <int> oldIndexes;
  44433. MissingItemsComponent (const MissingItemsComponent&);
  44434. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44435. };
  44436. Toolbar::Toolbar()
  44437. : vertical (false),
  44438. isEditingActive (false),
  44439. toolbarStyle (Toolbar::iconsOnly)
  44440. {
  44441. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44442. missingItemsButton->setAlwaysOnTop (true);
  44443. missingItemsButton->addButtonListener (this);
  44444. }
  44445. Toolbar::~Toolbar()
  44446. {
  44447. animator.cancelAllAnimations (true);
  44448. deleteAllChildren();
  44449. }
  44450. void Toolbar::setVertical (const bool shouldBeVertical)
  44451. {
  44452. if (vertical != shouldBeVertical)
  44453. {
  44454. vertical = shouldBeVertical;
  44455. resized();
  44456. }
  44457. }
  44458. void Toolbar::clear()
  44459. {
  44460. for (int i = items.size(); --i >= 0;)
  44461. {
  44462. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44463. items.remove (i);
  44464. delete tc;
  44465. }
  44466. resized();
  44467. }
  44468. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44469. {
  44470. if (itemId == ToolbarItemFactory::separatorBarId)
  44471. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44472. else if (itemId == ToolbarItemFactory::spacerId)
  44473. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44474. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44475. return new ToolbarSpacerComp (itemId, 0, false);
  44476. return factory.createItem (itemId);
  44477. }
  44478. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44479. const int itemId,
  44480. const int insertIndex)
  44481. {
  44482. // An ID can't be zero - this might indicate a mistake somewhere?
  44483. jassert (itemId != 0);
  44484. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44485. if (tc != 0)
  44486. {
  44487. #if JUCE_DEBUG
  44488. Array <int> allowedIds;
  44489. factory.getAllToolbarItemIds (allowedIds);
  44490. // If your factory can create an item for a given ID, it must also return
  44491. // that ID from its getAllToolbarItemIds() method!
  44492. jassert (allowedIds.contains (itemId));
  44493. #endif
  44494. items.insert (insertIndex, tc);
  44495. addAndMakeVisible (tc, insertIndex);
  44496. }
  44497. }
  44498. void Toolbar::addItem (ToolbarItemFactory& factory,
  44499. const int itemId,
  44500. const int insertIndex)
  44501. {
  44502. addItemInternal (factory, itemId, insertIndex);
  44503. resized();
  44504. }
  44505. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44506. {
  44507. Array <int> ids;
  44508. factoryToUse.getDefaultItemSet (ids);
  44509. clear();
  44510. for (int i = 0; i < ids.size(); ++i)
  44511. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44512. resized();
  44513. }
  44514. void Toolbar::removeToolbarItem (const int itemIndex)
  44515. {
  44516. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44517. if (tc != 0)
  44518. {
  44519. items.removeValue (tc);
  44520. delete tc;
  44521. resized();
  44522. }
  44523. }
  44524. int Toolbar::getNumItems() const throw()
  44525. {
  44526. return items.size();
  44527. }
  44528. int Toolbar::getItemId (const int itemIndex) const throw()
  44529. {
  44530. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44531. return tc != 0 ? tc->getItemId() : 0;
  44532. }
  44533. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44534. {
  44535. return items [itemIndex];
  44536. }
  44537. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44538. {
  44539. for (;;)
  44540. {
  44541. index += delta;
  44542. ToolbarItemComponent* const tc = getItemComponent (index);
  44543. if (tc == 0)
  44544. break;
  44545. if (tc->isActive)
  44546. return tc;
  44547. }
  44548. return 0;
  44549. }
  44550. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44551. {
  44552. if (toolbarStyle != newStyle)
  44553. {
  44554. toolbarStyle = newStyle;
  44555. updateAllItemPositions (false);
  44556. }
  44557. }
  44558. const String Toolbar::toString() const
  44559. {
  44560. String s ("TB:");
  44561. for (int i = 0; i < getNumItems(); ++i)
  44562. s << getItemId(i) << ' ';
  44563. return s.trimEnd();
  44564. }
  44565. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44566. const String& savedVersion)
  44567. {
  44568. if (! savedVersion.startsWith ("TB:"))
  44569. return false;
  44570. StringArray tokens;
  44571. tokens.addTokens (savedVersion.substring (3), false);
  44572. clear();
  44573. for (int i = 0; i < tokens.size(); ++i)
  44574. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44575. resized();
  44576. return true;
  44577. }
  44578. void Toolbar::paint (Graphics& g)
  44579. {
  44580. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44581. }
  44582. int Toolbar::getThickness() const throw()
  44583. {
  44584. return vertical ? getWidth() : getHeight();
  44585. }
  44586. int Toolbar::getLength() const throw()
  44587. {
  44588. return vertical ? getHeight() : getWidth();
  44589. }
  44590. void Toolbar::setEditingActive (const bool active)
  44591. {
  44592. if (isEditingActive != active)
  44593. {
  44594. isEditingActive = active;
  44595. updateAllItemPositions (false);
  44596. }
  44597. }
  44598. void Toolbar::resized()
  44599. {
  44600. updateAllItemPositions (false);
  44601. }
  44602. void Toolbar::updateAllItemPositions (const bool animate)
  44603. {
  44604. if (getWidth() > 0 && getHeight() > 0)
  44605. {
  44606. StretchableObjectResizer resizer;
  44607. int i;
  44608. for (i = 0; i < items.size(); ++i)
  44609. {
  44610. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44611. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44612. : ToolbarItemComponent::normalMode);
  44613. tc->setStyle (toolbarStyle);
  44614. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44615. int preferredSize = 1, minSize = 1, maxSize = 1;
  44616. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44617. preferredSize, minSize, maxSize))
  44618. {
  44619. tc->isActive = true;
  44620. resizer.addItem (preferredSize, minSize, maxSize,
  44621. spacer != 0 ? spacer->getResizeOrder() : 2);
  44622. }
  44623. else
  44624. {
  44625. tc->isActive = false;
  44626. tc->setVisible (false);
  44627. }
  44628. }
  44629. resizer.resizeToFit (getLength());
  44630. int totalLength = 0;
  44631. for (i = 0; i < resizer.getNumItems(); ++i)
  44632. totalLength += (int) resizer.getItemSize (i);
  44633. const bool itemsOffTheEnd = totalLength > getLength();
  44634. const int extrasButtonSize = getThickness() / 2;
  44635. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44636. missingItemsButton->setVisible (itemsOffTheEnd);
  44637. missingItemsButton->setEnabled (! isEditingActive);
  44638. if (vertical)
  44639. missingItemsButton->setCentrePosition (getWidth() / 2,
  44640. getHeight() - 4 - extrasButtonSize / 2);
  44641. else
  44642. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44643. getHeight() / 2);
  44644. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44645. : missingItemsButton->getX()) - 4
  44646. : getLength();
  44647. int pos = 0, activeIndex = 0;
  44648. for (i = 0; i < items.size(); ++i)
  44649. {
  44650. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44651. if (tc->isActive)
  44652. {
  44653. const int size = (int) resizer.getItemSize (activeIndex++);
  44654. Rectangle<int> newBounds;
  44655. if (vertical)
  44656. newBounds.setBounds (0, pos, getWidth(), size);
  44657. else
  44658. newBounds.setBounds (pos, 0, size, getHeight());
  44659. if (animate)
  44660. {
  44661. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44662. }
  44663. else
  44664. {
  44665. animator.cancelAnimation (tc, false);
  44666. tc->setBounds (newBounds);
  44667. }
  44668. pos += size;
  44669. tc->setVisible (pos <= maxLength
  44670. && ((! tc->isBeingDragged)
  44671. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44672. }
  44673. }
  44674. }
  44675. }
  44676. void Toolbar::buttonClicked (Button*)
  44677. {
  44678. jassert (missingItemsButton->isShowing());
  44679. if (missingItemsButton->isShowing())
  44680. {
  44681. PopupMenu m;
  44682. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44683. m.showAt (missingItemsButton);
  44684. }
  44685. }
  44686. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44687. Component* /*sourceComponent*/)
  44688. {
  44689. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44690. }
  44691. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44692. {
  44693. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44694. if (tc != 0)
  44695. {
  44696. if (getNumItems() == 0)
  44697. {
  44698. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44699. {
  44700. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44701. if (palette != 0)
  44702. palette->replaceComponent (tc);
  44703. }
  44704. else
  44705. {
  44706. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44707. }
  44708. items.add (tc);
  44709. addChildComponent (tc);
  44710. updateAllItemPositions (false);
  44711. }
  44712. else
  44713. {
  44714. for (int i = getNumItems(); --i >= 0;)
  44715. {
  44716. int currentIndex = getIndexOfChildComponent (tc);
  44717. if (currentIndex < 0)
  44718. {
  44719. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44720. {
  44721. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44722. if (palette != 0)
  44723. palette->replaceComponent (tc);
  44724. }
  44725. else
  44726. {
  44727. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44728. }
  44729. items.add (tc);
  44730. addChildComponent (tc);
  44731. currentIndex = getIndexOfChildComponent (tc);
  44732. updateAllItemPositions (true);
  44733. }
  44734. int newIndex = currentIndex;
  44735. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44736. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44737. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44738. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44739. if (prev != 0)
  44740. {
  44741. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44742. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44743. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44744. {
  44745. newIndex = getIndexOfChildComponent (prev);
  44746. }
  44747. }
  44748. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44749. if (next != 0)
  44750. {
  44751. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44752. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44753. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44754. {
  44755. newIndex = getIndexOfChildComponent (next) + 1;
  44756. }
  44757. }
  44758. if (newIndex != currentIndex)
  44759. {
  44760. items.removeValue (tc);
  44761. removeChildComponent (tc);
  44762. addChildComponent (tc, newIndex);
  44763. items.insert (newIndex, tc);
  44764. updateAllItemPositions (true);
  44765. }
  44766. else
  44767. {
  44768. break;
  44769. }
  44770. }
  44771. }
  44772. }
  44773. }
  44774. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44775. {
  44776. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44777. if (tc != 0)
  44778. {
  44779. if (isParentOf (tc))
  44780. {
  44781. items.removeValue (tc);
  44782. removeChildComponent (tc);
  44783. updateAllItemPositions (true);
  44784. }
  44785. }
  44786. }
  44787. void Toolbar::itemDropped (const String&, Component*, int, int)
  44788. {
  44789. }
  44790. void Toolbar::mouseDown (const MouseEvent& e)
  44791. {
  44792. if (e.mods.isPopupMenu())
  44793. {
  44794. }
  44795. }
  44796. class ToolbarCustomisationDialog : public DialogWindow
  44797. {
  44798. public:
  44799. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44800. Toolbar* const toolbar_,
  44801. const int optionFlags)
  44802. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44803. toolbar (toolbar_)
  44804. {
  44805. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44806. setResizable (true, true);
  44807. setResizeLimits (400, 300, 1500, 1000);
  44808. positionNearBar();
  44809. }
  44810. ~ToolbarCustomisationDialog()
  44811. {
  44812. setContentComponent (0, true);
  44813. }
  44814. void closeButtonPressed()
  44815. {
  44816. setVisible (false);
  44817. }
  44818. bool canModalEventBeSentToComponent (const Component* comp)
  44819. {
  44820. return toolbar->isParentOf (comp);
  44821. }
  44822. void positionNearBar()
  44823. {
  44824. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44825. const int tbx = toolbar->getScreenX();
  44826. const int tby = toolbar->getScreenY();
  44827. const int gap = 8;
  44828. int x, y;
  44829. if (toolbar->isVertical())
  44830. {
  44831. y = tby;
  44832. if (tbx > screenSize.getCentreX())
  44833. x = tbx - getWidth() - gap;
  44834. else
  44835. x = tbx + toolbar->getWidth() + gap;
  44836. }
  44837. else
  44838. {
  44839. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44840. if (tby > screenSize.getCentreY())
  44841. y = tby - getHeight() - gap;
  44842. else
  44843. y = tby + toolbar->getHeight() + gap;
  44844. }
  44845. setTopLeftPosition (x, y);
  44846. }
  44847. private:
  44848. Toolbar* const toolbar;
  44849. class CustomiserPanel : public Component,
  44850. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44851. private ButtonListener
  44852. {
  44853. public:
  44854. CustomiserPanel (ToolbarItemFactory& factory_,
  44855. Toolbar* const toolbar_,
  44856. const int optionFlags)
  44857. : factory (factory_),
  44858. toolbar (toolbar_),
  44859. styleBox (0),
  44860. defaultButton (0)
  44861. {
  44862. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44863. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44864. | Toolbar::allowIconsWithTextChoice
  44865. | Toolbar::allowTextOnlyChoice)) != 0)
  44866. {
  44867. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44868. styleBox->setEditableText (false);
  44869. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44870. styleBox->addItem (TRANS("Show icons only"), 1);
  44871. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44872. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44873. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44874. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44875. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44876. styleBox->setSelectedId (1);
  44877. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44878. styleBox->setSelectedId (2);
  44879. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44880. styleBox->setSelectedId (3);
  44881. styleBox->addListener (this);
  44882. }
  44883. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44884. {
  44885. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44886. defaultButton->addButtonListener (this);
  44887. }
  44888. addAndMakeVisible (instructions = new Label (String::empty,
  44889. 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.")));
  44890. instructions->setFont (Font (13.0f));
  44891. setSize (500, 300);
  44892. }
  44893. ~CustomiserPanel()
  44894. {
  44895. deleteAllChildren();
  44896. }
  44897. void comboBoxChanged (ComboBox*)
  44898. {
  44899. if (styleBox->getSelectedId() == 1)
  44900. toolbar->setStyle (Toolbar::iconsOnly);
  44901. else if (styleBox->getSelectedId() == 2)
  44902. toolbar->setStyle (Toolbar::iconsWithText);
  44903. else if (styleBox->getSelectedId() == 3)
  44904. toolbar->setStyle (Toolbar::textOnly);
  44905. palette->resized(); // to make it update the styles
  44906. }
  44907. void buttonClicked (Button*)
  44908. {
  44909. toolbar->addDefaultItems (factory);
  44910. }
  44911. void paint (Graphics& g)
  44912. {
  44913. Colour background;
  44914. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44915. if (dw != 0)
  44916. background = dw->getBackgroundColour();
  44917. g.setColour (background.contrasting().withAlpha (0.3f));
  44918. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44919. }
  44920. void resized()
  44921. {
  44922. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44923. if (styleBox != 0)
  44924. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44925. if (defaultButton != 0)
  44926. {
  44927. defaultButton->changeWidthToFitText (22);
  44928. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44929. }
  44930. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44931. }
  44932. private:
  44933. ToolbarItemFactory& factory;
  44934. Toolbar* const toolbar;
  44935. Label* instructions;
  44936. ToolbarItemPalette* palette;
  44937. ComboBox* styleBox;
  44938. TextButton* defaultButton;
  44939. };
  44940. };
  44941. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44942. {
  44943. setEditingActive (true);
  44944. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44945. dw.runModalLoop();
  44946. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44947. setEditingActive (false);
  44948. }
  44949. END_JUCE_NAMESPACE
  44950. /*** End of inlined file: juce_Toolbar.cpp ***/
  44951. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44952. BEGIN_JUCE_NAMESPACE
  44953. ToolbarItemFactory::ToolbarItemFactory()
  44954. {
  44955. }
  44956. ToolbarItemFactory::~ToolbarItemFactory()
  44957. {
  44958. }
  44959. class ItemDragAndDropOverlayComponent : public Component
  44960. {
  44961. public:
  44962. ItemDragAndDropOverlayComponent()
  44963. : isDragging (false)
  44964. {
  44965. setAlwaysOnTop (true);
  44966. setRepaintsOnMouseActivity (true);
  44967. setMouseCursor (MouseCursor::DraggingHandCursor);
  44968. }
  44969. ~ItemDragAndDropOverlayComponent()
  44970. {
  44971. }
  44972. void paint (Graphics& g)
  44973. {
  44974. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44975. if (isMouseOverOrDragging()
  44976. && tc != 0
  44977. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44978. {
  44979. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44980. g.drawRect (0, 0, getWidth(), getHeight(),
  44981. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44982. }
  44983. }
  44984. void mouseDown (const MouseEvent& e)
  44985. {
  44986. isDragging = false;
  44987. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44988. if (tc != 0)
  44989. {
  44990. tc->dragOffsetX = e.x;
  44991. tc->dragOffsetY = e.y;
  44992. }
  44993. }
  44994. void mouseDrag (const MouseEvent& e)
  44995. {
  44996. if (! (isDragging || e.mouseWasClicked()))
  44997. {
  44998. isDragging = true;
  44999. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45000. if (dnd != 0)
  45001. {
  45002. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45003. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45004. if (tc != 0)
  45005. {
  45006. tc->isBeingDragged = true;
  45007. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45008. tc->setVisible (false);
  45009. }
  45010. }
  45011. }
  45012. }
  45013. void mouseUp (const MouseEvent&)
  45014. {
  45015. isDragging = false;
  45016. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45017. if (tc != 0)
  45018. {
  45019. tc->isBeingDragged = false;
  45020. Toolbar* const tb = tc->getToolbar();
  45021. if (tb != 0)
  45022. tb->updateAllItemPositions (true);
  45023. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45024. delete tc;
  45025. }
  45026. }
  45027. void parentSizeChanged()
  45028. {
  45029. setBounds (0, 0, getParentWidth(), getParentHeight());
  45030. }
  45031. juce_UseDebuggingNewOperator
  45032. private:
  45033. bool isDragging;
  45034. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45035. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45036. };
  45037. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45038. const String& labelText,
  45039. const bool isBeingUsedAsAButton_)
  45040. : Button (labelText),
  45041. itemId (itemId_),
  45042. mode (normalMode),
  45043. toolbarStyle (Toolbar::iconsOnly),
  45044. dragOffsetX (0),
  45045. dragOffsetY (0),
  45046. isActive (true),
  45047. isBeingDragged (false),
  45048. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45049. {
  45050. // Your item ID can't be 0!
  45051. jassert (itemId_ != 0);
  45052. }
  45053. ToolbarItemComponent::~ToolbarItemComponent()
  45054. {
  45055. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45056. overlayComp = 0;
  45057. }
  45058. Toolbar* ToolbarItemComponent::getToolbar() const
  45059. {
  45060. return dynamic_cast <Toolbar*> (getParentComponent());
  45061. }
  45062. bool ToolbarItemComponent::isToolbarVertical() const
  45063. {
  45064. const Toolbar* const t = getToolbar();
  45065. return t != 0 && t->isVertical();
  45066. }
  45067. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45068. {
  45069. if (toolbarStyle != newStyle)
  45070. {
  45071. toolbarStyle = newStyle;
  45072. repaint();
  45073. resized();
  45074. }
  45075. }
  45076. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45077. {
  45078. if (isBeingUsedAsAButton)
  45079. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45080. over, down, *this);
  45081. if (toolbarStyle != Toolbar::iconsOnly)
  45082. {
  45083. const int indent = contentArea.getX();
  45084. int y = indent;
  45085. int h = getHeight() - indent * 2;
  45086. if (toolbarStyle == Toolbar::iconsWithText)
  45087. {
  45088. y = contentArea.getBottom() + indent / 2;
  45089. h -= contentArea.getHeight();
  45090. }
  45091. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45092. getButtonText(), *this);
  45093. }
  45094. if (! contentArea.isEmpty())
  45095. {
  45096. g.saveState();
  45097. g.setOrigin (contentArea.getX(), contentArea.getY());
  45098. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45099. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45100. g.restoreState();
  45101. }
  45102. }
  45103. void ToolbarItemComponent::resized()
  45104. {
  45105. if (toolbarStyle != Toolbar::textOnly)
  45106. {
  45107. const int indent = jmin (proportionOfWidth (0.08f),
  45108. proportionOfHeight (0.08f));
  45109. contentArea = Rectangle<int> (indent, indent,
  45110. getWidth() - indent * 2,
  45111. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45112. : (getHeight() - indent * 2));
  45113. }
  45114. else
  45115. {
  45116. contentArea = Rectangle<int>();
  45117. }
  45118. contentAreaChanged (contentArea);
  45119. }
  45120. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45121. {
  45122. if (mode != newMode)
  45123. {
  45124. mode = newMode;
  45125. repaint();
  45126. if (mode == normalMode)
  45127. {
  45128. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45129. overlayComp = 0;
  45130. }
  45131. else if (overlayComp == 0)
  45132. {
  45133. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45134. overlayComp->parentSizeChanged();
  45135. }
  45136. resized();
  45137. }
  45138. }
  45139. END_JUCE_NAMESPACE
  45140. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45141. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45142. BEGIN_JUCE_NAMESPACE
  45143. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45144. Toolbar* const toolbar_)
  45145. : factory (factory_),
  45146. toolbar (toolbar_)
  45147. {
  45148. Component* const itemHolder = new Component();
  45149. Array <int> allIds;
  45150. factory_.getAllToolbarItemIds (allIds);
  45151. for (int i = 0; i < allIds.size(); ++i)
  45152. {
  45153. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45154. jassert (tc != 0);
  45155. if (tc != 0)
  45156. {
  45157. itemHolder->addAndMakeVisible (tc);
  45158. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45159. }
  45160. }
  45161. viewport = new Viewport();
  45162. viewport->setViewedComponent (itemHolder);
  45163. addAndMakeVisible (viewport);
  45164. }
  45165. ToolbarItemPalette::~ToolbarItemPalette()
  45166. {
  45167. viewport->getViewedComponent()->deleteAllChildren();
  45168. deleteAllChildren();
  45169. }
  45170. void ToolbarItemPalette::resized()
  45171. {
  45172. viewport->setBoundsInset (BorderSize (1));
  45173. Component* const itemHolder = viewport->getViewedComponent();
  45174. const int indent = 8;
  45175. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45176. const int height = toolbar->getThickness();
  45177. int x = indent;
  45178. int y = indent;
  45179. int maxX = 0;
  45180. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45181. {
  45182. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45183. if (tc != 0)
  45184. {
  45185. tc->setStyle (toolbar->getStyle());
  45186. int preferredSize = 1, minSize = 1, maxSize = 1;
  45187. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45188. {
  45189. if (x + preferredSize > preferredWidth && x > indent)
  45190. {
  45191. x = indent;
  45192. y += height;
  45193. }
  45194. tc->setBounds (x, y, preferredSize, height);
  45195. x += preferredSize + 8;
  45196. maxX = jmax (maxX, x);
  45197. }
  45198. }
  45199. }
  45200. itemHolder->setSize (maxX, y + height + 8);
  45201. }
  45202. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45203. {
  45204. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45205. jassert (tc != 0);
  45206. if (tc != 0)
  45207. {
  45208. tc->setBounds (comp->getBounds());
  45209. tc->setStyle (toolbar->getStyle());
  45210. tc->setEditingMode (comp->getEditingMode());
  45211. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45212. }
  45213. }
  45214. END_JUCE_NAMESPACE
  45215. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45216. /*** Start of inlined file: juce_TreeView.cpp ***/
  45217. BEGIN_JUCE_NAMESPACE
  45218. class TreeViewContentComponent : public Component,
  45219. public TooltipClient
  45220. {
  45221. public:
  45222. TreeViewContentComponent (TreeView& owner_)
  45223. : owner (owner_),
  45224. buttonUnderMouse (0),
  45225. isDragging (false)
  45226. {
  45227. }
  45228. ~TreeViewContentComponent()
  45229. {
  45230. deleteAllChildren();
  45231. }
  45232. void mouseDown (const MouseEvent& e)
  45233. {
  45234. updateButtonUnderMouse (e);
  45235. isDragging = false;
  45236. needSelectionOnMouseUp = false;
  45237. Rectangle<int> pos;
  45238. TreeViewItem* const item = findItemAt (e.y, pos);
  45239. if (item == 0)
  45240. return;
  45241. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45242. // as selection clicks)
  45243. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45244. {
  45245. if (e.x >= pos.getX() - owner.getIndentSize())
  45246. item->setOpen (! item->isOpen());
  45247. // (clicks to the left of an open/close button are ignored)
  45248. }
  45249. else
  45250. {
  45251. // mouse-down inside the body of the item..
  45252. if (! owner.isMultiSelectEnabled())
  45253. item->setSelected (true, true);
  45254. else if (item->isSelected())
  45255. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45256. else
  45257. selectBasedOnModifiers (item, e.mods);
  45258. if (e.x >= pos.getX())
  45259. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45260. }
  45261. }
  45262. void mouseUp (const MouseEvent& e)
  45263. {
  45264. updateButtonUnderMouse (e);
  45265. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45266. {
  45267. Rectangle<int> pos;
  45268. TreeViewItem* const item = findItemAt (e.y, pos);
  45269. if (item != 0)
  45270. selectBasedOnModifiers (item, e.mods);
  45271. }
  45272. }
  45273. void mouseDoubleClick (const MouseEvent& e)
  45274. {
  45275. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45276. {
  45277. Rectangle<int> pos;
  45278. TreeViewItem* const item = findItemAt (e.y, pos);
  45279. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45280. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45281. }
  45282. }
  45283. void mouseDrag (const MouseEvent& e)
  45284. {
  45285. if (isEnabled()
  45286. && ! (isDragging || e.mouseWasClicked()
  45287. || e.getDistanceFromDragStart() < 5
  45288. || e.mods.isPopupMenu()))
  45289. {
  45290. isDragging = true;
  45291. Rectangle<int> pos;
  45292. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45293. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45294. {
  45295. const String dragDescription (item->getDragSourceDescription());
  45296. if (dragDescription.isNotEmpty())
  45297. {
  45298. DragAndDropContainer* const dragContainer
  45299. = DragAndDropContainer::findParentDragContainerFor (this);
  45300. if (dragContainer != 0)
  45301. {
  45302. pos.setSize (pos.getWidth(), item->itemHeight);
  45303. Image dragImage (Component::createComponentSnapshot (pos, true));
  45304. dragImage.multiplyAllAlphas (0.6f);
  45305. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45306. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45307. }
  45308. else
  45309. {
  45310. // to be able to do a drag-and-drop operation, the treeview needs to
  45311. // be inside a component which is also a DragAndDropContainer.
  45312. jassertfalse;
  45313. }
  45314. }
  45315. }
  45316. }
  45317. }
  45318. void mouseMove (const MouseEvent& e)
  45319. {
  45320. updateButtonUnderMouse (e);
  45321. }
  45322. void mouseExit (const MouseEvent& e)
  45323. {
  45324. updateButtonUnderMouse (e);
  45325. }
  45326. void paint (Graphics& g)
  45327. {
  45328. if (owner.rootItem != 0)
  45329. {
  45330. owner.handleAsyncUpdate();
  45331. if (! owner.rootItemVisible)
  45332. g.setOrigin (0, -owner.rootItem->itemHeight);
  45333. owner.rootItem->paintRecursively (g, getWidth());
  45334. }
  45335. }
  45336. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45337. {
  45338. if (owner.rootItem != 0)
  45339. {
  45340. owner.handleAsyncUpdate();
  45341. if (! owner.rootItemVisible)
  45342. y += owner.rootItem->itemHeight;
  45343. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45344. if (ti != 0)
  45345. itemPosition = ti->getItemPosition (false);
  45346. return ti;
  45347. }
  45348. return 0;
  45349. }
  45350. void updateComponents()
  45351. {
  45352. const int visibleTop = -getY();
  45353. const int visibleBottom = visibleTop + getParentHeight();
  45354. BigInteger itemsToKeep;
  45355. {
  45356. TreeViewItem* item = owner.rootItem;
  45357. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45358. while (item != 0 && y < visibleBottom)
  45359. {
  45360. y += item->itemHeight;
  45361. if (y >= visibleTop)
  45362. {
  45363. const int index = rowComponentIds.indexOf (item->uid);
  45364. if (index < 0)
  45365. {
  45366. Component* const comp = item->createItemComponent();
  45367. if (comp != 0)
  45368. {
  45369. addAndMakeVisible (comp);
  45370. itemsToKeep.setBit (rowComponentItems.size());
  45371. rowComponentItems.add (item);
  45372. rowComponentIds.add (item->uid);
  45373. rowComponents.add (comp);
  45374. }
  45375. }
  45376. else
  45377. {
  45378. itemsToKeep.setBit (index);
  45379. }
  45380. }
  45381. item = item->getNextVisibleItem (true);
  45382. }
  45383. }
  45384. for (int i = rowComponentItems.size(); --i >= 0;)
  45385. {
  45386. Component* const comp = rowComponents.getUnchecked(i);
  45387. bool keep = false;
  45388. if (isParentOf (comp))
  45389. {
  45390. if (itemsToKeep[i])
  45391. {
  45392. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45393. Rectangle<int> pos (item->getItemPosition (false));
  45394. pos.setSize (pos.getWidth(), item->itemHeight);
  45395. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45396. {
  45397. keep = true;
  45398. comp->setBounds (pos);
  45399. }
  45400. }
  45401. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45402. {
  45403. keep = true;
  45404. comp->setSize (0, 0);
  45405. }
  45406. }
  45407. if (! keep)
  45408. {
  45409. delete comp;
  45410. rowComponents.remove (i);
  45411. rowComponentIds.remove (i);
  45412. rowComponentItems.remove (i);
  45413. }
  45414. }
  45415. }
  45416. void updateButtonUnderMouse (const MouseEvent& e)
  45417. {
  45418. TreeViewItem* newItem = 0;
  45419. if (owner.openCloseButtonsVisible)
  45420. {
  45421. Rectangle<int> pos;
  45422. TreeViewItem* item = findItemAt (e.y, pos);
  45423. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45424. {
  45425. newItem = item;
  45426. if (! newItem->mightContainSubItems())
  45427. newItem = 0;
  45428. }
  45429. }
  45430. if (buttonUnderMouse != newItem)
  45431. {
  45432. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45433. {
  45434. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45435. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45436. }
  45437. buttonUnderMouse = newItem;
  45438. if (buttonUnderMouse != 0)
  45439. {
  45440. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45441. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45442. }
  45443. }
  45444. }
  45445. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45446. {
  45447. return item == buttonUnderMouse;
  45448. }
  45449. void resized()
  45450. {
  45451. owner.itemsChanged();
  45452. }
  45453. const String getTooltip()
  45454. {
  45455. Rectangle<int> pos;
  45456. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45457. if (item != 0)
  45458. return item->getTooltip();
  45459. return owner.getTooltip();
  45460. }
  45461. juce_UseDebuggingNewOperator
  45462. private:
  45463. TreeView& owner;
  45464. Array <TreeViewItem*> rowComponentItems;
  45465. Array <int> rowComponentIds;
  45466. Array <Component*> rowComponents;
  45467. TreeViewItem* buttonUnderMouse;
  45468. bool isDragging, needSelectionOnMouseUp;
  45469. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45470. {
  45471. TreeViewItem* firstSelected = 0;
  45472. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45473. {
  45474. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45475. jassert (lastSelected != 0);
  45476. int rowStart = firstSelected->getRowNumberInTree();
  45477. int rowEnd = lastSelected->getRowNumberInTree();
  45478. if (rowStart > rowEnd)
  45479. swapVariables (rowStart, rowEnd);
  45480. int ourRow = item->getRowNumberInTree();
  45481. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45482. if (ourRow > otherEnd)
  45483. swapVariables (ourRow, otherEnd);
  45484. for (int i = ourRow; i <= otherEnd; ++i)
  45485. owner.getItemOnRow (i)->setSelected (true, false);
  45486. }
  45487. else
  45488. {
  45489. const bool cmd = modifiers.isCommandDown();
  45490. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45491. }
  45492. }
  45493. bool containsItem (TreeViewItem* const item) const
  45494. {
  45495. for (int i = rowComponentItems.size(); --i >= 0;)
  45496. if (rowComponentItems.getUnchecked(i) == item)
  45497. return true;
  45498. return false;
  45499. }
  45500. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45501. {
  45502. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45503. {
  45504. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45505. if (source->isDragging())
  45506. {
  45507. Component* const underMouse = source->getComponentUnderMouse();
  45508. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45509. return true;
  45510. }
  45511. }
  45512. return false;
  45513. }
  45514. TreeViewContentComponent (const TreeViewContentComponent&);
  45515. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45516. };
  45517. class TreeView::TreeViewport : public Viewport
  45518. {
  45519. public:
  45520. TreeViewport() throw() : lastX (-1) {}
  45521. ~TreeViewport() throw() {}
  45522. void updateComponents (const bool triggerResize = false)
  45523. {
  45524. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45525. if (tvc != 0)
  45526. {
  45527. if (triggerResize)
  45528. tvc->resized();
  45529. else
  45530. tvc->updateComponents();
  45531. }
  45532. repaint();
  45533. }
  45534. void visibleAreaChanged (int x, int, int, int)
  45535. {
  45536. const bool hasScrolledSideways = (x != lastX);
  45537. lastX = x;
  45538. updateComponents (hasScrolledSideways);
  45539. }
  45540. juce_UseDebuggingNewOperator
  45541. private:
  45542. int lastX;
  45543. TreeViewport (const TreeViewport&);
  45544. TreeViewport& operator= (const TreeViewport&);
  45545. };
  45546. TreeView::TreeView (const String& componentName)
  45547. : Component (componentName),
  45548. rootItem (0),
  45549. indentSize (24),
  45550. defaultOpenness (false),
  45551. needsRecalculating (true),
  45552. rootItemVisible (true),
  45553. multiSelectEnabled (false),
  45554. openCloseButtonsVisible (true)
  45555. {
  45556. addAndMakeVisible (viewport = new TreeViewport());
  45557. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45558. viewport->setWantsKeyboardFocus (false);
  45559. setWantsKeyboardFocus (true);
  45560. }
  45561. TreeView::~TreeView()
  45562. {
  45563. if (rootItem != 0)
  45564. rootItem->setOwnerView (0);
  45565. }
  45566. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45567. {
  45568. if (rootItem != newRootItem)
  45569. {
  45570. if (newRootItem != 0)
  45571. {
  45572. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45573. if (newRootItem->ownerView != 0)
  45574. newRootItem->ownerView->setRootItem (0);
  45575. }
  45576. if (rootItem != 0)
  45577. rootItem->setOwnerView (0);
  45578. rootItem = newRootItem;
  45579. if (newRootItem != 0)
  45580. newRootItem->setOwnerView (this);
  45581. needsRecalculating = true;
  45582. handleAsyncUpdate();
  45583. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45584. {
  45585. rootItem->setOpen (false); // force a re-open
  45586. rootItem->setOpen (true);
  45587. }
  45588. }
  45589. }
  45590. void TreeView::deleteRootItem()
  45591. {
  45592. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45593. setRootItem (0);
  45594. }
  45595. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45596. {
  45597. rootItemVisible = shouldBeVisible;
  45598. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45599. {
  45600. rootItem->setOpen (false); // force a re-open
  45601. rootItem->setOpen (true);
  45602. }
  45603. itemsChanged();
  45604. }
  45605. void TreeView::colourChanged()
  45606. {
  45607. setOpaque (findColour (backgroundColourId).isOpaque());
  45608. repaint();
  45609. }
  45610. void TreeView::setIndentSize (const int newIndentSize)
  45611. {
  45612. if (indentSize != newIndentSize)
  45613. {
  45614. indentSize = newIndentSize;
  45615. resized();
  45616. }
  45617. }
  45618. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45619. {
  45620. if (defaultOpenness != isOpenByDefault)
  45621. {
  45622. defaultOpenness = isOpenByDefault;
  45623. itemsChanged();
  45624. }
  45625. }
  45626. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45627. {
  45628. multiSelectEnabled = canMultiSelect;
  45629. }
  45630. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45631. {
  45632. if (openCloseButtonsVisible != shouldBeVisible)
  45633. {
  45634. openCloseButtonsVisible = shouldBeVisible;
  45635. itemsChanged();
  45636. }
  45637. }
  45638. Viewport* TreeView::getViewport() const throw()
  45639. {
  45640. return viewport;
  45641. }
  45642. void TreeView::clearSelectedItems()
  45643. {
  45644. if (rootItem != 0)
  45645. rootItem->deselectAllRecursively();
  45646. }
  45647. int TreeView::getNumSelectedItems() const throw()
  45648. {
  45649. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45650. }
  45651. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45652. {
  45653. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45654. }
  45655. int TreeView::getNumRowsInTree() const
  45656. {
  45657. if (rootItem != 0)
  45658. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45659. return 0;
  45660. }
  45661. TreeViewItem* TreeView::getItemOnRow (int index) const
  45662. {
  45663. if (! rootItemVisible)
  45664. ++index;
  45665. if (rootItem != 0 && index >= 0)
  45666. return rootItem->getItemOnRow (index);
  45667. return 0;
  45668. }
  45669. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45670. {
  45671. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45672. Rectangle<int> pos;
  45673. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45674. }
  45675. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45676. {
  45677. if (rootItem == 0)
  45678. return 0;
  45679. return rootItem->findItemFromIdentifierString (identifierString);
  45680. }
  45681. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45682. {
  45683. XmlElement* e = 0;
  45684. if (rootItem != 0)
  45685. {
  45686. e = rootItem->getOpennessState();
  45687. if (e != 0 && alsoIncludeScrollPosition)
  45688. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45689. }
  45690. return e;
  45691. }
  45692. void TreeView::restoreOpennessState (const XmlElement& newState)
  45693. {
  45694. if (rootItem != 0)
  45695. {
  45696. rootItem->restoreOpennessState (newState);
  45697. if (newState.hasAttribute ("scrollPos"))
  45698. viewport->setViewPosition (viewport->getViewPositionX(),
  45699. newState.getIntAttribute ("scrollPos"));
  45700. }
  45701. }
  45702. void TreeView::paint (Graphics& g)
  45703. {
  45704. g.fillAll (findColour (backgroundColourId));
  45705. }
  45706. void TreeView::resized()
  45707. {
  45708. viewport->setBounds (getLocalBounds());
  45709. itemsChanged();
  45710. handleAsyncUpdate();
  45711. }
  45712. void TreeView::enablementChanged()
  45713. {
  45714. repaint();
  45715. }
  45716. void TreeView::moveSelectedRow (int delta)
  45717. {
  45718. if (delta == 0)
  45719. return;
  45720. int rowSelected = 0;
  45721. TreeViewItem* const firstSelected = getSelectedItem (0);
  45722. if (firstSelected != 0)
  45723. rowSelected = firstSelected->getRowNumberInTree();
  45724. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45725. for (;;)
  45726. {
  45727. TreeViewItem* item = getItemOnRow (rowSelected);
  45728. if (item != 0)
  45729. {
  45730. if (! item->canBeSelected())
  45731. {
  45732. // if the row we want to highlight doesn't allow it, try skipping
  45733. // to the next item..
  45734. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45735. rowSelected + (delta < 0 ? -1 : 1));
  45736. if (rowSelected != nextRowToTry)
  45737. {
  45738. rowSelected = nextRowToTry;
  45739. continue;
  45740. }
  45741. else
  45742. {
  45743. break;
  45744. }
  45745. }
  45746. item->setSelected (true, true);
  45747. scrollToKeepItemVisible (item);
  45748. }
  45749. break;
  45750. }
  45751. }
  45752. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45753. {
  45754. if (item != 0 && item->ownerView == this)
  45755. {
  45756. handleAsyncUpdate();
  45757. item = item->getDeepestOpenParentItem();
  45758. int y = item->y;
  45759. int viewTop = viewport->getViewPositionY();
  45760. if (y < viewTop)
  45761. {
  45762. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45763. }
  45764. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45765. {
  45766. viewport->setViewPosition (viewport->getViewPositionX(),
  45767. (y + item->itemHeight) - viewport->getViewHeight());
  45768. }
  45769. }
  45770. }
  45771. bool TreeView::keyPressed (const KeyPress& key)
  45772. {
  45773. if (key.isKeyCode (KeyPress::upKey))
  45774. {
  45775. moveSelectedRow (-1);
  45776. }
  45777. else if (key.isKeyCode (KeyPress::downKey))
  45778. {
  45779. moveSelectedRow (1);
  45780. }
  45781. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45782. {
  45783. if (rootItem != 0)
  45784. {
  45785. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45786. if (key.isKeyCode (KeyPress::pageUpKey))
  45787. rowsOnScreen = -rowsOnScreen;
  45788. moveSelectedRow (rowsOnScreen);
  45789. }
  45790. }
  45791. else if (key.isKeyCode (KeyPress::homeKey))
  45792. {
  45793. moveSelectedRow (-0x3fffffff);
  45794. }
  45795. else if (key.isKeyCode (KeyPress::endKey))
  45796. {
  45797. moveSelectedRow (0x3fffffff);
  45798. }
  45799. else if (key.isKeyCode (KeyPress::returnKey))
  45800. {
  45801. TreeViewItem* const firstSelected = getSelectedItem (0);
  45802. if (firstSelected != 0)
  45803. firstSelected->setOpen (! firstSelected->isOpen());
  45804. }
  45805. else if (key.isKeyCode (KeyPress::leftKey))
  45806. {
  45807. TreeViewItem* const firstSelected = getSelectedItem (0);
  45808. if (firstSelected != 0)
  45809. {
  45810. if (firstSelected->isOpen())
  45811. {
  45812. firstSelected->setOpen (false);
  45813. }
  45814. else
  45815. {
  45816. TreeViewItem* parent = firstSelected->parentItem;
  45817. if ((! rootItemVisible) && parent == rootItem)
  45818. parent = 0;
  45819. if (parent != 0)
  45820. {
  45821. parent->setSelected (true, true);
  45822. scrollToKeepItemVisible (parent);
  45823. }
  45824. }
  45825. }
  45826. }
  45827. else if (key.isKeyCode (KeyPress::rightKey))
  45828. {
  45829. TreeViewItem* const firstSelected = getSelectedItem (0);
  45830. if (firstSelected != 0)
  45831. {
  45832. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45833. moveSelectedRow (1);
  45834. else
  45835. firstSelected->setOpen (true);
  45836. }
  45837. }
  45838. else
  45839. {
  45840. return false;
  45841. }
  45842. return true;
  45843. }
  45844. void TreeView::itemsChanged() throw()
  45845. {
  45846. needsRecalculating = true;
  45847. repaint();
  45848. triggerAsyncUpdate();
  45849. }
  45850. void TreeView::handleAsyncUpdate()
  45851. {
  45852. if (needsRecalculating)
  45853. {
  45854. needsRecalculating = false;
  45855. const ScopedLock sl (nodeAlterationLock);
  45856. if (rootItem != 0)
  45857. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45858. viewport->updateComponents();
  45859. if (rootItem != 0)
  45860. {
  45861. viewport->getViewedComponent()
  45862. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45863. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45864. }
  45865. else
  45866. {
  45867. viewport->getViewedComponent()->setSize (0, 0);
  45868. }
  45869. }
  45870. }
  45871. class TreeView::InsertPointHighlight : public Component
  45872. {
  45873. public:
  45874. InsertPointHighlight()
  45875. : lastItem (0)
  45876. {
  45877. setSize (100, 12);
  45878. setAlwaysOnTop (true);
  45879. setInterceptsMouseClicks (false, false);
  45880. }
  45881. ~InsertPointHighlight() {}
  45882. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45883. {
  45884. lastItem = item;
  45885. lastIndex = insertIndex;
  45886. const int offset = getHeight() / 2;
  45887. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45888. }
  45889. void paint (Graphics& g)
  45890. {
  45891. Path p;
  45892. const float h = (float) getHeight();
  45893. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45894. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45895. p.lineTo ((float) getWidth(), h / 2.0f);
  45896. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45897. g.strokePath (p, PathStrokeType (2.0f));
  45898. }
  45899. TreeViewItem* lastItem;
  45900. int lastIndex;
  45901. private:
  45902. InsertPointHighlight (const InsertPointHighlight&);
  45903. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45904. };
  45905. class TreeView::TargetGroupHighlight : public Component
  45906. {
  45907. public:
  45908. TargetGroupHighlight()
  45909. {
  45910. setAlwaysOnTop (true);
  45911. setInterceptsMouseClicks (false, false);
  45912. }
  45913. ~TargetGroupHighlight() {}
  45914. void setTargetPosition (TreeViewItem* const item) throw()
  45915. {
  45916. Rectangle<int> r (item->getItemPosition (true));
  45917. r.setHeight (item->getItemHeight());
  45918. setBounds (r);
  45919. }
  45920. void paint (Graphics& g)
  45921. {
  45922. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45923. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45924. }
  45925. private:
  45926. TargetGroupHighlight (const TargetGroupHighlight&);
  45927. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45928. };
  45929. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45930. {
  45931. beginDragAutoRepeat (100);
  45932. if (dragInsertPointHighlight == 0)
  45933. {
  45934. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45935. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45936. }
  45937. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45938. dragTargetGroupHighlight->setTargetPosition (item);
  45939. }
  45940. void TreeView::hideDragHighlight() throw()
  45941. {
  45942. dragInsertPointHighlight = 0;
  45943. dragTargetGroupHighlight = 0;
  45944. }
  45945. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45946. const StringArray& files, const String& sourceDescription,
  45947. Component* sourceComponent) const throw()
  45948. {
  45949. insertIndex = 0;
  45950. TreeViewItem* item = getItemAt (y);
  45951. if (item == 0)
  45952. return 0;
  45953. Rectangle<int> itemPos (item->getItemPosition (true));
  45954. insertIndex = item->getIndexInParent();
  45955. const int oldY = y;
  45956. y = itemPos.getY();
  45957. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45958. {
  45959. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45960. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45961. {
  45962. // Check if we're trying to drag into an empty group item..
  45963. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45964. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45965. {
  45966. insertIndex = 0;
  45967. x = itemPos.getX() + getIndentSize();
  45968. y = itemPos.getBottom();
  45969. return item;
  45970. }
  45971. }
  45972. }
  45973. if (oldY > itemPos.getCentreY())
  45974. {
  45975. y += item->getItemHeight();
  45976. while (item->isLastOfSiblings() && item->parentItem != 0
  45977. && item->parentItem->parentItem != 0)
  45978. {
  45979. if (x > itemPos.getX())
  45980. break;
  45981. item = item->parentItem;
  45982. itemPos = item->getItemPosition (true);
  45983. insertIndex = item->getIndexInParent();
  45984. }
  45985. ++insertIndex;
  45986. }
  45987. x = itemPos.getX();
  45988. return item->parentItem;
  45989. }
  45990. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45991. {
  45992. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45993. int insertIndex;
  45994. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45995. if (item != 0)
  45996. {
  45997. if (scrolled || dragInsertPointHighlight == 0
  45998. || dragInsertPointHighlight->lastItem != item
  45999. || dragInsertPointHighlight->lastIndex != insertIndex)
  46000. {
  46001. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46002. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46003. showDragHighlight (item, insertIndex, x, y);
  46004. else
  46005. hideDragHighlight();
  46006. }
  46007. }
  46008. else
  46009. {
  46010. hideDragHighlight();
  46011. }
  46012. }
  46013. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46014. {
  46015. hideDragHighlight();
  46016. int insertIndex;
  46017. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46018. if (item != 0)
  46019. {
  46020. if (files.size() > 0)
  46021. {
  46022. if (item->isInterestedInFileDrag (files))
  46023. item->filesDropped (files, insertIndex);
  46024. }
  46025. else
  46026. {
  46027. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46028. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46029. }
  46030. }
  46031. }
  46032. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46033. {
  46034. return true;
  46035. }
  46036. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46037. {
  46038. fileDragMove (files, x, y);
  46039. }
  46040. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46041. {
  46042. handleDrag (files, String::empty, 0, x, y);
  46043. }
  46044. void TreeView::fileDragExit (const StringArray&)
  46045. {
  46046. hideDragHighlight();
  46047. }
  46048. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46049. {
  46050. handleDrop (files, String::empty, 0, x, y);
  46051. }
  46052. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46053. {
  46054. return true;
  46055. }
  46056. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46057. {
  46058. itemDragMove (sourceDescription, sourceComponent, x, y);
  46059. }
  46060. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46061. {
  46062. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46063. }
  46064. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46065. {
  46066. hideDragHighlight();
  46067. }
  46068. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46069. {
  46070. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46071. }
  46072. enum TreeViewOpenness
  46073. {
  46074. opennessDefault = 0,
  46075. opennessClosed = 1,
  46076. opennessOpen = 2
  46077. };
  46078. TreeViewItem::TreeViewItem()
  46079. : ownerView (0),
  46080. parentItem (0),
  46081. y (0),
  46082. itemHeight (0),
  46083. totalHeight (0),
  46084. selected (false),
  46085. redrawNeeded (true),
  46086. drawLinesInside (true),
  46087. drawsInLeftMargin (false),
  46088. openness (opennessDefault)
  46089. {
  46090. static int nextUID = 0;
  46091. uid = nextUID++;
  46092. }
  46093. TreeViewItem::~TreeViewItem()
  46094. {
  46095. }
  46096. const String TreeViewItem::getUniqueName() const
  46097. {
  46098. return String::empty;
  46099. }
  46100. void TreeViewItem::itemOpennessChanged (bool)
  46101. {
  46102. }
  46103. int TreeViewItem::getNumSubItems() const throw()
  46104. {
  46105. return subItems.size();
  46106. }
  46107. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46108. {
  46109. return subItems [index];
  46110. }
  46111. void TreeViewItem::clearSubItems()
  46112. {
  46113. if (subItems.size() > 0)
  46114. {
  46115. if (ownerView != 0)
  46116. {
  46117. const ScopedLock sl (ownerView->nodeAlterationLock);
  46118. subItems.clear();
  46119. treeHasChanged();
  46120. }
  46121. else
  46122. {
  46123. subItems.clear();
  46124. }
  46125. }
  46126. }
  46127. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46128. {
  46129. if (newItem != 0)
  46130. {
  46131. newItem->parentItem = this;
  46132. newItem->setOwnerView (ownerView);
  46133. newItem->y = 0;
  46134. newItem->itemHeight = newItem->getItemHeight();
  46135. newItem->totalHeight = 0;
  46136. newItem->itemWidth = newItem->getItemWidth();
  46137. newItem->totalWidth = 0;
  46138. if (ownerView != 0)
  46139. {
  46140. const ScopedLock sl (ownerView->nodeAlterationLock);
  46141. subItems.insert (insertPosition, newItem);
  46142. treeHasChanged();
  46143. if (newItem->isOpen())
  46144. newItem->itemOpennessChanged (true);
  46145. }
  46146. else
  46147. {
  46148. subItems.insert (insertPosition, newItem);
  46149. if (newItem->isOpen())
  46150. newItem->itemOpennessChanged (true);
  46151. }
  46152. }
  46153. }
  46154. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46155. {
  46156. if (ownerView != 0)
  46157. {
  46158. const ScopedLock sl (ownerView->nodeAlterationLock);
  46159. if (((unsigned int) index) < (unsigned int) subItems.size())
  46160. {
  46161. subItems.remove (index, deleteItem);
  46162. treeHasChanged();
  46163. }
  46164. }
  46165. else
  46166. {
  46167. subItems.remove (index, deleteItem);
  46168. }
  46169. }
  46170. bool TreeViewItem::isOpen() const throw()
  46171. {
  46172. if (openness == opennessDefault)
  46173. return ownerView != 0 && ownerView->defaultOpenness;
  46174. else
  46175. return openness == opennessOpen;
  46176. }
  46177. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46178. {
  46179. if (isOpen() != shouldBeOpen)
  46180. {
  46181. openness = shouldBeOpen ? opennessOpen
  46182. : opennessClosed;
  46183. treeHasChanged();
  46184. itemOpennessChanged (isOpen());
  46185. }
  46186. }
  46187. bool TreeViewItem::isSelected() const throw()
  46188. {
  46189. return selected;
  46190. }
  46191. void TreeViewItem::deselectAllRecursively()
  46192. {
  46193. setSelected (false, false);
  46194. for (int i = 0; i < subItems.size(); ++i)
  46195. subItems.getUnchecked(i)->deselectAllRecursively();
  46196. }
  46197. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46198. const bool deselectOtherItemsFirst)
  46199. {
  46200. if (shouldBeSelected && ! canBeSelected())
  46201. return;
  46202. if (deselectOtherItemsFirst)
  46203. getTopLevelItem()->deselectAllRecursively();
  46204. if (shouldBeSelected != selected)
  46205. {
  46206. selected = shouldBeSelected;
  46207. if (ownerView != 0)
  46208. ownerView->repaint();
  46209. itemSelectionChanged (shouldBeSelected);
  46210. }
  46211. }
  46212. void TreeViewItem::paintItem (Graphics&, int, int)
  46213. {
  46214. }
  46215. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46216. {
  46217. ownerView->getLookAndFeel()
  46218. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46219. }
  46220. void TreeViewItem::itemClicked (const MouseEvent&)
  46221. {
  46222. }
  46223. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46224. {
  46225. if (mightContainSubItems())
  46226. setOpen (! isOpen());
  46227. }
  46228. void TreeViewItem::itemSelectionChanged (bool)
  46229. {
  46230. }
  46231. const String TreeViewItem::getTooltip()
  46232. {
  46233. return String::empty;
  46234. }
  46235. const String TreeViewItem::getDragSourceDescription()
  46236. {
  46237. return String::empty;
  46238. }
  46239. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46240. {
  46241. return false;
  46242. }
  46243. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46244. {
  46245. }
  46246. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46247. {
  46248. return false;
  46249. }
  46250. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46251. {
  46252. }
  46253. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46254. {
  46255. const int indentX = getIndentX();
  46256. int width = itemWidth;
  46257. if (ownerView != 0 && width < 0)
  46258. width = ownerView->viewport->getViewWidth() - indentX;
  46259. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46260. if (relativeToTreeViewTopLeft)
  46261. r -= ownerView->viewport->getViewPosition();
  46262. return r;
  46263. }
  46264. void TreeViewItem::treeHasChanged() const throw()
  46265. {
  46266. if (ownerView != 0)
  46267. ownerView->itemsChanged();
  46268. }
  46269. void TreeViewItem::repaintItem() const
  46270. {
  46271. if (ownerView != 0 && areAllParentsOpen())
  46272. {
  46273. Rectangle<int> r (getItemPosition (true));
  46274. r.setLeft (0);
  46275. ownerView->viewport->repaint (r);
  46276. }
  46277. }
  46278. bool TreeViewItem::areAllParentsOpen() const throw()
  46279. {
  46280. return parentItem == 0
  46281. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46282. }
  46283. void TreeViewItem::updatePositions (int newY)
  46284. {
  46285. y = newY;
  46286. itemHeight = getItemHeight();
  46287. totalHeight = itemHeight;
  46288. itemWidth = getItemWidth();
  46289. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46290. if (isOpen())
  46291. {
  46292. newY += totalHeight;
  46293. for (int i = 0; i < subItems.size(); ++i)
  46294. {
  46295. TreeViewItem* const ti = subItems.getUnchecked(i);
  46296. ti->updatePositions (newY);
  46297. newY += ti->totalHeight;
  46298. totalHeight += ti->totalHeight;
  46299. totalWidth = jmax (totalWidth, ti->totalWidth);
  46300. }
  46301. }
  46302. }
  46303. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46304. {
  46305. TreeViewItem* result = this;
  46306. TreeViewItem* item = this;
  46307. while (item->parentItem != 0)
  46308. {
  46309. item = item->parentItem;
  46310. if (! item->isOpen())
  46311. result = item;
  46312. }
  46313. return result;
  46314. }
  46315. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46316. {
  46317. ownerView = newOwner;
  46318. for (int i = subItems.size(); --i >= 0;)
  46319. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46320. }
  46321. int TreeViewItem::getIndentX() const throw()
  46322. {
  46323. const int indentWidth = ownerView->getIndentSize();
  46324. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46325. if (! ownerView->openCloseButtonsVisible)
  46326. x -= indentWidth;
  46327. TreeViewItem* p = parentItem;
  46328. while (p != 0)
  46329. {
  46330. x += indentWidth;
  46331. p = p->parentItem;
  46332. }
  46333. return x;
  46334. }
  46335. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46336. {
  46337. drawsInLeftMargin = canDrawInLeftMargin;
  46338. }
  46339. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46340. {
  46341. jassert (ownerView != 0);
  46342. if (ownerView == 0)
  46343. return;
  46344. const int indent = getIndentX();
  46345. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46346. {
  46347. g.saveState();
  46348. g.setOrigin (indent, 0);
  46349. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46350. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46351. paintItem (g, itemW, itemHeight);
  46352. g.restoreState();
  46353. }
  46354. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46355. const float halfH = itemHeight * 0.5f;
  46356. int depth = 0;
  46357. TreeViewItem* p = parentItem;
  46358. while (p != 0)
  46359. {
  46360. ++depth;
  46361. p = p->parentItem;
  46362. }
  46363. if (! ownerView->rootItemVisible)
  46364. --depth;
  46365. const int indentWidth = ownerView->getIndentSize();
  46366. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46367. {
  46368. float x = (depth + 0.5f) * indentWidth;
  46369. if (depth >= 0)
  46370. {
  46371. if (parentItem != 0 && parentItem->drawLinesInside)
  46372. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46373. if ((parentItem != 0 && parentItem->drawLinesInside)
  46374. || (parentItem == 0 && drawLinesInside))
  46375. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46376. }
  46377. p = parentItem;
  46378. int d = depth;
  46379. while (p != 0 && --d >= 0)
  46380. {
  46381. x -= (float) indentWidth;
  46382. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46383. && ! p->isLastOfSiblings())
  46384. {
  46385. g.drawLine (x, 0, x, (float) itemHeight);
  46386. }
  46387. p = p->parentItem;
  46388. }
  46389. if (mightContainSubItems())
  46390. {
  46391. g.saveState();
  46392. g.setOrigin (depth * indentWidth, 0);
  46393. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46394. paintOpenCloseButton (g, indentWidth, itemHeight,
  46395. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46396. ->isMouseOverButton (this));
  46397. g.restoreState();
  46398. }
  46399. }
  46400. if (isOpen())
  46401. {
  46402. const Rectangle<int> clip (g.getClipBounds());
  46403. for (int i = 0; i < subItems.size(); ++i)
  46404. {
  46405. TreeViewItem* const ti = subItems.getUnchecked(i);
  46406. const int relY = ti->y - y;
  46407. if (relY >= clip.getBottom())
  46408. break;
  46409. if (relY + ti->totalHeight >= clip.getY())
  46410. {
  46411. g.saveState();
  46412. g.setOrigin (0, relY);
  46413. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46414. ti->paintRecursively (g, width);
  46415. g.restoreState();
  46416. }
  46417. }
  46418. }
  46419. }
  46420. bool TreeViewItem::isLastOfSiblings() const throw()
  46421. {
  46422. return parentItem == 0
  46423. || parentItem->subItems.getLast() == this;
  46424. }
  46425. int TreeViewItem::getIndexInParent() const throw()
  46426. {
  46427. if (parentItem == 0)
  46428. return 0;
  46429. return parentItem->subItems.indexOf (this);
  46430. }
  46431. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46432. {
  46433. return (parentItem == 0) ? this
  46434. : parentItem->getTopLevelItem();
  46435. }
  46436. int TreeViewItem::getNumRows() const throw()
  46437. {
  46438. int num = 1;
  46439. if (isOpen())
  46440. {
  46441. for (int i = subItems.size(); --i >= 0;)
  46442. num += subItems.getUnchecked(i)->getNumRows();
  46443. }
  46444. return num;
  46445. }
  46446. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46447. {
  46448. if (index == 0)
  46449. return this;
  46450. if (index > 0 && isOpen())
  46451. {
  46452. --index;
  46453. for (int i = 0; i < subItems.size(); ++i)
  46454. {
  46455. TreeViewItem* const item = subItems.getUnchecked(i);
  46456. if (index == 0)
  46457. return item;
  46458. const int numRows = item->getNumRows();
  46459. if (numRows > index)
  46460. return item->getItemOnRow (index);
  46461. index -= numRows;
  46462. }
  46463. }
  46464. return 0;
  46465. }
  46466. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46467. {
  46468. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46469. {
  46470. const int h = itemHeight;
  46471. if (targetY < h)
  46472. return this;
  46473. if (isOpen())
  46474. {
  46475. targetY -= h;
  46476. for (int i = 0; i < subItems.size(); ++i)
  46477. {
  46478. TreeViewItem* const ti = subItems.getUnchecked(i);
  46479. if (targetY < ti->totalHeight)
  46480. return ti->findItemRecursively (targetY);
  46481. targetY -= ti->totalHeight;
  46482. }
  46483. }
  46484. }
  46485. return 0;
  46486. }
  46487. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46488. {
  46489. int total = 0;
  46490. if (isSelected())
  46491. ++total;
  46492. for (int i = subItems.size(); --i >= 0;)
  46493. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46494. return total;
  46495. }
  46496. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46497. {
  46498. if (isSelected())
  46499. {
  46500. if (index == 0)
  46501. return this;
  46502. --index;
  46503. }
  46504. if (index >= 0)
  46505. {
  46506. for (int i = 0; i < subItems.size(); ++i)
  46507. {
  46508. TreeViewItem* const item = subItems.getUnchecked(i);
  46509. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46510. if (found != 0)
  46511. return found;
  46512. index -= item->countSelectedItemsRecursively();
  46513. }
  46514. }
  46515. return 0;
  46516. }
  46517. int TreeViewItem::getRowNumberInTree() const throw()
  46518. {
  46519. if (parentItem != 0 && ownerView != 0)
  46520. {
  46521. int n = 1 + parentItem->getRowNumberInTree();
  46522. int ourIndex = parentItem->subItems.indexOf (this);
  46523. jassert (ourIndex >= 0);
  46524. while (--ourIndex >= 0)
  46525. n += parentItem->subItems [ourIndex]->getNumRows();
  46526. if (parentItem->parentItem == 0
  46527. && ! ownerView->rootItemVisible)
  46528. --n;
  46529. return n;
  46530. }
  46531. else
  46532. {
  46533. return 0;
  46534. }
  46535. }
  46536. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46537. {
  46538. drawLinesInside = drawLines;
  46539. }
  46540. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46541. {
  46542. if (recurse && isOpen() && subItems.size() > 0)
  46543. return subItems [0];
  46544. if (parentItem != 0)
  46545. {
  46546. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46547. if (nextIndex >= parentItem->subItems.size())
  46548. return parentItem->getNextVisibleItem (false);
  46549. return parentItem->subItems [nextIndex];
  46550. }
  46551. return 0;
  46552. }
  46553. const String TreeViewItem::getItemIdentifierString() const
  46554. {
  46555. String s;
  46556. if (parentItem != 0)
  46557. s = parentItem->getItemIdentifierString();
  46558. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46559. }
  46560. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46561. {
  46562. const String thisId (getUniqueName());
  46563. if (thisId == identifierString)
  46564. return this;
  46565. if (identifierString.startsWith (thisId + "/"))
  46566. {
  46567. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46568. bool wasOpen = isOpen();
  46569. setOpen (true);
  46570. for (int i = subItems.size(); --i >= 0;)
  46571. {
  46572. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46573. if (item != 0)
  46574. return item;
  46575. }
  46576. setOpen (wasOpen);
  46577. }
  46578. return 0;
  46579. }
  46580. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46581. {
  46582. if (e.hasTagName ("CLOSED"))
  46583. {
  46584. setOpen (false);
  46585. }
  46586. else if (e.hasTagName ("OPEN"))
  46587. {
  46588. setOpen (true);
  46589. forEachXmlChildElement (e, n)
  46590. {
  46591. const String id (n->getStringAttribute ("id"));
  46592. for (int i = 0; i < subItems.size(); ++i)
  46593. {
  46594. TreeViewItem* const ti = subItems.getUnchecked(i);
  46595. if (ti->getUniqueName() == id)
  46596. {
  46597. ti->restoreOpennessState (*n);
  46598. break;
  46599. }
  46600. }
  46601. }
  46602. }
  46603. }
  46604. XmlElement* TreeViewItem::getOpennessState() const throw()
  46605. {
  46606. const String name (getUniqueName());
  46607. if (name.isNotEmpty())
  46608. {
  46609. XmlElement* e;
  46610. if (isOpen())
  46611. {
  46612. e = new XmlElement ("OPEN");
  46613. for (int i = 0; i < subItems.size(); ++i)
  46614. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46615. }
  46616. else
  46617. {
  46618. e = new XmlElement ("CLOSED");
  46619. }
  46620. e->setAttribute ("id", name);
  46621. return e;
  46622. }
  46623. else
  46624. {
  46625. // trying to save the openness for an element that has no name - this won't
  46626. // work because it needs the names to identify what to open.
  46627. jassertfalse;
  46628. }
  46629. return 0;
  46630. }
  46631. END_JUCE_NAMESPACE
  46632. /*** End of inlined file: juce_TreeView.cpp ***/
  46633. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46634. BEGIN_JUCE_NAMESPACE
  46635. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46636. : fileList (listToShow)
  46637. {
  46638. }
  46639. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46640. {
  46641. }
  46642. FileBrowserListener::~FileBrowserListener()
  46643. {
  46644. }
  46645. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46646. {
  46647. listeners.add (listener);
  46648. }
  46649. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46650. {
  46651. listeners.remove (listener);
  46652. }
  46653. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46654. {
  46655. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46656. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46657. }
  46658. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46659. {
  46660. if (fileList.getDirectory().exists())
  46661. {
  46662. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46663. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46664. }
  46665. }
  46666. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46667. {
  46668. if (fileList.getDirectory().exists())
  46669. {
  46670. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46671. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46672. }
  46673. }
  46674. END_JUCE_NAMESPACE
  46675. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46676. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46677. BEGIN_JUCE_NAMESPACE
  46678. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46679. TimeSliceThread& thread_)
  46680. : fileFilter (fileFilter_),
  46681. thread (thread_),
  46682. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46683. fileFindHandle (0),
  46684. shouldStop (true)
  46685. {
  46686. }
  46687. DirectoryContentsList::~DirectoryContentsList()
  46688. {
  46689. clear();
  46690. }
  46691. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46692. {
  46693. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46694. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46695. }
  46696. bool DirectoryContentsList::ignoresHiddenFiles() const
  46697. {
  46698. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46699. }
  46700. const File& DirectoryContentsList::getDirectory() const
  46701. {
  46702. return root;
  46703. }
  46704. void DirectoryContentsList::setDirectory (const File& directory,
  46705. const bool includeDirectories,
  46706. const bool includeFiles)
  46707. {
  46708. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46709. if (directory != root)
  46710. {
  46711. clear();
  46712. root = directory;
  46713. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46714. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46715. }
  46716. int newFlags = fileTypeFlags;
  46717. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46718. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46719. setTypeFlags (newFlags);
  46720. }
  46721. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46722. {
  46723. if (fileTypeFlags != newFlags)
  46724. {
  46725. fileTypeFlags = newFlags;
  46726. refresh();
  46727. }
  46728. }
  46729. void DirectoryContentsList::clear()
  46730. {
  46731. shouldStop = true;
  46732. thread.removeTimeSliceClient (this);
  46733. fileFindHandle = 0;
  46734. if (files.size() > 0)
  46735. {
  46736. files.clear();
  46737. changed();
  46738. }
  46739. }
  46740. void DirectoryContentsList::refresh()
  46741. {
  46742. clear();
  46743. if (root.isDirectory())
  46744. {
  46745. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46746. shouldStop = false;
  46747. thread.addTimeSliceClient (this);
  46748. }
  46749. }
  46750. int DirectoryContentsList::getNumFiles() const
  46751. {
  46752. return files.size();
  46753. }
  46754. bool DirectoryContentsList::getFileInfo (const int index,
  46755. FileInfo& result) const
  46756. {
  46757. const ScopedLock sl (fileListLock);
  46758. const FileInfo* const info = files [index];
  46759. if (info != 0)
  46760. {
  46761. result = *info;
  46762. return true;
  46763. }
  46764. return false;
  46765. }
  46766. const File DirectoryContentsList::getFile (const int index) const
  46767. {
  46768. const ScopedLock sl (fileListLock);
  46769. const FileInfo* const info = files [index];
  46770. if (info != 0)
  46771. return root.getChildFile (info->filename);
  46772. return File::nonexistent;
  46773. }
  46774. bool DirectoryContentsList::isStillLoading() const
  46775. {
  46776. return fileFindHandle != 0;
  46777. }
  46778. void DirectoryContentsList::changed()
  46779. {
  46780. sendChangeMessage (this);
  46781. }
  46782. bool DirectoryContentsList::useTimeSlice()
  46783. {
  46784. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46785. bool hasChanged = false;
  46786. for (int i = 100; --i >= 0;)
  46787. {
  46788. if (! checkNextFile (hasChanged))
  46789. {
  46790. if (hasChanged)
  46791. changed();
  46792. return false;
  46793. }
  46794. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46795. break;
  46796. }
  46797. if (hasChanged)
  46798. changed();
  46799. return true;
  46800. }
  46801. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46802. {
  46803. if (fileFindHandle != 0)
  46804. {
  46805. bool fileFoundIsDir, isHidden, isReadOnly;
  46806. int64 fileSize;
  46807. Time modTime, creationTime;
  46808. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46809. &modTime, &creationTime, &isReadOnly))
  46810. {
  46811. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46812. fileSize, modTime, creationTime, isReadOnly))
  46813. {
  46814. hasChanged = true;
  46815. }
  46816. return true;
  46817. }
  46818. else
  46819. {
  46820. fileFindHandle = 0;
  46821. }
  46822. }
  46823. return false;
  46824. }
  46825. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46826. const DirectoryContentsList::FileInfo* const second)
  46827. {
  46828. #if JUCE_WINDOWS
  46829. if (first->isDirectory != second->isDirectory)
  46830. return first->isDirectory ? -1 : 1;
  46831. #endif
  46832. return first->filename.compareIgnoreCase (second->filename);
  46833. }
  46834. bool DirectoryContentsList::addFile (const File& file,
  46835. const bool isDir,
  46836. const int64 fileSize,
  46837. const Time& modTime,
  46838. const Time& creationTime,
  46839. const bool isReadOnly)
  46840. {
  46841. if (fileFilter == 0
  46842. || ((! isDir) && fileFilter->isFileSuitable (file))
  46843. || (isDir && fileFilter->isDirectorySuitable (file)))
  46844. {
  46845. ScopedPointer <FileInfo> info (new FileInfo());
  46846. info->filename = file.getFileName();
  46847. info->fileSize = fileSize;
  46848. info->modificationTime = modTime;
  46849. info->creationTime = creationTime;
  46850. info->isDirectory = isDir;
  46851. info->isReadOnly = isReadOnly;
  46852. const ScopedLock sl (fileListLock);
  46853. for (int i = files.size(); --i >= 0;)
  46854. if (files.getUnchecked(i)->filename == info->filename)
  46855. return false;
  46856. files.addSorted (*this, info.release());
  46857. return true;
  46858. }
  46859. return false;
  46860. }
  46861. END_JUCE_NAMESPACE
  46862. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46863. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46864. BEGIN_JUCE_NAMESPACE
  46865. FileBrowserComponent::FileBrowserComponent (int flags_,
  46866. const File& initialFileOrDirectory,
  46867. const FileFilter* fileFilter_,
  46868. FilePreviewComponent* previewComp_)
  46869. : FileFilter (String::empty),
  46870. fileFilter (fileFilter_),
  46871. flags (flags_),
  46872. previewComp (previewComp_),
  46873. thread ("Juce FileBrowser")
  46874. {
  46875. // You need to specify one or other of the open/save flags..
  46876. jassert ((flags & (saveMode | openMode)) != 0);
  46877. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46878. // You need to specify at least one of these flags..
  46879. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46880. String filename;
  46881. if (initialFileOrDirectory == File::nonexistent)
  46882. {
  46883. currentRoot = File::getCurrentWorkingDirectory();
  46884. }
  46885. else if (initialFileOrDirectory.isDirectory())
  46886. {
  46887. currentRoot = initialFileOrDirectory;
  46888. }
  46889. else
  46890. {
  46891. chosenFiles.add (initialFileOrDirectory);
  46892. currentRoot = initialFileOrDirectory.getParentDirectory();
  46893. filename = initialFileOrDirectory.getFileName();
  46894. }
  46895. fileList = new DirectoryContentsList (this, thread);
  46896. if ((flags & useTreeView) != 0)
  46897. {
  46898. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46899. if ((flags & canSelectMultipleItems) != 0)
  46900. tree->setMultiSelectEnabled (true);
  46901. addAndMakeVisible (tree);
  46902. fileListComponent = tree;
  46903. }
  46904. else
  46905. {
  46906. FileListComponent* const list = new FileListComponent (*fileList);
  46907. list->setOutlineThickness (1);
  46908. if ((flags & canSelectMultipleItems) != 0)
  46909. list->setMultipleSelectionEnabled (true);
  46910. addAndMakeVisible (list);
  46911. fileListComponent = list;
  46912. }
  46913. fileListComponent->addListener (this);
  46914. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46915. currentPathBox->setEditableText (true);
  46916. StringArray rootNames, rootPaths;
  46917. const BigInteger separators (getRoots (rootNames, rootPaths));
  46918. for (int i = 0; i < rootNames.size(); ++i)
  46919. {
  46920. if (separators [i])
  46921. currentPathBox->addSeparator();
  46922. currentPathBox->addItem (rootNames[i], i + 1);
  46923. }
  46924. currentPathBox->addSeparator();
  46925. currentPathBox->addListener (this);
  46926. addAndMakeVisible (filenameBox = new TextEditor());
  46927. filenameBox->setMultiLine (false);
  46928. filenameBox->setSelectAllWhenFocused (true);
  46929. filenameBox->setText (filename, false);
  46930. filenameBox->addListener (this);
  46931. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46932. Label* label = new Label ("f", TRANS("file:"));
  46933. addAndMakeVisible (label);
  46934. label->attachToComponent (filenameBox, true);
  46935. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46936. goUpButton->addButtonListener (this);
  46937. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46938. if (previewComp != 0)
  46939. addAndMakeVisible (previewComp);
  46940. setRoot (currentRoot);
  46941. thread.startThread (4);
  46942. }
  46943. FileBrowserComponent::~FileBrowserComponent()
  46944. {
  46945. if (previewComp != 0)
  46946. removeChildComponent (previewComp);
  46947. deleteAllChildren();
  46948. fileList = 0;
  46949. thread.stopThread (10000);
  46950. }
  46951. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46952. {
  46953. listeners.add (newListener);
  46954. }
  46955. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46956. {
  46957. listeners.remove (listener);
  46958. }
  46959. bool FileBrowserComponent::isSaveMode() const throw()
  46960. {
  46961. return (flags & saveMode) != 0;
  46962. }
  46963. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46964. {
  46965. if (chosenFiles.size() == 0 && currentFileIsValid())
  46966. return 1;
  46967. return chosenFiles.size();
  46968. }
  46969. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46970. {
  46971. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46972. return currentRoot;
  46973. if (! filenameBox->isReadOnly())
  46974. return currentRoot.getChildFile (filenameBox->getText());
  46975. return chosenFiles[index];
  46976. }
  46977. bool FileBrowserComponent::currentFileIsValid() const
  46978. {
  46979. if (isSaveMode())
  46980. return ! getSelectedFile (0).isDirectory();
  46981. else
  46982. return getSelectedFile (0).exists();
  46983. }
  46984. const File FileBrowserComponent::getHighlightedFile() const throw()
  46985. {
  46986. return fileListComponent->getSelectedFile (0);
  46987. }
  46988. void FileBrowserComponent::deselectAllFiles()
  46989. {
  46990. fileListComponent->deselectAllFiles();
  46991. }
  46992. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46993. {
  46994. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46995. : false;
  46996. }
  46997. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46998. {
  46999. return true;
  47000. }
  47001. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47002. {
  47003. if (f.isDirectory())
  47004. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47005. return (flags & canSelectFiles) != 0 && f.exists()
  47006. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47007. }
  47008. const File FileBrowserComponent::getRoot() const
  47009. {
  47010. return currentRoot;
  47011. }
  47012. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47013. {
  47014. if (currentRoot != newRootDirectory)
  47015. {
  47016. fileListComponent->scrollToTop();
  47017. String path (newRootDirectory.getFullPathName());
  47018. if (path.isEmpty())
  47019. path = File::separatorString;
  47020. StringArray rootNames, rootPaths;
  47021. getRoots (rootNames, rootPaths);
  47022. if (! rootPaths.contains (path, true))
  47023. {
  47024. bool alreadyListed = false;
  47025. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47026. {
  47027. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47028. {
  47029. alreadyListed = true;
  47030. break;
  47031. }
  47032. }
  47033. if (! alreadyListed)
  47034. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47035. }
  47036. }
  47037. currentRoot = newRootDirectory;
  47038. fileList->setDirectory (currentRoot, true, true);
  47039. String currentRootName (currentRoot.getFullPathName());
  47040. if (currentRootName.isEmpty())
  47041. currentRootName = File::separatorString;
  47042. currentPathBox->setText (currentRootName, true);
  47043. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47044. && currentRoot.getParentDirectory() != currentRoot);
  47045. }
  47046. void FileBrowserComponent::goUp()
  47047. {
  47048. setRoot (getRoot().getParentDirectory());
  47049. }
  47050. void FileBrowserComponent::refresh()
  47051. {
  47052. fileList->refresh();
  47053. }
  47054. const String FileBrowserComponent::getActionVerb() const
  47055. {
  47056. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47057. }
  47058. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47059. {
  47060. return previewComp;
  47061. }
  47062. void FileBrowserComponent::resized()
  47063. {
  47064. getLookAndFeel()
  47065. .layoutFileBrowserComponent (*this, fileListComponent,
  47066. previewComp, currentPathBox,
  47067. filenameBox, goUpButton);
  47068. }
  47069. void FileBrowserComponent::sendListenerChangeMessage()
  47070. {
  47071. Component::BailOutChecker checker (this);
  47072. if (previewComp != 0)
  47073. previewComp->selectedFileChanged (getSelectedFile (0));
  47074. // You shouldn't delete the browser when the file gets changed!
  47075. jassert (! checker.shouldBailOut());
  47076. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47077. }
  47078. void FileBrowserComponent::selectionChanged()
  47079. {
  47080. StringArray newFilenames;
  47081. bool resetChosenFiles = true;
  47082. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47083. {
  47084. const File f (fileListComponent->getSelectedFile (i));
  47085. if (isFileOrDirSuitable (f))
  47086. {
  47087. if (resetChosenFiles)
  47088. {
  47089. chosenFiles.clear();
  47090. resetChosenFiles = false;
  47091. }
  47092. chosenFiles.add (f);
  47093. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47094. }
  47095. }
  47096. if (newFilenames.size() > 0)
  47097. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47098. sendListenerChangeMessage();
  47099. }
  47100. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47101. {
  47102. Component::BailOutChecker checker (this);
  47103. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47104. }
  47105. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47106. {
  47107. if (f.isDirectory())
  47108. {
  47109. setRoot (f);
  47110. if ((flags & canSelectDirectories) != 0)
  47111. filenameBox->setText (String::empty);
  47112. }
  47113. else
  47114. {
  47115. Component::BailOutChecker checker (this);
  47116. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47117. }
  47118. }
  47119. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47120. {
  47121. (void) key;
  47122. #if JUCE_LINUX || JUCE_WINDOWS
  47123. if (key.getModifiers().isCommandDown()
  47124. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47125. {
  47126. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47127. fileList->refresh();
  47128. return true;
  47129. }
  47130. #endif
  47131. return false;
  47132. }
  47133. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47134. {
  47135. sendListenerChangeMessage();
  47136. }
  47137. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47138. {
  47139. if (filenameBox->getText().containsChar (File::separator))
  47140. {
  47141. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47142. if (f.isDirectory())
  47143. {
  47144. setRoot (f);
  47145. chosenFiles.clear();
  47146. filenameBox->setText (String::empty);
  47147. }
  47148. else
  47149. {
  47150. setRoot (f.getParentDirectory());
  47151. chosenFiles.clear();
  47152. chosenFiles.add (f);
  47153. filenameBox->setText (f.getFileName());
  47154. }
  47155. }
  47156. else
  47157. {
  47158. fileDoubleClicked (getSelectedFile (0));
  47159. }
  47160. }
  47161. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47162. {
  47163. }
  47164. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47165. {
  47166. if (! isSaveMode())
  47167. selectionChanged();
  47168. }
  47169. void FileBrowserComponent::buttonClicked (Button*)
  47170. {
  47171. goUp();
  47172. }
  47173. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47174. {
  47175. const String newText (currentPathBox->getText().trim().unquoted());
  47176. if (newText.isNotEmpty())
  47177. {
  47178. const int index = currentPathBox->getSelectedId() - 1;
  47179. StringArray rootNames, rootPaths;
  47180. getRoots (rootNames, rootPaths);
  47181. if (rootPaths [index].isNotEmpty())
  47182. {
  47183. setRoot (File (rootPaths [index]));
  47184. }
  47185. else
  47186. {
  47187. File f (newText);
  47188. for (;;)
  47189. {
  47190. if (f.isDirectory())
  47191. {
  47192. setRoot (f);
  47193. break;
  47194. }
  47195. if (f.getParentDirectory() == f)
  47196. break;
  47197. f = f.getParentDirectory();
  47198. }
  47199. }
  47200. }
  47201. }
  47202. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47203. {
  47204. BigInteger separators;
  47205. #if JUCE_WINDOWS
  47206. Array<File> roots;
  47207. File::findFileSystemRoots (roots);
  47208. rootPaths.clear();
  47209. for (int i = 0; i < roots.size(); ++i)
  47210. {
  47211. const File& drive = roots.getReference(i);
  47212. String name (drive.getFullPathName());
  47213. rootPaths.add (name);
  47214. if (drive.isOnHardDisk())
  47215. {
  47216. String volume (drive.getVolumeLabel());
  47217. if (volume.isEmpty())
  47218. volume = TRANS("Hard Drive");
  47219. name << " [" << drive.getVolumeLabel() << ']';
  47220. }
  47221. else if (drive.isOnCDRomDrive())
  47222. {
  47223. name << TRANS(" [CD/DVD drive]");
  47224. }
  47225. rootNames.add (name);
  47226. }
  47227. separators.setBit (rootPaths.size());
  47228. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47229. rootNames.add ("Documents");
  47230. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47231. rootNames.add ("Desktop");
  47232. #endif
  47233. #if JUCE_MAC
  47234. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47235. rootNames.add ("Home folder");
  47236. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47237. rootNames.add ("Documents");
  47238. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47239. rootNames.add ("Desktop");
  47240. separators.setBit (rootPaths.size());
  47241. Array <File> volumes;
  47242. File vol ("/Volumes");
  47243. vol.findChildFiles (volumes, File::findDirectories, false);
  47244. for (int i = 0; i < volumes.size(); ++i)
  47245. {
  47246. const File& volume = volumes.getReference(i);
  47247. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47248. {
  47249. rootPaths.add (volume.getFullPathName());
  47250. rootNames.add (volume.getFileName());
  47251. }
  47252. }
  47253. #endif
  47254. #if JUCE_LINUX
  47255. rootPaths.add ("/");
  47256. rootNames.add ("/");
  47257. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47258. rootNames.add ("Home folder");
  47259. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47260. rootNames.add ("Desktop");
  47261. #endif
  47262. return separators;
  47263. }
  47264. END_JUCE_NAMESPACE
  47265. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47266. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47267. BEGIN_JUCE_NAMESPACE
  47268. FileChooser::FileChooser (const String& chooserBoxTitle,
  47269. const File& currentFileOrDirectory,
  47270. const String& fileFilters,
  47271. const bool useNativeDialogBox_)
  47272. : title (chooserBoxTitle),
  47273. filters (fileFilters),
  47274. startingFile (currentFileOrDirectory),
  47275. useNativeDialogBox (useNativeDialogBox_)
  47276. {
  47277. #if JUCE_LINUX
  47278. useNativeDialogBox = false;
  47279. #endif
  47280. if (! fileFilters.containsNonWhitespaceChars())
  47281. filters = "*";
  47282. }
  47283. FileChooser::~FileChooser()
  47284. {
  47285. }
  47286. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47287. {
  47288. return showDialog (false, true, false, false, false, previewComponent);
  47289. }
  47290. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47291. {
  47292. return showDialog (false, true, false, false, true, previewComponent);
  47293. }
  47294. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47295. {
  47296. return showDialog (true, true, false, false, true, previewComponent);
  47297. }
  47298. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47299. {
  47300. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47301. }
  47302. bool FileChooser::browseForDirectory()
  47303. {
  47304. return showDialog (true, false, false, false, false, 0);
  47305. }
  47306. const File FileChooser::getResult() const
  47307. {
  47308. // if you've used a multiple-file select, you should use the getResults() method
  47309. // to retrieve all the files that were chosen.
  47310. jassert (results.size() <= 1);
  47311. return results.getFirst();
  47312. }
  47313. const Array<File>& FileChooser::getResults() const
  47314. {
  47315. return results;
  47316. }
  47317. bool FileChooser::showDialog (const bool selectsDirectories,
  47318. const bool selectsFiles,
  47319. const bool isSave,
  47320. const bool warnAboutOverwritingExistingFiles,
  47321. const bool selectMultipleFiles,
  47322. FilePreviewComponent* const previewComponent)
  47323. {
  47324. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47325. results.clear();
  47326. // the preview component needs to be the right size before you pass it in here..
  47327. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47328. && previewComponent->getHeight() > 10));
  47329. #if JUCE_WINDOWS
  47330. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47331. #elif JUCE_MAC
  47332. if (useNativeDialogBox && (previewComponent == 0))
  47333. #else
  47334. if (false)
  47335. #endif
  47336. {
  47337. showPlatformDialog (results, title, startingFile, filters,
  47338. selectsDirectories, selectsFiles, isSave,
  47339. warnAboutOverwritingExistingFiles,
  47340. selectMultipleFiles,
  47341. previewComponent);
  47342. }
  47343. else
  47344. {
  47345. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47346. selectsDirectories ? "*" : String::empty,
  47347. String::empty);
  47348. int flags = isSave ? FileBrowserComponent::saveMode
  47349. : FileBrowserComponent::openMode;
  47350. if (selectsFiles)
  47351. flags |= FileBrowserComponent::canSelectFiles;
  47352. if (selectsDirectories)
  47353. {
  47354. flags |= FileBrowserComponent::canSelectDirectories;
  47355. if (! isSave)
  47356. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47357. }
  47358. if (selectMultipleFiles)
  47359. flags |= FileBrowserComponent::canSelectMultipleItems;
  47360. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47361. FileChooserDialogBox box (title, String::empty,
  47362. browserComponent,
  47363. warnAboutOverwritingExistingFiles,
  47364. browserComponent.findColour (AlertWindow::backgroundColourId));
  47365. if (box.show())
  47366. {
  47367. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47368. results.add (browserComponent.getSelectedFile (i));
  47369. }
  47370. }
  47371. if (previouslyFocused != 0)
  47372. previouslyFocused->grabKeyboardFocus();
  47373. return results.size() > 0;
  47374. }
  47375. FilePreviewComponent::FilePreviewComponent()
  47376. {
  47377. }
  47378. FilePreviewComponent::~FilePreviewComponent()
  47379. {
  47380. }
  47381. END_JUCE_NAMESPACE
  47382. /*** End of inlined file: juce_FileChooser.cpp ***/
  47383. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47384. BEGIN_JUCE_NAMESPACE
  47385. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47386. const String& instructions,
  47387. FileBrowserComponent& chooserComponent,
  47388. const bool warnAboutOverwritingExistingFiles_,
  47389. const Colour& backgroundColour)
  47390. : ResizableWindow (name, backgroundColour, true),
  47391. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47392. {
  47393. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47394. setResizable (true, true);
  47395. setResizeLimits (300, 300, 1200, 1000);
  47396. content->okButton.addButtonListener (this);
  47397. content->cancelButton.addButtonListener (this);
  47398. content->chooserComponent.addListener (this);
  47399. }
  47400. FileChooserDialogBox::~FileChooserDialogBox()
  47401. {
  47402. content->chooserComponent.removeListener (this);
  47403. }
  47404. bool FileChooserDialogBox::show (int w, int h)
  47405. {
  47406. return showAt (-1, -1, w, h);
  47407. }
  47408. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47409. {
  47410. if (w <= 0)
  47411. {
  47412. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47413. if (previewComp != 0)
  47414. w = 400 + previewComp->getWidth();
  47415. else
  47416. w = 600;
  47417. }
  47418. if (h <= 0)
  47419. h = 500;
  47420. if (x < 0 || y < 0)
  47421. centreWithSize (w, h);
  47422. else
  47423. setBounds (x, y, w, h);
  47424. const bool ok = (runModalLoop() != 0);
  47425. setVisible (false);
  47426. return ok;
  47427. }
  47428. void FileChooserDialogBox::buttonClicked (Button* button)
  47429. {
  47430. if (button == &(content->okButton))
  47431. {
  47432. if (warnAboutOverwritingExistingFiles
  47433. && content->chooserComponent.isSaveMode()
  47434. && content->chooserComponent.getSelectedFile(0).exists())
  47435. {
  47436. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47437. TRANS("File already exists"),
  47438. TRANS("There's already a file called:")
  47439. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47440. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47441. TRANS("overwrite"),
  47442. TRANS("cancel")))
  47443. {
  47444. return;
  47445. }
  47446. }
  47447. exitModalState (1);
  47448. }
  47449. else if (button == &(content->cancelButton))
  47450. {
  47451. closeButtonPressed();
  47452. }
  47453. }
  47454. void FileChooserDialogBox::closeButtonPressed()
  47455. {
  47456. setVisible (false);
  47457. }
  47458. void FileChooserDialogBox::selectionChanged()
  47459. {
  47460. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47461. }
  47462. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47463. {
  47464. }
  47465. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47466. {
  47467. selectionChanged();
  47468. content->okButton.triggerClick();
  47469. }
  47470. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47471. : Component (name), instructions (instructions_),
  47472. chooserComponent (chooserComponent_),
  47473. okButton (chooserComponent_.getActionVerb()),
  47474. cancelButton (TRANS ("Cancel"))
  47475. {
  47476. addAndMakeVisible (&chooserComponent);
  47477. addAndMakeVisible (&okButton);
  47478. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47479. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47480. addAndMakeVisible (&cancelButton);
  47481. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47482. setInterceptsMouseClicks (false, true);
  47483. }
  47484. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47485. {
  47486. }
  47487. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47488. {
  47489. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47490. text.draw (g);
  47491. }
  47492. void FileChooserDialogBox::ContentComponent::resized()
  47493. {
  47494. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47495. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47496. const int y = roundToInt (bb.getBottom()) + 10;
  47497. const int buttonHeight = 26;
  47498. const int buttonY = getHeight() - buttonHeight - 8;
  47499. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47500. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47501. proportionOfWidth (0.2f), buttonHeight);
  47502. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47503. proportionOfWidth (0.2f), buttonHeight);
  47504. }
  47505. END_JUCE_NAMESPACE
  47506. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47507. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47508. BEGIN_JUCE_NAMESPACE
  47509. FileFilter::FileFilter (const String& filterDescription)
  47510. : description (filterDescription)
  47511. {
  47512. }
  47513. FileFilter::~FileFilter()
  47514. {
  47515. }
  47516. const String& FileFilter::getDescription() const throw()
  47517. {
  47518. return description;
  47519. }
  47520. END_JUCE_NAMESPACE
  47521. /*** End of inlined file: juce_FileFilter.cpp ***/
  47522. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47523. BEGIN_JUCE_NAMESPACE
  47524. const Image juce_createIconForFile (const File& file);
  47525. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47526. : ListBox (String::empty, 0),
  47527. DirectoryContentsDisplayComponent (listToShow)
  47528. {
  47529. setModel (this);
  47530. fileList.addChangeListener (this);
  47531. }
  47532. FileListComponent::~FileListComponent()
  47533. {
  47534. fileList.removeChangeListener (this);
  47535. }
  47536. int FileListComponent::getNumSelectedFiles() const
  47537. {
  47538. return getNumSelectedRows();
  47539. }
  47540. const File FileListComponent::getSelectedFile (int index) const
  47541. {
  47542. return fileList.getFile (getSelectedRow (index));
  47543. }
  47544. void FileListComponent::deselectAllFiles()
  47545. {
  47546. deselectAllRows();
  47547. }
  47548. void FileListComponent::scrollToTop()
  47549. {
  47550. getVerticalScrollBar()->setCurrentRangeStart (0);
  47551. }
  47552. void FileListComponent::changeListenerCallback (void*)
  47553. {
  47554. updateContent();
  47555. if (lastDirectory != fileList.getDirectory())
  47556. {
  47557. lastDirectory = fileList.getDirectory();
  47558. deselectAllRows();
  47559. }
  47560. }
  47561. class FileListItemComponent : public Component,
  47562. public TimeSliceClient,
  47563. public AsyncUpdater
  47564. {
  47565. public:
  47566. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47567. : owner (owner_), thread (thread_),
  47568. highlighted (false), index (0), icon (0)
  47569. {
  47570. }
  47571. ~FileListItemComponent()
  47572. {
  47573. thread.removeTimeSliceClient (this);
  47574. clearIcon();
  47575. }
  47576. void paint (Graphics& g)
  47577. {
  47578. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47579. file.getFileName(),
  47580. &icon,
  47581. fileSize, modTime,
  47582. isDirectory, highlighted,
  47583. index, owner);
  47584. }
  47585. void mouseDown (const MouseEvent& e)
  47586. {
  47587. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47588. owner.sendMouseClickMessage (file, e);
  47589. }
  47590. void mouseDoubleClick (const MouseEvent&)
  47591. {
  47592. owner.sendDoubleClickMessage (file);
  47593. }
  47594. void update (const File& root,
  47595. const DirectoryContentsList::FileInfo* const fileInfo,
  47596. const int index_,
  47597. const bool highlighted_)
  47598. {
  47599. thread.removeTimeSliceClient (this);
  47600. if (highlighted_ != highlighted
  47601. || index_ != index)
  47602. {
  47603. index = index_;
  47604. highlighted = highlighted_;
  47605. repaint();
  47606. }
  47607. File newFile;
  47608. String newFileSize;
  47609. String newModTime;
  47610. if (fileInfo != 0)
  47611. {
  47612. newFile = root.getChildFile (fileInfo->filename);
  47613. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47614. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47615. }
  47616. if (newFile != file
  47617. || fileSize != newFileSize
  47618. || modTime != newModTime)
  47619. {
  47620. file = newFile;
  47621. fileSize = newFileSize;
  47622. modTime = newModTime;
  47623. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47624. repaint();
  47625. clearIcon();
  47626. }
  47627. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47628. {
  47629. updateIcon (true);
  47630. if (! icon.isValid())
  47631. thread.addTimeSliceClient (this);
  47632. }
  47633. }
  47634. bool useTimeSlice()
  47635. {
  47636. updateIcon (false);
  47637. return false;
  47638. }
  47639. void handleAsyncUpdate()
  47640. {
  47641. repaint();
  47642. }
  47643. juce_UseDebuggingNewOperator
  47644. private:
  47645. FileListComponent& owner;
  47646. TimeSliceThread& thread;
  47647. bool highlighted;
  47648. int index;
  47649. File file;
  47650. String fileSize;
  47651. String modTime;
  47652. Image icon;
  47653. bool isDirectory;
  47654. void clearIcon()
  47655. {
  47656. icon = Image::null;
  47657. }
  47658. void updateIcon (const bool onlyUpdateIfCached)
  47659. {
  47660. if (icon.isNull())
  47661. {
  47662. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47663. Image im (ImageCache::getFromHashCode (hashCode));
  47664. if (im.isNull() && ! onlyUpdateIfCached)
  47665. {
  47666. im = juce_createIconForFile (file);
  47667. if (im.isValid())
  47668. ImageCache::addImageToCache (im, hashCode);
  47669. }
  47670. if (im.isValid())
  47671. {
  47672. icon = im;
  47673. triggerAsyncUpdate();
  47674. }
  47675. }
  47676. }
  47677. };
  47678. int FileListComponent::getNumRows()
  47679. {
  47680. return fileList.getNumFiles();
  47681. }
  47682. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47683. {
  47684. }
  47685. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47686. {
  47687. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47688. if (comp == 0)
  47689. {
  47690. delete existingComponentToUpdate;
  47691. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47692. }
  47693. DirectoryContentsList::FileInfo fileInfo;
  47694. if (fileList.getFileInfo (row, fileInfo))
  47695. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47696. else
  47697. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47698. return comp;
  47699. }
  47700. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47701. {
  47702. sendSelectionChangeMessage();
  47703. }
  47704. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47705. {
  47706. }
  47707. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47708. {
  47709. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47710. }
  47711. END_JUCE_NAMESPACE
  47712. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47713. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47714. BEGIN_JUCE_NAMESPACE
  47715. FilenameComponent::FilenameComponent (const String& name,
  47716. const File& currentFile,
  47717. const bool canEditFilename,
  47718. const bool isDirectory,
  47719. const bool isForSaving,
  47720. const String& fileBrowserWildcard,
  47721. const String& enforcedSuffix_,
  47722. const String& textWhenNothingSelected)
  47723. : Component (name),
  47724. maxRecentFiles (30),
  47725. isDir (isDirectory),
  47726. isSaving (isForSaving),
  47727. isFileDragOver (false),
  47728. wildcard (fileBrowserWildcard),
  47729. enforcedSuffix (enforcedSuffix_)
  47730. {
  47731. addAndMakeVisible (&filenameBox);
  47732. filenameBox.setEditableText (canEditFilename);
  47733. filenameBox.addListener (this);
  47734. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47735. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47736. setBrowseButtonText ("...");
  47737. setCurrentFile (currentFile, true);
  47738. }
  47739. FilenameComponent::~FilenameComponent()
  47740. {
  47741. }
  47742. void FilenameComponent::paintOverChildren (Graphics& g)
  47743. {
  47744. if (isFileDragOver)
  47745. {
  47746. g.setColour (Colours::red.withAlpha (0.2f));
  47747. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47748. }
  47749. }
  47750. void FilenameComponent::resized()
  47751. {
  47752. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47753. }
  47754. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47755. {
  47756. browseButtonText = newBrowseButtonText;
  47757. lookAndFeelChanged();
  47758. }
  47759. void FilenameComponent::lookAndFeelChanged()
  47760. {
  47761. browseButton = 0;
  47762. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47763. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47764. resized();
  47765. browseButton->addButtonListener (this);
  47766. }
  47767. void FilenameComponent::setTooltip (const String& newTooltip)
  47768. {
  47769. SettableTooltipClient::setTooltip (newTooltip);
  47770. filenameBox.setTooltip (newTooltip);
  47771. }
  47772. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47773. {
  47774. defaultBrowseFile = newDefaultDirectory;
  47775. }
  47776. void FilenameComponent::buttonClicked (Button*)
  47777. {
  47778. FileChooser fc (TRANS("Choose a new file"),
  47779. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47780. : getCurrentFile(),
  47781. wildcard);
  47782. if (isDir ? fc.browseForDirectory()
  47783. : (isSaving ? fc.browseForFileToSave (false)
  47784. : fc.browseForFileToOpen()))
  47785. {
  47786. setCurrentFile (fc.getResult(), true);
  47787. }
  47788. }
  47789. void FilenameComponent::comboBoxChanged (ComboBox*)
  47790. {
  47791. setCurrentFile (getCurrentFile(), true);
  47792. }
  47793. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47794. {
  47795. return true;
  47796. }
  47797. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47798. {
  47799. isFileDragOver = false;
  47800. repaint();
  47801. const File f (filenames[0]);
  47802. if (f.exists() && (f.isDirectory() == isDir))
  47803. setCurrentFile (f, true);
  47804. }
  47805. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47806. {
  47807. isFileDragOver = true;
  47808. repaint();
  47809. }
  47810. void FilenameComponent::fileDragExit (const StringArray&)
  47811. {
  47812. isFileDragOver = false;
  47813. repaint();
  47814. }
  47815. const File FilenameComponent::getCurrentFile() const
  47816. {
  47817. File f (filenameBox.getText());
  47818. if (enforcedSuffix.isNotEmpty())
  47819. f = f.withFileExtension (enforcedSuffix);
  47820. return f;
  47821. }
  47822. void FilenameComponent::setCurrentFile (File newFile,
  47823. const bool addToRecentlyUsedList,
  47824. const bool sendChangeNotification)
  47825. {
  47826. if (enforcedSuffix.isNotEmpty())
  47827. newFile = newFile.withFileExtension (enforcedSuffix);
  47828. if (newFile.getFullPathName() != lastFilename)
  47829. {
  47830. lastFilename = newFile.getFullPathName();
  47831. if (addToRecentlyUsedList)
  47832. addRecentlyUsedFile (newFile);
  47833. filenameBox.setText (lastFilename, true);
  47834. if (sendChangeNotification)
  47835. triggerAsyncUpdate();
  47836. }
  47837. }
  47838. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47839. {
  47840. filenameBox.setEditableText (shouldBeEditable);
  47841. }
  47842. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47843. {
  47844. StringArray names;
  47845. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47846. names.add (filenameBox.getItemText (i));
  47847. return names;
  47848. }
  47849. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47850. {
  47851. if (filenames != getRecentlyUsedFilenames())
  47852. {
  47853. filenameBox.clear();
  47854. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47855. filenameBox.addItem (filenames[i], i + 1);
  47856. }
  47857. }
  47858. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47859. {
  47860. maxRecentFiles = jmax (1, newMaximum);
  47861. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47862. }
  47863. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47864. {
  47865. StringArray files (getRecentlyUsedFilenames());
  47866. if (file.getFullPathName().isNotEmpty())
  47867. {
  47868. files.removeString (file.getFullPathName(), true);
  47869. files.insert (0, file.getFullPathName());
  47870. setRecentlyUsedFilenames (files);
  47871. }
  47872. }
  47873. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47874. {
  47875. listeners.add (listener);
  47876. }
  47877. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47878. {
  47879. listeners.remove (listener);
  47880. }
  47881. void FilenameComponent::handleAsyncUpdate()
  47882. {
  47883. Component::BailOutChecker checker (this);
  47884. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47885. }
  47886. END_JUCE_NAMESPACE
  47887. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47888. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47889. BEGIN_JUCE_NAMESPACE
  47890. FileSearchPathListComponent::FileSearchPathListComponent()
  47891. {
  47892. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47893. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47894. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47895. listBox->setOutlineThickness (1);
  47896. addAndMakeVisible (addButton = new TextButton ("+"));
  47897. addButton->addButtonListener (this);
  47898. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47899. addAndMakeVisible (removeButton = new TextButton ("-"));
  47900. removeButton->addButtonListener (this);
  47901. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47902. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47903. changeButton->addButtonListener (this);
  47904. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47905. upButton->addButtonListener (this);
  47906. {
  47907. Path arrowPath;
  47908. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47909. DrawablePath arrowImage;
  47910. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47911. arrowImage.setPath (arrowPath);
  47912. upButton->setImages (&arrowImage);
  47913. }
  47914. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47915. downButton->addButtonListener (this);
  47916. {
  47917. Path arrowPath;
  47918. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47919. DrawablePath arrowImage;
  47920. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47921. arrowImage.setPath (arrowPath);
  47922. downButton->setImages (&arrowImage);
  47923. }
  47924. updateButtons();
  47925. }
  47926. FileSearchPathListComponent::~FileSearchPathListComponent()
  47927. {
  47928. deleteAllChildren();
  47929. }
  47930. void FileSearchPathListComponent::updateButtons()
  47931. {
  47932. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47933. removeButton->setEnabled (anythingSelected);
  47934. changeButton->setEnabled (anythingSelected);
  47935. upButton->setEnabled (anythingSelected);
  47936. downButton->setEnabled (anythingSelected);
  47937. }
  47938. void FileSearchPathListComponent::changed()
  47939. {
  47940. listBox->updateContent();
  47941. listBox->repaint();
  47942. updateButtons();
  47943. }
  47944. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47945. {
  47946. if (newPath.toString() != path.toString())
  47947. {
  47948. path = newPath;
  47949. changed();
  47950. }
  47951. }
  47952. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47953. {
  47954. defaultBrowseTarget = newDefaultDirectory;
  47955. }
  47956. int FileSearchPathListComponent::getNumRows()
  47957. {
  47958. return path.getNumPaths();
  47959. }
  47960. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47961. {
  47962. if (rowIsSelected)
  47963. g.fillAll (findColour (TextEditor::highlightColourId));
  47964. g.setColour (findColour (ListBox::textColourId));
  47965. Font f (height * 0.7f);
  47966. f.setHorizontalScale (0.9f);
  47967. g.setFont (f);
  47968. g.drawText (path [rowNumber].getFullPathName(),
  47969. 4, 0, width - 6, height,
  47970. Justification::centredLeft, true);
  47971. }
  47972. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47973. {
  47974. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47975. {
  47976. path.remove (row);
  47977. changed();
  47978. }
  47979. }
  47980. void FileSearchPathListComponent::returnKeyPressed (int row)
  47981. {
  47982. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47983. if (chooser.browseForDirectory())
  47984. {
  47985. path.remove (row);
  47986. path.add (chooser.getResult(), row);
  47987. changed();
  47988. }
  47989. }
  47990. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47991. {
  47992. returnKeyPressed (row);
  47993. }
  47994. void FileSearchPathListComponent::selectedRowsChanged (int)
  47995. {
  47996. updateButtons();
  47997. }
  47998. void FileSearchPathListComponent::paint (Graphics& g)
  47999. {
  48000. g.fillAll (findColour (backgroundColourId));
  48001. }
  48002. void FileSearchPathListComponent::resized()
  48003. {
  48004. const int buttonH = 22;
  48005. const int buttonY = getHeight() - buttonH - 4;
  48006. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48007. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48008. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48009. changeButton->changeWidthToFitText (buttonH);
  48010. downButton->setSize (buttonH * 2, buttonH);
  48011. upButton->setSize (buttonH * 2, buttonH);
  48012. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48013. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48014. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48015. }
  48016. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48017. {
  48018. return true;
  48019. }
  48020. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48021. {
  48022. for (int i = filenames.size(); --i >= 0;)
  48023. {
  48024. const File f (filenames[i]);
  48025. if (f.isDirectory())
  48026. {
  48027. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48028. path.add (f, row);
  48029. changed();
  48030. }
  48031. }
  48032. }
  48033. void FileSearchPathListComponent::buttonClicked (Button* button)
  48034. {
  48035. const int currentRow = listBox->getSelectedRow();
  48036. if (button == removeButton)
  48037. {
  48038. deleteKeyPressed (currentRow);
  48039. }
  48040. else if (button == addButton)
  48041. {
  48042. File start (defaultBrowseTarget);
  48043. if (start == File::nonexistent)
  48044. start = path [0];
  48045. if (start == File::nonexistent)
  48046. start = File::getCurrentWorkingDirectory();
  48047. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48048. if (chooser.browseForDirectory())
  48049. {
  48050. path.add (chooser.getResult(), currentRow);
  48051. }
  48052. }
  48053. else if (button == changeButton)
  48054. {
  48055. returnKeyPressed (currentRow);
  48056. }
  48057. else if (button == upButton)
  48058. {
  48059. if (currentRow > 0 && currentRow < path.getNumPaths())
  48060. {
  48061. const File f (path[currentRow]);
  48062. path.remove (currentRow);
  48063. path.add (f, currentRow - 1);
  48064. listBox->selectRow (currentRow - 1);
  48065. }
  48066. }
  48067. else if (button == downButton)
  48068. {
  48069. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48070. {
  48071. const File f (path[currentRow]);
  48072. path.remove (currentRow);
  48073. path.add (f, currentRow + 1);
  48074. listBox->selectRow (currentRow + 1);
  48075. }
  48076. }
  48077. changed();
  48078. }
  48079. END_JUCE_NAMESPACE
  48080. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48081. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48082. BEGIN_JUCE_NAMESPACE
  48083. const Image juce_createIconForFile (const File& file);
  48084. class FileListTreeItem : public TreeViewItem,
  48085. public TimeSliceClient,
  48086. public AsyncUpdater,
  48087. public ChangeListener
  48088. {
  48089. public:
  48090. FileListTreeItem (FileTreeComponent& owner_,
  48091. DirectoryContentsList* const parentContentsList_,
  48092. const int indexInContentsList_,
  48093. const File& file_,
  48094. TimeSliceThread& thread_)
  48095. : file (file_),
  48096. owner (owner_),
  48097. parentContentsList (parentContentsList_),
  48098. indexInContentsList (indexInContentsList_),
  48099. subContentsList (0),
  48100. canDeleteSubContentsList (false),
  48101. thread (thread_),
  48102. icon (0)
  48103. {
  48104. DirectoryContentsList::FileInfo fileInfo;
  48105. if (parentContentsList_ != 0
  48106. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48107. {
  48108. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48109. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48110. isDirectory = fileInfo.isDirectory;
  48111. }
  48112. else
  48113. {
  48114. isDirectory = true;
  48115. }
  48116. }
  48117. ~FileListTreeItem()
  48118. {
  48119. thread.removeTimeSliceClient (this);
  48120. clearSubItems();
  48121. if (canDeleteSubContentsList)
  48122. delete subContentsList;
  48123. }
  48124. bool mightContainSubItems() { return isDirectory; }
  48125. const String getUniqueName() const { return file.getFullPathName(); }
  48126. int getItemHeight() const { return 22; }
  48127. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48128. void itemOpennessChanged (bool isNowOpen)
  48129. {
  48130. if (isNowOpen)
  48131. {
  48132. clearSubItems();
  48133. isDirectory = file.isDirectory();
  48134. if (isDirectory)
  48135. {
  48136. if (subContentsList == 0)
  48137. {
  48138. jassert (parentContentsList != 0);
  48139. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48140. l->setDirectory (file, true, true);
  48141. setSubContentsList (l);
  48142. canDeleteSubContentsList = true;
  48143. }
  48144. changeListenerCallback (0);
  48145. }
  48146. }
  48147. }
  48148. void setSubContentsList (DirectoryContentsList* newList)
  48149. {
  48150. jassert (subContentsList == 0);
  48151. subContentsList = newList;
  48152. newList->addChangeListener (this);
  48153. }
  48154. void changeListenerCallback (void*)
  48155. {
  48156. clearSubItems();
  48157. if (isOpen() && subContentsList != 0)
  48158. {
  48159. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48160. {
  48161. FileListTreeItem* const item
  48162. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48163. addSubItem (item);
  48164. }
  48165. }
  48166. }
  48167. void paintItem (Graphics& g, int width, int height)
  48168. {
  48169. if (file != File::nonexistent)
  48170. {
  48171. updateIcon (true);
  48172. if (icon.isNull())
  48173. thread.addTimeSliceClient (this);
  48174. }
  48175. owner.getLookAndFeel()
  48176. .drawFileBrowserRow (g, width, height,
  48177. file.getFileName(),
  48178. &icon, fileSize, modTime,
  48179. isDirectory, isSelected(),
  48180. indexInContentsList, owner);
  48181. }
  48182. void itemClicked (const MouseEvent& e)
  48183. {
  48184. owner.sendMouseClickMessage (file, e);
  48185. }
  48186. void itemDoubleClicked (const MouseEvent& e)
  48187. {
  48188. TreeViewItem::itemDoubleClicked (e);
  48189. owner.sendDoubleClickMessage (file);
  48190. }
  48191. void itemSelectionChanged (bool)
  48192. {
  48193. owner.sendSelectionChangeMessage();
  48194. }
  48195. bool useTimeSlice()
  48196. {
  48197. updateIcon (false);
  48198. thread.removeTimeSliceClient (this);
  48199. return false;
  48200. }
  48201. void handleAsyncUpdate()
  48202. {
  48203. owner.repaint();
  48204. }
  48205. const File file;
  48206. juce_UseDebuggingNewOperator
  48207. private:
  48208. FileTreeComponent& owner;
  48209. DirectoryContentsList* parentContentsList;
  48210. int indexInContentsList;
  48211. DirectoryContentsList* subContentsList;
  48212. bool isDirectory, canDeleteSubContentsList;
  48213. TimeSliceThread& thread;
  48214. Image icon;
  48215. String fileSize;
  48216. String modTime;
  48217. void updateIcon (const bool onlyUpdateIfCached)
  48218. {
  48219. if (icon.isNull())
  48220. {
  48221. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48222. Image im (ImageCache::getFromHashCode (hashCode));
  48223. if (im.isNull() && ! onlyUpdateIfCached)
  48224. {
  48225. im = juce_createIconForFile (file);
  48226. if (im.isValid())
  48227. ImageCache::addImageToCache (im, hashCode);
  48228. }
  48229. if (im.isValid())
  48230. {
  48231. icon = im;
  48232. triggerAsyncUpdate();
  48233. }
  48234. }
  48235. }
  48236. };
  48237. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48238. : DirectoryContentsDisplayComponent (listToShow)
  48239. {
  48240. FileListTreeItem* const root
  48241. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48242. listToShow.getTimeSliceThread());
  48243. root->setSubContentsList (&listToShow);
  48244. setRootItemVisible (false);
  48245. setRootItem (root);
  48246. }
  48247. FileTreeComponent::~FileTreeComponent()
  48248. {
  48249. deleteRootItem();
  48250. }
  48251. const File FileTreeComponent::getSelectedFile (const int index) const
  48252. {
  48253. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48254. return item != 0 ? item->file
  48255. : File::nonexistent;
  48256. }
  48257. void FileTreeComponent::deselectAllFiles()
  48258. {
  48259. clearSelectedItems();
  48260. }
  48261. void FileTreeComponent::scrollToTop()
  48262. {
  48263. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48264. }
  48265. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48266. {
  48267. dragAndDropDescription = description;
  48268. }
  48269. END_JUCE_NAMESPACE
  48270. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48271. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48272. BEGIN_JUCE_NAMESPACE
  48273. ImagePreviewComponent::ImagePreviewComponent()
  48274. {
  48275. }
  48276. ImagePreviewComponent::~ImagePreviewComponent()
  48277. {
  48278. }
  48279. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48280. {
  48281. const int availableW = proportionOfWidth (0.97f);
  48282. const int availableH = getHeight() - 13 * 4;
  48283. const double scale = jmin (1.0,
  48284. availableW / (double) w,
  48285. availableH / (double) h);
  48286. w = roundToInt (scale * w);
  48287. h = roundToInt (scale * h);
  48288. }
  48289. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48290. {
  48291. if (fileToLoad != file)
  48292. {
  48293. fileToLoad = file;
  48294. startTimer (100);
  48295. }
  48296. }
  48297. void ImagePreviewComponent::timerCallback()
  48298. {
  48299. stopTimer();
  48300. currentThumbnail = Image::null;
  48301. currentDetails = String::empty;
  48302. repaint();
  48303. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48304. if (in != 0)
  48305. {
  48306. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48307. if (format != 0)
  48308. {
  48309. currentThumbnail = format->decodeImage (*in);
  48310. if (currentThumbnail.isValid())
  48311. {
  48312. int w = currentThumbnail.getWidth();
  48313. int h = currentThumbnail.getHeight();
  48314. currentDetails
  48315. << fileToLoad.getFileName() << "\n"
  48316. << format->getFormatName() << "\n"
  48317. << w << " x " << h << " pixels\n"
  48318. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48319. getThumbSize (w, h);
  48320. currentThumbnail = currentThumbnail.rescaled (w, h);
  48321. }
  48322. }
  48323. }
  48324. }
  48325. void ImagePreviewComponent::paint (Graphics& g)
  48326. {
  48327. if (currentThumbnail.isValid())
  48328. {
  48329. g.setFont (13.0f);
  48330. int w = currentThumbnail.getWidth();
  48331. int h = currentThumbnail.getHeight();
  48332. getThumbSize (w, h);
  48333. const int numLines = 4;
  48334. const int totalH = 13 * numLines + h + 4;
  48335. const int y = (getHeight() - totalH) / 2;
  48336. g.drawImageWithin (currentThumbnail,
  48337. (getWidth() - w) / 2, y, w, h,
  48338. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48339. false);
  48340. g.drawFittedText (currentDetails,
  48341. 0, y + h + 4, getWidth(), 100,
  48342. Justification::centredTop, numLines);
  48343. }
  48344. }
  48345. END_JUCE_NAMESPACE
  48346. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48347. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48348. BEGIN_JUCE_NAMESPACE
  48349. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48350. const String& directoryWildcardPatterns,
  48351. const String& description_)
  48352. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48353. : (description_ + " (" + fileWildcardPatterns + ")"))
  48354. {
  48355. parse (fileWildcardPatterns, fileWildcards);
  48356. parse (directoryWildcardPatterns, directoryWildcards);
  48357. }
  48358. WildcardFileFilter::~WildcardFileFilter()
  48359. {
  48360. }
  48361. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48362. {
  48363. return match (file, fileWildcards);
  48364. }
  48365. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48366. {
  48367. return match (file, directoryWildcards);
  48368. }
  48369. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48370. {
  48371. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48372. result.trim();
  48373. result.removeEmptyStrings();
  48374. // special case for *.*, because people use it to mean "any file", but it
  48375. // would actually ignore files with no extension.
  48376. for (int i = result.size(); --i >= 0;)
  48377. if (result[i] == "*.*")
  48378. result.set (i, "*");
  48379. }
  48380. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48381. {
  48382. const String filename (file.getFileName());
  48383. for (int i = wildcards.size(); --i >= 0;)
  48384. if (filename.matchesWildcard (wildcards[i], true))
  48385. return true;
  48386. return false;
  48387. }
  48388. END_JUCE_NAMESPACE
  48389. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48390. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48391. BEGIN_JUCE_NAMESPACE
  48392. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48393. {
  48394. }
  48395. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48396. {
  48397. }
  48398. namespace KeyboardFocusHelpers
  48399. {
  48400. // This will sort a set of components, so that they are ordered in terms of
  48401. // left-to-right and then top-to-bottom.
  48402. class ScreenPositionComparator
  48403. {
  48404. public:
  48405. ScreenPositionComparator() {}
  48406. static int compareElements (const Component* const first, const Component* const second)
  48407. {
  48408. int explicitOrder1 = first->getExplicitFocusOrder();
  48409. if (explicitOrder1 <= 0)
  48410. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48411. int explicitOrder2 = second->getExplicitFocusOrder();
  48412. if (explicitOrder2 <= 0)
  48413. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48414. if (explicitOrder1 != explicitOrder2)
  48415. return explicitOrder1 - explicitOrder2;
  48416. const int diff = first->getY() - second->getY();
  48417. return (diff == 0) ? first->getX() - second->getX()
  48418. : diff;
  48419. }
  48420. };
  48421. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48422. {
  48423. if (parent->getNumChildComponents() > 0)
  48424. {
  48425. Array <Component*> localComps;
  48426. ScreenPositionComparator comparator;
  48427. int i;
  48428. for (i = parent->getNumChildComponents(); --i >= 0;)
  48429. {
  48430. Component* const c = parent->getChildComponent (i);
  48431. if (c->isVisible() && c->isEnabled())
  48432. localComps.addSorted (comparator, c);
  48433. }
  48434. for (i = 0; i < localComps.size(); ++i)
  48435. {
  48436. Component* const c = localComps.getUnchecked (i);
  48437. if (c->getWantsKeyboardFocus())
  48438. comps.add (c);
  48439. if (! c->isFocusContainer())
  48440. findAllFocusableComponents (c, comps);
  48441. }
  48442. }
  48443. }
  48444. }
  48445. static Component* getIncrementedComponent (Component* const current, const int delta)
  48446. {
  48447. Component* focusContainer = current->getParentComponent();
  48448. if (focusContainer != 0)
  48449. {
  48450. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48451. focusContainer = focusContainer->getParentComponent();
  48452. if (focusContainer != 0)
  48453. {
  48454. Array <Component*> comps;
  48455. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48456. if (comps.size() > 0)
  48457. {
  48458. const int index = comps.indexOf (current);
  48459. return comps [(index + comps.size() + delta) % comps.size()];
  48460. }
  48461. }
  48462. }
  48463. return 0;
  48464. }
  48465. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48466. {
  48467. return getIncrementedComponent (current, 1);
  48468. }
  48469. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48470. {
  48471. return getIncrementedComponent (current, -1);
  48472. }
  48473. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48474. {
  48475. Array <Component*> comps;
  48476. if (parentComponent != 0)
  48477. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48478. return comps.getFirst();
  48479. }
  48480. END_JUCE_NAMESPACE
  48481. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48482. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48483. BEGIN_JUCE_NAMESPACE
  48484. bool KeyListener::keyStateChanged (const bool, Component*)
  48485. {
  48486. return false;
  48487. }
  48488. END_JUCE_NAMESPACE
  48489. /*** End of inlined file: juce_KeyListener.cpp ***/
  48490. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48491. BEGIN_JUCE_NAMESPACE
  48492. // N.B. these two includes are put here deliberately to avoid problems with
  48493. // old GCCs failing on long include paths
  48494. const int maxKeys = 3;
  48495. class KeyMappingChangeButton : public Button
  48496. {
  48497. public:
  48498. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48499. const CommandID commandID_,
  48500. const String& keyName,
  48501. const int keyNum_)
  48502. : Button (keyName),
  48503. owner (owner_),
  48504. commandID (commandID_),
  48505. keyNum (keyNum_)
  48506. {
  48507. setWantsKeyboardFocus (false);
  48508. setTriggeredOnMouseDown (keyNum >= 0);
  48509. if (keyNum_ < 0)
  48510. setTooltip (TRANS("adds a new key-mapping"));
  48511. else
  48512. setTooltip (TRANS("click to change this key-mapping"));
  48513. }
  48514. ~KeyMappingChangeButton()
  48515. {
  48516. }
  48517. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48518. {
  48519. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48520. keyNum >= 0 ? getName() : String::empty);
  48521. }
  48522. void clicked()
  48523. {
  48524. if (keyNum >= 0)
  48525. {
  48526. // existing key clicked..
  48527. PopupMenu m;
  48528. m.addItem (1, TRANS("change this key-mapping"));
  48529. m.addSeparator();
  48530. m.addItem (2, TRANS("remove this key-mapping"));
  48531. const int res = m.show();
  48532. if (res == 1)
  48533. {
  48534. owner->assignNewKey (commandID, keyNum);
  48535. }
  48536. else if (res == 2)
  48537. {
  48538. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48539. }
  48540. }
  48541. else
  48542. {
  48543. // + button pressed..
  48544. owner->assignNewKey (commandID, -1);
  48545. }
  48546. }
  48547. void fitToContent (const int h) throw()
  48548. {
  48549. if (keyNum < 0)
  48550. {
  48551. setSize (h, h);
  48552. }
  48553. else
  48554. {
  48555. Font f (h * 0.6f);
  48556. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48557. }
  48558. }
  48559. juce_UseDebuggingNewOperator
  48560. private:
  48561. KeyMappingEditorComponent* const owner;
  48562. const CommandID commandID;
  48563. const int keyNum;
  48564. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48565. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48566. };
  48567. class KeyMappingItemComponent : public Component
  48568. {
  48569. public:
  48570. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48571. const CommandID commandID_)
  48572. : owner (owner_),
  48573. commandID (commandID_)
  48574. {
  48575. setInterceptsMouseClicks (false, true);
  48576. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48577. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48578. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48579. {
  48580. KeyMappingChangeButton* const kb
  48581. = new KeyMappingChangeButton (owner_, commandID,
  48582. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48583. kb->setEnabled (! isReadOnly);
  48584. addAndMakeVisible (kb);
  48585. }
  48586. KeyMappingChangeButton* const kb
  48587. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48588. addChildComponent (kb);
  48589. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48590. }
  48591. ~KeyMappingItemComponent()
  48592. {
  48593. deleteAllChildren();
  48594. }
  48595. void paint (Graphics& g)
  48596. {
  48597. g.setFont (getHeight() * 0.7f);
  48598. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48599. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48600. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48601. Justification::centredLeft, true);
  48602. }
  48603. void resized()
  48604. {
  48605. int x = getWidth() - 4;
  48606. for (int i = getNumChildComponents(); --i >= 0;)
  48607. {
  48608. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48609. kb->fitToContent (getHeight() - 2);
  48610. kb->setTopRightPosition (x, 1);
  48611. x -= kb->getWidth() + 5;
  48612. }
  48613. }
  48614. juce_UseDebuggingNewOperator
  48615. private:
  48616. KeyMappingEditorComponent* const owner;
  48617. const CommandID commandID;
  48618. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48619. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48620. };
  48621. class KeyMappingTreeViewItem : public TreeViewItem
  48622. {
  48623. public:
  48624. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48625. const CommandID commandID_)
  48626. : owner (owner_),
  48627. commandID (commandID_)
  48628. {
  48629. }
  48630. ~KeyMappingTreeViewItem()
  48631. {
  48632. }
  48633. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48634. bool mightContainSubItems() { return false; }
  48635. int getItemHeight() const { return 20; }
  48636. Component* createItemComponent()
  48637. {
  48638. return new KeyMappingItemComponent (owner, commandID);
  48639. }
  48640. juce_UseDebuggingNewOperator
  48641. private:
  48642. KeyMappingEditorComponent* const owner;
  48643. const CommandID commandID;
  48644. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48645. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48646. };
  48647. class KeyCategoryTreeViewItem : public TreeViewItem
  48648. {
  48649. public:
  48650. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48651. const String& name)
  48652. : owner (owner_),
  48653. categoryName (name)
  48654. {
  48655. }
  48656. ~KeyCategoryTreeViewItem()
  48657. {
  48658. }
  48659. const String getUniqueName() const { return categoryName + "_cat"; }
  48660. bool mightContainSubItems() { return true; }
  48661. int getItemHeight() const { return 28; }
  48662. void paintItem (Graphics& g, int width, int height)
  48663. {
  48664. g.setFont (height * 0.6f, Font::bold);
  48665. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48666. g.drawText (categoryName,
  48667. 2, 0, width - 2, height,
  48668. Justification::centredLeft, true);
  48669. }
  48670. void itemOpennessChanged (bool isNowOpen)
  48671. {
  48672. if (isNowOpen)
  48673. {
  48674. if (getNumSubItems() == 0)
  48675. {
  48676. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48677. for (int i = 0; i < commands.size(); ++i)
  48678. {
  48679. if (owner->shouldCommandBeIncluded (commands[i]))
  48680. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48681. }
  48682. }
  48683. }
  48684. else
  48685. {
  48686. clearSubItems();
  48687. }
  48688. }
  48689. juce_UseDebuggingNewOperator
  48690. private:
  48691. KeyMappingEditorComponent* owner;
  48692. String categoryName;
  48693. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48694. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48695. };
  48696. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48697. const bool showResetToDefaultButton)
  48698. : mappings (mappingManager)
  48699. {
  48700. jassert (mappingManager != 0); // can't be null!
  48701. mappingManager->addChangeListener (this);
  48702. setLinesDrawnForSubItems (false);
  48703. resetButton = 0;
  48704. if (showResetToDefaultButton)
  48705. {
  48706. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48707. resetButton->addButtonListener (this);
  48708. }
  48709. addAndMakeVisible (tree = new TreeView());
  48710. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48711. tree->setRootItemVisible (false);
  48712. tree->setDefaultOpenness (true);
  48713. tree->setRootItem (this);
  48714. }
  48715. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48716. {
  48717. mappings->removeChangeListener (this);
  48718. deleteAllChildren();
  48719. }
  48720. bool KeyMappingEditorComponent::mightContainSubItems()
  48721. {
  48722. return true;
  48723. }
  48724. const String KeyMappingEditorComponent::getUniqueName() const
  48725. {
  48726. return "keys";
  48727. }
  48728. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48729. const Colour& textColour)
  48730. {
  48731. setColour (backgroundColourId, mainBackground);
  48732. setColour (textColourId, textColour);
  48733. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48734. }
  48735. void KeyMappingEditorComponent::parentHierarchyChanged()
  48736. {
  48737. changeListenerCallback (0);
  48738. }
  48739. void KeyMappingEditorComponent::resized()
  48740. {
  48741. int h = getHeight();
  48742. if (resetButton != 0)
  48743. {
  48744. const int buttonHeight = 20;
  48745. h -= buttonHeight + 8;
  48746. int x = getWidth() - 8;
  48747. resetButton->changeWidthToFitText (buttonHeight);
  48748. resetButton->setTopRightPosition (x, h + 6);
  48749. }
  48750. tree->setBounds (0, 0, getWidth(), h);
  48751. }
  48752. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48753. {
  48754. if (button == resetButton)
  48755. {
  48756. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48757. TRANS("Reset to defaults"),
  48758. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48759. TRANS("Reset")))
  48760. {
  48761. mappings->resetToDefaultMappings();
  48762. }
  48763. }
  48764. }
  48765. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48766. {
  48767. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48768. clearSubItems();
  48769. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48770. for (int i = 0; i < categories.size(); ++i)
  48771. {
  48772. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48773. int count = 0;
  48774. for (int j = 0; j < commands.size(); ++j)
  48775. if (shouldCommandBeIncluded (commands[j]))
  48776. ++count;
  48777. if (count > 0)
  48778. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48779. }
  48780. if (oldOpenness != 0)
  48781. tree->restoreOpennessState (*oldOpenness);
  48782. }
  48783. class KeyEntryWindow : public AlertWindow
  48784. {
  48785. public:
  48786. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48787. : AlertWindow (TRANS("New key-mapping"),
  48788. TRANS("Please press a key combination now..."),
  48789. AlertWindow::NoIcon),
  48790. owner (owner_)
  48791. {
  48792. addButton (TRANS("ok"), 1);
  48793. addButton (TRANS("cancel"), 0);
  48794. // (avoid return + escape keys getting processed by the buttons..)
  48795. for (int i = getNumChildComponents(); --i >= 0;)
  48796. getChildComponent (i)->setWantsKeyboardFocus (false);
  48797. setWantsKeyboardFocus (true);
  48798. grabKeyboardFocus();
  48799. }
  48800. ~KeyEntryWindow()
  48801. {
  48802. }
  48803. bool keyPressed (const KeyPress& key)
  48804. {
  48805. lastPress = key;
  48806. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48807. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48808. if (previousCommand != 0)
  48809. {
  48810. message << "\n\n"
  48811. << TRANS("(Currently assigned to \"")
  48812. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48813. << "\")";
  48814. }
  48815. setMessage (message);
  48816. return true;
  48817. }
  48818. bool keyStateChanged (bool)
  48819. {
  48820. return true;
  48821. }
  48822. KeyPress lastPress;
  48823. juce_UseDebuggingNewOperator
  48824. private:
  48825. KeyMappingEditorComponent* owner;
  48826. KeyEntryWindow (const KeyEntryWindow&);
  48827. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48828. };
  48829. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48830. {
  48831. KeyEntryWindow entryWindow (this);
  48832. if (entryWindow.runModalLoop() != 0)
  48833. {
  48834. entryWindow.setVisible (false);
  48835. if (entryWindow.lastPress.isValid())
  48836. {
  48837. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48838. if (previousCommand != 0)
  48839. {
  48840. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48841. TRANS("Change key-mapping"),
  48842. TRANS("This key is already assigned to the command \"")
  48843. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48844. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48845. TRANS("re-assign"),
  48846. TRANS("cancel")))
  48847. {
  48848. return;
  48849. }
  48850. }
  48851. mappings->removeKeyPress (entryWindow.lastPress);
  48852. if (index >= 0)
  48853. mappings->removeKeyPress (commandID, index);
  48854. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48855. }
  48856. }
  48857. }
  48858. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48859. {
  48860. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48861. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48862. }
  48863. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48864. {
  48865. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48866. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48867. }
  48868. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48869. {
  48870. return key.getTextDescription();
  48871. }
  48872. END_JUCE_NAMESPACE
  48873. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48874. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48875. BEGIN_JUCE_NAMESPACE
  48876. KeyPress::KeyPress() throw()
  48877. : keyCode (0),
  48878. mods (0),
  48879. textCharacter (0)
  48880. {
  48881. }
  48882. KeyPress::KeyPress (const int keyCode_,
  48883. const ModifierKeys& mods_,
  48884. const juce_wchar textCharacter_) throw()
  48885. : keyCode (keyCode_),
  48886. mods (mods_),
  48887. textCharacter (textCharacter_)
  48888. {
  48889. }
  48890. KeyPress::KeyPress (const int keyCode_) throw()
  48891. : keyCode (keyCode_),
  48892. textCharacter (0)
  48893. {
  48894. }
  48895. KeyPress::KeyPress (const KeyPress& other) throw()
  48896. : keyCode (other.keyCode),
  48897. mods (other.mods),
  48898. textCharacter (other.textCharacter)
  48899. {
  48900. }
  48901. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48902. {
  48903. keyCode = other.keyCode;
  48904. mods = other.mods;
  48905. textCharacter = other.textCharacter;
  48906. return *this;
  48907. }
  48908. bool KeyPress::operator== (const KeyPress& other) const throw()
  48909. {
  48910. return mods.getRawFlags() == other.mods.getRawFlags()
  48911. && (textCharacter == other.textCharacter
  48912. || textCharacter == 0
  48913. || other.textCharacter == 0)
  48914. && (keyCode == other.keyCode
  48915. || (keyCode < 256
  48916. && other.keyCode < 256
  48917. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48918. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48919. }
  48920. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48921. {
  48922. return ! operator== (other);
  48923. }
  48924. bool KeyPress::isCurrentlyDown() const
  48925. {
  48926. return isKeyCurrentlyDown (keyCode)
  48927. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48928. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48929. }
  48930. namespace KeyPressHelpers
  48931. {
  48932. struct KeyNameAndCode
  48933. {
  48934. const char* name;
  48935. int code;
  48936. };
  48937. static const KeyNameAndCode translations[] =
  48938. {
  48939. { "spacebar", KeyPress::spaceKey },
  48940. { "return", KeyPress::returnKey },
  48941. { "escape", KeyPress::escapeKey },
  48942. { "backspace", KeyPress::backspaceKey },
  48943. { "cursor left", KeyPress::leftKey },
  48944. { "cursor right", KeyPress::rightKey },
  48945. { "cursor up", KeyPress::upKey },
  48946. { "cursor down", KeyPress::downKey },
  48947. { "page up", KeyPress::pageUpKey },
  48948. { "page down", KeyPress::pageDownKey },
  48949. { "home", KeyPress::homeKey },
  48950. { "end", KeyPress::endKey },
  48951. { "delete", KeyPress::deleteKey },
  48952. { "insert", KeyPress::insertKey },
  48953. { "tab", KeyPress::tabKey },
  48954. { "play", KeyPress::playKey },
  48955. { "stop", KeyPress::stopKey },
  48956. { "fast forward", KeyPress::fastForwardKey },
  48957. { "rewind", KeyPress::rewindKey }
  48958. };
  48959. static const String numberPadPrefix() { return "numpad "; }
  48960. }
  48961. const KeyPress KeyPress::createFromDescription (const String& desc)
  48962. {
  48963. int modifiers = 0;
  48964. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48965. || desc.containsWholeWordIgnoreCase ("control")
  48966. || desc.containsWholeWordIgnoreCase ("ctl"))
  48967. modifiers |= ModifierKeys::ctrlModifier;
  48968. if (desc.containsWholeWordIgnoreCase ("shift")
  48969. || desc.containsWholeWordIgnoreCase ("shft"))
  48970. modifiers |= ModifierKeys::shiftModifier;
  48971. if (desc.containsWholeWordIgnoreCase ("alt")
  48972. || desc.containsWholeWordIgnoreCase ("option"))
  48973. modifiers |= ModifierKeys::altModifier;
  48974. if (desc.containsWholeWordIgnoreCase ("command")
  48975. || desc.containsWholeWordIgnoreCase ("cmd"))
  48976. modifiers |= ModifierKeys::commandModifier;
  48977. int key = 0;
  48978. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48979. {
  48980. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48981. {
  48982. key = KeyPressHelpers::translations[i].code;
  48983. break;
  48984. }
  48985. }
  48986. if (key == 0)
  48987. {
  48988. // see if it's a numpad key..
  48989. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48990. {
  48991. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48992. if (lastChar >= '0' && lastChar <= '9')
  48993. key = numberPad0 + lastChar - '0';
  48994. else if (lastChar == '+')
  48995. key = numberPadAdd;
  48996. else if (lastChar == '-')
  48997. key = numberPadSubtract;
  48998. else if (lastChar == '*')
  48999. key = numberPadMultiply;
  49000. else if (lastChar == '/')
  49001. key = numberPadDivide;
  49002. else if (lastChar == '.')
  49003. key = numberPadDecimalPoint;
  49004. else if (lastChar == '=')
  49005. key = numberPadEquals;
  49006. else if (desc.endsWith ("separator"))
  49007. key = numberPadSeparator;
  49008. else if (desc.endsWith ("delete"))
  49009. key = numberPadDelete;
  49010. }
  49011. if (key == 0)
  49012. {
  49013. // see if it's a function key..
  49014. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49015. for (int i = 1; i <= 12; ++i)
  49016. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49017. key = F1Key + i - 1;
  49018. if (key == 0)
  49019. {
  49020. // give up and use the hex code..
  49021. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49022. .toLowerCase()
  49023. .retainCharacters ("0123456789abcdef")
  49024. .getHexValue32();
  49025. if (hexCode > 0)
  49026. key = hexCode;
  49027. else
  49028. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49029. }
  49030. }
  49031. }
  49032. return KeyPress (key, ModifierKeys (modifiers), 0);
  49033. }
  49034. const String KeyPress::getTextDescription() const
  49035. {
  49036. String desc;
  49037. if (keyCode > 0)
  49038. {
  49039. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49040. // want to store it as being a slash, not shift+whatever.
  49041. if (textCharacter == '/')
  49042. return "/";
  49043. if (mods.isCtrlDown())
  49044. desc << "ctrl + ";
  49045. if (mods.isShiftDown())
  49046. desc << "shift + ";
  49047. #if JUCE_MAC
  49048. // only do this on the mac, because on Windows ctrl and command are the same,
  49049. // and this would get confusing
  49050. if (mods.isCommandDown())
  49051. desc << "command + ";
  49052. if (mods.isAltDown())
  49053. desc << "option + ";
  49054. #else
  49055. if (mods.isAltDown())
  49056. desc << "alt + ";
  49057. #endif
  49058. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49059. if (keyCode == KeyPressHelpers::translations[i].code)
  49060. return desc + KeyPressHelpers::translations[i].name;
  49061. if (keyCode >= F1Key && keyCode <= F16Key)
  49062. desc << 'F' << (1 + keyCode - F1Key);
  49063. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49064. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49065. else if (keyCode >= 33 && keyCode < 176)
  49066. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49067. else if (keyCode == numberPadAdd)
  49068. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49069. else if (keyCode == numberPadSubtract)
  49070. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49071. else if (keyCode == numberPadMultiply)
  49072. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49073. else if (keyCode == numberPadDivide)
  49074. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49075. else if (keyCode == numberPadSeparator)
  49076. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49077. else if (keyCode == numberPadDecimalPoint)
  49078. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49079. else if (keyCode == numberPadDelete)
  49080. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49081. else
  49082. desc << '#' << String::toHexString (keyCode);
  49083. }
  49084. return desc;
  49085. }
  49086. END_JUCE_NAMESPACE
  49087. /*** End of inlined file: juce_KeyPress.cpp ***/
  49088. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49089. BEGIN_JUCE_NAMESPACE
  49090. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49091. : commandManager (commandManager_)
  49092. {
  49093. // A manager is needed to get the descriptions of commands, and will be called when
  49094. // a command is invoked. So you can't leave this null..
  49095. jassert (commandManager_ != 0);
  49096. Desktop::getInstance().addFocusChangeListener (this);
  49097. }
  49098. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49099. : commandManager (other.commandManager)
  49100. {
  49101. Desktop::getInstance().addFocusChangeListener (this);
  49102. }
  49103. KeyPressMappingSet::~KeyPressMappingSet()
  49104. {
  49105. Desktop::getInstance().removeFocusChangeListener (this);
  49106. }
  49107. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49108. {
  49109. for (int i = 0; i < mappings.size(); ++i)
  49110. if (mappings.getUnchecked(i)->commandID == commandID)
  49111. return mappings.getUnchecked (i)->keypresses;
  49112. return Array <KeyPress> ();
  49113. }
  49114. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49115. const KeyPress& newKeyPress,
  49116. int insertIndex)
  49117. {
  49118. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49119. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49120. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49121. && ! newKeyPress.getModifiers().isShiftDown()));
  49122. if (findCommandForKeyPress (newKeyPress) != commandID)
  49123. {
  49124. removeKeyPress (newKeyPress);
  49125. if (newKeyPress.isValid())
  49126. {
  49127. for (int i = mappings.size(); --i >= 0;)
  49128. {
  49129. if (mappings.getUnchecked(i)->commandID == commandID)
  49130. {
  49131. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49132. sendChangeMessage (this);
  49133. return;
  49134. }
  49135. }
  49136. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49137. if (ci != 0)
  49138. {
  49139. CommandMapping* const cm = new CommandMapping();
  49140. cm->commandID = commandID;
  49141. cm->keypresses.add (newKeyPress);
  49142. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49143. mappings.add (cm);
  49144. sendChangeMessage (this);
  49145. }
  49146. }
  49147. }
  49148. }
  49149. void KeyPressMappingSet::resetToDefaultMappings()
  49150. {
  49151. mappings.clear();
  49152. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49153. {
  49154. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49155. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49156. {
  49157. addKeyPress (ci->commandID,
  49158. ci->defaultKeypresses.getReference (j));
  49159. }
  49160. }
  49161. sendChangeMessage (this);
  49162. }
  49163. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49164. {
  49165. clearAllKeyPresses (commandID);
  49166. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49167. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49168. {
  49169. addKeyPress (ci->commandID,
  49170. ci->defaultKeypresses.getReference (j));
  49171. }
  49172. }
  49173. void KeyPressMappingSet::clearAllKeyPresses()
  49174. {
  49175. if (mappings.size() > 0)
  49176. {
  49177. sendChangeMessage (this);
  49178. mappings.clear();
  49179. }
  49180. }
  49181. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49182. {
  49183. for (int i = mappings.size(); --i >= 0;)
  49184. {
  49185. if (mappings.getUnchecked(i)->commandID == commandID)
  49186. {
  49187. mappings.remove (i);
  49188. sendChangeMessage (this);
  49189. }
  49190. }
  49191. }
  49192. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49193. {
  49194. if (keypress.isValid())
  49195. {
  49196. for (int i = mappings.size(); --i >= 0;)
  49197. {
  49198. CommandMapping* const cm = mappings.getUnchecked(i);
  49199. for (int j = cm->keypresses.size(); --j >= 0;)
  49200. {
  49201. if (keypress == cm->keypresses [j])
  49202. {
  49203. cm->keypresses.remove (j);
  49204. sendChangeMessage (this);
  49205. }
  49206. }
  49207. }
  49208. }
  49209. }
  49210. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49211. {
  49212. for (int i = mappings.size(); --i >= 0;)
  49213. {
  49214. if (mappings.getUnchecked(i)->commandID == commandID)
  49215. {
  49216. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49217. sendChangeMessage (this);
  49218. break;
  49219. }
  49220. }
  49221. }
  49222. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49223. {
  49224. for (int i = 0; i < mappings.size(); ++i)
  49225. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49226. return mappings.getUnchecked(i)->commandID;
  49227. return 0;
  49228. }
  49229. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49230. {
  49231. for (int i = mappings.size(); --i >= 0;)
  49232. if (mappings.getUnchecked(i)->commandID == commandID)
  49233. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49234. return false;
  49235. }
  49236. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49237. const KeyPress& key,
  49238. const bool isKeyDown,
  49239. const int millisecsSinceKeyPressed,
  49240. Component* const originatingComponent) const
  49241. {
  49242. ApplicationCommandTarget::InvocationInfo info (commandID);
  49243. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49244. info.isKeyDown = isKeyDown;
  49245. info.keyPress = key;
  49246. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49247. info.originatingComponent = originatingComponent;
  49248. commandManager->invoke (info, false);
  49249. }
  49250. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49251. {
  49252. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49253. {
  49254. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49255. {
  49256. // if the XML was created as a set of differences from the default mappings,
  49257. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49258. resetToDefaultMappings();
  49259. }
  49260. else
  49261. {
  49262. // if the XML was created calling createXml (false), then we need to clear all
  49263. // the keys and treat the xml as describing the entire set of mappings.
  49264. clearAllKeyPresses();
  49265. }
  49266. forEachXmlChildElement (xmlVersion, map)
  49267. {
  49268. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49269. if (commandId != 0)
  49270. {
  49271. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49272. if (map->hasTagName ("MAPPING"))
  49273. {
  49274. addKeyPress (commandId, key);
  49275. }
  49276. else if (map->hasTagName ("UNMAPPING"))
  49277. {
  49278. if (containsMapping (commandId, key))
  49279. removeKeyPress (key);
  49280. }
  49281. }
  49282. }
  49283. return true;
  49284. }
  49285. return false;
  49286. }
  49287. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49288. {
  49289. ScopedPointer <KeyPressMappingSet> defaultSet;
  49290. if (saveDifferencesFromDefaultSet)
  49291. {
  49292. defaultSet = new KeyPressMappingSet (commandManager);
  49293. defaultSet->resetToDefaultMappings();
  49294. }
  49295. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49296. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49297. int i;
  49298. for (i = 0; i < mappings.size(); ++i)
  49299. {
  49300. const CommandMapping* const cm = mappings.getUnchecked(i);
  49301. for (int j = 0; j < cm->keypresses.size(); ++j)
  49302. {
  49303. if (defaultSet == 0
  49304. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49305. {
  49306. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49307. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49308. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49309. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49310. }
  49311. }
  49312. }
  49313. if (defaultSet != 0)
  49314. {
  49315. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49316. {
  49317. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49318. for (int j = 0; j < cm->keypresses.size(); ++j)
  49319. {
  49320. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49321. {
  49322. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49323. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49324. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49325. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49326. }
  49327. }
  49328. }
  49329. }
  49330. return doc;
  49331. }
  49332. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49333. Component* originatingComponent)
  49334. {
  49335. bool used = false;
  49336. const CommandID commandID = findCommandForKeyPress (key);
  49337. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49338. if (ci != 0
  49339. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49340. {
  49341. ApplicationCommandInfo info (0);
  49342. if (commandManager->getTargetForCommand (commandID, info) != 0
  49343. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49344. {
  49345. invokeCommand (commandID, key, true, 0, originatingComponent);
  49346. used = true;
  49347. }
  49348. else
  49349. {
  49350. if (originatingComponent != 0)
  49351. originatingComponent->getLookAndFeel().playAlertSound();
  49352. }
  49353. }
  49354. return used;
  49355. }
  49356. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49357. {
  49358. bool used = false;
  49359. const uint32 now = Time::getMillisecondCounter();
  49360. for (int i = mappings.size(); --i >= 0;)
  49361. {
  49362. CommandMapping* const cm = mappings.getUnchecked(i);
  49363. if (cm->wantsKeyUpDownCallbacks)
  49364. {
  49365. for (int j = cm->keypresses.size(); --j >= 0;)
  49366. {
  49367. const KeyPress key (cm->keypresses.getReference (j));
  49368. const bool isDown = key.isCurrentlyDown();
  49369. int keyPressEntryIndex = 0;
  49370. bool wasDown = false;
  49371. for (int k = keysDown.size(); --k >= 0;)
  49372. {
  49373. if (key == keysDown.getUnchecked(k)->key)
  49374. {
  49375. keyPressEntryIndex = k;
  49376. wasDown = true;
  49377. used = true;
  49378. break;
  49379. }
  49380. }
  49381. if (isDown != wasDown)
  49382. {
  49383. int millisecs = 0;
  49384. if (isDown)
  49385. {
  49386. KeyPressTime* const k = new KeyPressTime();
  49387. k->key = key;
  49388. k->timeWhenPressed = now;
  49389. keysDown.add (k);
  49390. }
  49391. else
  49392. {
  49393. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49394. if (now > pressTime)
  49395. millisecs = now - pressTime;
  49396. keysDown.remove (keyPressEntryIndex);
  49397. }
  49398. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49399. used = true;
  49400. }
  49401. }
  49402. }
  49403. }
  49404. return used;
  49405. }
  49406. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49407. {
  49408. if (focusedComponent != 0)
  49409. focusedComponent->keyStateChanged (false);
  49410. }
  49411. END_JUCE_NAMESPACE
  49412. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49413. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49414. BEGIN_JUCE_NAMESPACE
  49415. ModifierKeys::ModifierKeys (const int flags_) throw()
  49416. : flags (flags_)
  49417. {
  49418. }
  49419. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49420. : flags (other.flags)
  49421. {
  49422. }
  49423. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49424. {
  49425. flags = other.flags;
  49426. return *this;
  49427. }
  49428. ModifierKeys ModifierKeys::currentModifiers;
  49429. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49430. {
  49431. return currentModifiers;
  49432. }
  49433. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49434. {
  49435. int num = 0;
  49436. if (isLeftButtonDown()) ++num;
  49437. if (isRightButtonDown()) ++num;
  49438. if (isMiddleButtonDown()) ++num;
  49439. return num;
  49440. }
  49441. END_JUCE_NAMESPACE
  49442. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49443. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49444. BEGIN_JUCE_NAMESPACE
  49445. class ComponentAnimator::AnimationTask
  49446. {
  49447. public:
  49448. AnimationTask (Component* const comp)
  49449. : component (comp)
  49450. {
  49451. }
  49452. Component::SafePointer<Component> component;
  49453. Rectangle<int> destination;
  49454. int msElapsed, msTotal;
  49455. double startSpeed, midSpeed, endSpeed, lastProgress;
  49456. double left, top, right, bottom;
  49457. bool useTimeslice (const int elapsed)
  49458. {
  49459. if (component == 0)
  49460. return false;
  49461. msElapsed += elapsed;
  49462. double newProgress = msElapsed / (double) msTotal;
  49463. if (newProgress >= 0 && newProgress < 1.0)
  49464. {
  49465. newProgress = timeToDistance (newProgress);
  49466. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49467. jassert (newProgress >= lastProgress);
  49468. lastProgress = newProgress;
  49469. left += (destination.getX() - left) * delta;
  49470. top += (destination.getY() - top) * delta;
  49471. right += (destination.getRight() - right) * delta;
  49472. bottom += (destination.getBottom() - bottom) * delta;
  49473. if (delta < 1.0)
  49474. {
  49475. const Rectangle<int> newBounds (roundToInt (left),
  49476. roundToInt (top),
  49477. roundToInt (right - left),
  49478. roundToInt (bottom - top));
  49479. if (newBounds != destination)
  49480. {
  49481. component->setBounds (newBounds);
  49482. return true;
  49483. }
  49484. }
  49485. }
  49486. component->setBounds (destination);
  49487. return false;
  49488. }
  49489. void moveToFinalDestination()
  49490. {
  49491. if (component != 0)
  49492. component->setBounds (destination);
  49493. }
  49494. private:
  49495. inline double timeToDistance (const double time) const
  49496. {
  49497. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49498. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49499. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49500. }
  49501. };
  49502. ComponentAnimator::ComponentAnimator()
  49503. : lastTime (0)
  49504. {
  49505. }
  49506. ComponentAnimator::~ComponentAnimator()
  49507. {
  49508. cancelAllAnimations (false);
  49509. jassert (tasks.size() == 0);
  49510. }
  49511. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49512. {
  49513. for (int i = tasks.size(); --i >= 0;)
  49514. if (component == tasks.getUnchecked(i)->component.getComponent())
  49515. return tasks.getUnchecked(i);
  49516. return 0;
  49517. }
  49518. void ComponentAnimator::animateComponent (Component* const component,
  49519. const Rectangle<int>& finalPosition,
  49520. const int millisecondsToSpendMoving,
  49521. const double startSpeed,
  49522. const double endSpeed)
  49523. {
  49524. if (component != 0)
  49525. {
  49526. AnimationTask* at = findTaskFor (component);
  49527. if (at == 0)
  49528. {
  49529. at = new AnimationTask (component);
  49530. tasks.add (at);
  49531. sendChangeMessage (this);
  49532. }
  49533. at->msElapsed = 0;
  49534. at->lastProgress = 0;
  49535. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49536. at->destination = finalPosition;
  49537. // the speeds must be 0 or greater!
  49538. jassert (startSpeed >= 0 && endSpeed >= 0)
  49539. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49540. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49541. at->midSpeed = invTotalDistance;
  49542. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49543. at->left = component->getX();
  49544. at->top = component->getY();
  49545. at->right = component->getRight();
  49546. at->bottom = component->getBottom();
  49547. if (! isTimerRunning())
  49548. {
  49549. lastTime = Time::getMillisecondCounter();
  49550. startTimer (1000 / 50);
  49551. }
  49552. }
  49553. }
  49554. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49555. {
  49556. for (int i = tasks.size(); --i >= 0;)
  49557. {
  49558. AnimationTask* const at = tasks.getUnchecked(i);
  49559. if (moveComponentsToTheirFinalPositions)
  49560. at->moveToFinalDestination();
  49561. delete at;
  49562. tasks.remove (i);
  49563. sendChangeMessage (this);
  49564. }
  49565. }
  49566. void ComponentAnimator::cancelAnimation (Component* const component,
  49567. const bool moveComponentToItsFinalPosition)
  49568. {
  49569. AnimationTask* const at = findTaskFor (component);
  49570. if (at != 0)
  49571. {
  49572. if (moveComponentToItsFinalPosition)
  49573. at->moveToFinalDestination();
  49574. tasks.removeValue (at);
  49575. delete at;
  49576. sendChangeMessage (this);
  49577. }
  49578. }
  49579. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49580. {
  49581. AnimationTask* const at = findTaskFor (component);
  49582. if (at != 0)
  49583. return at->destination;
  49584. else if (component != 0)
  49585. return component->getBounds();
  49586. return Rectangle<int>();
  49587. }
  49588. bool ComponentAnimator::isAnimating (Component* component) const
  49589. {
  49590. return findTaskFor (component) != 0;
  49591. }
  49592. void ComponentAnimator::timerCallback()
  49593. {
  49594. const uint32 timeNow = Time::getMillisecondCounter();
  49595. if (lastTime == 0 || lastTime == timeNow)
  49596. lastTime = timeNow;
  49597. const int elapsed = timeNow - lastTime;
  49598. for (int i = tasks.size(); --i >= 0;)
  49599. {
  49600. AnimationTask* const at = tasks.getUnchecked(i);
  49601. if (! at->useTimeslice (elapsed))
  49602. {
  49603. tasks.remove (i);
  49604. delete at;
  49605. sendChangeMessage (this);
  49606. }
  49607. }
  49608. lastTime = timeNow;
  49609. if (tasks.size() == 0)
  49610. stopTimer();
  49611. }
  49612. END_JUCE_NAMESPACE
  49613. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49614. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49615. BEGIN_JUCE_NAMESPACE
  49616. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49617. : minW (0),
  49618. maxW (0x3fffffff),
  49619. minH (0),
  49620. maxH (0x3fffffff),
  49621. minOffTop (0),
  49622. minOffLeft (0),
  49623. minOffBottom (0),
  49624. minOffRight (0),
  49625. aspectRatio (0.0)
  49626. {
  49627. }
  49628. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49629. {
  49630. }
  49631. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49632. {
  49633. minW = minimumWidth;
  49634. }
  49635. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49636. {
  49637. maxW = maximumWidth;
  49638. }
  49639. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49640. {
  49641. minH = minimumHeight;
  49642. }
  49643. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49644. {
  49645. maxH = maximumHeight;
  49646. }
  49647. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49648. {
  49649. jassert (maxW >= minimumWidth);
  49650. jassert (maxH >= minimumHeight);
  49651. jassert (minimumWidth > 0 && minimumHeight > 0);
  49652. minW = minimumWidth;
  49653. minH = minimumHeight;
  49654. if (minW > maxW)
  49655. maxW = minW;
  49656. if (minH > maxH)
  49657. maxH = minH;
  49658. }
  49659. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49660. {
  49661. jassert (maximumWidth >= minW);
  49662. jassert (maximumHeight >= minH);
  49663. jassert (maximumWidth > 0 && maximumHeight > 0);
  49664. maxW = jmax (minW, maximumWidth);
  49665. maxH = jmax (minH, maximumHeight);
  49666. }
  49667. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49668. const int minimumHeight,
  49669. const int maximumWidth,
  49670. const int maximumHeight) throw()
  49671. {
  49672. jassert (maximumWidth >= minimumWidth);
  49673. jassert (maximumHeight >= minimumHeight);
  49674. jassert (maximumWidth > 0 && maximumHeight > 0);
  49675. jassert (minimumWidth > 0 && minimumHeight > 0);
  49676. minW = jmax (0, minimumWidth);
  49677. minH = jmax (0, minimumHeight);
  49678. maxW = jmax (minW, maximumWidth);
  49679. maxH = jmax (minH, maximumHeight);
  49680. }
  49681. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49682. const int minimumWhenOffTheLeft,
  49683. const int minimumWhenOffTheBottom,
  49684. const int minimumWhenOffTheRight) throw()
  49685. {
  49686. minOffTop = minimumWhenOffTheTop;
  49687. minOffLeft = minimumWhenOffTheLeft;
  49688. minOffBottom = minimumWhenOffTheBottom;
  49689. minOffRight = minimumWhenOffTheRight;
  49690. }
  49691. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49692. {
  49693. aspectRatio = jmax (0.0, widthOverHeight);
  49694. }
  49695. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49696. {
  49697. return aspectRatio;
  49698. }
  49699. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49700. const Rectangle<int>& targetBounds,
  49701. const bool isStretchingTop,
  49702. const bool isStretchingLeft,
  49703. const bool isStretchingBottom,
  49704. const bool isStretchingRight)
  49705. {
  49706. jassert (component != 0);
  49707. Rectangle<int> limits, bounds (targetBounds);
  49708. BorderSize border;
  49709. Component* const parent = component->getParentComponent();
  49710. if (parent == 0)
  49711. {
  49712. ComponentPeer* peer = component->getPeer();
  49713. if (peer != 0)
  49714. border = peer->getFrameSize();
  49715. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49716. }
  49717. else
  49718. {
  49719. limits.setSize (parent->getWidth(), parent->getHeight());
  49720. }
  49721. border.addTo (bounds);
  49722. checkBounds (bounds,
  49723. border.addedTo (component->getBounds()), limits,
  49724. isStretchingTop, isStretchingLeft,
  49725. isStretchingBottom, isStretchingRight);
  49726. border.subtractFrom (bounds);
  49727. applyBoundsToComponent (component, bounds);
  49728. }
  49729. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49730. {
  49731. setBoundsForComponent (component, component->getBounds(),
  49732. false, false, false, false);
  49733. }
  49734. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49735. const Rectangle<int>& bounds)
  49736. {
  49737. component->setBounds (bounds);
  49738. }
  49739. void ComponentBoundsConstrainer::resizeStart()
  49740. {
  49741. }
  49742. void ComponentBoundsConstrainer::resizeEnd()
  49743. {
  49744. }
  49745. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49746. const Rectangle<int>& old,
  49747. const Rectangle<int>& limits,
  49748. const bool isStretchingTop,
  49749. const bool isStretchingLeft,
  49750. const bool isStretchingBottom,
  49751. const bool isStretchingRight)
  49752. {
  49753. int x = bounds.getX();
  49754. int y = bounds.getY();
  49755. int w = bounds.getWidth();
  49756. int h = bounds.getHeight();
  49757. // constrain the size if it's being stretched..
  49758. if (isStretchingLeft)
  49759. {
  49760. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49761. w = old.getRight() - x;
  49762. }
  49763. if (isStretchingRight)
  49764. {
  49765. w = jlimit (minW, maxW, w);
  49766. }
  49767. if (isStretchingTop)
  49768. {
  49769. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49770. h = old.getBottom() - y;
  49771. }
  49772. if (isStretchingBottom)
  49773. {
  49774. h = jlimit (minH, maxH, h);
  49775. }
  49776. // constrain the aspect ratio if one has been specified..
  49777. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49778. {
  49779. bool adjustWidth;
  49780. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49781. {
  49782. adjustWidth = true;
  49783. }
  49784. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49785. {
  49786. adjustWidth = false;
  49787. }
  49788. else
  49789. {
  49790. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49791. const double newRatio = std::abs (w / (double) h);
  49792. adjustWidth = (oldRatio > newRatio);
  49793. }
  49794. if (adjustWidth)
  49795. {
  49796. w = roundToInt (h * aspectRatio);
  49797. if (w > maxW || w < minW)
  49798. {
  49799. w = jlimit (minW, maxW, w);
  49800. h = roundToInt (w / aspectRatio);
  49801. }
  49802. }
  49803. else
  49804. {
  49805. h = roundToInt (w / aspectRatio);
  49806. if (h > maxH || h < minH)
  49807. {
  49808. h = jlimit (minH, maxH, h);
  49809. w = roundToInt (h * aspectRatio);
  49810. }
  49811. }
  49812. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49813. {
  49814. x = old.getX() + (old.getWidth() - w) / 2;
  49815. }
  49816. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49817. {
  49818. y = old.getY() + (old.getHeight() - h) / 2;
  49819. }
  49820. else
  49821. {
  49822. if (isStretchingLeft)
  49823. x = old.getRight() - w;
  49824. if (isStretchingTop)
  49825. y = old.getBottom() - h;
  49826. }
  49827. }
  49828. // ...and constrain the position if limits have been set for that.
  49829. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49830. {
  49831. if (minOffTop > 0)
  49832. {
  49833. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49834. if (y < limit)
  49835. {
  49836. if (isStretchingTop)
  49837. h -= (limit - y);
  49838. y = limit;
  49839. }
  49840. }
  49841. if (minOffLeft > 0)
  49842. {
  49843. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49844. if (x < limit)
  49845. {
  49846. if (isStretchingLeft)
  49847. w -= (limit - x);
  49848. x = limit;
  49849. }
  49850. }
  49851. if (minOffBottom > 0)
  49852. {
  49853. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49854. if (y > limit)
  49855. {
  49856. if (isStretchingBottom)
  49857. h += (limit - y);
  49858. else
  49859. y = limit;
  49860. }
  49861. }
  49862. if (minOffRight > 0)
  49863. {
  49864. const int limit = limits.getRight() - jmin (minOffRight, w);
  49865. if (x > limit)
  49866. {
  49867. if (isStretchingRight)
  49868. w += (limit - x);
  49869. else
  49870. x = limit;
  49871. }
  49872. }
  49873. }
  49874. jassert (w >= 0 && h >= 0);
  49875. bounds = Rectangle<int> (x, y, w, h);
  49876. }
  49877. END_JUCE_NAMESPACE
  49878. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49879. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49880. BEGIN_JUCE_NAMESPACE
  49881. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49882. : component (component_),
  49883. lastPeer (0),
  49884. reentrant (false)
  49885. {
  49886. jassert (component != 0); // can't use this with a null pointer..
  49887. component->addComponentListener (this);
  49888. registerWithParentComps();
  49889. }
  49890. ComponentMovementWatcher::~ComponentMovementWatcher()
  49891. {
  49892. component->removeComponentListener (this);
  49893. unregister();
  49894. }
  49895. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49896. {
  49897. // agh! don't delete the target component without deleting this object first!
  49898. jassert (component != 0);
  49899. if (! reentrant)
  49900. {
  49901. reentrant = true;
  49902. ComponentPeer* const peer = component->getPeer();
  49903. if (peer != lastPeer)
  49904. {
  49905. componentPeerChanged();
  49906. if (component == 0)
  49907. return;
  49908. lastPeer = peer;
  49909. }
  49910. unregister();
  49911. registerWithParentComps();
  49912. reentrant = false;
  49913. componentMovedOrResized (*component, true, true);
  49914. }
  49915. }
  49916. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49917. {
  49918. // agh! don't delete the target component without deleting this object first!
  49919. jassert (component != 0);
  49920. if (wasMoved)
  49921. {
  49922. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49923. wasMoved = lastBounds.getPosition() != pos;
  49924. lastBounds.setPosition (pos);
  49925. }
  49926. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49927. lastBounds.setSize (component->getWidth(), component->getHeight());
  49928. if (wasMoved || wasResized)
  49929. componentMovedOrResized (wasMoved, wasResized);
  49930. }
  49931. void ComponentMovementWatcher::registerWithParentComps()
  49932. {
  49933. Component* p = component->getParentComponent();
  49934. while (p != 0)
  49935. {
  49936. p->addComponentListener (this);
  49937. registeredParentComps.add (p);
  49938. p = p->getParentComponent();
  49939. }
  49940. }
  49941. void ComponentMovementWatcher::unregister()
  49942. {
  49943. for (int i = registeredParentComps.size(); --i >= 0;)
  49944. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49945. registeredParentComps.clear();
  49946. }
  49947. END_JUCE_NAMESPACE
  49948. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49949. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49950. BEGIN_JUCE_NAMESPACE
  49951. GroupComponent::GroupComponent (const String& componentName,
  49952. const String& labelText)
  49953. : Component (componentName),
  49954. text (labelText),
  49955. justification (Justification::left)
  49956. {
  49957. setInterceptsMouseClicks (false, true);
  49958. }
  49959. GroupComponent::~GroupComponent()
  49960. {
  49961. }
  49962. void GroupComponent::setText (const String& newText)
  49963. {
  49964. if (text != newText)
  49965. {
  49966. text = newText;
  49967. repaint();
  49968. }
  49969. }
  49970. const String GroupComponent::getText() const
  49971. {
  49972. return text;
  49973. }
  49974. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49975. {
  49976. if (justification != newJustification)
  49977. {
  49978. justification = newJustification;
  49979. repaint();
  49980. }
  49981. }
  49982. void GroupComponent::paint (Graphics& g)
  49983. {
  49984. getLookAndFeel()
  49985. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49986. text, justification,
  49987. *this);
  49988. }
  49989. void GroupComponent::enablementChanged()
  49990. {
  49991. repaint();
  49992. }
  49993. void GroupComponent::colourChanged()
  49994. {
  49995. repaint();
  49996. }
  49997. END_JUCE_NAMESPACE
  49998. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49999. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50000. BEGIN_JUCE_NAMESPACE
  50001. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50002. : DocumentWindow (String::empty, backgroundColour,
  50003. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50004. {
  50005. }
  50006. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50007. {
  50008. }
  50009. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50010. {
  50011. MultiDocumentPanel* const owner = getOwner();
  50012. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50013. if (owner != 0)
  50014. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50015. }
  50016. void MultiDocumentPanelWindow::closeButtonPressed()
  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->closeDocument (getContentComponent(), true);
  50022. }
  50023. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50024. {
  50025. DocumentWindow::activeWindowStatusChanged();
  50026. updateOrder();
  50027. }
  50028. void MultiDocumentPanelWindow::broughtToFront()
  50029. {
  50030. DocumentWindow::broughtToFront();
  50031. updateOrder();
  50032. }
  50033. void MultiDocumentPanelWindow::updateOrder()
  50034. {
  50035. MultiDocumentPanel* const owner = getOwner();
  50036. if (owner != 0)
  50037. owner->updateOrder();
  50038. }
  50039. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50040. {
  50041. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50042. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50043. }
  50044. class MDITabbedComponentInternal : public TabbedComponent
  50045. {
  50046. public:
  50047. MDITabbedComponentInternal()
  50048. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50049. {
  50050. }
  50051. ~MDITabbedComponentInternal()
  50052. {
  50053. }
  50054. void currentTabChanged (int, const String&)
  50055. {
  50056. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50057. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50058. if (owner != 0)
  50059. owner->updateOrder();
  50060. }
  50061. };
  50062. MultiDocumentPanel::MultiDocumentPanel()
  50063. : mode (MaximisedWindowsWithTabs),
  50064. backgroundColour (Colours::lightblue),
  50065. maximumNumDocuments (0),
  50066. numDocsBeforeTabsUsed (0)
  50067. {
  50068. setOpaque (true);
  50069. }
  50070. MultiDocumentPanel::~MultiDocumentPanel()
  50071. {
  50072. closeAllDocuments (false);
  50073. }
  50074. static bool shouldDeleteComp (Component* const c)
  50075. {
  50076. return c->getProperties() ["mdiDocumentDelete_"];
  50077. }
  50078. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50079. {
  50080. while (components.size() > 0)
  50081. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50082. return false;
  50083. return true;
  50084. }
  50085. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50086. {
  50087. return new MultiDocumentPanelWindow (backgroundColour);
  50088. }
  50089. void MultiDocumentPanel::addWindow (Component* component)
  50090. {
  50091. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50092. dw->setResizable (true, false);
  50093. dw->setContentComponent (component, false, true);
  50094. dw->setName (component->getName());
  50095. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50096. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50097. int x = 4;
  50098. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50099. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50100. x += 16;
  50101. dw->setTopLeftPosition (x, x);
  50102. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50103. if (pos.toString().isNotEmpty())
  50104. dw->restoreWindowStateFromString (pos.toString());
  50105. addAndMakeVisible (dw);
  50106. dw->toFront (true);
  50107. }
  50108. bool MultiDocumentPanel::addDocument (Component* const component,
  50109. const Colour& docColour,
  50110. const bool deleteWhenRemoved)
  50111. {
  50112. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50113. // with a frame-within-a-frame! Just pass in the bare content component.
  50114. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50115. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50116. return false;
  50117. components.add (component);
  50118. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50119. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50120. component->addComponentListener (this);
  50121. if (mode == FloatingWindows)
  50122. {
  50123. if (isFullscreenWhenOneDocument())
  50124. {
  50125. if (components.size() == 1)
  50126. {
  50127. addAndMakeVisible (component);
  50128. }
  50129. else
  50130. {
  50131. if (components.size() == 2)
  50132. addWindow (components.getFirst());
  50133. addWindow (component);
  50134. }
  50135. }
  50136. else
  50137. {
  50138. addWindow (component);
  50139. }
  50140. }
  50141. else
  50142. {
  50143. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50144. {
  50145. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50146. Array <Component*> temp (components);
  50147. for (int i = 0; i < temp.size(); ++i)
  50148. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50149. resized();
  50150. }
  50151. else
  50152. {
  50153. if (tabComponent != 0)
  50154. tabComponent->addTab (component->getName(), docColour, component, false);
  50155. else
  50156. addAndMakeVisible (component);
  50157. }
  50158. setActiveDocument (component);
  50159. }
  50160. resized();
  50161. activeDocumentChanged();
  50162. return true;
  50163. }
  50164. bool MultiDocumentPanel::closeDocument (Component* component,
  50165. const bool checkItsOkToCloseFirst)
  50166. {
  50167. if (components.contains (component))
  50168. {
  50169. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50170. return false;
  50171. component->removeComponentListener (this);
  50172. const bool shouldDelete = shouldDeleteComp (component);
  50173. component->getProperties().remove ("mdiDocumentDelete_");
  50174. component->getProperties().remove ("mdiDocumentBkg_");
  50175. if (mode == FloatingWindows)
  50176. {
  50177. for (int i = getNumChildComponents(); --i >= 0;)
  50178. {
  50179. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50180. if (dw != 0 && dw->getContentComponent() == component)
  50181. {
  50182. dw->setContentComponent (0, false);
  50183. delete dw;
  50184. break;
  50185. }
  50186. }
  50187. if (shouldDelete)
  50188. delete component;
  50189. components.removeValue (component);
  50190. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50191. {
  50192. for (int i = getNumChildComponents(); --i >= 0;)
  50193. {
  50194. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50195. if (dw != 0)
  50196. {
  50197. dw->setContentComponent (0, false);
  50198. delete dw;
  50199. }
  50200. }
  50201. addAndMakeVisible (components.getFirst());
  50202. }
  50203. }
  50204. else
  50205. {
  50206. jassert (components.indexOf (component) >= 0);
  50207. if (tabComponent != 0)
  50208. {
  50209. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50210. if (tabComponent->getTabContentComponent (i) == component)
  50211. tabComponent->removeTab (i);
  50212. }
  50213. else
  50214. {
  50215. removeChildComponent (component);
  50216. }
  50217. if (shouldDelete)
  50218. delete component;
  50219. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50220. tabComponent = 0;
  50221. components.removeValue (component);
  50222. if (components.size() > 0 && tabComponent == 0)
  50223. addAndMakeVisible (components.getFirst());
  50224. }
  50225. resized();
  50226. activeDocumentChanged();
  50227. }
  50228. else
  50229. {
  50230. jassertfalse;
  50231. }
  50232. return true;
  50233. }
  50234. int MultiDocumentPanel::getNumDocuments() const throw()
  50235. {
  50236. return components.size();
  50237. }
  50238. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50239. {
  50240. return components [index];
  50241. }
  50242. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50243. {
  50244. if (mode == FloatingWindows)
  50245. {
  50246. for (int i = getNumChildComponents(); --i >= 0;)
  50247. {
  50248. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50249. if (dw != 0 && dw->isActiveWindow())
  50250. return dw->getContentComponent();
  50251. }
  50252. }
  50253. return components.getLast();
  50254. }
  50255. void MultiDocumentPanel::setActiveDocument (Component* component)
  50256. {
  50257. if (mode == FloatingWindows)
  50258. {
  50259. component = getContainerComp (component);
  50260. if (component != 0)
  50261. component->toFront (true);
  50262. }
  50263. else if (tabComponent != 0)
  50264. {
  50265. jassert (components.indexOf (component) >= 0);
  50266. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50267. {
  50268. if (tabComponent->getTabContentComponent (i) == component)
  50269. {
  50270. tabComponent->setCurrentTabIndex (i);
  50271. break;
  50272. }
  50273. }
  50274. }
  50275. else
  50276. {
  50277. component->grabKeyboardFocus();
  50278. }
  50279. }
  50280. void MultiDocumentPanel::activeDocumentChanged()
  50281. {
  50282. }
  50283. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50284. {
  50285. maximumNumDocuments = newNumber;
  50286. }
  50287. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50288. {
  50289. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50290. }
  50291. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50292. {
  50293. return numDocsBeforeTabsUsed != 0;
  50294. }
  50295. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50296. {
  50297. if (mode != newLayoutMode)
  50298. {
  50299. mode = newLayoutMode;
  50300. if (mode == FloatingWindows)
  50301. {
  50302. tabComponent = 0;
  50303. }
  50304. else
  50305. {
  50306. for (int i = getNumChildComponents(); --i >= 0;)
  50307. {
  50308. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50309. if (dw != 0)
  50310. {
  50311. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50312. dw->setContentComponent (0, false);
  50313. delete dw;
  50314. }
  50315. }
  50316. }
  50317. resized();
  50318. const Array <Component*> tempComps (components);
  50319. components.clear();
  50320. for (int i = 0; i < tempComps.size(); ++i)
  50321. {
  50322. Component* const c = tempComps.getUnchecked(i);
  50323. addDocument (c,
  50324. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50325. shouldDeleteComp (c));
  50326. }
  50327. }
  50328. }
  50329. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50330. {
  50331. if (backgroundColour != newBackgroundColour)
  50332. {
  50333. backgroundColour = newBackgroundColour;
  50334. setOpaque (newBackgroundColour.isOpaque());
  50335. repaint();
  50336. }
  50337. }
  50338. void MultiDocumentPanel::paint (Graphics& g)
  50339. {
  50340. g.fillAll (backgroundColour);
  50341. }
  50342. void MultiDocumentPanel::resized()
  50343. {
  50344. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50345. {
  50346. for (int i = getNumChildComponents(); --i >= 0;)
  50347. getChildComponent (i)->setBounds (getLocalBounds());
  50348. }
  50349. setWantsKeyboardFocus (components.size() == 0);
  50350. }
  50351. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50352. {
  50353. if (mode == FloatingWindows)
  50354. {
  50355. for (int i = 0; i < getNumChildComponents(); ++i)
  50356. {
  50357. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50358. if (dw != 0 && dw->getContentComponent() == c)
  50359. {
  50360. c = dw;
  50361. break;
  50362. }
  50363. }
  50364. }
  50365. return c;
  50366. }
  50367. void MultiDocumentPanel::componentNameChanged (Component&)
  50368. {
  50369. if (mode == FloatingWindows)
  50370. {
  50371. for (int i = 0; i < getNumChildComponents(); ++i)
  50372. {
  50373. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50374. if (dw != 0)
  50375. dw->setName (dw->getContentComponent()->getName());
  50376. }
  50377. }
  50378. else if (tabComponent != 0)
  50379. {
  50380. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50381. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50382. }
  50383. }
  50384. void MultiDocumentPanel::updateOrder()
  50385. {
  50386. const Array <Component*> oldList (components);
  50387. if (mode == FloatingWindows)
  50388. {
  50389. components.clear();
  50390. for (int i = 0; i < getNumChildComponents(); ++i)
  50391. {
  50392. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50393. if (dw != 0)
  50394. components.add (dw->getContentComponent());
  50395. }
  50396. }
  50397. else
  50398. {
  50399. if (tabComponent != 0)
  50400. {
  50401. Component* const current = tabComponent->getCurrentContentComponent();
  50402. if (current != 0)
  50403. {
  50404. components.removeValue (current);
  50405. components.add (current);
  50406. }
  50407. }
  50408. }
  50409. if (components != oldList)
  50410. activeDocumentChanged();
  50411. }
  50412. END_JUCE_NAMESPACE
  50413. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50414. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50415. BEGIN_JUCE_NAMESPACE
  50416. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50417. : zone (zoneFlags)
  50418. {
  50419. }
  50420. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50421. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50422. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50423. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50424. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50425. const BorderSize& border,
  50426. const Point<int>& position)
  50427. {
  50428. int z = 0;
  50429. if (totalSize.contains (position)
  50430. && ! border.subtractedFrom (totalSize).contains (position))
  50431. {
  50432. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50433. if (position.getX() < jmax (border.getLeft(), minW))
  50434. z |= left;
  50435. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50436. z |= right;
  50437. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50438. if (position.getY() < jmax (border.getTop(), minH))
  50439. z |= top;
  50440. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50441. z |= bottom;
  50442. }
  50443. return Zone (z);
  50444. }
  50445. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50446. {
  50447. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50448. switch (zone)
  50449. {
  50450. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50451. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50452. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50453. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50454. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50455. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50456. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50457. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50458. default: break;
  50459. }
  50460. return mc;
  50461. }
  50462. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50463. {
  50464. if (isDraggingWholeObject())
  50465. return b + offset;
  50466. if (isDraggingLeftEdge())
  50467. b.setLeft (b.getX() + offset.getX());
  50468. if (isDraggingRightEdge())
  50469. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50470. if (isDraggingTopEdge())
  50471. b.setTop (b.getY() + offset.getY());
  50472. if (isDraggingBottomEdge())
  50473. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50474. return b;
  50475. }
  50476. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50477. {
  50478. if (isDraggingWholeObject())
  50479. return b + offset;
  50480. if (isDraggingLeftEdge())
  50481. b.setLeft (b.getX() + offset.getX());
  50482. if (isDraggingRightEdge())
  50483. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50484. if (isDraggingTopEdge())
  50485. b.setTop (b.getY() + offset.getY());
  50486. if (isDraggingBottomEdge())
  50487. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50488. return b;
  50489. }
  50490. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50491. ComponentBoundsConstrainer* const constrainer_)
  50492. : component (componentToResize),
  50493. constrainer (constrainer_),
  50494. borderSize (5),
  50495. mouseZone (0)
  50496. {
  50497. }
  50498. ResizableBorderComponent::~ResizableBorderComponent()
  50499. {
  50500. }
  50501. void ResizableBorderComponent::paint (Graphics& g)
  50502. {
  50503. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50504. }
  50505. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50506. {
  50507. updateMouseZone (e);
  50508. }
  50509. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50510. {
  50511. updateMouseZone (e);
  50512. }
  50513. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50514. {
  50515. if (component == 0)
  50516. {
  50517. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50518. return;
  50519. }
  50520. updateMouseZone (e);
  50521. originalBounds = component->getBounds();
  50522. if (constrainer != 0)
  50523. constrainer->resizeStart();
  50524. }
  50525. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50526. {
  50527. if (component == 0)
  50528. {
  50529. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50530. return;
  50531. }
  50532. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50533. if (constrainer != 0)
  50534. constrainer->setBoundsForComponent (component, bounds,
  50535. mouseZone.isDraggingTopEdge(),
  50536. mouseZone.isDraggingLeftEdge(),
  50537. mouseZone.isDraggingBottomEdge(),
  50538. mouseZone.isDraggingRightEdge());
  50539. else
  50540. component->setBounds (bounds);
  50541. }
  50542. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50543. {
  50544. if (constrainer != 0)
  50545. constrainer->resizeEnd();
  50546. }
  50547. bool ResizableBorderComponent::hitTest (int x, int y)
  50548. {
  50549. return x < borderSize.getLeft()
  50550. || x >= getWidth() - borderSize.getRight()
  50551. || y < borderSize.getTop()
  50552. || y >= getHeight() - borderSize.getBottom();
  50553. }
  50554. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50555. {
  50556. if (borderSize != newBorderSize)
  50557. {
  50558. borderSize = newBorderSize;
  50559. repaint();
  50560. }
  50561. }
  50562. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50563. {
  50564. return borderSize;
  50565. }
  50566. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50567. {
  50568. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50569. if (mouseZone != newZone)
  50570. {
  50571. mouseZone = newZone;
  50572. setMouseCursor (newZone.getMouseCursor());
  50573. }
  50574. }
  50575. END_JUCE_NAMESPACE
  50576. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50577. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50578. BEGIN_JUCE_NAMESPACE
  50579. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50580. ComponentBoundsConstrainer* const constrainer_)
  50581. : component (componentToResize),
  50582. constrainer (constrainer_)
  50583. {
  50584. setRepaintsOnMouseActivity (true);
  50585. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50586. }
  50587. ResizableCornerComponent::~ResizableCornerComponent()
  50588. {
  50589. }
  50590. void ResizableCornerComponent::paint (Graphics& g)
  50591. {
  50592. getLookAndFeel()
  50593. .drawCornerResizer (g, getWidth(), getHeight(),
  50594. isMouseOverOrDragging(),
  50595. isMouseButtonDown());
  50596. }
  50597. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50598. {
  50599. if (component == 0)
  50600. {
  50601. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50602. return;
  50603. }
  50604. originalBounds = component->getBounds();
  50605. if (constrainer != 0)
  50606. constrainer->resizeStart();
  50607. }
  50608. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50609. {
  50610. if (component == 0)
  50611. {
  50612. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50613. return;
  50614. }
  50615. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50616. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50617. if (constrainer != 0)
  50618. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50619. else
  50620. component->setBounds (r);
  50621. }
  50622. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50623. {
  50624. if (constrainer != 0)
  50625. constrainer->resizeStart();
  50626. }
  50627. bool ResizableCornerComponent::hitTest (int x, int y)
  50628. {
  50629. if (getWidth() <= 0)
  50630. return false;
  50631. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50632. return y >= yAtX - getHeight() / 4;
  50633. }
  50634. END_JUCE_NAMESPACE
  50635. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50636. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50637. BEGIN_JUCE_NAMESPACE
  50638. class ScrollBar::ScrollbarButton : public Button
  50639. {
  50640. public:
  50641. int direction;
  50642. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50643. : Button (String::empty),
  50644. direction (direction_),
  50645. owner (owner_)
  50646. {
  50647. setWantsKeyboardFocus (false);
  50648. }
  50649. ~ScrollbarButton()
  50650. {
  50651. }
  50652. void paintButton (Graphics& g, bool over, bool down)
  50653. {
  50654. getLookAndFeel()
  50655. .drawScrollbarButton (g, owner,
  50656. getWidth(), getHeight(),
  50657. direction,
  50658. owner.isVertical(),
  50659. over, down);
  50660. }
  50661. void clicked()
  50662. {
  50663. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50664. }
  50665. juce_UseDebuggingNewOperator
  50666. private:
  50667. ScrollBar& owner;
  50668. ScrollbarButton (const ScrollbarButton&);
  50669. ScrollbarButton& operator= (const ScrollbarButton&);
  50670. };
  50671. ScrollBar::ScrollBar (const bool vertical_,
  50672. const bool buttonsAreVisible)
  50673. : totalRange (0.0, 1.0),
  50674. visibleRange (0.0, 0.1),
  50675. singleStepSize (0.1),
  50676. thumbAreaStart (0),
  50677. thumbAreaSize (0),
  50678. thumbStart (0),
  50679. thumbSize (0),
  50680. initialDelayInMillisecs (100),
  50681. repeatDelayInMillisecs (50),
  50682. minimumDelayInMillisecs (10),
  50683. vertical (vertical_),
  50684. isDraggingThumb (false),
  50685. autohides (true)
  50686. {
  50687. setButtonVisibility (buttonsAreVisible);
  50688. setRepaintsOnMouseActivity (true);
  50689. setFocusContainer (true);
  50690. }
  50691. ScrollBar::~ScrollBar()
  50692. {
  50693. upButton = 0;
  50694. downButton = 0;
  50695. }
  50696. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50697. {
  50698. if (totalRange != newRangeLimit)
  50699. {
  50700. totalRange = newRangeLimit;
  50701. setCurrentRange (visibleRange);
  50702. updateThumbPosition();
  50703. }
  50704. }
  50705. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50706. {
  50707. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50708. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50709. }
  50710. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50711. {
  50712. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50713. if (visibleRange != constrainedRange)
  50714. {
  50715. visibleRange = constrainedRange;
  50716. updateThumbPosition();
  50717. triggerAsyncUpdate();
  50718. }
  50719. }
  50720. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50721. {
  50722. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50723. }
  50724. void ScrollBar::setCurrentRangeStart (const double newStart)
  50725. {
  50726. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50727. }
  50728. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50729. {
  50730. singleStepSize = newSingleStepSize;
  50731. }
  50732. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50733. {
  50734. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50735. }
  50736. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50737. {
  50738. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50739. }
  50740. void ScrollBar::scrollToTop()
  50741. {
  50742. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50743. }
  50744. void ScrollBar::scrollToBottom()
  50745. {
  50746. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50747. }
  50748. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50749. const int repeatDelayInMillisecs_,
  50750. const int minimumDelayInMillisecs_)
  50751. {
  50752. initialDelayInMillisecs = initialDelayInMillisecs_;
  50753. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50754. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50755. if (upButton != 0)
  50756. {
  50757. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50758. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50759. }
  50760. }
  50761. void ScrollBar::addListener (Listener* const listener)
  50762. {
  50763. listeners.add (listener);
  50764. }
  50765. void ScrollBar::removeListener (Listener* const listener)
  50766. {
  50767. listeners.remove (listener);
  50768. }
  50769. void ScrollBar::handleAsyncUpdate()
  50770. {
  50771. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50772. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50773. }
  50774. void ScrollBar::updateThumbPosition()
  50775. {
  50776. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50777. : thumbAreaSize);
  50778. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50779. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50780. if (newThumbSize > thumbAreaSize)
  50781. newThumbSize = thumbAreaSize;
  50782. int newThumbStart = thumbAreaStart;
  50783. if (totalRange.getLength() > visibleRange.getLength())
  50784. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50785. / (totalRange.getLength() - visibleRange.getLength()));
  50786. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50787. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50788. {
  50789. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50790. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50791. if (vertical)
  50792. repaint (0, repaintStart, getWidth(), repaintSize);
  50793. else
  50794. repaint (repaintStart, 0, repaintSize, getHeight());
  50795. thumbStart = newThumbStart;
  50796. thumbSize = newThumbSize;
  50797. }
  50798. }
  50799. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50800. {
  50801. if (vertical != shouldBeVertical)
  50802. {
  50803. vertical = shouldBeVertical;
  50804. if (upButton != 0)
  50805. {
  50806. upButton->direction = vertical ? 0 : 3;
  50807. downButton->direction = vertical ? 2 : 1;
  50808. }
  50809. updateThumbPosition();
  50810. }
  50811. }
  50812. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50813. {
  50814. upButton = 0;
  50815. downButton = 0;
  50816. if (buttonsAreVisible)
  50817. {
  50818. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50819. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50820. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50821. }
  50822. updateThumbPosition();
  50823. }
  50824. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50825. {
  50826. autohides = shouldHideWhenFullRange;
  50827. updateThumbPosition();
  50828. }
  50829. bool ScrollBar::autoHides() const throw()
  50830. {
  50831. return autohides;
  50832. }
  50833. void ScrollBar::paint (Graphics& g)
  50834. {
  50835. if (thumbAreaSize > 0)
  50836. {
  50837. LookAndFeel& lf = getLookAndFeel();
  50838. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50839. ? thumbSize : 0;
  50840. if (vertical)
  50841. {
  50842. lf.drawScrollbar (g, *this,
  50843. 0, thumbAreaStart,
  50844. getWidth(), thumbAreaSize,
  50845. vertical,
  50846. thumbStart, thumb,
  50847. isMouseOver(), isMouseButtonDown());
  50848. }
  50849. else
  50850. {
  50851. lf.drawScrollbar (g, *this,
  50852. thumbAreaStart, 0,
  50853. thumbAreaSize, getHeight(),
  50854. vertical,
  50855. thumbStart, thumb,
  50856. isMouseOver(), isMouseButtonDown());
  50857. }
  50858. }
  50859. }
  50860. void ScrollBar::lookAndFeelChanged()
  50861. {
  50862. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50863. }
  50864. void ScrollBar::resized()
  50865. {
  50866. const int length = ((vertical) ? getHeight() : getWidth());
  50867. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50868. : 0;
  50869. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50870. {
  50871. thumbAreaStart = length >> 1;
  50872. thumbAreaSize = 0;
  50873. }
  50874. else
  50875. {
  50876. thumbAreaStart = buttonSize;
  50877. thumbAreaSize = length - (buttonSize << 1);
  50878. }
  50879. if (upButton != 0)
  50880. {
  50881. if (vertical)
  50882. {
  50883. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50884. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50885. }
  50886. else
  50887. {
  50888. upButton->setBounds (0, 0, buttonSize, getHeight());
  50889. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50890. }
  50891. }
  50892. updateThumbPosition();
  50893. }
  50894. void ScrollBar::mouseDown (const MouseEvent& e)
  50895. {
  50896. isDraggingThumb = false;
  50897. lastMousePos = vertical ? e.y : e.x;
  50898. dragStartMousePos = lastMousePos;
  50899. dragStartRange = visibleRange.getStart();
  50900. if (dragStartMousePos < thumbStart)
  50901. {
  50902. moveScrollbarInPages (-1);
  50903. startTimer (400);
  50904. }
  50905. else if (dragStartMousePos >= thumbStart + thumbSize)
  50906. {
  50907. moveScrollbarInPages (1);
  50908. startTimer (400);
  50909. }
  50910. else
  50911. {
  50912. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50913. && (thumbAreaSize > thumbSize);
  50914. }
  50915. }
  50916. void ScrollBar::mouseDrag (const MouseEvent& e)
  50917. {
  50918. if (isDraggingThumb)
  50919. {
  50920. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50921. setCurrentRangeStart (dragStartRange
  50922. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50923. / (thumbAreaSize - thumbSize));
  50924. }
  50925. else
  50926. {
  50927. lastMousePos = (vertical) ? e.y : e.x;
  50928. }
  50929. }
  50930. void ScrollBar::mouseUp (const MouseEvent&)
  50931. {
  50932. isDraggingThumb = false;
  50933. stopTimer();
  50934. repaint();
  50935. }
  50936. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50937. float wheelIncrementX,
  50938. float wheelIncrementY)
  50939. {
  50940. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50941. if (increment < 0)
  50942. increment = jmin (increment * 10.0f, -1.0f);
  50943. else if (increment > 0)
  50944. increment = jmax (increment * 10.0f, 1.0f);
  50945. setCurrentRange (visibleRange - singleStepSize * increment);
  50946. }
  50947. void ScrollBar::timerCallback()
  50948. {
  50949. if (isMouseButtonDown())
  50950. {
  50951. startTimer (40);
  50952. if (lastMousePos < thumbStart)
  50953. setCurrentRange (visibleRange - visibleRange.getLength());
  50954. else if (lastMousePos > thumbStart + thumbSize)
  50955. setCurrentRangeStart (visibleRange.getEnd());
  50956. }
  50957. else
  50958. {
  50959. stopTimer();
  50960. }
  50961. }
  50962. bool ScrollBar::keyPressed (const KeyPress& key)
  50963. {
  50964. if (! isVisible())
  50965. return false;
  50966. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50967. moveScrollbarInSteps (-1);
  50968. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50969. moveScrollbarInSteps (1);
  50970. else if (key.isKeyCode (KeyPress::pageUpKey))
  50971. moveScrollbarInPages (-1);
  50972. else if (key.isKeyCode (KeyPress::pageDownKey))
  50973. moveScrollbarInPages (1);
  50974. else if (key.isKeyCode (KeyPress::homeKey))
  50975. scrollToTop();
  50976. else if (key.isKeyCode (KeyPress::endKey))
  50977. scrollToBottom();
  50978. else
  50979. return false;
  50980. return true;
  50981. }
  50982. END_JUCE_NAMESPACE
  50983. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50984. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50985. BEGIN_JUCE_NAMESPACE
  50986. StretchableLayoutManager::StretchableLayoutManager()
  50987. : totalSize (0)
  50988. {
  50989. }
  50990. StretchableLayoutManager::~StretchableLayoutManager()
  50991. {
  50992. }
  50993. void StretchableLayoutManager::clearAllItems()
  50994. {
  50995. items.clear();
  50996. totalSize = 0;
  50997. }
  50998. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50999. const double minimumSize,
  51000. const double maximumSize,
  51001. const double preferredSize)
  51002. {
  51003. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51004. if (layout == 0)
  51005. {
  51006. layout = new ItemLayoutProperties();
  51007. layout->itemIndex = itemIndex;
  51008. int i;
  51009. for (i = 0; i < items.size(); ++i)
  51010. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51011. break;
  51012. items.insert (i, layout);
  51013. }
  51014. layout->minSize = minimumSize;
  51015. layout->maxSize = maximumSize;
  51016. layout->preferredSize = preferredSize;
  51017. layout->currentSize = 0;
  51018. }
  51019. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51020. double& minimumSize,
  51021. double& maximumSize,
  51022. double& preferredSize) const
  51023. {
  51024. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51025. if (layout != 0)
  51026. {
  51027. minimumSize = layout->minSize;
  51028. maximumSize = layout->maxSize;
  51029. preferredSize = layout->preferredSize;
  51030. return true;
  51031. }
  51032. return false;
  51033. }
  51034. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51035. {
  51036. totalSize = newTotalSize;
  51037. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51038. }
  51039. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51040. {
  51041. int pos = 0;
  51042. for (int i = 0; i < itemIndex; ++i)
  51043. {
  51044. const ItemLayoutProperties* const layout = getInfoFor (i);
  51045. if (layout != 0)
  51046. pos += layout->currentSize;
  51047. }
  51048. return pos;
  51049. }
  51050. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51051. {
  51052. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51053. if (layout != 0)
  51054. return layout->currentSize;
  51055. return 0;
  51056. }
  51057. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51058. {
  51059. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51060. if (layout != 0)
  51061. return -layout->currentSize / (double) totalSize;
  51062. return 0;
  51063. }
  51064. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51065. int newPosition)
  51066. {
  51067. for (int i = items.size(); --i >= 0;)
  51068. {
  51069. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51070. if (layout->itemIndex == itemIndex)
  51071. {
  51072. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51073. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51074. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51075. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51076. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51077. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51078. endPos += layout->currentSize;
  51079. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51080. updatePrefSizesToMatchCurrentPositions();
  51081. break;
  51082. }
  51083. }
  51084. }
  51085. void StretchableLayoutManager::layOutComponents (Component** const components,
  51086. int numComponents,
  51087. int x, int y, int w, int h,
  51088. const bool vertically,
  51089. const bool resizeOtherDimension)
  51090. {
  51091. setTotalSize (vertically ? h : w);
  51092. int pos = vertically ? y : x;
  51093. for (int i = 0; i < numComponents; ++i)
  51094. {
  51095. const ItemLayoutProperties* const layout = getInfoFor (i);
  51096. if (layout != 0)
  51097. {
  51098. Component* const c = components[i];
  51099. if (c != 0)
  51100. {
  51101. if (i == numComponents - 1)
  51102. {
  51103. // if it's the last item, crop it to exactly fit the available space..
  51104. if (resizeOtherDimension)
  51105. {
  51106. if (vertically)
  51107. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51108. else
  51109. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51110. }
  51111. else
  51112. {
  51113. if (vertically)
  51114. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51115. else
  51116. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51117. }
  51118. }
  51119. else
  51120. {
  51121. if (resizeOtherDimension)
  51122. {
  51123. if (vertically)
  51124. c->setBounds (x, pos, w, layout->currentSize);
  51125. else
  51126. c->setBounds (pos, y, layout->currentSize, h);
  51127. }
  51128. else
  51129. {
  51130. if (vertically)
  51131. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51132. else
  51133. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51134. }
  51135. }
  51136. }
  51137. pos += layout->currentSize;
  51138. }
  51139. }
  51140. }
  51141. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51142. {
  51143. for (int i = items.size(); --i >= 0;)
  51144. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51145. return items.getUnchecked(i);
  51146. return 0;
  51147. }
  51148. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51149. const int endIndex,
  51150. const int availableSpace,
  51151. int startPos)
  51152. {
  51153. // calculate the total sizes
  51154. int i;
  51155. double totalIdealSize = 0.0;
  51156. int totalMinimums = 0;
  51157. for (i = startIndex; i < endIndex; ++i)
  51158. {
  51159. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51160. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51161. totalMinimums += layout->currentSize;
  51162. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51163. }
  51164. if (totalIdealSize <= 0)
  51165. totalIdealSize = 1.0;
  51166. // now calc the best sizes..
  51167. int extraSpace = availableSpace - totalMinimums;
  51168. while (extraSpace > 0)
  51169. {
  51170. int numWantingMoreSpace = 0;
  51171. int numHavingTakenExtraSpace = 0;
  51172. // first figure out how many comps want a slice of the extra space..
  51173. for (i = startIndex; i < endIndex; ++i)
  51174. {
  51175. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51176. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51177. const int bestSize = jlimit (layout->currentSize,
  51178. jmax (layout->currentSize,
  51179. sizeToRealSize (layout->maxSize, totalSize)),
  51180. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51181. if (bestSize > layout->currentSize)
  51182. ++numWantingMoreSpace;
  51183. }
  51184. // ..share out the extra space..
  51185. for (i = startIndex; i < endIndex; ++i)
  51186. {
  51187. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51188. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51189. int bestSize = jlimit (layout->currentSize,
  51190. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51191. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51192. const int extraWanted = bestSize - layout->currentSize;
  51193. if (extraWanted > 0)
  51194. {
  51195. const int extraAllowed = jmin (extraWanted,
  51196. extraSpace / jmax (1, numWantingMoreSpace));
  51197. if (extraAllowed > 0)
  51198. {
  51199. ++numHavingTakenExtraSpace;
  51200. --numWantingMoreSpace;
  51201. layout->currentSize += extraAllowed;
  51202. extraSpace -= extraAllowed;
  51203. }
  51204. }
  51205. }
  51206. if (numHavingTakenExtraSpace <= 0)
  51207. break;
  51208. }
  51209. // ..and calculate the end position
  51210. for (i = startIndex; i < endIndex; ++i)
  51211. {
  51212. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51213. startPos += layout->currentSize;
  51214. }
  51215. return startPos;
  51216. }
  51217. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51218. const int endIndex) const
  51219. {
  51220. int totalMinimums = 0;
  51221. for (int i = startIndex; i < endIndex; ++i)
  51222. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51223. return totalMinimums;
  51224. }
  51225. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51226. {
  51227. int totalMaximums = 0;
  51228. for (int i = startIndex; i < endIndex; ++i)
  51229. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51230. return totalMaximums;
  51231. }
  51232. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51233. {
  51234. for (int i = 0; i < items.size(); ++i)
  51235. {
  51236. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51237. layout->preferredSize
  51238. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51239. : getItemCurrentAbsoluteSize (i);
  51240. }
  51241. }
  51242. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51243. {
  51244. if (size < 0)
  51245. size *= -totalSpace;
  51246. return roundToInt (size);
  51247. }
  51248. END_JUCE_NAMESPACE
  51249. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51250. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51251. BEGIN_JUCE_NAMESPACE
  51252. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51253. const int itemIndex_,
  51254. const bool isVertical_)
  51255. : layout (layout_),
  51256. itemIndex (itemIndex_),
  51257. isVertical (isVertical_)
  51258. {
  51259. setRepaintsOnMouseActivity (true);
  51260. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51261. : MouseCursor::UpDownResizeCursor));
  51262. }
  51263. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51264. {
  51265. }
  51266. void StretchableLayoutResizerBar::paint (Graphics& g)
  51267. {
  51268. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51269. getWidth(), getHeight(),
  51270. isVertical,
  51271. isMouseOver(),
  51272. isMouseButtonDown());
  51273. }
  51274. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51275. {
  51276. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51277. }
  51278. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51279. {
  51280. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51281. : e.getDistanceFromDragStartY());
  51282. layout->setItemPosition (itemIndex, desiredPos);
  51283. hasBeenMoved();
  51284. }
  51285. void StretchableLayoutResizerBar::hasBeenMoved()
  51286. {
  51287. if (getParentComponent() != 0)
  51288. getParentComponent()->resized();
  51289. }
  51290. END_JUCE_NAMESPACE
  51291. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51292. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51293. BEGIN_JUCE_NAMESPACE
  51294. StretchableObjectResizer::StretchableObjectResizer()
  51295. {
  51296. }
  51297. StretchableObjectResizer::~StretchableObjectResizer()
  51298. {
  51299. }
  51300. void StretchableObjectResizer::addItem (const double size,
  51301. const double minSize, const double maxSize,
  51302. const int order)
  51303. {
  51304. // the order must be >= 0 but less than the maximum integer value.
  51305. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51306. Item* const item = new Item();
  51307. item->size = size;
  51308. item->minSize = minSize;
  51309. item->maxSize = maxSize;
  51310. item->order = order;
  51311. items.add (item);
  51312. }
  51313. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51314. {
  51315. const Item* const it = items [index];
  51316. return it != 0 ? it->size : 0;
  51317. }
  51318. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51319. {
  51320. int order = 0;
  51321. for (;;)
  51322. {
  51323. double currentSize = 0;
  51324. double minSize = 0;
  51325. double maxSize = 0;
  51326. int nextHighestOrder = std::numeric_limits<int>::max();
  51327. for (int i = 0; i < items.size(); ++i)
  51328. {
  51329. const Item* const it = items.getUnchecked(i);
  51330. currentSize += it->size;
  51331. if (it->order <= order)
  51332. {
  51333. minSize += it->minSize;
  51334. maxSize += it->maxSize;
  51335. }
  51336. else
  51337. {
  51338. minSize += it->size;
  51339. maxSize += it->size;
  51340. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51341. }
  51342. }
  51343. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51344. if (thisIterationTarget >= currentSize)
  51345. {
  51346. const double availableExtraSpace = maxSize - currentSize;
  51347. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51348. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51349. for (int i = 0; i < items.size(); ++i)
  51350. {
  51351. Item* const it = items.getUnchecked(i);
  51352. if (it->order <= order)
  51353. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51354. }
  51355. }
  51356. else
  51357. {
  51358. const double amountOfSlack = currentSize - minSize;
  51359. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51360. const double scale = targetAmountOfSlack / amountOfSlack;
  51361. for (int i = 0; i < items.size(); ++i)
  51362. {
  51363. Item* const it = items.getUnchecked(i);
  51364. if (it->order <= order)
  51365. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51366. }
  51367. }
  51368. if (nextHighestOrder < std::numeric_limits<int>::max())
  51369. order = nextHighestOrder;
  51370. else
  51371. break;
  51372. }
  51373. }
  51374. END_JUCE_NAMESPACE
  51375. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51376. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51377. BEGIN_JUCE_NAMESPACE
  51378. TabBarButton::TabBarButton (const String& name,
  51379. TabbedButtonBar* const owner_,
  51380. const int index)
  51381. : Button (name),
  51382. owner (owner_),
  51383. tabIndex (index),
  51384. overlapPixels (0)
  51385. {
  51386. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51387. setComponentEffect (&shadow);
  51388. setWantsKeyboardFocus (false);
  51389. }
  51390. TabBarButton::~TabBarButton()
  51391. {
  51392. }
  51393. void TabBarButton::paintButton (Graphics& g,
  51394. bool isMouseOverButton,
  51395. bool isButtonDown)
  51396. {
  51397. int x, y, w, h;
  51398. getActiveArea (x, y, w, h);
  51399. g.setOrigin (x, y);
  51400. getLookAndFeel()
  51401. .drawTabButton (g, w, h,
  51402. owner->getTabBackgroundColour (tabIndex),
  51403. tabIndex, getButtonText(), *this,
  51404. owner->getOrientation(),
  51405. isMouseOverButton, isButtonDown,
  51406. getToggleState());
  51407. }
  51408. void TabBarButton::clicked (const ModifierKeys& mods)
  51409. {
  51410. if (mods.isPopupMenu())
  51411. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51412. else
  51413. owner->setCurrentTabIndex (tabIndex);
  51414. }
  51415. bool TabBarButton::hitTest (int mx, int my)
  51416. {
  51417. int x, y, w, h;
  51418. getActiveArea (x, y, w, h);
  51419. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51420. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51421. {
  51422. if (((unsigned int) mx) < (unsigned int) getWidth()
  51423. && my >= y + overlapPixels
  51424. && my < y + h - overlapPixels)
  51425. return true;
  51426. }
  51427. else
  51428. {
  51429. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51430. && ((unsigned int) my) < (unsigned int) getHeight())
  51431. return true;
  51432. }
  51433. Path p;
  51434. getLookAndFeel()
  51435. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51436. owner->getOrientation(),
  51437. false, false, getToggleState());
  51438. return p.contains ((float) (mx - x),
  51439. (float) (my - y));
  51440. }
  51441. int TabBarButton::getBestTabLength (const int depth)
  51442. {
  51443. return jlimit (depth * 2,
  51444. depth * 7,
  51445. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51446. }
  51447. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51448. {
  51449. x = 0;
  51450. y = 0;
  51451. int r = getWidth();
  51452. int b = getHeight();
  51453. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51454. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51455. r -= spaceAroundImage;
  51456. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51457. x += spaceAroundImage;
  51458. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51459. y += spaceAroundImage;
  51460. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51461. b -= spaceAroundImage;
  51462. w = r - x;
  51463. h = b - y;
  51464. }
  51465. class TabAreaBehindFrontButtonComponent : public Component
  51466. {
  51467. public:
  51468. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51469. : owner (owner_)
  51470. {
  51471. setInterceptsMouseClicks (false, false);
  51472. }
  51473. ~TabAreaBehindFrontButtonComponent()
  51474. {
  51475. }
  51476. void paint (Graphics& g)
  51477. {
  51478. getLookAndFeel()
  51479. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51480. *owner, owner->getOrientation());
  51481. }
  51482. void enablementChanged()
  51483. {
  51484. repaint();
  51485. }
  51486. private:
  51487. TabbedButtonBar* const owner;
  51488. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51489. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51490. };
  51491. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51492. : orientation (orientation_),
  51493. currentTabIndex (-1)
  51494. {
  51495. setInterceptsMouseClicks (false, true);
  51496. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51497. setFocusContainer (true);
  51498. }
  51499. TabbedButtonBar::~TabbedButtonBar()
  51500. {
  51501. extraTabsButton = 0;
  51502. deleteAllChildren();
  51503. }
  51504. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51505. {
  51506. orientation = newOrientation;
  51507. for (int i = getNumChildComponents(); --i >= 0;)
  51508. getChildComponent (i)->resized();
  51509. resized();
  51510. }
  51511. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51512. {
  51513. return new TabBarButton (name, this, index);
  51514. }
  51515. void TabbedButtonBar::clearTabs()
  51516. {
  51517. tabs.clear();
  51518. tabColours.clear();
  51519. currentTabIndex = -1;
  51520. extraTabsButton = 0;
  51521. removeChildComponent (behindFrontTab);
  51522. deleteAllChildren();
  51523. addChildComponent (behindFrontTab);
  51524. setCurrentTabIndex (-1);
  51525. }
  51526. void TabbedButtonBar::addTab (const String& tabName,
  51527. const Colour& tabBackgroundColour,
  51528. int insertIndex)
  51529. {
  51530. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51531. if (tabName.isNotEmpty())
  51532. {
  51533. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51534. insertIndex = tabs.size();
  51535. for (int i = tabs.size(); --i >= insertIndex;)
  51536. {
  51537. TabBarButton* const tb = getTabButton (i);
  51538. if (tb != 0)
  51539. tb->tabIndex++;
  51540. }
  51541. tabs.insert (insertIndex, tabName);
  51542. tabColours.insert (insertIndex, tabBackgroundColour);
  51543. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51544. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51545. addAndMakeVisible (tb, insertIndex);
  51546. resized();
  51547. if (currentTabIndex < 0)
  51548. setCurrentTabIndex (0);
  51549. }
  51550. }
  51551. void TabbedButtonBar::setTabName (const int tabIndex,
  51552. const String& newName)
  51553. {
  51554. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51555. && tabs[tabIndex] != newName)
  51556. {
  51557. tabs.set (tabIndex, newName);
  51558. TabBarButton* const tb = getTabButton (tabIndex);
  51559. if (tb != 0)
  51560. tb->setButtonText (newName);
  51561. resized();
  51562. }
  51563. }
  51564. void TabbedButtonBar::removeTab (const int tabIndex)
  51565. {
  51566. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51567. {
  51568. const int oldTabIndex = currentTabIndex;
  51569. if (currentTabIndex == tabIndex)
  51570. currentTabIndex = -1;
  51571. tabs.remove (tabIndex);
  51572. tabColours.remove (tabIndex);
  51573. delete getTabButton (tabIndex);
  51574. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51575. {
  51576. TabBarButton* const tb = getTabButton (i);
  51577. if (tb != 0)
  51578. tb->tabIndex--;
  51579. }
  51580. resized();
  51581. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51582. }
  51583. }
  51584. void TabbedButtonBar::moveTab (const int currentIndex,
  51585. const int newIndex)
  51586. {
  51587. tabs.move (currentIndex, newIndex);
  51588. tabColours.move (currentIndex, newIndex);
  51589. resized();
  51590. }
  51591. int TabbedButtonBar::getNumTabs() const
  51592. {
  51593. return tabs.size();
  51594. }
  51595. const StringArray TabbedButtonBar::getTabNames() const
  51596. {
  51597. return tabs;
  51598. }
  51599. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51600. {
  51601. if (currentTabIndex != newIndex)
  51602. {
  51603. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51604. newIndex = -1;
  51605. currentTabIndex = newIndex;
  51606. for (int i = 0; i < getNumChildComponents(); ++i)
  51607. {
  51608. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51609. if (tb != 0)
  51610. tb->setToggleState (tb->tabIndex == newIndex, false);
  51611. }
  51612. resized();
  51613. if (sendChangeMessage_)
  51614. sendChangeMessage (this);
  51615. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51616. }
  51617. }
  51618. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51619. {
  51620. for (int i = getNumChildComponents(); --i >= 0;)
  51621. {
  51622. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51623. if (tb != 0 && tb->tabIndex == index)
  51624. return tb;
  51625. }
  51626. return 0;
  51627. }
  51628. void TabbedButtonBar::lookAndFeelChanged()
  51629. {
  51630. extraTabsButton = 0;
  51631. resized();
  51632. }
  51633. void TabbedButtonBar::resized()
  51634. {
  51635. const double minimumScale = 0.7;
  51636. int depth = getWidth();
  51637. int length = getHeight();
  51638. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51639. swapVariables (depth, length);
  51640. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51641. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51642. int i, totalLength = overlap;
  51643. int numVisibleButtons = tabs.size();
  51644. for (i = 0; i < getNumChildComponents(); ++i)
  51645. {
  51646. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51647. if (tb != 0)
  51648. {
  51649. totalLength += tb->getBestTabLength (depth) - overlap;
  51650. tb->overlapPixels = overlap / 2;
  51651. }
  51652. }
  51653. double scale = 1.0;
  51654. if (totalLength > length)
  51655. scale = jmax (minimumScale, length / (double) totalLength);
  51656. const bool isTooBig = totalLength * scale > length;
  51657. int tabsButtonPos = 0;
  51658. if (isTooBig)
  51659. {
  51660. if (extraTabsButton == 0)
  51661. {
  51662. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51663. extraTabsButton->addButtonListener (this);
  51664. extraTabsButton->setAlwaysOnTop (true);
  51665. extraTabsButton->setTriggeredOnMouseDown (true);
  51666. }
  51667. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51668. extraTabsButton->setSize (buttonSize, buttonSize);
  51669. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51670. {
  51671. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51672. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51673. }
  51674. else
  51675. {
  51676. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51677. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51678. }
  51679. totalLength = 0;
  51680. for (i = 0; i < tabs.size(); ++i)
  51681. {
  51682. TabBarButton* const tb = getTabButton (i);
  51683. if (tb != 0)
  51684. {
  51685. const int newLength = totalLength + tb->getBestTabLength (depth);
  51686. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51687. {
  51688. totalLength += overlap;
  51689. break;
  51690. }
  51691. numVisibleButtons = i + 1;
  51692. totalLength = newLength - overlap;
  51693. }
  51694. }
  51695. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51696. }
  51697. else
  51698. {
  51699. extraTabsButton = 0;
  51700. }
  51701. int pos = 0;
  51702. TabBarButton* frontTab = 0;
  51703. for (i = 0; i < tabs.size(); ++i)
  51704. {
  51705. TabBarButton* const tb = getTabButton (i);
  51706. if (tb != 0)
  51707. {
  51708. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51709. if (i < numVisibleButtons)
  51710. {
  51711. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51712. tb->setBounds (pos, 0, bestLength, getHeight());
  51713. else
  51714. tb->setBounds (0, pos, getWidth(), bestLength);
  51715. tb->toBack();
  51716. if (tb->tabIndex == currentTabIndex)
  51717. frontTab = tb;
  51718. tb->setVisible (true);
  51719. }
  51720. else
  51721. {
  51722. tb->setVisible (false);
  51723. }
  51724. pos += bestLength - overlap;
  51725. }
  51726. }
  51727. behindFrontTab->setBounds (getLocalBounds());
  51728. if (frontTab != 0)
  51729. {
  51730. frontTab->toFront (false);
  51731. behindFrontTab->toBehind (frontTab);
  51732. }
  51733. }
  51734. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51735. {
  51736. return tabColours [tabIndex];
  51737. }
  51738. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51739. {
  51740. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51741. && tabColours [tabIndex] != newColour)
  51742. {
  51743. tabColours.set (tabIndex, newColour);
  51744. repaint();
  51745. }
  51746. }
  51747. void TabbedButtonBar::buttonClicked (Button* button)
  51748. {
  51749. if (button == extraTabsButton)
  51750. {
  51751. PopupMenu m;
  51752. for (int i = 0; i < tabs.size(); ++i)
  51753. {
  51754. TabBarButton* const tb = getTabButton (i);
  51755. if (tb != 0 && ! tb->isVisible())
  51756. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51757. }
  51758. const int res = m.showAt (extraTabsButton);
  51759. if (res != 0)
  51760. setCurrentTabIndex (res - 1);
  51761. }
  51762. }
  51763. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51764. {
  51765. }
  51766. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51767. {
  51768. }
  51769. END_JUCE_NAMESPACE
  51770. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51771. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51772. BEGIN_JUCE_NAMESPACE
  51773. class TabCompButtonBar : public TabbedButtonBar
  51774. {
  51775. public:
  51776. TabCompButtonBar (TabbedComponent* const owner_,
  51777. const TabbedButtonBar::Orientation orientation_)
  51778. : TabbedButtonBar (orientation_),
  51779. owner (owner_)
  51780. {
  51781. }
  51782. ~TabCompButtonBar()
  51783. {
  51784. }
  51785. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51786. {
  51787. owner->changeCallback (newCurrentTabIndex, newTabName);
  51788. }
  51789. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51790. {
  51791. owner->popupMenuClickOnTab (tabIndex, tabName);
  51792. }
  51793. const Colour getTabBackgroundColour (const int tabIndex)
  51794. {
  51795. return owner->tabs->getTabBackgroundColour (tabIndex);
  51796. }
  51797. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51798. {
  51799. return owner->createTabButton (tabName, tabIndex);
  51800. }
  51801. juce_UseDebuggingNewOperator
  51802. private:
  51803. TabbedComponent* const owner;
  51804. TabCompButtonBar (const TabCompButtonBar&);
  51805. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51806. };
  51807. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51808. : panelComponent (0),
  51809. tabDepth (30),
  51810. outlineThickness (1),
  51811. edgeIndent (0)
  51812. {
  51813. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51814. }
  51815. TabbedComponent::~TabbedComponent()
  51816. {
  51817. clearTabs();
  51818. delete tabs;
  51819. }
  51820. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51821. {
  51822. tabs->setOrientation (orientation);
  51823. resized();
  51824. }
  51825. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51826. {
  51827. return tabs->getOrientation();
  51828. }
  51829. void TabbedComponent::setTabBarDepth (const int newDepth)
  51830. {
  51831. if (tabDepth != newDepth)
  51832. {
  51833. tabDepth = newDepth;
  51834. resized();
  51835. }
  51836. }
  51837. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51838. {
  51839. return new TabBarButton (tabName, tabs, tabIndex);
  51840. }
  51841. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51842. void TabbedComponent::clearTabs()
  51843. {
  51844. if (panelComponent != 0)
  51845. {
  51846. panelComponent->setVisible (false);
  51847. removeChildComponent (panelComponent);
  51848. panelComponent = 0;
  51849. }
  51850. tabs->clearTabs();
  51851. for (int i = contentComponents.size(); --i >= 0;)
  51852. {
  51853. Component* const c = contentComponents.getUnchecked(i);
  51854. // be careful not to delete these components until they've been removed from the tab component
  51855. jassert (c == 0 || c->isValidComponent());
  51856. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51857. delete c;
  51858. }
  51859. contentComponents.clear();
  51860. }
  51861. void TabbedComponent::addTab (const String& tabName,
  51862. const Colour& tabBackgroundColour,
  51863. Component* const contentComponent,
  51864. const bool deleteComponentWhenNotNeeded,
  51865. const int insertIndex)
  51866. {
  51867. contentComponents.insert (insertIndex, contentComponent);
  51868. if (contentComponent != 0)
  51869. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51870. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51871. }
  51872. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51873. {
  51874. tabs->setTabName (tabIndex, newName);
  51875. }
  51876. void TabbedComponent::removeTab (const int tabIndex)
  51877. {
  51878. Component* const c = contentComponents [tabIndex];
  51879. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51880. {
  51881. if (c == panelComponent)
  51882. panelComponent = 0;
  51883. delete c;
  51884. }
  51885. contentComponents.remove (tabIndex);
  51886. tabs->removeTab (tabIndex);
  51887. }
  51888. int TabbedComponent::getNumTabs() const
  51889. {
  51890. return tabs->getNumTabs();
  51891. }
  51892. const StringArray TabbedComponent::getTabNames() const
  51893. {
  51894. return tabs->getTabNames();
  51895. }
  51896. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51897. {
  51898. return contentComponents [tabIndex];
  51899. }
  51900. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51901. {
  51902. return tabs->getTabBackgroundColour (tabIndex);
  51903. }
  51904. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51905. {
  51906. tabs->setTabBackgroundColour (tabIndex, newColour);
  51907. if (getCurrentTabIndex() == tabIndex)
  51908. repaint();
  51909. }
  51910. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51911. {
  51912. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51913. }
  51914. int TabbedComponent::getCurrentTabIndex() const
  51915. {
  51916. return tabs->getCurrentTabIndex();
  51917. }
  51918. const String& TabbedComponent::getCurrentTabName() const
  51919. {
  51920. return tabs->getCurrentTabName();
  51921. }
  51922. void TabbedComponent::setOutline (int thickness)
  51923. {
  51924. outlineThickness = thickness;
  51925. repaint();
  51926. }
  51927. void TabbedComponent::setIndent (const int indentThickness)
  51928. {
  51929. edgeIndent = indentThickness;
  51930. }
  51931. void TabbedComponent::paint (Graphics& g)
  51932. {
  51933. g.fillAll (findColour (backgroundColourId));
  51934. const TabbedButtonBar::Orientation o = getOrientation();
  51935. int x = 0;
  51936. int y = 0;
  51937. int r = getWidth();
  51938. int b = getHeight();
  51939. if (o == TabbedButtonBar::TabsAtTop)
  51940. y += tabDepth;
  51941. else if (o == TabbedButtonBar::TabsAtBottom)
  51942. b -= tabDepth;
  51943. else if (o == TabbedButtonBar::TabsAtLeft)
  51944. x += tabDepth;
  51945. else if (o == TabbedButtonBar::TabsAtRight)
  51946. r -= tabDepth;
  51947. g.reduceClipRegion (x, y, r - x, b - y);
  51948. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51949. if (outlineThickness > 0)
  51950. {
  51951. if (o == TabbedButtonBar::TabsAtTop)
  51952. --y;
  51953. else if (o == TabbedButtonBar::TabsAtBottom)
  51954. ++b;
  51955. else if (o == TabbedButtonBar::TabsAtLeft)
  51956. --x;
  51957. else if (o == TabbedButtonBar::TabsAtRight)
  51958. ++r;
  51959. g.setColour (findColour (outlineColourId));
  51960. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51961. }
  51962. }
  51963. void TabbedComponent::resized()
  51964. {
  51965. const TabbedButtonBar::Orientation o = getOrientation();
  51966. const int indent = edgeIndent + outlineThickness;
  51967. BorderSize indents (indent);
  51968. if (o == TabbedButtonBar::TabsAtTop)
  51969. {
  51970. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51971. indents.setTop (tabDepth + edgeIndent);
  51972. }
  51973. else if (o == TabbedButtonBar::TabsAtBottom)
  51974. {
  51975. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51976. indents.setBottom (tabDepth + edgeIndent);
  51977. }
  51978. else if (o == TabbedButtonBar::TabsAtLeft)
  51979. {
  51980. tabs->setBounds (0, 0, tabDepth, getHeight());
  51981. indents.setLeft (tabDepth + edgeIndent);
  51982. }
  51983. else if (o == TabbedButtonBar::TabsAtRight)
  51984. {
  51985. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51986. indents.setRight (tabDepth + edgeIndent);
  51987. }
  51988. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51989. for (int i = contentComponents.size(); --i >= 0;)
  51990. if (contentComponents.getUnchecked (i) != 0)
  51991. contentComponents.getUnchecked (i)->setBounds (bounds);
  51992. }
  51993. void TabbedComponent::lookAndFeelChanged()
  51994. {
  51995. for (int i = contentComponents.size(); --i >= 0;)
  51996. if (contentComponents.getUnchecked (i) != 0)
  51997. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51998. }
  51999. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52000. const String& newTabName)
  52001. {
  52002. if (panelComponent != 0)
  52003. {
  52004. panelComponent->setVisible (false);
  52005. removeChildComponent (panelComponent);
  52006. panelComponent = 0;
  52007. }
  52008. if (getCurrentTabIndex() >= 0)
  52009. {
  52010. panelComponent = contentComponents [getCurrentTabIndex()];
  52011. if (panelComponent != 0)
  52012. {
  52013. // do these ops as two stages instead of addAndMakeVisible() so that the
  52014. // component has always got a parent when it gets the visibilityChanged() callback
  52015. addChildComponent (panelComponent);
  52016. panelComponent->setVisible (true);
  52017. panelComponent->toFront (true);
  52018. }
  52019. repaint();
  52020. }
  52021. resized();
  52022. currentTabChanged (newCurrentTabIndex, newTabName);
  52023. }
  52024. void TabbedComponent::currentTabChanged (const int, const String&)
  52025. {
  52026. }
  52027. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52028. {
  52029. }
  52030. END_JUCE_NAMESPACE
  52031. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52032. /*** Start of inlined file: juce_Viewport.cpp ***/
  52033. BEGIN_JUCE_NAMESPACE
  52034. Viewport::Viewport (const String& componentName)
  52035. : Component (componentName),
  52036. scrollBarThickness (0),
  52037. singleStepX (16),
  52038. singleStepY (16),
  52039. showHScrollbar (true),
  52040. showVScrollbar (true),
  52041. verticalScrollBar (true),
  52042. horizontalScrollBar (false)
  52043. {
  52044. // content holder is used to clip the contents so they don't overlap the scrollbars
  52045. addAndMakeVisible (&contentHolder);
  52046. contentHolder.setInterceptsMouseClicks (false, true);
  52047. addChildComponent (&verticalScrollBar);
  52048. addChildComponent (&horizontalScrollBar);
  52049. verticalScrollBar.addListener (this);
  52050. horizontalScrollBar.addListener (this);
  52051. setInterceptsMouseClicks (false, true);
  52052. setWantsKeyboardFocus (true);
  52053. }
  52054. Viewport::~Viewport()
  52055. {
  52056. contentHolder.deleteAllChildren();
  52057. }
  52058. void Viewport::visibleAreaChanged (int, int, int, int)
  52059. {
  52060. }
  52061. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52062. {
  52063. if (contentComp.getComponent() != newViewedComponent)
  52064. {
  52065. {
  52066. ScopedPointer<Component> oldCompDeleter (contentComp);
  52067. contentComp = 0;
  52068. }
  52069. contentComp = newViewedComponent;
  52070. if (contentComp != 0)
  52071. {
  52072. contentComp->setTopLeftPosition (0, 0);
  52073. contentHolder.addAndMakeVisible (contentComp);
  52074. contentComp->addComponentListener (this);
  52075. }
  52076. updateVisibleArea();
  52077. }
  52078. }
  52079. int Viewport::getMaximumVisibleWidth() const
  52080. {
  52081. return contentHolder.getWidth();
  52082. }
  52083. int Viewport::getMaximumVisibleHeight() const
  52084. {
  52085. return contentHolder.getHeight();
  52086. }
  52087. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52088. {
  52089. if (contentComp != 0)
  52090. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52091. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52092. }
  52093. void Viewport::setViewPosition (const Point<int>& newPosition)
  52094. {
  52095. setViewPosition (newPosition.getX(), newPosition.getY());
  52096. }
  52097. void Viewport::setViewPositionProportionately (const double x, const double y)
  52098. {
  52099. if (contentComp != 0)
  52100. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52101. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52102. }
  52103. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52104. {
  52105. if (contentComp != 0)
  52106. {
  52107. int dx = 0, dy = 0;
  52108. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52109. {
  52110. if (mouseX < activeBorderThickness)
  52111. dx = activeBorderThickness - mouseX;
  52112. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52113. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52114. if (dx < 0)
  52115. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52116. else
  52117. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52118. }
  52119. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52120. {
  52121. if (mouseY < activeBorderThickness)
  52122. dy = activeBorderThickness - mouseY;
  52123. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52124. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52125. if (dy < 0)
  52126. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52127. else
  52128. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52129. }
  52130. if (dx != 0 || dy != 0)
  52131. {
  52132. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52133. contentComp->getY() + dy);
  52134. return true;
  52135. }
  52136. }
  52137. return false;
  52138. }
  52139. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52140. {
  52141. updateVisibleArea();
  52142. }
  52143. void Viewport::resized()
  52144. {
  52145. updateVisibleArea();
  52146. }
  52147. void Viewport::updateVisibleArea()
  52148. {
  52149. const int scrollbarWidth = getScrollBarThickness();
  52150. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52151. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52152. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52153. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52154. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52155. Rectangle<int> contentArea (getLocalBounds());
  52156. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52157. {
  52158. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52159. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52160. if (vBarVisible)
  52161. contentArea.setWidth (getWidth() - scrollbarWidth);
  52162. if (hBarVisible)
  52163. contentArea.setHeight (getHeight() - scrollbarWidth);
  52164. if (! contentArea.contains (contentComp->getBounds()))
  52165. {
  52166. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52167. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52168. }
  52169. }
  52170. if (vBarVisible)
  52171. contentArea.setWidth (getWidth() - scrollbarWidth);
  52172. if (hBarVisible)
  52173. contentArea.setHeight (getHeight() - scrollbarWidth);
  52174. contentHolder.setBounds (contentArea);
  52175. Rectangle<int> contentBounds;
  52176. if (contentComp != 0)
  52177. contentBounds = contentComp->getBounds();
  52178. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52179. if (hBarVisible)
  52180. {
  52181. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52182. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52183. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52184. horizontalScrollBar.setSingleStepSize (singleStepX);
  52185. horizontalScrollBar.cancelPendingUpdate();
  52186. }
  52187. if (vBarVisible)
  52188. {
  52189. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52190. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52191. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52192. verticalScrollBar.setSingleStepSize (singleStepY);
  52193. verticalScrollBar.cancelPendingUpdate();
  52194. }
  52195. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52196. horizontalScrollBar.setVisible (hBarVisible);
  52197. verticalScrollBar.setVisible (vBarVisible);
  52198. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52199. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52200. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52201. if (lastVisibleArea != visibleArea)
  52202. {
  52203. lastVisibleArea = visibleArea;
  52204. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52205. }
  52206. horizontalScrollBar.handleUpdateNowIfNeeded();
  52207. verticalScrollBar.handleUpdateNowIfNeeded();
  52208. }
  52209. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52210. {
  52211. if (singleStepX != stepX || singleStepY != stepY)
  52212. {
  52213. singleStepX = stepX;
  52214. singleStepY = stepY;
  52215. updateVisibleArea();
  52216. }
  52217. }
  52218. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52219. const bool showHorizontalScrollbarIfNeeded)
  52220. {
  52221. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52222. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52223. {
  52224. showVScrollbar = showVerticalScrollbarIfNeeded;
  52225. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52226. updateVisibleArea();
  52227. }
  52228. }
  52229. void Viewport::setScrollBarThickness (const int thickness)
  52230. {
  52231. if (scrollBarThickness != thickness)
  52232. {
  52233. scrollBarThickness = thickness;
  52234. updateVisibleArea();
  52235. }
  52236. }
  52237. int Viewport::getScrollBarThickness() const
  52238. {
  52239. return scrollBarThickness > 0 ? scrollBarThickness
  52240. : getLookAndFeel().getDefaultScrollbarWidth();
  52241. }
  52242. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52243. {
  52244. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52245. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52246. }
  52247. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52248. {
  52249. const int newRangeStartInt = roundToInt (newRangeStart);
  52250. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52251. {
  52252. setViewPosition (newRangeStartInt, getViewPositionY());
  52253. }
  52254. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52255. {
  52256. setViewPosition (getViewPositionX(), newRangeStartInt);
  52257. }
  52258. }
  52259. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52260. {
  52261. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52262. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52263. }
  52264. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52265. {
  52266. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52267. {
  52268. const bool hasVertBar = verticalScrollBar.isVisible();
  52269. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52270. if (hasHorzBar || hasVertBar)
  52271. {
  52272. if (wheelIncrementX != 0)
  52273. {
  52274. wheelIncrementX *= 14.0f * singleStepX;
  52275. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52276. : jmax (wheelIncrementX, 1.0f);
  52277. }
  52278. if (wheelIncrementY != 0)
  52279. {
  52280. wheelIncrementY *= 14.0f * singleStepY;
  52281. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52282. : jmax (wheelIncrementY, 1.0f);
  52283. }
  52284. Point<int> pos (getViewPosition());
  52285. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52286. {
  52287. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52288. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52289. }
  52290. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52291. {
  52292. if (wheelIncrementX == 0 && ! hasVertBar)
  52293. wheelIncrementX = wheelIncrementY;
  52294. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52295. }
  52296. else if (hasVertBar && wheelIncrementY != 0)
  52297. {
  52298. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52299. }
  52300. if (pos != getViewPosition())
  52301. {
  52302. setViewPosition (pos);
  52303. return true;
  52304. }
  52305. }
  52306. }
  52307. return false;
  52308. }
  52309. bool Viewport::keyPressed (const KeyPress& key)
  52310. {
  52311. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52312. || key.isKeyCode (KeyPress::downKey)
  52313. || key.isKeyCode (KeyPress::pageUpKey)
  52314. || key.isKeyCode (KeyPress::pageDownKey)
  52315. || key.isKeyCode (KeyPress::homeKey)
  52316. || key.isKeyCode (KeyPress::endKey);
  52317. if (verticalScrollBar.isVisible() && isUpDownKey)
  52318. return verticalScrollBar.keyPressed (key);
  52319. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52320. || key.isKeyCode (KeyPress::rightKey);
  52321. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52322. return horizontalScrollBar.keyPressed (key);
  52323. return false;
  52324. }
  52325. END_JUCE_NAMESPACE
  52326. /*** End of inlined file: juce_Viewport.cpp ***/
  52327. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52328. BEGIN_JUCE_NAMESPACE
  52329. static const Colour createBaseColour (const Colour& buttonColour,
  52330. const bool hasKeyboardFocus,
  52331. const bool isMouseOverButton,
  52332. const bool isButtonDown) throw()
  52333. {
  52334. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52335. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52336. if (isButtonDown)
  52337. return baseColour.contrasting (0.2f);
  52338. else if (isMouseOverButton)
  52339. return baseColour.contrasting (0.1f);
  52340. return baseColour;
  52341. }
  52342. LookAndFeel::LookAndFeel()
  52343. {
  52344. /* if this fails it means you're trying to create a LookAndFeel object before
  52345. the static Colours have been initialised. That ain't gonna work. It probably
  52346. means that you're using a static LookAndFeel object and that your compiler has
  52347. decided to intialise it before the Colours class.
  52348. */
  52349. jassert (Colours::white == Colour (0xffffffff));
  52350. // set up the standard set of colours..
  52351. const int textButtonColour = 0xffbbbbff;
  52352. const int textHighlightColour = 0x401111ee;
  52353. const int standardOutlineColour = 0xb2808080;
  52354. static const int standardColours[] =
  52355. {
  52356. TextButton::buttonColourId, textButtonColour,
  52357. TextButton::buttonOnColourId, 0xff4444ff,
  52358. TextButton::textColourOnId, 0xff000000,
  52359. TextButton::textColourOffId, 0xff000000,
  52360. ComboBox::buttonColourId, 0xffbbbbff,
  52361. ComboBox::outlineColourId, standardOutlineColour,
  52362. ToggleButton::textColourId, 0xff000000,
  52363. TextEditor::backgroundColourId, 0xffffffff,
  52364. TextEditor::textColourId, 0xff000000,
  52365. TextEditor::highlightColourId, textHighlightColour,
  52366. TextEditor::highlightedTextColourId, 0xff000000,
  52367. TextEditor::caretColourId, 0xff000000,
  52368. TextEditor::outlineColourId, 0x00000000,
  52369. TextEditor::focusedOutlineColourId, textButtonColour,
  52370. TextEditor::shadowColourId, 0x38000000,
  52371. Label::backgroundColourId, 0x00000000,
  52372. Label::textColourId, 0xff000000,
  52373. Label::outlineColourId, 0x00000000,
  52374. ScrollBar::backgroundColourId, 0x00000000,
  52375. ScrollBar::thumbColourId, 0xffffffff,
  52376. ScrollBar::trackColourId, 0xffffffff,
  52377. TreeView::linesColourId, 0x4c000000,
  52378. TreeView::backgroundColourId, 0x00000000,
  52379. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52380. PopupMenu::backgroundColourId, 0xffffffff,
  52381. PopupMenu::textColourId, 0xff000000,
  52382. PopupMenu::headerTextColourId, 0xff000000,
  52383. PopupMenu::highlightedTextColourId, 0xffffffff,
  52384. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52385. ComboBox::textColourId, 0xff000000,
  52386. ComboBox::backgroundColourId, 0xffffffff,
  52387. ComboBox::arrowColourId, 0x99000000,
  52388. ListBox::backgroundColourId, 0xffffffff,
  52389. ListBox::outlineColourId, standardOutlineColour,
  52390. ListBox::textColourId, 0xff000000,
  52391. Slider::backgroundColourId, 0x00000000,
  52392. Slider::thumbColourId, textButtonColour,
  52393. Slider::trackColourId, 0x7fffffff,
  52394. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52395. Slider::rotarySliderOutlineColourId, 0x66000000,
  52396. Slider::textBoxTextColourId, 0xff000000,
  52397. Slider::textBoxBackgroundColourId, 0xffffffff,
  52398. Slider::textBoxHighlightColourId, textHighlightColour,
  52399. Slider::textBoxOutlineColourId, standardOutlineColour,
  52400. ResizableWindow::backgroundColourId, 0xff777777,
  52401. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52402. AlertWindow::backgroundColourId, 0xffededed,
  52403. AlertWindow::textColourId, 0xff000000,
  52404. AlertWindow::outlineColourId, 0xff666666,
  52405. ProgressBar::backgroundColourId, 0xffeeeeee,
  52406. ProgressBar::foregroundColourId, 0xffaaaaee,
  52407. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52408. TooltipWindow::textColourId, 0xff000000,
  52409. TooltipWindow::outlineColourId, 0x4c000000,
  52410. TabbedComponent::backgroundColourId, 0x00000000,
  52411. TabbedComponent::outlineColourId, 0xff777777,
  52412. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52413. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52414. Toolbar::backgroundColourId, 0xfff6f8f9,
  52415. Toolbar::separatorColourId, 0x4c000000,
  52416. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52417. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52418. Toolbar::labelTextColourId, 0xff000000,
  52419. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52420. HyperlinkButton::textColourId, 0xcc1111ee,
  52421. GroupComponent::outlineColourId, 0x66000000,
  52422. GroupComponent::textColourId, 0xff000000,
  52423. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52424. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52425. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52426. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52427. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52428. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52429. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52430. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52431. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52432. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52433. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52434. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52435. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52436. CodeEditorComponent::caretColourId, 0xff000000,
  52437. CodeEditorComponent::highlightColourId, textHighlightColour,
  52438. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52439. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52440. ColourSelector::labelTextColourId, 0xff000000,
  52441. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52442. KeyMappingEditorComponent::textColourId, 0xff000000,
  52443. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52444. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52445. DrawableButton::textColourId, 0xff000000,
  52446. };
  52447. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52448. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52449. static String defaultSansName, defaultSerifName, defaultFixedName;
  52450. if (defaultSansName.isEmpty())
  52451. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52452. defaultSans = defaultSansName;
  52453. defaultSerif = defaultSerifName;
  52454. defaultFixed = defaultFixedName;
  52455. }
  52456. LookAndFeel::~LookAndFeel()
  52457. {
  52458. }
  52459. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52460. {
  52461. const int index = colourIds.indexOf (colourId);
  52462. if (index >= 0)
  52463. return colours [index];
  52464. jassertfalse;
  52465. return Colours::black;
  52466. }
  52467. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52468. {
  52469. const int index = colourIds.indexOf (colourId);
  52470. if (index >= 0)
  52471. {
  52472. colours.set (index, colour);
  52473. }
  52474. else
  52475. {
  52476. colourIds.add (colourId);
  52477. colours.add (colour);
  52478. }
  52479. }
  52480. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52481. {
  52482. return colourIds.contains (colourId);
  52483. }
  52484. static LookAndFeel* defaultLF = 0;
  52485. static LookAndFeel* currentDefaultLF = 0;
  52486. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52487. {
  52488. // if this happens, your app hasn't initialised itself properly.. if you're
  52489. // trying to hack your own main() function, have a look at
  52490. // JUCEApplication::initialiseForGUI()
  52491. jassert (currentDefaultLF != 0);
  52492. return *currentDefaultLF;
  52493. }
  52494. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52495. {
  52496. if (newDefaultLookAndFeel == 0)
  52497. {
  52498. if (defaultLF == 0)
  52499. defaultLF = new LookAndFeel();
  52500. newDefaultLookAndFeel = defaultLF;
  52501. }
  52502. currentDefaultLF = newDefaultLookAndFeel;
  52503. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52504. {
  52505. Component* const c = Desktop::getInstance().getComponent (i);
  52506. if (c != 0)
  52507. c->sendLookAndFeelChange();
  52508. }
  52509. }
  52510. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52511. {
  52512. if (currentDefaultLF == defaultLF)
  52513. currentDefaultLF = 0;
  52514. deleteAndZero (defaultLF);
  52515. }
  52516. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52517. {
  52518. String faceName (font.getTypefaceName());
  52519. if (faceName == Font::getDefaultSansSerifFontName())
  52520. faceName = defaultSans;
  52521. else if (faceName == Font::getDefaultSerifFontName())
  52522. faceName = defaultSerif;
  52523. else if (faceName == Font::getDefaultMonospacedFontName())
  52524. faceName = defaultFixed;
  52525. Font f (font);
  52526. f.setTypefaceName (faceName);
  52527. return Typeface::createSystemTypefaceFor (f);
  52528. }
  52529. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52530. {
  52531. defaultSans = newName;
  52532. }
  52533. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52534. {
  52535. return component.getMouseCursor();
  52536. }
  52537. void LookAndFeel::drawButtonBackground (Graphics& g,
  52538. Button& button,
  52539. const Colour& backgroundColour,
  52540. bool isMouseOverButton,
  52541. bool isButtonDown)
  52542. {
  52543. const int width = button.getWidth();
  52544. const int height = button.getHeight();
  52545. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52546. const float halfThickness = outlineThickness * 0.5f;
  52547. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52548. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52549. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52550. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52551. const Colour baseColour (createBaseColour (backgroundColour,
  52552. button.hasKeyboardFocus (true),
  52553. isMouseOverButton, isButtonDown)
  52554. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52555. drawGlassLozenge (g,
  52556. indentL,
  52557. indentT,
  52558. width - indentL - indentR,
  52559. height - indentT - indentB,
  52560. baseColour, outlineThickness, -1.0f,
  52561. button.isConnectedOnLeft(),
  52562. button.isConnectedOnRight(),
  52563. button.isConnectedOnTop(),
  52564. button.isConnectedOnBottom());
  52565. }
  52566. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52567. {
  52568. return button.getFont();
  52569. }
  52570. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52571. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52572. {
  52573. Font font (getFontForTextButton (button));
  52574. g.setFont (font);
  52575. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52576. : TextButton::textColourOffId)
  52577. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52578. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52579. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52580. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52581. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52582. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52583. g.drawFittedText (button.getButtonText(),
  52584. leftIndent,
  52585. yIndent,
  52586. button.getWidth() - leftIndent - rightIndent,
  52587. button.getHeight() - yIndent * 2,
  52588. Justification::centred, 2);
  52589. }
  52590. void LookAndFeel::drawTickBox (Graphics& g,
  52591. Component& component,
  52592. float x, float y, float w, float h,
  52593. const bool ticked,
  52594. const bool isEnabled,
  52595. const bool isMouseOverButton,
  52596. const bool isButtonDown)
  52597. {
  52598. const float boxSize = w * 0.7f;
  52599. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52600. createBaseColour (component.findColour (TextButton::buttonColourId)
  52601. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52602. true,
  52603. isMouseOverButton,
  52604. isButtonDown),
  52605. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52606. if (ticked)
  52607. {
  52608. Path tick;
  52609. tick.startNewSubPath (1.5f, 3.0f);
  52610. tick.lineTo (3.0f, 6.0f);
  52611. tick.lineTo (6.0f, 0.0f);
  52612. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52613. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52614. .translated (x, y));
  52615. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52616. }
  52617. }
  52618. void LookAndFeel::drawToggleButton (Graphics& g,
  52619. ToggleButton& button,
  52620. bool isMouseOverButton,
  52621. bool isButtonDown)
  52622. {
  52623. if (button.hasKeyboardFocus (true))
  52624. {
  52625. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52626. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52627. }
  52628. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52629. const float tickWidth = fontSize * 1.1f;
  52630. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52631. tickWidth, tickWidth,
  52632. button.getToggleState(),
  52633. button.isEnabled(),
  52634. isMouseOverButton,
  52635. isButtonDown);
  52636. g.setColour (button.findColour (ToggleButton::textColourId));
  52637. g.setFont (fontSize);
  52638. if (! button.isEnabled())
  52639. g.setOpacity (0.5f);
  52640. const int textX = (int) tickWidth + 5;
  52641. g.drawFittedText (button.getButtonText(),
  52642. textX, 0,
  52643. button.getWidth() - textX - 2, button.getHeight(),
  52644. Justification::centredLeft, 10);
  52645. }
  52646. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52647. {
  52648. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52649. const int tickWidth = jmin (24, button.getHeight());
  52650. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52651. button.getHeight());
  52652. }
  52653. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52654. const String& message,
  52655. const String& button1,
  52656. const String& button2,
  52657. const String& button3,
  52658. AlertWindow::AlertIconType iconType,
  52659. int numButtons,
  52660. Component* associatedComponent)
  52661. {
  52662. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52663. if (numButtons == 1)
  52664. {
  52665. aw->addButton (button1, 0,
  52666. KeyPress (KeyPress::escapeKey, 0, 0),
  52667. KeyPress (KeyPress::returnKey, 0, 0));
  52668. }
  52669. else
  52670. {
  52671. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52672. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52673. if (button1ShortCut == button2ShortCut)
  52674. button2ShortCut = KeyPress();
  52675. if (numButtons == 2)
  52676. {
  52677. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52678. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52679. }
  52680. else if (numButtons == 3)
  52681. {
  52682. aw->addButton (button1, 1, button1ShortCut);
  52683. aw->addButton (button2, 2, button2ShortCut);
  52684. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52685. }
  52686. }
  52687. return aw;
  52688. }
  52689. void LookAndFeel::drawAlertBox (Graphics& g,
  52690. AlertWindow& alert,
  52691. const Rectangle<int>& textArea,
  52692. TextLayout& textLayout)
  52693. {
  52694. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52695. int iconSpaceUsed = 0;
  52696. Justification alignment (Justification::horizontallyCentred);
  52697. const int iconWidth = 80;
  52698. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52699. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52700. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52701. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52702. iconSize, iconSize);
  52703. if (alert.getAlertType() != AlertWindow::NoIcon)
  52704. {
  52705. Path icon;
  52706. uint32 colour;
  52707. char character;
  52708. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52709. {
  52710. colour = 0x55ff5555;
  52711. character = '!';
  52712. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52713. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52714. (float) iconRect.getX(), (float) iconRect.getBottom());
  52715. icon = icon.createPathWithRoundedCorners (5.0f);
  52716. }
  52717. else
  52718. {
  52719. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52720. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52721. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52722. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52723. }
  52724. GlyphArrangement ga;
  52725. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52726. String::charToString (character),
  52727. (float) iconRect.getX(), (float) iconRect.getY(),
  52728. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52729. Justification::centred, false);
  52730. ga.createPath (icon);
  52731. icon.setUsingNonZeroWinding (false);
  52732. g.setColour (Colour (colour));
  52733. g.fillPath (icon);
  52734. iconSpaceUsed = iconWidth;
  52735. alignment = Justification::left;
  52736. }
  52737. g.setColour (alert.findColour (AlertWindow::textColourId));
  52738. textLayout.drawWithin (g,
  52739. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52740. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52741. alignment.getFlags() | Justification::top);
  52742. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52743. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52744. }
  52745. int LookAndFeel::getAlertBoxWindowFlags()
  52746. {
  52747. return ComponentPeer::windowAppearsOnTaskbar
  52748. | ComponentPeer::windowHasDropShadow;
  52749. }
  52750. int LookAndFeel::getAlertWindowButtonHeight()
  52751. {
  52752. return 28;
  52753. }
  52754. const Font LookAndFeel::getAlertWindowFont()
  52755. {
  52756. return Font (12.0f);
  52757. }
  52758. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52759. int width, int height,
  52760. double progress, const String& textToShow)
  52761. {
  52762. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52763. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52764. g.fillAll (background);
  52765. if (progress >= 0.0f && progress < 1.0f)
  52766. {
  52767. drawGlassLozenge (g, 1.0f, 1.0f,
  52768. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52769. (float) (height - 2),
  52770. foreground,
  52771. 0.5f, 0.0f,
  52772. true, true, true, true);
  52773. }
  52774. else
  52775. {
  52776. // spinning bar..
  52777. g.setColour (foreground);
  52778. const int stripeWidth = height * 2;
  52779. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52780. Path p;
  52781. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52782. p.addQuadrilateral (x, 0.0f,
  52783. x + stripeWidth * 0.5f, 0.0f,
  52784. x, (float) height,
  52785. x - stripeWidth * 0.5f, (float) height);
  52786. Image im (Image::ARGB, width, height, true);
  52787. {
  52788. Graphics g2 (im);
  52789. drawGlassLozenge (g2, 1.0f, 1.0f,
  52790. (float) (width - 2),
  52791. (float) (height - 2),
  52792. foreground,
  52793. 0.5f, 0.0f,
  52794. true, true, true, true);
  52795. }
  52796. g.setTiledImageFill (im, 0, 0, 0.85f);
  52797. g.fillPath (p);
  52798. }
  52799. if (textToShow.isNotEmpty())
  52800. {
  52801. g.setColour (Colour::contrasting (background, foreground));
  52802. g.setFont (height * 0.6f);
  52803. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52804. }
  52805. }
  52806. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52807. {
  52808. const float radius = jmin (w, h) * 0.4f;
  52809. const float thickness = radius * 0.15f;
  52810. Path p;
  52811. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52812. radius * 0.6f, thickness,
  52813. thickness * 0.5f);
  52814. const float cx = x + w * 0.5f;
  52815. const float cy = y + h * 0.5f;
  52816. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52817. for (int i = 0; i < 12; ++i)
  52818. {
  52819. const int n = (i + 12 - animationIndex) % 12;
  52820. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52821. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52822. .translated (cx, cy));
  52823. }
  52824. }
  52825. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52826. ScrollBar& scrollbar,
  52827. int width, int height,
  52828. int buttonDirection,
  52829. bool /*isScrollbarVertical*/,
  52830. bool /*isMouseOverButton*/,
  52831. bool isButtonDown)
  52832. {
  52833. Path p;
  52834. if (buttonDirection == 0)
  52835. p.addTriangle (width * 0.5f, height * 0.2f,
  52836. width * 0.1f, height * 0.7f,
  52837. width * 0.9f, height * 0.7f);
  52838. else if (buttonDirection == 1)
  52839. p.addTriangle (width * 0.8f, height * 0.5f,
  52840. width * 0.3f, height * 0.1f,
  52841. width * 0.3f, height * 0.9f);
  52842. else if (buttonDirection == 2)
  52843. p.addTriangle (width * 0.5f, height * 0.8f,
  52844. width * 0.1f, height * 0.3f,
  52845. width * 0.9f, height * 0.3f);
  52846. else if (buttonDirection == 3)
  52847. p.addTriangle (width * 0.2f, height * 0.5f,
  52848. width * 0.7f, height * 0.1f,
  52849. width * 0.7f, height * 0.9f);
  52850. if (isButtonDown)
  52851. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52852. else
  52853. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52854. g.fillPath (p);
  52855. g.setColour (Colour (0x80000000));
  52856. g.strokePath (p, PathStrokeType (0.5f));
  52857. }
  52858. void LookAndFeel::drawScrollbar (Graphics& g,
  52859. ScrollBar& scrollbar,
  52860. int x, int y,
  52861. int width, int height,
  52862. bool isScrollbarVertical,
  52863. int thumbStartPosition,
  52864. int thumbSize,
  52865. bool /*isMouseOver*/,
  52866. bool /*isMouseDown*/)
  52867. {
  52868. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52869. Path slotPath, thumbPath;
  52870. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52871. const float slotIndentx2 = slotIndent * 2.0f;
  52872. const float thumbIndent = slotIndent + 1.0f;
  52873. const float thumbIndentx2 = thumbIndent * 2.0f;
  52874. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52875. if (isScrollbarVertical)
  52876. {
  52877. slotPath.addRoundedRectangle (x + slotIndent,
  52878. y + slotIndent,
  52879. width - slotIndentx2,
  52880. height - slotIndentx2,
  52881. (width - slotIndentx2) * 0.5f);
  52882. if (thumbSize > 0)
  52883. thumbPath.addRoundedRectangle (x + thumbIndent,
  52884. thumbStartPosition + thumbIndent,
  52885. width - thumbIndentx2,
  52886. thumbSize - thumbIndentx2,
  52887. (width - thumbIndentx2) * 0.5f);
  52888. gx1 = (float) x;
  52889. gx2 = x + width * 0.7f;
  52890. }
  52891. else
  52892. {
  52893. slotPath.addRoundedRectangle (x + slotIndent,
  52894. y + slotIndent,
  52895. width - slotIndentx2,
  52896. height - slotIndentx2,
  52897. (height - slotIndentx2) * 0.5f);
  52898. if (thumbSize > 0)
  52899. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52900. y + thumbIndent,
  52901. thumbSize - thumbIndentx2,
  52902. height - thumbIndentx2,
  52903. (height - thumbIndentx2) * 0.5f);
  52904. gy1 = (float) y;
  52905. gy2 = y + height * 0.7f;
  52906. }
  52907. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52908. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52909. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52910. g.fillPath (slotPath);
  52911. if (isScrollbarVertical)
  52912. {
  52913. gx1 = x + width * 0.6f;
  52914. gx2 = (float) x + width;
  52915. }
  52916. else
  52917. {
  52918. gy1 = y + height * 0.6f;
  52919. gy2 = (float) y + height;
  52920. }
  52921. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52922. Colour (0x19000000), gx2, gy2, false));
  52923. g.fillPath (slotPath);
  52924. g.setColour (thumbColour);
  52925. g.fillPath (thumbPath);
  52926. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52927. Colours::transparentBlack, gx2, gy2, false));
  52928. g.saveState();
  52929. if (isScrollbarVertical)
  52930. g.reduceClipRegion (x + width / 2, y, width, height);
  52931. else
  52932. g.reduceClipRegion (x, y + height / 2, width, height);
  52933. g.fillPath (thumbPath);
  52934. g.restoreState();
  52935. g.setColour (Colour (0x4c000000));
  52936. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52937. }
  52938. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52939. {
  52940. return 0;
  52941. }
  52942. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52943. {
  52944. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52945. }
  52946. int LookAndFeel::getDefaultScrollbarWidth()
  52947. {
  52948. return 18;
  52949. }
  52950. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52951. {
  52952. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52953. : scrollbar.getHeight());
  52954. }
  52955. const Path LookAndFeel::getTickShape (const float height)
  52956. {
  52957. static const unsigned char tickShapeData[] =
  52958. {
  52959. 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,
  52960. 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,
  52961. 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,
  52962. 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,
  52963. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52964. };
  52965. Path p;
  52966. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52967. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52968. return p;
  52969. }
  52970. const Path LookAndFeel::getCrossShape (const float height)
  52971. {
  52972. static const unsigned char crossShapeData[] =
  52973. {
  52974. 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,
  52975. 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,
  52976. 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,
  52977. 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,
  52978. 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,
  52979. 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,
  52980. 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
  52981. };
  52982. Path p;
  52983. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52984. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52985. return p;
  52986. }
  52987. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52988. {
  52989. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52990. x += (w - boxSize) >> 1;
  52991. y += (h - boxSize) >> 1;
  52992. w = boxSize;
  52993. h = boxSize;
  52994. g.setColour (Colour (0xe5ffffff));
  52995. g.fillRect (x, y, w, h);
  52996. g.setColour (Colour (0x80000000));
  52997. g.drawRect (x, y, w, h);
  52998. const float size = boxSize / 2 + 1.0f;
  52999. const float centre = (float) (boxSize / 2);
  53000. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53001. if (isPlus)
  53002. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53003. }
  53004. void LookAndFeel::drawBubble (Graphics& g,
  53005. float tipX, float tipY,
  53006. float boxX, float boxY,
  53007. float boxW, float boxH)
  53008. {
  53009. int side = 0;
  53010. if (tipX < boxX)
  53011. side = 1;
  53012. else if (tipX > boxX + boxW)
  53013. side = 3;
  53014. else if (tipY > boxY + boxH)
  53015. side = 2;
  53016. const float indent = 2.0f;
  53017. Path p;
  53018. p.addBubble (boxX + indent,
  53019. boxY + indent,
  53020. boxW - indent * 2.0f,
  53021. boxH - indent * 2.0f,
  53022. 5.0f,
  53023. tipX, tipY,
  53024. side,
  53025. 0.5f,
  53026. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53027. //xxx need to take comp as param for colour
  53028. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53029. g.fillPath (p);
  53030. //xxx as above
  53031. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53032. g.strokePath (p, PathStrokeType (1.33f));
  53033. }
  53034. const Font LookAndFeel::getPopupMenuFont()
  53035. {
  53036. return Font (17.0f);
  53037. }
  53038. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53039. const bool isSeparator,
  53040. int standardMenuItemHeight,
  53041. int& idealWidth,
  53042. int& idealHeight)
  53043. {
  53044. if (isSeparator)
  53045. {
  53046. idealWidth = 50;
  53047. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53048. }
  53049. else
  53050. {
  53051. Font font (getPopupMenuFont());
  53052. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53053. font.setHeight (standardMenuItemHeight / 1.3f);
  53054. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53055. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53056. }
  53057. }
  53058. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53059. {
  53060. const Colour background (findColour (PopupMenu::backgroundColourId));
  53061. g.fillAll (background);
  53062. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53063. for (int i = 0; i < height; i += 3)
  53064. g.fillRect (0, i, width, 1);
  53065. #if ! JUCE_MAC
  53066. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53067. g.drawRect (0, 0, width, height);
  53068. #endif
  53069. }
  53070. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53071. int width, int height,
  53072. bool isScrollUpArrow)
  53073. {
  53074. const Colour background (findColour (PopupMenu::backgroundColourId));
  53075. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53076. background.withAlpha (0.0f),
  53077. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53078. false));
  53079. g.fillRect (1, 1, width - 2, height - 2);
  53080. const float hw = width * 0.5f;
  53081. const float arrowW = height * 0.3f;
  53082. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53083. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53084. Path p;
  53085. p.addTriangle (hw - arrowW, y1,
  53086. hw + arrowW, y1,
  53087. hw, y2);
  53088. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53089. g.fillPath (p);
  53090. }
  53091. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53092. int width, int height,
  53093. const bool isSeparator,
  53094. const bool isActive,
  53095. const bool isHighlighted,
  53096. const bool isTicked,
  53097. const bool hasSubMenu,
  53098. const String& text,
  53099. const String& shortcutKeyText,
  53100. Image* image,
  53101. const Colour* const textColourToUse)
  53102. {
  53103. const float halfH = height * 0.5f;
  53104. if (isSeparator)
  53105. {
  53106. const float separatorIndent = 5.5f;
  53107. g.setColour (Colour (0x33000000));
  53108. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53109. g.setColour (Colour (0x66ffffff));
  53110. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53111. }
  53112. else
  53113. {
  53114. Colour textColour (findColour (PopupMenu::textColourId));
  53115. if (textColourToUse != 0)
  53116. textColour = *textColourToUse;
  53117. if (isHighlighted)
  53118. {
  53119. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53120. g.fillRect (1, 1, width - 2, height - 2);
  53121. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53122. }
  53123. else
  53124. {
  53125. g.setColour (textColour);
  53126. }
  53127. if (! isActive)
  53128. g.setOpacity (0.3f);
  53129. Font font (getPopupMenuFont());
  53130. if (font.getHeight() > height / 1.3f)
  53131. font.setHeight (height / 1.3f);
  53132. g.setFont (font);
  53133. const int leftBorder = (height * 5) / 4;
  53134. const int rightBorder = 4;
  53135. if (image != 0)
  53136. {
  53137. g.drawImageWithin (*image,
  53138. 2, 1, leftBorder - 4, height - 2,
  53139. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53140. }
  53141. else if (isTicked)
  53142. {
  53143. const Path tick (getTickShape (1.0f));
  53144. const float th = font.getAscent();
  53145. const float ty = halfH - th * 0.5f;
  53146. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53147. th, true));
  53148. }
  53149. g.drawFittedText (text,
  53150. leftBorder, 0,
  53151. width - (leftBorder + rightBorder), height,
  53152. Justification::centredLeft, 1);
  53153. if (shortcutKeyText.isNotEmpty())
  53154. {
  53155. Font f2 (font);
  53156. f2.setHeight (f2.getHeight() * 0.75f);
  53157. f2.setHorizontalScale (0.95f);
  53158. g.setFont (f2);
  53159. g.drawText (shortcutKeyText,
  53160. leftBorder,
  53161. 0,
  53162. width - (leftBorder + rightBorder + 4),
  53163. height,
  53164. Justification::centredRight,
  53165. true);
  53166. }
  53167. if (hasSubMenu)
  53168. {
  53169. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53170. const float x = width - height * 0.6f;
  53171. Path p;
  53172. p.addTriangle (x, halfH - arrowH * 0.5f,
  53173. x, halfH + arrowH * 0.5f,
  53174. x + arrowH * 0.6f, halfH);
  53175. g.fillPath (p);
  53176. }
  53177. }
  53178. }
  53179. int LookAndFeel::getMenuWindowFlags()
  53180. {
  53181. return ComponentPeer::windowHasDropShadow;
  53182. }
  53183. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53184. bool, MenuBarComponent& menuBar)
  53185. {
  53186. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53187. if (menuBar.isEnabled())
  53188. {
  53189. drawShinyButtonShape (g,
  53190. -4.0f, 0.0f,
  53191. width + 8.0f, (float) height,
  53192. 0.0f,
  53193. baseColour,
  53194. 0.4f,
  53195. true, true, true, true);
  53196. }
  53197. else
  53198. {
  53199. g.fillAll (baseColour);
  53200. }
  53201. }
  53202. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53203. {
  53204. return Font (menuBar.getHeight() * 0.7f);
  53205. }
  53206. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53207. {
  53208. return getMenuBarFont (menuBar, itemIndex, itemText)
  53209. .getStringWidth (itemText) + menuBar.getHeight();
  53210. }
  53211. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53212. int width, int height,
  53213. int itemIndex,
  53214. const String& itemText,
  53215. bool isMouseOverItem,
  53216. bool isMenuOpen,
  53217. bool /*isMouseOverBar*/,
  53218. MenuBarComponent& menuBar)
  53219. {
  53220. if (! menuBar.isEnabled())
  53221. {
  53222. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53223. .withMultipliedAlpha (0.5f));
  53224. }
  53225. else if (isMenuOpen || isMouseOverItem)
  53226. {
  53227. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53228. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53229. }
  53230. else
  53231. {
  53232. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53233. }
  53234. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53235. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53236. }
  53237. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53238. TextEditor& textEditor)
  53239. {
  53240. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53241. }
  53242. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53243. {
  53244. if (textEditor.isEnabled())
  53245. {
  53246. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53247. {
  53248. const int border = 2;
  53249. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53250. g.drawRect (0, 0, width, height, border);
  53251. g.setOpacity (1.0f);
  53252. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53253. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53254. }
  53255. else
  53256. {
  53257. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53258. g.drawRect (0, 0, width, height);
  53259. g.setOpacity (1.0f);
  53260. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53261. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53262. }
  53263. }
  53264. }
  53265. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53266. const bool isButtonDown,
  53267. int buttonX, int buttonY,
  53268. int buttonW, int buttonH,
  53269. ComboBox& box)
  53270. {
  53271. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53272. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53273. {
  53274. g.setColour (box.findColour (TextButton::buttonColourId));
  53275. g.drawRect (0, 0, width, height, 2);
  53276. }
  53277. else
  53278. {
  53279. g.setColour (box.findColour (ComboBox::outlineColourId));
  53280. g.drawRect (0, 0, width, height);
  53281. }
  53282. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53283. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53284. box.hasKeyboardFocus (true),
  53285. false, isButtonDown)
  53286. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53287. drawGlassLozenge (g,
  53288. buttonX + outlineThickness, buttonY + outlineThickness,
  53289. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53290. baseColour, outlineThickness, -1.0f,
  53291. true, true, true, true);
  53292. if (box.isEnabled())
  53293. {
  53294. const float arrowX = 0.3f;
  53295. const float arrowH = 0.2f;
  53296. Path p;
  53297. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53298. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53299. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53300. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53301. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53302. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53303. g.setColour (box.findColour (ComboBox::arrowColourId));
  53304. g.fillPath (p);
  53305. }
  53306. }
  53307. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53308. {
  53309. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53310. }
  53311. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53312. {
  53313. return new Label (String::empty, String::empty);
  53314. }
  53315. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53316. {
  53317. label.setBounds (1, 1,
  53318. box.getWidth() + 3 - box.getHeight(),
  53319. box.getHeight() - 2);
  53320. label.setFont (getComboBoxFont (box));
  53321. }
  53322. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53323. {
  53324. g.fillAll (label.findColour (Label::backgroundColourId));
  53325. if (! label.isBeingEdited())
  53326. {
  53327. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53328. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53329. g.setFont (label.getFont());
  53330. g.drawFittedText (label.getText(),
  53331. label.getHorizontalBorderSize(),
  53332. label.getVerticalBorderSize(),
  53333. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53334. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53335. label.getJustificationType(),
  53336. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53337. label.getMinimumHorizontalScale());
  53338. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53339. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53340. }
  53341. else if (label.isEnabled())
  53342. {
  53343. g.setColour (label.findColour (Label::outlineColourId));
  53344. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53345. }
  53346. }
  53347. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53348. int x, int y,
  53349. int width, int height,
  53350. float /*sliderPos*/,
  53351. float /*minSliderPos*/,
  53352. float /*maxSliderPos*/,
  53353. const Slider::SliderStyle /*style*/,
  53354. Slider& slider)
  53355. {
  53356. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53357. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53358. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53359. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53360. Path indent;
  53361. if (slider.isHorizontal())
  53362. {
  53363. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53364. const float ih = sliderRadius;
  53365. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53366. gradCol2, 0.0f, iy + ih, false));
  53367. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53368. width + sliderRadius, ih,
  53369. 5.0f);
  53370. g.fillPath (indent);
  53371. }
  53372. else
  53373. {
  53374. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53375. const float iw = sliderRadius;
  53376. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53377. gradCol2, ix + iw, 0.0f, false));
  53378. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53379. iw, height + sliderRadius,
  53380. 5.0f);
  53381. g.fillPath (indent);
  53382. }
  53383. g.setColour (Colour (0x4c000000));
  53384. g.strokePath (indent, PathStrokeType (0.5f));
  53385. }
  53386. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53387. int x, int y,
  53388. int width, int height,
  53389. float sliderPos,
  53390. float minSliderPos,
  53391. float maxSliderPos,
  53392. const Slider::SliderStyle style,
  53393. Slider& slider)
  53394. {
  53395. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53396. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53397. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53398. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53399. slider.isMouseButtonDown() && slider.isEnabled()));
  53400. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53401. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53402. {
  53403. float kx, ky;
  53404. if (style == Slider::LinearVertical)
  53405. {
  53406. kx = x + width * 0.5f;
  53407. ky = sliderPos;
  53408. }
  53409. else
  53410. {
  53411. kx = sliderPos;
  53412. ky = y + height * 0.5f;
  53413. }
  53414. drawGlassSphere (g,
  53415. kx - sliderRadius,
  53416. ky - sliderRadius,
  53417. sliderRadius * 2.0f,
  53418. knobColour, outlineThickness);
  53419. }
  53420. else
  53421. {
  53422. if (style == Slider::ThreeValueVertical)
  53423. {
  53424. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53425. sliderPos - sliderRadius,
  53426. sliderRadius * 2.0f,
  53427. knobColour, outlineThickness);
  53428. }
  53429. else if (style == Slider::ThreeValueHorizontal)
  53430. {
  53431. drawGlassSphere (g,sliderPos - sliderRadius,
  53432. y + height * 0.5f - sliderRadius,
  53433. sliderRadius * 2.0f,
  53434. knobColour, outlineThickness);
  53435. }
  53436. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53437. {
  53438. const float sr = jmin (sliderRadius, width * 0.4f);
  53439. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53440. minSliderPos - sliderRadius,
  53441. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53442. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53443. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53444. }
  53445. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53446. {
  53447. const float sr = jmin (sliderRadius, height * 0.4f);
  53448. drawGlassPointer (g, minSliderPos - sr,
  53449. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53450. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53451. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53452. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53453. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53454. }
  53455. }
  53456. }
  53457. void LookAndFeel::drawLinearSlider (Graphics& g,
  53458. int x, int y,
  53459. int width, int height,
  53460. float sliderPos,
  53461. float minSliderPos,
  53462. float maxSliderPos,
  53463. const Slider::SliderStyle style,
  53464. Slider& slider)
  53465. {
  53466. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53467. if (style == Slider::LinearBar)
  53468. {
  53469. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53470. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53471. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53472. false,
  53473. isMouseOver,
  53474. isMouseOver || slider.isMouseButtonDown()));
  53475. drawShinyButtonShape (g,
  53476. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53477. baseColour,
  53478. slider.isEnabled() ? 0.9f : 0.3f,
  53479. true, true, true, true);
  53480. }
  53481. else
  53482. {
  53483. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53484. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53485. }
  53486. }
  53487. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53488. {
  53489. return jmin (7,
  53490. slider.getHeight() / 2,
  53491. slider.getWidth() / 2) + 2;
  53492. }
  53493. void LookAndFeel::drawRotarySlider (Graphics& g,
  53494. int x, int y,
  53495. int width, int height,
  53496. float sliderPos,
  53497. const float rotaryStartAngle,
  53498. const float rotaryEndAngle,
  53499. Slider& slider)
  53500. {
  53501. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53502. const float centreX = x + width * 0.5f;
  53503. const float centreY = y + height * 0.5f;
  53504. const float rx = centreX - radius;
  53505. const float ry = centreY - radius;
  53506. const float rw = radius * 2.0f;
  53507. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53508. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53509. if (radius > 12.0f)
  53510. {
  53511. if (slider.isEnabled())
  53512. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53513. else
  53514. g.setColour (Colour (0x80808080));
  53515. const float thickness = 0.7f;
  53516. {
  53517. Path filledArc;
  53518. filledArc.addPieSegment (rx, ry, rw, rw,
  53519. rotaryStartAngle,
  53520. angle,
  53521. thickness);
  53522. g.fillPath (filledArc);
  53523. }
  53524. if (thickness > 0)
  53525. {
  53526. const float innerRadius = radius * 0.2f;
  53527. Path p;
  53528. p.addTriangle (-innerRadius, 0.0f,
  53529. 0.0f, -radius * thickness * 1.1f,
  53530. innerRadius, 0.0f);
  53531. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53532. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53533. }
  53534. if (slider.isEnabled())
  53535. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53536. else
  53537. g.setColour (Colour (0x80808080));
  53538. Path outlineArc;
  53539. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53540. outlineArc.closeSubPath();
  53541. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53542. }
  53543. else
  53544. {
  53545. if (slider.isEnabled())
  53546. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53547. else
  53548. g.setColour (Colour (0x80808080));
  53549. Path p;
  53550. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53551. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53552. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53553. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53554. }
  53555. }
  53556. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53557. {
  53558. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53559. }
  53560. class SliderLabelComp : public Label
  53561. {
  53562. public:
  53563. SliderLabelComp() : Label (String::empty, String::empty) {}
  53564. ~SliderLabelComp() {}
  53565. void mouseWheelMove (const MouseEvent&, float, float) {}
  53566. };
  53567. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53568. {
  53569. Label* const l = new SliderLabelComp();
  53570. l->setJustificationType (Justification::centred);
  53571. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53572. l->setColour (Label::backgroundColourId,
  53573. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53574. : slider.findColour (Slider::textBoxBackgroundColourId));
  53575. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53576. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53577. l->setColour (TextEditor::backgroundColourId,
  53578. slider.findColour (Slider::textBoxBackgroundColourId)
  53579. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53580. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53581. return l;
  53582. }
  53583. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53584. {
  53585. return 0;
  53586. }
  53587. static const TextLayout layoutTooltipText (const String& text) throw()
  53588. {
  53589. const float tooltipFontSize = 12.0f;
  53590. const int maxToolTipWidth = 400;
  53591. const Font f (tooltipFontSize, Font::bold);
  53592. TextLayout tl (text, f);
  53593. tl.layout (maxToolTipWidth, Justification::left, true);
  53594. return tl;
  53595. }
  53596. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53597. {
  53598. const TextLayout tl (layoutTooltipText (tipText));
  53599. width = tl.getWidth() + 14;
  53600. height = tl.getHeight() + 6;
  53601. }
  53602. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53603. {
  53604. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53605. const Colour textCol (findColour (TooltipWindow::textColourId));
  53606. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53607. g.setColour (findColour (TooltipWindow::outlineColourId));
  53608. g.drawRect (0, 0, width, height, 1);
  53609. #endif
  53610. const TextLayout tl (layoutTooltipText (text));
  53611. g.setColour (findColour (TooltipWindow::textColourId));
  53612. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53613. }
  53614. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53615. {
  53616. return new TextButton (text, TRANS("click to browse for a different file"));
  53617. }
  53618. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53619. ComboBox* filenameBox,
  53620. Button* browseButton)
  53621. {
  53622. browseButton->setSize (80, filenameComp.getHeight());
  53623. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53624. if (tb != 0)
  53625. tb->changeWidthToFitText();
  53626. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53627. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53628. }
  53629. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53630. int imageX, int imageY, int imageW, int imageH,
  53631. const Colour& overlayColour,
  53632. float imageOpacity,
  53633. ImageButton& button)
  53634. {
  53635. if (! button.isEnabled())
  53636. imageOpacity *= 0.3f;
  53637. if (! overlayColour.isOpaque())
  53638. {
  53639. g.setOpacity (imageOpacity);
  53640. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53641. 0, 0, image->getWidth(), image->getHeight(), false);
  53642. }
  53643. if (! overlayColour.isTransparent())
  53644. {
  53645. g.setColour (overlayColour);
  53646. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53647. 0, 0, image->getWidth(), image->getHeight(), true);
  53648. }
  53649. }
  53650. void LookAndFeel::drawCornerResizer (Graphics& g,
  53651. int w, int h,
  53652. bool /*isMouseOver*/,
  53653. bool /*isMouseDragging*/)
  53654. {
  53655. const float lineThickness = jmin (w, h) * 0.075f;
  53656. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53657. {
  53658. g.setColour (Colours::lightgrey);
  53659. g.drawLine (w * i,
  53660. h + 1.0f,
  53661. w + 1.0f,
  53662. h * i,
  53663. lineThickness);
  53664. g.setColour (Colours::darkgrey);
  53665. g.drawLine (w * i + lineThickness,
  53666. h + 1.0f,
  53667. w + 1.0f,
  53668. h * i + lineThickness,
  53669. lineThickness);
  53670. }
  53671. }
  53672. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53673. {
  53674. if (! border.isEmpty())
  53675. {
  53676. const Rectangle<int> fullSize (0, 0, w, h);
  53677. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53678. g.saveState();
  53679. g.excludeClipRegion (centreArea);
  53680. g.setColour (Colour (0x50000000));
  53681. g.drawRect (fullSize);
  53682. g.setColour (Colour (0x19000000));
  53683. g.drawRect (centreArea.expanded (1, 1));
  53684. g.restoreState();
  53685. }
  53686. }
  53687. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53688. const BorderSize& /*border*/, ResizableWindow& window)
  53689. {
  53690. g.fillAll (window.getBackgroundColour());
  53691. }
  53692. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53693. const BorderSize& /*border*/, ResizableWindow&)
  53694. {
  53695. }
  53696. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53697. Graphics& g, int w, int h,
  53698. int titleSpaceX, int titleSpaceW,
  53699. const Image* icon,
  53700. bool drawTitleTextOnLeft)
  53701. {
  53702. const bool isActive = window.isActiveWindow();
  53703. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53704. 0.0f, 0.0f,
  53705. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53706. 0.0f, (float) h, false));
  53707. g.fillAll();
  53708. Font font (h * 0.65f, Font::bold);
  53709. g.setFont (font);
  53710. int textW = font.getStringWidth (window.getName());
  53711. int iconW = 0;
  53712. int iconH = 0;
  53713. if (icon != 0)
  53714. {
  53715. iconH = (int) font.getHeight();
  53716. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53717. }
  53718. textW = jmin (titleSpaceW, textW + iconW);
  53719. int textX = drawTitleTextOnLeft ? titleSpaceX
  53720. : jmax (titleSpaceX, (w - textW) / 2);
  53721. if (textX + textW > titleSpaceX + titleSpaceW)
  53722. textX = titleSpaceX + titleSpaceW - textW;
  53723. if (icon != 0)
  53724. {
  53725. g.setOpacity (isActive ? 1.0f : 0.6f);
  53726. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53727. RectanglePlacement::centred, false);
  53728. textX += iconW;
  53729. textW -= iconW;
  53730. }
  53731. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53732. g.setColour (findColour (DocumentWindow::textColourId));
  53733. else
  53734. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53735. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53736. }
  53737. class GlassWindowButton : public Button
  53738. {
  53739. public:
  53740. GlassWindowButton (const String& name, const Colour& col,
  53741. const Path& normalShape_,
  53742. const Path& toggledShape_) throw()
  53743. : Button (name),
  53744. colour (col),
  53745. normalShape (normalShape_),
  53746. toggledShape (toggledShape_)
  53747. {
  53748. }
  53749. ~GlassWindowButton()
  53750. {
  53751. }
  53752. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53753. {
  53754. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53755. if (! isEnabled())
  53756. alpha *= 0.5f;
  53757. float x = 0, y = 0, diam;
  53758. if (getWidth() < getHeight())
  53759. {
  53760. diam = (float) getWidth();
  53761. y = (getHeight() - getWidth()) * 0.5f;
  53762. }
  53763. else
  53764. {
  53765. diam = (float) getHeight();
  53766. y = (getWidth() - getHeight()) * 0.5f;
  53767. }
  53768. x += diam * 0.05f;
  53769. y += diam * 0.05f;
  53770. diam *= 0.9f;
  53771. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53772. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53773. g.fillEllipse (x, y, diam, diam);
  53774. x += 2.0f;
  53775. y += 2.0f;
  53776. diam -= 4.0f;
  53777. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53778. Path& p = getToggleState() ? toggledShape : normalShape;
  53779. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53780. diam * 0.4f, diam * 0.4f, true));
  53781. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53782. g.fillPath (p, t);
  53783. }
  53784. juce_UseDebuggingNewOperator
  53785. private:
  53786. Colour colour;
  53787. Path normalShape, toggledShape;
  53788. GlassWindowButton (const GlassWindowButton&);
  53789. GlassWindowButton& operator= (const GlassWindowButton&);
  53790. };
  53791. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53792. {
  53793. Path shape;
  53794. const float crossThickness = 0.25f;
  53795. if (buttonType == DocumentWindow::closeButton)
  53796. {
  53797. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53798. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53799. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53800. }
  53801. else if (buttonType == DocumentWindow::minimiseButton)
  53802. {
  53803. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53804. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53805. }
  53806. else if (buttonType == DocumentWindow::maximiseButton)
  53807. {
  53808. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53809. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53810. Path fullscreenShape;
  53811. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53812. fullscreenShape.lineTo (0.0f, 100.0f);
  53813. fullscreenShape.lineTo (0.0f, 0.0f);
  53814. fullscreenShape.lineTo (100.0f, 0.0f);
  53815. fullscreenShape.lineTo (100.0f, 45.0f);
  53816. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53817. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53818. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53819. }
  53820. jassertfalse;
  53821. return 0;
  53822. }
  53823. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53824. int titleBarX,
  53825. int titleBarY,
  53826. int titleBarW,
  53827. int titleBarH,
  53828. Button* minimiseButton,
  53829. Button* maximiseButton,
  53830. Button* closeButton,
  53831. bool positionTitleBarButtonsOnLeft)
  53832. {
  53833. const int buttonW = titleBarH - titleBarH / 8;
  53834. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53835. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53836. if (closeButton != 0)
  53837. {
  53838. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53839. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53840. }
  53841. if (positionTitleBarButtonsOnLeft)
  53842. swapVariables (minimiseButton, maximiseButton);
  53843. if (maximiseButton != 0)
  53844. {
  53845. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53846. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53847. }
  53848. if (minimiseButton != 0)
  53849. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53850. }
  53851. int LookAndFeel::getDefaultMenuBarHeight()
  53852. {
  53853. return 24;
  53854. }
  53855. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53856. {
  53857. return new DropShadower (0.4f, 1, 5, 10);
  53858. }
  53859. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53860. int w, int h,
  53861. bool /*isVerticalBar*/,
  53862. bool isMouseOver,
  53863. bool isMouseDragging)
  53864. {
  53865. float alpha = 0.5f;
  53866. if (isMouseOver || isMouseDragging)
  53867. {
  53868. g.fillAll (Colour (0x190000ff));
  53869. alpha = 1.0f;
  53870. }
  53871. const float cx = w * 0.5f;
  53872. const float cy = h * 0.5f;
  53873. const float cr = jmin (w, h) * 0.4f;
  53874. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53875. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53876. true));
  53877. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53878. }
  53879. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53880. const String& text,
  53881. const Justification& position,
  53882. GroupComponent& group)
  53883. {
  53884. const float textH = 15.0f;
  53885. const float indent = 3.0f;
  53886. const float textEdgeGap = 4.0f;
  53887. float cs = 5.0f;
  53888. Font f (textH);
  53889. Path p;
  53890. float x = indent;
  53891. float y = f.getAscent() - 3.0f;
  53892. float w = jmax (0.0f, width - x * 2.0f);
  53893. float h = jmax (0.0f, height - y - indent);
  53894. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53895. const float cs2 = 2.0f * cs;
  53896. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53897. float textX = cs + textEdgeGap;
  53898. if (position.testFlags (Justification::horizontallyCentred))
  53899. textX = cs + (w - cs2 - textW) * 0.5f;
  53900. else if (position.testFlags (Justification::right))
  53901. textX = w - cs - textW - textEdgeGap;
  53902. p.startNewSubPath (x + textX + textW, y);
  53903. p.lineTo (x + w - cs, y);
  53904. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53905. p.lineTo (x + w, y + h - cs);
  53906. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53907. p.lineTo (x + cs, y + h);
  53908. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53909. p.lineTo (x, y + cs);
  53910. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53911. p.lineTo (x + textX, y);
  53912. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53913. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53914. .withMultipliedAlpha (alpha));
  53915. g.strokePath (p, PathStrokeType (2.0f));
  53916. g.setColour (group.findColour (GroupComponent::textColourId)
  53917. .withMultipliedAlpha (alpha));
  53918. g.setFont (f);
  53919. g.drawText (text,
  53920. roundToInt (x + textX), 0,
  53921. roundToInt (textW),
  53922. roundToInt (textH),
  53923. Justification::centred, true);
  53924. }
  53925. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53926. {
  53927. return 1 + tabDepth / 3;
  53928. }
  53929. int LookAndFeel::getTabButtonSpaceAroundImage()
  53930. {
  53931. return 4;
  53932. }
  53933. void LookAndFeel::createTabButtonShape (Path& p,
  53934. int width, int height,
  53935. int /*tabIndex*/,
  53936. const String& /*text*/,
  53937. Button& /*button*/,
  53938. TabbedButtonBar::Orientation orientation,
  53939. const bool /*isMouseOver*/,
  53940. const bool /*isMouseDown*/,
  53941. const bool /*isFrontTab*/)
  53942. {
  53943. const float w = (float) width;
  53944. const float h = (float) height;
  53945. float length = w;
  53946. float depth = h;
  53947. if (orientation == TabbedButtonBar::TabsAtLeft
  53948. || orientation == TabbedButtonBar::TabsAtRight)
  53949. {
  53950. swapVariables (length, depth);
  53951. }
  53952. const float indent = (float) getTabButtonOverlap ((int) depth);
  53953. const float overhang = 4.0f;
  53954. if (orientation == TabbedButtonBar::TabsAtLeft)
  53955. {
  53956. p.startNewSubPath (w, 0.0f);
  53957. p.lineTo (0.0f, indent);
  53958. p.lineTo (0.0f, h - indent);
  53959. p.lineTo (w, h);
  53960. p.lineTo (w + overhang, h + overhang);
  53961. p.lineTo (w + overhang, -overhang);
  53962. }
  53963. else if (orientation == TabbedButtonBar::TabsAtRight)
  53964. {
  53965. p.startNewSubPath (0.0f, 0.0f);
  53966. p.lineTo (w, indent);
  53967. p.lineTo (w, h - indent);
  53968. p.lineTo (0.0f, h);
  53969. p.lineTo (-overhang, h + overhang);
  53970. p.lineTo (-overhang, -overhang);
  53971. }
  53972. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53973. {
  53974. p.startNewSubPath (0.0f, 0.0f);
  53975. p.lineTo (indent, h);
  53976. p.lineTo (w - indent, h);
  53977. p.lineTo (w, 0.0f);
  53978. p.lineTo (w + overhang, -overhang);
  53979. p.lineTo (-overhang, -overhang);
  53980. }
  53981. else
  53982. {
  53983. p.startNewSubPath (0.0f, h);
  53984. p.lineTo (indent, 0.0f);
  53985. p.lineTo (w - indent, 0.0f);
  53986. p.lineTo (w, h);
  53987. p.lineTo (w + overhang, h + overhang);
  53988. p.lineTo (-overhang, h + overhang);
  53989. }
  53990. p.closeSubPath();
  53991. p = p.createPathWithRoundedCorners (3.0f);
  53992. }
  53993. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53994. const Path& path,
  53995. const Colour& preferredColour,
  53996. int /*tabIndex*/,
  53997. const String& /*text*/,
  53998. Button& button,
  53999. TabbedButtonBar::Orientation /*orientation*/,
  54000. const bool /*isMouseOver*/,
  54001. const bool /*isMouseDown*/,
  54002. const bool isFrontTab)
  54003. {
  54004. g.setColour (isFrontTab ? preferredColour
  54005. : preferredColour.withMultipliedAlpha (0.9f));
  54006. g.fillPath (path);
  54007. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54008. : TabbedButtonBar::tabOutlineColourId, false)
  54009. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54010. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54011. }
  54012. void LookAndFeel::drawTabButtonText (Graphics& g,
  54013. int x, int y, int w, int h,
  54014. const Colour& preferredBackgroundColour,
  54015. int /*tabIndex*/,
  54016. const String& text,
  54017. Button& button,
  54018. TabbedButtonBar::Orientation orientation,
  54019. const bool isMouseOver,
  54020. const bool isMouseDown,
  54021. const bool isFrontTab)
  54022. {
  54023. int length = w;
  54024. int depth = h;
  54025. if (orientation == TabbedButtonBar::TabsAtLeft
  54026. || orientation == TabbedButtonBar::TabsAtRight)
  54027. {
  54028. swapVariables (length, depth);
  54029. }
  54030. Font font (depth * 0.6f);
  54031. font.setUnderline (button.hasKeyboardFocus (false));
  54032. GlyphArrangement textLayout;
  54033. textLayout.addFittedText (font, text.trim(),
  54034. 0.0f, 0.0f, (float) length, (float) depth,
  54035. Justification::centred,
  54036. jmax (1, depth / 12));
  54037. AffineTransform transform;
  54038. if (orientation == TabbedButtonBar::TabsAtLeft)
  54039. {
  54040. transform = transform.rotated (float_Pi * -0.5f)
  54041. .translated ((float) x, (float) (y + h));
  54042. }
  54043. else if (orientation == TabbedButtonBar::TabsAtRight)
  54044. {
  54045. transform = transform.rotated (float_Pi * 0.5f)
  54046. .translated ((float) (x + w), (float) y);
  54047. }
  54048. else
  54049. {
  54050. transform = transform.translated ((float) x, (float) y);
  54051. }
  54052. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54053. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54054. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54055. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54056. else
  54057. g.setColour (preferredBackgroundColour.contrasting());
  54058. if (! (isMouseOver || isMouseDown))
  54059. g.setOpacity (0.8f);
  54060. if (! button.isEnabled())
  54061. g.setOpacity (0.3f);
  54062. textLayout.draw (g, transform);
  54063. }
  54064. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54065. const String& text,
  54066. int tabDepth,
  54067. Button&)
  54068. {
  54069. Font f (tabDepth * 0.6f);
  54070. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54071. }
  54072. void LookAndFeel::drawTabButton (Graphics& g,
  54073. int w, int h,
  54074. const Colour& preferredColour,
  54075. int tabIndex,
  54076. const String& text,
  54077. Button& button,
  54078. TabbedButtonBar::Orientation orientation,
  54079. const bool isMouseOver,
  54080. const bool isMouseDown,
  54081. const bool isFrontTab)
  54082. {
  54083. int length = w;
  54084. int depth = h;
  54085. if (orientation == TabbedButtonBar::TabsAtLeft
  54086. || orientation == TabbedButtonBar::TabsAtRight)
  54087. {
  54088. swapVariables (length, depth);
  54089. }
  54090. Path tabShape;
  54091. createTabButtonShape (tabShape, w, h,
  54092. tabIndex, text, button, orientation,
  54093. isMouseOver, isMouseDown, isFrontTab);
  54094. fillTabButtonShape (g, tabShape, preferredColour,
  54095. tabIndex, text, button, orientation,
  54096. isMouseOver, isMouseDown, isFrontTab);
  54097. const int indent = getTabButtonOverlap (depth);
  54098. int x = 0, y = 0;
  54099. if (orientation == TabbedButtonBar::TabsAtLeft
  54100. || orientation == TabbedButtonBar::TabsAtRight)
  54101. {
  54102. y += indent;
  54103. h -= indent * 2;
  54104. }
  54105. else
  54106. {
  54107. x += indent;
  54108. w -= indent * 2;
  54109. }
  54110. drawTabButtonText (g, x, y, w, h, preferredColour,
  54111. tabIndex, text, button, orientation,
  54112. isMouseOver, isMouseDown, isFrontTab);
  54113. }
  54114. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54115. int w, int h,
  54116. TabbedButtonBar& tabBar,
  54117. TabbedButtonBar::Orientation orientation)
  54118. {
  54119. const float shadowSize = 0.2f;
  54120. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54121. Rectangle<int> shadowRect;
  54122. if (orientation == TabbedButtonBar::TabsAtLeft)
  54123. {
  54124. x1 = (float) w;
  54125. x2 = w * (1.0f - shadowSize);
  54126. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54127. }
  54128. else if (orientation == TabbedButtonBar::TabsAtRight)
  54129. {
  54130. x2 = w * shadowSize;
  54131. shadowRect.setBounds (0, 0, (int) x2, h);
  54132. }
  54133. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54134. {
  54135. y2 = h * shadowSize;
  54136. shadowRect.setBounds (0, 0, w, (int) y2);
  54137. }
  54138. else
  54139. {
  54140. y1 = (float) h;
  54141. y2 = h * (1.0f - shadowSize);
  54142. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54143. }
  54144. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54145. Colours::transparentBlack, x2, y2, false));
  54146. shadowRect.expand (2, 2);
  54147. g.fillRect (shadowRect);
  54148. g.setColour (Colour (0x80000000));
  54149. if (orientation == TabbedButtonBar::TabsAtLeft)
  54150. {
  54151. g.fillRect (w - 1, 0, 1, h);
  54152. }
  54153. else if (orientation == TabbedButtonBar::TabsAtRight)
  54154. {
  54155. g.fillRect (0, 0, 1, h);
  54156. }
  54157. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54158. {
  54159. g.fillRect (0, 0, w, 1);
  54160. }
  54161. else
  54162. {
  54163. g.fillRect (0, h - 1, w, 1);
  54164. }
  54165. }
  54166. Button* LookAndFeel::createTabBarExtrasButton()
  54167. {
  54168. const float thickness = 7.0f;
  54169. const float indent = 22.0f;
  54170. Path p;
  54171. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54172. DrawablePath ellipse;
  54173. ellipse.setPath (p);
  54174. ellipse.setFill (Colour (0x99ffffff));
  54175. p.clear();
  54176. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54177. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54178. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54179. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54180. p.setUsingNonZeroWinding (false);
  54181. DrawablePath dp;
  54182. dp.setPath (p);
  54183. dp.setFill (Colour (0x59000000));
  54184. DrawableComposite normalImage;
  54185. normalImage.insertDrawable (ellipse);
  54186. normalImage.insertDrawable (dp);
  54187. dp.setFill (Colour (0xcc000000));
  54188. DrawableComposite overImage;
  54189. overImage.insertDrawable (ellipse);
  54190. overImage.insertDrawable (dp);
  54191. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54192. db->setImages (&normalImage, &overImage, 0);
  54193. return db;
  54194. }
  54195. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54196. {
  54197. g.fillAll (Colours::white);
  54198. const int w = header.getWidth();
  54199. const int h = header.getHeight();
  54200. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54201. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54202. false));
  54203. g.fillRect (0, h / 2, w, h);
  54204. g.setColour (Colour (0x33000000));
  54205. g.fillRect (0, h - 1, w, 1);
  54206. for (int i = header.getNumColumns (true); --i >= 0;)
  54207. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54208. }
  54209. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54210. int width, int height,
  54211. bool isMouseOver, bool isMouseDown,
  54212. int columnFlags)
  54213. {
  54214. if (isMouseDown)
  54215. g.fillAll (Colour (0x8899aadd));
  54216. else if (isMouseOver)
  54217. g.fillAll (Colour (0x5599aadd));
  54218. int rightOfText = width - 4;
  54219. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54220. {
  54221. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54222. const float bottom = height - top;
  54223. const float w = height * 0.5f;
  54224. const float x = rightOfText - (w * 1.25f);
  54225. rightOfText = (int) x;
  54226. Path sortArrow;
  54227. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54228. g.setColour (Colour (0x99000000));
  54229. g.fillPath (sortArrow);
  54230. }
  54231. g.setColour (Colours::black);
  54232. g.setFont (height * 0.5f, Font::bold);
  54233. const int textX = 4;
  54234. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54235. }
  54236. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54237. {
  54238. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54239. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54240. background.darker (0.1f),
  54241. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54242. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54243. false));
  54244. g.fillAll();
  54245. }
  54246. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54247. {
  54248. return createTabBarExtrasButton();
  54249. }
  54250. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54251. bool isMouseOver, bool isMouseDown,
  54252. ToolbarItemComponent& component)
  54253. {
  54254. if (isMouseDown)
  54255. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54256. else if (isMouseOver)
  54257. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54258. }
  54259. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54260. const String& text, ToolbarItemComponent& component)
  54261. {
  54262. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54263. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54264. const float fontHeight = jmin (14.0f, height * 0.85f);
  54265. g.setFont (fontHeight);
  54266. g.drawFittedText (text,
  54267. x, y, width, height,
  54268. Justification::centred,
  54269. jmax (1, height / (int) fontHeight));
  54270. }
  54271. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54272. bool isOpen, int width, int height)
  54273. {
  54274. const int buttonSize = (height * 3) / 4;
  54275. const int buttonIndent = (height - buttonSize) / 2;
  54276. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54277. const int textX = buttonIndent * 2 + buttonSize + 2;
  54278. g.setColour (Colours::black);
  54279. g.setFont (height * 0.7f, Font::bold);
  54280. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54281. }
  54282. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54283. PropertyComponent&)
  54284. {
  54285. g.setColour (Colour (0x66ffffff));
  54286. g.fillRect (0, 0, width, height - 1);
  54287. }
  54288. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54289. PropertyComponent& component)
  54290. {
  54291. g.setColour (Colours::black);
  54292. if (! component.isEnabled())
  54293. g.setOpacity (0.6f);
  54294. g.setFont (jmin (height, 24) * 0.65f);
  54295. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54296. g.drawFittedText (component.getName(),
  54297. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54298. Justification::centredLeft, 2);
  54299. }
  54300. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54301. {
  54302. return Rectangle<int> (component.getWidth() / 3, 1,
  54303. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54304. }
  54305. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54306. {
  54307. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54308. {
  54309. Graphics g2 (content);
  54310. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54311. g2.fillPath (path);
  54312. g2.setColour (Colours::white.withAlpha (0.8f));
  54313. g2.strokePath (path, PathStrokeType (2.0f));
  54314. }
  54315. DropShadowEffect shadow;
  54316. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54317. shadow.applyEffect (content, g);
  54318. }
  54319. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54320. const String& instructions,
  54321. GlyphArrangement& text,
  54322. int width)
  54323. {
  54324. text.clear();
  54325. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54326. 8.0f, 22.0f, width - 16.0f,
  54327. Justification::centred);
  54328. text.addJustifiedText (Font (14.0f), instructions,
  54329. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54330. Justification::centred);
  54331. }
  54332. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54333. const String& filename, Image* icon,
  54334. const String& fileSizeDescription,
  54335. const String& fileTimeDescription,
  54336. const bool isDirectory,
  54337. const bool isItemSelected,
  54338. const int /*itemIndex*/,
  54339. DirectoryContentsDisplayComponent&)
  54340. {
  54341. if (isItemSelected)
  54342. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54343. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54344. g.setFont (height * 0.7f);
  54345. Image im;
  54346. if (icon != 0)
  54347. im = *icon;
  54348. if (im.isNull())
  54349. im = isDirectory ? getDefaultFolderImage()
  54350. : getDefaultDocumentFileImage();
  54351. const int x = 32;
  54352. if (im.isValid())
  54353. {
  54354. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54355. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54356. false);
  54357. }
  54358. if (width > 450 && ! isDirectory)
  54359. {
  54360. const int sizeX = roundToInt (width * 0.7f);
  54361. const int dateX = roundToInt (width * 0.8f);
  54362. g.drawFittedText (filename,
  54363. x, 0, sizeX - x, height,
  54364. Justification::centredLeft, 1);
  54365. g.setFont (height * 0.5f);
  54366. g.setColour (Colours::darkgrey);
  54367. if (! isDirectory)
  54368. {
  54369. g.drawFittedText (fileSizeDescription,
  54370. sizeX, 0, dateX - sizeX - 8, height,
  54371. Justification::centredRight, 1);
  54372. g.drawFittedText (fileTimeDescription,
  54373. dateX, 0, width - 8 - dateX, height,
  54374. Justification::centredRight, 1);
  54375. }
  54376. }
  54377. else
  54378. {
  54379. g.drawFittedText (filename,
  54380. x, 0, width - x, height,
  54381. Justification::centredLeft, 1);
  54382. }
  54383. }
  54384. Button* LookAndFeel::createFileBrowserGoUpButton()
  54385. {
  54386. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54387. Path arrowPath;
  54388. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54389. DrawablePath arrowImage;
  54390. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54391. arrowImage.setPath (arrowPath);
  54392. goUpButton->setImages (&arrowImage);
  54393. return goUpButton;
  54394. }
  54395. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54396. DirectoryContentsDisplayComponent* fileListComponent,
  54397. FilePreviewComponent* previewComp,
  54398. ComboBox* currentPathBox,
  54399. TextEditor* filenameBox,
  54400. Button* goUpButton)
  54401. {
  54402. const int x = 8;
  54403. int w = browserComp.getWidth() - x - x;
  54404. if (previewComp != 0)
  54405. {
  54406. const int previewWidth = w / 3;
  54407. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54408. w -= previewWidth + 4;
  54409. }
  54410. int y = 4;
  54411. const int controlsHeight = 22;
  54412. const int bottomSectionHeight = controlsHeight + 8;
  54413. const int upButtonWidth = 50;
  54414. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54415. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54416. y += controlsHeight + 4;
  54417. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54418. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54419. y = listAsComp->getBottom() + 4;
  54420. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54421. }
  54422. const Image LookAndFeel::getDefaultFolderImage()
  54423. {
  54424. 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,
  54425. 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,
  54426. 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,
  54427. 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,
  54428. 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,
  54429. 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,
  54430. 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,
  54431. 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,
  54432. 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,
  54433. 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,
  54434. 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,
  54435. 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,
  54436. 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,
  54437. 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,
  54438. 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,
  54439. 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,
  54440. 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,
  54441. 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,
  54442. 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,
  54443. 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,
  54444. 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,
  54445. 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,
  54446. 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,
  54447. 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,
  54448. 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,
  54449. 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,
  54450. 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,
  54451. 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,
  54452. 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,
  54453. 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,
  54454. 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,
  54455. 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,
  54456. 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,
  54457. 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,
  54458. 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,
  54459. 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,
  54460. 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,
  54461. 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,
  54462. 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,
  54463. 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,
  54464. 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,
  54465. 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,
  54466. 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,
  54467. 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};
  54468. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54469. }
  54470. const Image LookAndFeel::getDefaultDocumentFileImage()
  54471. {
  54472. 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,
  54473. 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,
  54474. 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,
  54475. 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,
  54476. 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,
  54477. 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,
  54478. 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,
  54479. 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,
  54480. 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,
  54481. 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,
  54482. 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,
  54483. 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,
  54484. 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,
  54485. 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,
  54486. 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,
  54487. 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,
  54488. 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,
  54489. 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,
  54490. 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,
  54491. 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,
  54492. 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,
  54493. 174,66,96,130,0,0};
  54494. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54495. }
  54496. void LookAndFeel::playAlertSound()
  54497. {
  54498. PlatformUtilities::beep();
  54499. }
  54500. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54501. {
  54502. g.setColour (Colours::white.withAlpha (0.7f));
  54503. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54504. g.setColour (Colours::black.withAlpha (0.2f));
  54505. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54506. const int totalBlocks = 7;
  54507. const int numBlocks = roundToInt (totalBlocks * level);
  54508. const float w = (width - 6.0f) / (float) totalBlocks;
  54509. for (int i = 0; i < totalBlocks; ++i)
  54510. {
  54511. if (i >= numBlocks)
  54512. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54513. else
  54514. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54515. : Colours::red);
  54516. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54517. }
  54518. }
  54519. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54520. {
  54521. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54522. if (keyDescription.isNotEmpty())
  54523. {
  54524. if (button.isEnabled())
  54525. {
  54526. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54527. g.fillAll (textColour.withAlpha (alpha));
  54528. g.setOpacity (0.3f);
  54529. g.drawBevel (0, 0, width, height, 2);
  54530. }
  54531. g.setColour (textColour);
  54532. g.setFont (height * 0.6f);
  54533. g.drawFittedText (keyDescription,
  54534. 3, 0, width - 6, height,
  54535. Justification::centred, 1);
  54536. }
  54537. else
  54538. {
  54539. const float thickness = 7.0f;
  54540. const float indent = 22.0f;
  54541. Path p;
  54542. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54543. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54544. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54545. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54546. p.setUsingNonZeroWinding (false);
  54547. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54548. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54549. }
  54550. if (button.hasKeyboardFocus (false))
  54551. {
  54552. g.setColour (textColour.withAlpha (0.4f));
  54553. g.drawRect (0, 0, width, height);
  54554. }
  54555. }
  54556. static void createRoundedPath (Path& p,
  54557. const float x, const float y,
  54558. const float w, const float h,
  54559. const float cs,
  54560. const bool curveTopLeft, const bool curveTopRight,
  54561. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54562. {
  54563. const float cs2 = 2.0f * cs;
  54564. if (curveTopLeft)
  54565. {
  54566. p.startNewSubPath (x, y + cs);
  54567. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54568. }
  54569. else
  54570. {
  54571. p.startNewSubPath (x, y);
  54572. }
  54573. if (curveTopRight)
  54574. {
  54575. p.lineTo (x + w - cs, y);
  54576. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54577. }
  54578. else
  54579. {
  54580. p.lineTo (x + w, y);
  54581. }
  54582. if (curveBottomRight)
  54583. {
  54584. p.lineTo (x + w, y + h - cs);
  54585. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54586. }
  54587. else
  54588. {
  54589. p.lineTo (x + w, y + h);
  54590. }
  54591. if (curveBottomLeft)
  54592. {
  54593. p.lineTo (x + cs, y + h);
  54594. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54595. }
  54596. else
  54597. {
  54598. p.lineTo (x, y + h);
  54599. }
  54600. p.closeSubPath();
  54601. }
  54602. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54603. float x, float y, float w, float h,
  54604. float maxCornerSize,
  54605. const Colour& baseColour,
  54606. const float strokeWidth,
  54607. const bool flatOnLeft,
  54608. const bool flatOnRight,
  54609. const bool flatOnTop,
  54610. const bool flatOnBottom) throw()
  54611. {
  54612. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54613. return;
  54614. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54615. Path outline;
  54616. createRoundedPath (outline, x, y, w, h, cs,
  54617. ! (flatOnLeft || flatOnTop),
  54618. ! (flatOnRight || flatOnTop),
  54619. ! (flatOnLeft || flatOnBottom),
  54620. ! (flatOnRight || flatOnBottom));
  54621. ColourGradient cg (baseColour, 0.0f, y,
  54622. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54623. false);
  54624. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54625. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54626. g.setGradientFill (cg);
  54627. g.fillPath (outline);
  54628. g.setColour (Colour (0x80000000));
  54629. g.strokePath (outline, PathStrokeType (strokeWidth));
  54630. }
  54631. void LookAndFeel::drawGlassSphere (Graphics& g,
  54632. const float x, const float y,
  54633. const float diameter,
  54634. const Colour& colour,
  54635. const float outlineThickness) throw()
  54636. {
  54637. if (diameter <= outlineThickness)
  54638. return;
  54639. Path p;
  54640. p.addEllipse (x, y, diameter, diameter);
  54641. {
  54642. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54643. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54644. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54645. g.setGradientFill (cg);
  54646. g.fillPath (p);
  54647. }
  54648. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54649. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54650. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54651. ColourGradient cg (Colours::transparentBlack,
  54652. x + diameter * 0.5f, y + diameter * 0.5f,
  54653. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54654. x, y + diameter * 0.5f, true);
  54655. cg.addColour (0.7, Colours::transparentBlack);
  54656. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54657. g.setGradientFill (cg);
  54658. g.fillPath (p);
  54659. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54660. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54661. }
  54662. void LookAndFeel::drawGlassPointer (Graphics& g,
  54663. const float x, const float y,
  54664. const float diameter,
  54665. const Colour& colour, const float outlineThickness,
  54666. const int direction) throw()
  54667. {
  54668. if (diameter <= outlineThickness)
  54669. return;
  54670. Path p;
  54671. p.startNewSubPath (x + diameter * 0.5f, y);
  54672. p.lineTo (x + diameter, y + diameter * 0.6f);
  54673. p.lineTo (x + diameter, y + diameter);
  54674. p.lineTo (x, y + diameter);
  54675. p.lineTo (x, y + diameter * 0.6f);
  54676. p.closeSubPath();
  54677. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54678. {
  54679. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54680. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54681. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54682. g.setGradientFill (cg);
  54683. g.fillPath (p);
  54684. }
  54685. ColourGradient cg (Colours::transparentBlack,
  54686. x + diameter * 0.5f, y + diameter * 0.5f,
  54687. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54688. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54689. cg.addColour (0.5, Colours::transparentBlack);
  54690. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54691. g.setGradientFill (cg);
  54692. g.fillPath (p);
  54693. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54694. g.strokePath (p, PathStrokeType (outlineThickness));
  54695. }
  54696. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54697. const float x, const float y,
  54698. const float width, const float height,
  54699. const Colour& colour,
  54700. const float outlineThickness,
  54701. const float cornerSize,
  54702. const bool flatOnLeft,
  54703. const bool flatOnRight,
  54704. const bool flatOnTop,
  54705. const bool flatOnBottom) throw()
  54706. {
  54707. if (width <= outlineThickness || height <= outlineThickness)
  54708. return;
  54709. const int intX = (int) x;
  54710. const int intY = (int) y;
  54711. const int intW = (int) width;
  54712. const int intH = (int) height;
  54713. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54714. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54715. const int intEdge = (int) edgeBlurRadius;
  54716. Path outline;
  54717. createRoundedPath (outline, x, y, width, height, cs,
  54718. ! (flatOnLeft || flatOnTop),
  54719. ! (flatOnRight || flatOnTop),
  54720. ! (flatOnLeft || flatOnBottom),
  54721. ! (flatOnRight || flatOnBottom));
  54722. {
  54723. ColourGradient cg (colour.darker (0.2f), 0, y,
  54724. colour.darker (0.2f), 0, y + height, false);
  54725. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54726. cg.addColour (0.4, colour);
  54727. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54728. g.setGradientFill (cg);
  54729. g.fillPath (outline);
  54730. }
  54731. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54732. colour.darker (0.2f), x, y + height * 0.5f, true);
  54733. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54734. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54735. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54736. {
  54737. g.saveState();
  54738. g.setGradientFill (cg);
  54739. g.reduceClipRegion (intX, intY, intEdge, intH);
  54740. g.fillPath (outline);
  54741. g.restoreState();
  54742. }
  54743. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54744. {
  54745. cg.point1.setX (x + width - edgeBlurRadius);
  54746. cg.point2.setX (x + width);
  54747. g.saveState();
  54748. g.setGradientFill (cg);
  54749. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54750. g.fillPath (outline);
  54751. g.restoreState();
  54752. }
  54753. {
  54754. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54755. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54756. Path highlight;
  54757. createRoundedPath (highlight,
  54758. x + leftIndent,
  54759. y + cs * 0.1f,
  54760. width - (leftIndent + rightIndent),
  54761. height * 0.4f, cs * 0.4f,
  54762. ! (flatOnLeft || flatOnTop),
  54763. ! (flatOnRight || flatOnTop),
  54764. ! (flatOnLeft || flatOnBottom),
  54765. ! (flatOnRight || flatOnBottom));
  54766. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54767. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54768. g.fillPath (highlight);
  54769. }
  54770. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54771. g.strokePath (outline, PathStrokeType (outlineThickness));
  54772. }
  54773. END_JUCE_NAMESPACE
  54774. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54775. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54776. BEGIN_JUCE_NAMESPACE
  54777. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54778. {
  54779. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54780. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54781. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54782. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54783. setColour (Slider::thumbColourId, Colours::white);
  54784. setColour (Slider::trackColourId, Colour (0x7f000000));
  54785. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54786. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54787. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54788. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54789. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54790. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54791. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54792. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54793. }
  54794. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54795. {
  54796. }
  54797. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54798. Button& button,
  54799. const Colour& backgroundColour,
  54800. bool isMouseOverButton,
  54801. bool isButtonDown)
  54802. {
  54803. const int width = button.getWidth();
  54804. const int height = button.getHeight();
  54805. const float indent = 2.0f;
  54806. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54807. roundToInt (height * 0.4f));
  54808. Path p;
  54809. p.addRoundedRectangle (indent, indent,
  54810. width - indent * 2.0f,
  54811. height - indent * 2.0f,
  54812. (float) cornerSize);
  54813. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54814. if (isMouseOverButton)
  54815. {
  54816. if (isButtonDown)
  54817. bc = bc.brighter();
  54818. else if (bc.getBrightness() > 0.5f)
  54819. bc = bc.darker (0.1f);
  54820. else
  54821. bc = bc.brighter (0.1f);
  54822. }
  54823. g.setColour (bc);
  54824. g.fillPath (p);
  54825. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54826. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54827. }
  54828. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54829. Component& /*component*/,
  54830. float x, float y, float w, float h,
  54831. const bool ticked,
  54832. const bool isEnabled,
  54833. const bool /*isMouseOverButton*/,
  54834. const bool isButtonDown)
  54835. {
  54836. Path box;
  54837. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54838. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54839. : Colours::lightgrey.withAlpha (0.1f));
  54840. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54841. g.fillPath (box, trans);
  54842. g.setColour (Colours::black.withAlpha (0.6f));
  54843. g.strokePath (box, PathStrokeType (0.9f), trans);
  54844. if (ticked)
  54845. {
  54846. Path tick;
  54847. tick.startNewSubPath (1.5f, 3.0f);
  54848. tick.lineTo (3.0f, 6.0f);
  54849. tick.lineTo (6.0f, 0.0f);
  54850. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54851. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54852. }
  54853. }
  54854. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54855. ToggleButton& button,
  54856. bool isMouseOverButton,
  54857. bool isButtonDown)
  54858. {
  54859. if (button.hasKeyboardFocus (true))
  54860. {
  54861. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54862. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54863. }
  54864. const int tickWidth = jmin (20, button.getHeight() - 4);
  54865. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54866. (float) tickWidth, (float) tickWidth,
  54867. button.getToggleState(),
  54868. button.isEnabled(),
  54869. isMouseOverButton,
  54870. isButtonDown);
  54871. g.setColour (button.findColour (ToggleButton::textColourId));
  54872. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54873. if (! button.isEnabled())
  54874. g.setOpacity (0.5f);
  54875. const int textX = tickWidth + 5;
  54876. g.drawFittedText (button.getButtonText(),
  54877. textX, 4,
  54878. button.getWidth() - textX - 2, button.getHeight() - 8,
  54879. Justification::centredLeft, 10);
  54880. }
  54881. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54882. int width, int height,
  54883. double progress, const String& textToShow)
  54884. {
  54885. if (progress < 0 || progress >= 1.0)
  54886. {
  54887. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54888. }
  54889. else
  54890. {
  54891. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54892. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54893. g.fillAll (background);
  54894. g.setColour (foreground);
  54895. g.fillRect (1, 1,
  54896. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54897. height - 2);
  54898. if (textToShow.isNotEmpty())
  54899. {
  54900. g.setColour (Colour::contrasting (background, foreground));
  54901. g.setFont (height * 0.6f);
  54902. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54903. }
  54904. }
  54905. }
  54906. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54907. ScrollBar& bar,
  54908. int width, int height,
  54909. int buttonDirection,
  54910. bool isScrollbarVertical,
  54911. bool isMouseOverButton,
  54912. bool isButtonDown)
  54913. {
  54914. if (isScrollbarVertical)
  54915. width -= 2;
  54916. else
  54917. height -= 2;
  54918. Path p;
  54919. if (buttonDirection == 0)
  54920. p.addTriangle (width * 0.5f, height * 0.2f,
  54921. width * 0.1f, height * 0.7f,
  54922. width * 0.9f, height * 0.7f);
  54923. else if (buttonDirection == 1)
  54924. p.addTriangle (width * 0.8f, height * 0.5f,
  54925. width * 0.3f, height * 0.1f,
  54926. width * 0.3f, height * 0.9f);
  54927. else if (buttonDirection == 2)
  54928. p.addTriangle (width * 0.5f, height * 0.8f,
  54929. width * 0.1f, height * 0.3f,
  54930. width * 0.9f, height * 0.3f);
  54931. else if (buttonDirection == 3)
  54932. p.addTriangle (width * 0.2f, height * 0.5f,
  54933. width * 0.7f, height * 0.1f,
  54934. width * 0.7f, height * 0.9f);
  54935. if (isButtonDown)
  54936. g.setColour (Colours::white);
  54937. else if (isMouseOverButton)
  54938. g.setColour (Colours::white.withAlpha (0.7f));
  54939. else
  54940. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54941. g.fillPath (p);
  54942. g.setColour (Colours::black.withAlpha (0.5f));
  54943. g.strokePath (p, PathStrokeType (0.5f));
  54944. }
  54945. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54946. ScrollBar& bar,
  54947. int x, int y,
  54948. int width, int height,
  54949. bool isScrollbarVertical,
  54950. int thumbStartPosition,
  54951. int thumbSize,
  54952. bool isMouseOver,
  54953. bool isMouseDown)
  54954. {
  54955. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54956. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54957. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54958. if (thumbSize > 0.0f)
  54959. {
  54960. Rectangle<int> thumb;
  54961. if (isScrollbarVertical)
  54962. {
  54963. width -= 2;
  54964. g.fillRect (x + roundToInt (width * 0.35f), y,
  54965. roundToInt (width * 0.3f), height);
  54966. thumb.setBounds (x + 1, thumbStartPosition,
  54967. width - 2, thumbSize);
  54968. }
  54969. else
  54970. {
  54971. height -= 2;
  54972. g.fillRect (x, y + roundToInt (height * 0.35f),
  54973. width, roundToInt (height * 0.3f));
  54974. thumb.setBounds (thumbStartPosition, y + 1,
  54975. thumbSize, height - 2);
  54976. }
  54977. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54978. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54979. g.fillRect (thumb);
  54980. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54981. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54982. if (thumbSize > 16)
  54983. {
  54984. for (int i = 3; --i >= 0;)
  54985. {
  54986. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54987. g.setColour (Colours::black.withAlpha (0.15f));
  54988. if (isScrollbarVertical)
  54989. {
  54990. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54991. g.setColour (Colours::white.withAlpha (0.15f));
  54992. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54993. }
  54994. else
  54995. {
  54996. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54997. g.setColour (Colours::white.withAlpha (0.15f));
  54998. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54999. }
  55000. }
  55001. }
  55002. }
  55003. }
  55004. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55005. {
  55006. return &scrollbarShadow;
  55007. }
  55008. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55009. {
  55010. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55011. g.setColour (Colours::black.withAlpha (0.6f));
  55012. g.drawRect (0, 0, width, height);
  55013. }
  55014. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55015. bool, MenuBarComponent& menuBar)
  55016. {
  55017. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55018. }
  55019. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55020. {
  55021. if (textEditor.isEnabled())
  55022. {
  55023. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55024. g.drawRect (0, 0, width, height);
  55025. }
  55026. }
  55027. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55028. const bool isButtonDown,
  55029. int buttonX, int buttonY,
  55030. int buttonW, int buttonH,
  55031. ComboBox& box)
  55032. {
  55033. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55034. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55035. : ComboBox::backgroundColourId));
  55036. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55037. g.setColour (box.findColour (ComboBox::outlineColourId));
  55038. g.drawRect (0, 0, width, height);
  55039. const float arrowX = 0.2f;
  55040. const float arrowH = 0.3f;
  55041. if (box.isEnabled())
  55042. {
  55043. Path p;
  55044. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55045. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55046. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55047. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55048. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55049. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55050. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55051. : ComboBox::buttonColourId));
  55052. g.fillPath (p);
  55053. }
  55054. }
  55055. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55056. {
  55057. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55058. f.setHorizontalScale (0.9f);
  55059. return f;
  55060. }
  55061. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55062. {
  55063. Path p;
  55064. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55065. g.setColour (fill);
  55066. g.fillPath (p);
  55067. g.setColour (outline);
  55068. g.strokePath (p, PathStrokeType (0.3f));
  55069. }
  55070. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55071. int x, int y,
  55072. int w, int h,
  55073. float sliderPos,
  55074. float minSliderPos,
  55075. float maxSliderPos,
  55076. const Slider::SliderStyle style,
  55077. Slider& slider)
  55078. {
  55079. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55080. if (style == Slider::LinearBar)
  55081. {
  55082. g.setColour (slider.findColour (Slider::thumbColourId));
  55083. g.fillRect (x, y, (int) sliderPos - x, h);
  55084. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55085. g.drawRect (x, y, (int) sliderPos - x, h);
  55086. }
  55087. else
  55088. {
  55089. g.setColour (slider.findColour (Slider::trackColourId)
  55090. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55091. if (slider.isHorizontal())
  55092. {
  55093. g.fillRect (x, y + roundToInt (h * 0.6f),
  55094. w, roundToInt (h * 0.2f));
  55095. }
  55096. else
  55097. {
  55098. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55099. jmin (4, roundToInt (w * 0.2f)), h);
  55100. }
  55101. float alpha = 0.35f;
  55102. if (slider.isEnabled())
  55103. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55104. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55105. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55106. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55107. {
  55108. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55109. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55110. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55111. fill, outline);
  55112. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55113. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55114. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55115. fill, outline);
  55116. }
  55117. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55118. {
  55119. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55120. minSliderPos - 7.0f, y + h * 0.9f ,
  55121. minSliderPos, y + h * 0.9f,
  55122. fill, outline);
  55123. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55124. maxSliderPos, y + h * 0.9f,
  55125. maxSliderPos + 7.0f, y + h * 0.9f,
  55126. fill, outline);
  55127. }
  55128. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55129. {
  55130. drawTriangle (g, sliderPos, y + h * 0.9f,
  55131. sliderPos - 7.0f, y + h * 0.2f,
  55132. sliderPos + 7.0f, y + h * 0.2f,
  55133. fill, outline);
  55134. }
  55135. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55136. {
  55137. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55138. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55139. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55140. fill, outline);
  55141. }
  55142. }
  55143. }
  55144. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55145. {
  55146. if (isIncrement)
  55147. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55148. else
  55149. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55150. }
  55151. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55152. {
  55153. return &scrollbarShadow;
  55154. }
  55155. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55156. {
  55157. return 8;
  55158. }
  55159. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55160. int w, int h,
  55161. bool isMouseOver,
  55162. bool isMouseDragging)
  55163. {
  55164. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55165. : Colours::darkgrey);
  55166. const float lineThickness = jmin (w, h) * 0.1f;
  55167. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55168. {
  55169. g.drawLine (w * i,
  55170. h + 1.0f,
  55171. w + 1.0f,
  55172. h * i,
  55173. lineThickness);
  55174. }
  55175. }
  55176. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55177. {
  55178. Path shape;
  55179. if (buttonType == DocumentWindow::closeButton)
  55180. {
  55181. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55182. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55183. ShapeButton* const b = new ShapeButton ("close",
  55184. Colour (0x7fff3333),
  55185. Colour (0xd7ff3333),
  55186. Colour (0xf7ff3333));
  55187. b->setShape (shape, true, true, true);
  55188. return b;
  55189. }
  55190. else if (buttonType == DocumentWindow::minimiseButton)
  55191. {
  55192. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55193. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55194. DrawablePath dp;
  55195. dp.setPath (shape);
  55196. dp.setFill (Colours::black.withAlpha (0.3f));
  55197. b->setImages (&dp);
  55198. return b;
  55199. }
  55200. else if (buttonType == DocumentWindow::maximiseButton)
  55201. {
  55202. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55203. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55204. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55205. DrawablePath dp;
  55206. dp.setPath (shape);
  55207. dp.setFill (Colours::black.withAlpha (0.3f));
  55208. b->setImages (&dp);
  55209. return b;
  55210. }
  55211. jassertfalse;
  55212. return 0;
  55213. }
  55214. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55215. int titleBarX,
  55216. int titleBarY,
  55217. int titleBarW,
  55218. int titleBarH,
  55219. Button* minimiseButton,
  55220. Button* maximiseButton,
  55221. Button* closeButton,
  55222. bool positionTitleBarButtonsOnLeft)
  55223. {
  55224. titleBarY += titleBarH / 8;
  55225. titleBarH -= titleBarH / 4;
  55226. const int buttonW = titleBarH;
  55227. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55228. : titleBarX + titleBarW - buttonW - 4;
  55229. if (closeButton != 0)
  55230. {
  55231. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55232. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55233. : -(buttonW + buttonW / 5);
  55234. }
  55235. if (positionTitleBarButtonsOnLeft)
  55236. swapVariables (minimiseButton, maximiseButton);
  55237. if (maximiseButton != 0)
  55238. {
  55239. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55240. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55241. }
  55242. if (minimiseButton != 0)
  55243. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55244. }
  55245. END_JUCE_NAMESPACE
  55246. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55247. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55248. BEGIN_JUCE_NAMESPACE
  55249. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55250. : model (0),
  55251. itemUnderMouse (-1),
  55252. currentPopupIndex (-1),
  55253. topLevelIndexClicked (0),
  55254. lastMouseX (0),
  55255. lastMouseY (0)
  55256. {
  55257. setRepaintsOnMouseActivity (true);
  55258. setWantsKeyboardFocus (false);
  55259. setMouseClickGrabsKeyboardFocus (false);
  55260. setModel (model_);
  55261. }
  55262. MenuBarComponent::~MenuBarComponent()
  55263. {
  55264. setModel (0);
  55265. Desktop::getInstance().removeGlobalMouseListener (this);
  55266. }
  55267. MenuBarModel* MenuBarComponent::getModel() const throw()
  55268. {
  55269. return model;
  55270. }
  55271. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55272. {
  55273. if (model != newModel)
  55274. {
  55275. if (model != 0)
  55276. model->removeListener (this);
  55277. model = newModel;
  55278. if (model != 0)
  55279. model->addListener (this);
  55280. repaint();
  55281. menuBarItemsChanged (0);
  55282. }
  55283. }
  55284. void MenuBarComponent::paint (Graphics& g)
  55285. {
  55286. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55287. getLookAndFeel().drawMenuBarBackground (g,
  55288. getWidth(),
  55289. getHeight(),
  55290. isMouseOverBar,
  55291. *this);
  55292. if (model != 0)
  55293. {
  55294. for (int i = 0; i < menuNames.size(); ++i)
  55295. {
  55296. g.saveState();
  55297. g.setOrigin (xPositions [i], 0);
  55298. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55299. getLookAndFeel().drawMenuBarItem (g,
  55300. xPositions[i + 1] - xPositions[i],
  55301. getHeight(),
  55302. i,
  55303. menuNames[i],
  55304. i == itemUnderMouse,
  55305. i == currentPopupIndex,
  55306. isMouseOverBar,
  55307. *this);
  55308. g.restoreState();
  55309. }
  55310. }
  55311. }
  55312. void MenuBarComponent::resized()
  55313. {
  55314. xPositions.clear();
  55315. int x = 0;
  55316. xPositions.add (x);
  55317. for (int i = 0; i < menuNames.size(); ++i)
  55318. {
  55319. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55320. xPositions.add (x);
  55321. }
  55322. }
  55323. int MenuBarComponent::getItemAt (const int x, const int y)
  55324. {
  55325. for (int i = 0; i < xPositions.size(); ++i)
  55326. if (x >= xPositions[i] && x < xPositions[i + 1])
  55327. return reallyContains (x, y, true) ? i : -1;
  55328. return -1;
  55329. }
  55330. void MenuBarComponent::repaintMenuItem (int index)
  55331. {
  55332. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55333. {
  55334. const int x1 = xPositions [index];
  55335. const int x2 = xPositions [index + 1];
  55336. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55337. }
  55338. }
  55339. void MenuBarComponent::setItemUnderMouse (const int index)
  55340. {
  55341. if (itemUnderMouse != index)
  55342. {
  55343. repaintMenuItem (itemUnderMouse);
  55344. itemUnderMouse = index;
  55345. repaintMenuItem (itemUnderMouse);
  55346. }
  55347. }
  55348. void MenuBarComponent::setOpenItem (int index)
  55349. {
  55350. if (currentPopupIndex != index)
  55351. {
  55352. repaintMenuItem (currentPopupIndex);
  55353. currentPopupIndex = index;
  55354. repaintMenuItem (currentPopupIndex);
  55355. if (index >= 0)
  55356. Desktop::getInstance().addGlobalMouseListener (this);
  55357. else
  55358. Desktop::getInstance().removeGlobalMouseListener (this);
  55359. }
  55360. }
  55361. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55362. {
  55363. setItemUnderMouse (getItemAt (x, y));
  55364. }
  55365. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55366. {
  55367. public:
  55368. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55369. : bar (bar_), topLevelIndex (topLevelIndex_)
  55370. {
  55371. }
  55372. ~AsyncCallback() {}
  55373. void modalStateFinished (int returnValue)
  55374. {
  55375. if (bar != 0)
  55376. bar->menuDismissed (topLevelIndex, returnValue);
  55377. }
  55378. private:
  55379. Component::SafePointer<MenuBarComponent> bar;
  55380. const int topLevelIndex;
  55381. AsyncCallback (const AsyncCallback&);
  55382. AsyncCallback& operator= (const AsyncCallback&);
  55383. };
  55384. void MenuBarComponent::showMenu (int index)
  55385. {
  55386. if (index != currentPopupIndex)
  55387. {
  55388. PopupMenu::dismissAllActiveMenus();
  55389. menuBarItemsChanged (0);
  55390. setOpenItem (index);
  55391. setItemUnderMouse (index);
  55392. if (index >= 0)
  55393. {
  55394. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55395. menuNames [itemUnderMouse]));
  55396. if (m.lookAndFeel == 0)
  55397. m.setLookAndFeel (&getLookAndFeel());
  55398. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55399. m.showMenu (itemPos + getScreenPosition(),
  55400. 0, itemPos.getWidth(), 0, 0, true, this,
  55401. new AsyncCallback (this, index));
  55402. }
  55403. }
  55404. }
  55405. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55406. {
  55407. topLevelIndexClicked = topLevelIndex;
  55408. postCommandMessage (itemId);
  55409. }
  55410. void MenuBarComponent::handleCommandMessage (int commandId)
  55411. {
  55412. const Point<int> mousePos (getMouseXYRelative());
  55413. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55414. if (currentPopupIndex == topLevelIndexClicked)
  55415. setOpenItem (-1);
  55416. if (commandId != 0 && model != 0)
  55417. model->menuItemSelected (commandId, topLevelIndexClicked);
  55418. }
  55419. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55420. {
  55421. if (e.eventComponent == this)
  55422. updateItemUnderMouse (e.x, e.y);
  55423. }
  55424. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55425. {
  55426. if (e.eventComponent == this)
  55427. updateItemUnderMouse (e.x, e.y);
  55428. }
  55429. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55430. {
  55431. if (currentPopupIndex < 0)
  55432. {
  55433. const MouseEvent e2 (e.getEventRelativeTo (this));
  55434. updateItemUnderMouse (e2.x, e2.y);
  55435. currentPopupIndex = -2;
  55436. showMenu (itemUnderMouse);
  55437. }
  55438. }
  55439. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55440. {
  55441. const MouseEvent e2 (e.getEventRelativeTo (this));
  55442. const int item = getItemAt (e2.x, e2.y);
  55443. if (item >= 0)
  55444. showMenu (item);
  55445. }
  55446. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55447. {
  55448. const MouseEvent e2 (e.getEventRelativeTo (this));
  55449. updateItemUnderMouse (e2.x, e2.y);
  55450. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55451. {
  55452. setOpenItem (-1);
  55453. PopupMenu::dismissAllActiveMenus();
  55454. }
  55455. }
  55456. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55457. {
  55458. const MouseEvent e2 (e.getEventRelativeTo (this));
  55459. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55460. {
  55461. if (currentPopupIndex >= 0)
  55462. {
  55463. const int item = getItemAt (e2.x, e2.y);
  55464. if (item >= 0)
  55465. showMenu (item);
  55466. }
  55467. else
  55468. {
  55469. updateItemUnderMouse (e2.x, e2.y);
  55470. }
  55471. lastMouseX = e2.x;
  55472. lastMouseY = e2.y;
  55473. }
  55474. }
  55475. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55476. {
  55477. bool used = false;
  55478. const int numMenus = menuNames.size();
  55479. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55480. if (key.isKeyCode (KeyPress::leftKey))
  55481. {
  55482. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55483. used = true;
  55484. }
  55485. else if (key.isKeyCode (KeyPress::rightKey))
  55486. {
  55487. showMenu ((currentIndex + 1) % numMenus);
  55488. used = true;
  55489. }
  55490. return used;
  55491. }
  55492. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55493. {
  55494. StringArray newNames;
  55495. if (model != 0)
  55496. newNames = model->getMenuBarNames();
  55497. if (newNames != menuNames)
  55498. {
  55499. menuNames = newNames;
  55500. repaint();
  55501. resized();
  55502. }
  55503. }
  55504. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55505. const ApplicationCommandTarget::InvocationInfo& info)
  55506. {
  55507. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55508. return;
  55509. for (int i = 0; i < menuNames.size(); ++i)
  55510. {
  55511. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55512. if (menu.containsCommandItem (info.commandID))
  55513. {
  55514. setItemUnderMouse (i);
  55515. startTimer (200);
  55516. break;
  55517. }
  55518. }
  55519. }
  55520. void MenuBarComponent::timerCallback()
  55521. {
  55522. stopTimer();
  55523. const Point<int> mousePos (getMouseXYRelative());
  55524. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55525. }
  55526. END_JUCE_NAMESPACE
  55527. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55528. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55529. BEGIN_JUCE_NAMESPACE
  55530. MenuBarModel::MenuBarModel() throw()
  55531. : manager (0)
  55532. {
  55533. }
  55534. MenuBarModel::~MenuBarModel()
  55535. {
  55536. setApplicationCommandManagerToWatch (0);
  55537. }
  55538. void MenuBarModel::menuItemsChanged()
  55539. {
  55540. triggerAsyncUpdate();
  55541. }
  55542. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55543. {
  55544. if (manager != newManager)
  55545. {
  55546. if (manager != 0)
  55547. manager->removeListener (this);
  55548. manager = newManager;
  55549. if (manager != 0)
  55550. manager->addListener (this);
  55551. }
  55552. }
  55553. void MenuBarModel::addListener (Listener* const newListener) throw()
  55554. {
  55555. listeners.add (newListener);
  55556. }
  55557. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55558. {
  55559. // Trying to remove a listener that isn't on the list!
  55560. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55561. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55562. jassert (listeners.contains (listenerToRemove));
  55563. listeners.remove (listenerToRemove);
  55564. }
  55565. void MenuBarModel::handleAsyncUpdate()
  55566. {
  55567. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55568. }
  55569. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55570. {
  55571. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55572. }
  55573. void MenuBarModel::applicationCommandListChanged()
  55574. {
  55575. menuItemsChanged();
  55576. }
  55577. END_JUCE_NAMESPACE
  55578. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55579. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55580. BEGIN_JUCE_NAMESPACE
  55581. class PopupMenu::Item
  55582. {
  55583. public:
  55584. Item()
  55585. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55586. usesColour (false), customComp (0), commandManager (0)
  55587. {
  55588. }
  55589. Item (const int itemId_,
  55590. const String& text_,
  55591. const bool active_,
  55592. const bool isTicked_,
  55593. const Image& im,
  55594. const Colour& textColour_,
  55595. const bool usesColour_,
  55596. PopupMenuCustomComponent* const customComp_,
  55597. const PopupMenu* const subMenu_,
  55598. ApplicationCommandManager* const commandManager_)
  55599. : itemId (itemId_), text (text_), textColour (textColour_),
  55600. active (active_), isSeparator (false), isTicked (isTicked_),
  55601. usesColour (usesColour_), image (im), customComp (customComp_),
  55602. commandManager (commandManager_)
  55603. {
  55604. if (subMenu_ != 0)
  55605. subMenu = new PopupMenu (*subMenu_);
  55606. if (commandManager_ != 0 && itemId_ != 0)
  55607. {
  55608. String shortcutKey;
  55609. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55610. ->getKeyPressesAssignedToCommand (itemId_));
  55611. for (int i = 0; i < keyPresses.size(); ++i)
  55612. {
  55613. const String key (keyPresses.getReference(i).getTextDescription());
  55614. if (shortcutKey.isNotEmpty())
  55615. shortcutKey << ", ";
  55616. if (key.length() == 1)
  55617. shortcutKey << "shortcut: '" << key << '\'';
  55618. else
  55619. shortcutKey << key;
  55620. }
  55621. shortcutKey = shortcutKey.trim();
  55622. if (shortcutKey.isNotEmpty())
  55623. text << "<end>" << shortcutKey;
  55624. }
  55625. }
  55626. Item (const Item& other)
  55627. : itemId (other.itemId),
  55628. text (other.text),
  55629. textColour (other.textColour),
  55630. active (other.active),
  55631. isSeparator (other.isSeparator),
  55632. isTicked (other.isTicked),
  55633. usesColour (other.usesColour),
  55634. image (other.image),
  55635. customComp (other.customComp),
  55636. commandManager (other.commandManager)
  55637. {
  55638. if (other.subMenu != 0)
  55639. subMenu = new PopupMenu (*(other.subMenu));
  55640. }
  55641. ~Item()
  55642. {
  55643. customComp = 0;
  55644. }
  55645. bool canBeTriggered() const throw()
  55646. {
  55647. return active && ! (isSeparator || (subMenu != 0));
  55648. }
  55649. bool hasActiveSubMenu() const throw()
  55650. {
  55651. return active && (subMenu != 0);
  55652. }
  55653. const int itemId;
  55654. String text;
  55655. const Colour textColour;
  55656. const bool active, isSeparator, isTicked, usesColour;
  55657. Image image;
  55658. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55659. ScopedPointer <PopupMenu> subMenu;
  55660. ApplicationCommandManager* const commandManager;
  55661. juce_UseDebuggingNewOperator
  55662. private:
  55663. Item& operator= (const Item&);
  55664. };
  55665. class PopupMenu::ItemComponent : public Component
  55666. {
  55667. public:
  55668. ItemComponent (const PopupMenu::Item& itemInfo_)
  55669. : itemInfo (itemInfo_),
  55670. isHighlighted (false)
  55671. {
  55672. if (itemInfo.customComp != 0)
  55673. addAndMakeVisible (itemInfo.customComp);
  55674. }
  55675. ~ItemComponent()
  55676. {
  55677. if (itemInfo.customComp != 0)
  55678. removeChildComponent (itemInfo.customComp);
  55679. }
  55680. void getIdealSize (int& idealWidth,
  55681. int& idealHeight,
  55682. const int standardItemHeight)
  55683. {
  55684. if (itemInfo.customComp != 0)
  55685. {
  55686. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55687. }
  55688. else
  55689. {
  55690. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55691. itemInfo.isSeparator,
  55692. standardItemHeight,
  55693. idealWidth,
  55694. idealHeight);
  55695. }
  55696. }
  55697. void paint (Graphics& g)
  55698. {
  55699. if (itemInfo.customComp == 0)
  55700. {
  55701. String mainText (itemInfo.text);
  55702. String endText;
  55703. const int endIndex = mainText.indexOf ("<end>");
  55704. if (endIndex >= 0)
  55705. {
  55706. endText = mainText.substring (endIndex + 5).trim();
  55707. mainText = mainText.substring (0, endIndex);
  55708. }
  55709. getLookAndFeel()
  55710. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55711. itemInfo.isSeparator,
  55712. itemInfo.active,
  55713. isHighlighted,
  55714. itemInfo.isTicked,
  55715. itemInfo.subMenu != 0,
  55716. mainText, endText,
  55717. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55718. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55719. }
  55720. }
  55721. void resized()
  55722. {
  55723. if (getNumChildComponents() > 0)
  55724. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55725. }
  55726. void setHighlighted (bool shouldBeHighlighted)
  55727. {
  55728. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55729. if (isHighlighted != shouldBeHighlighted)
  55730. {
  55731. isHighlighted = shouldBeHighlighted;
  55732. if (itemInfo.customComp != 0)
  55733. {
  55734. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55735. itemInfo.customComp->repaint();
  55736. }
  55737. repaint();
  55738. }
  55739. }
  55740. PopupMenu::Item itemInfo;
  55741. juce_UseDebuggingNewOperator
  55742. private:
  55743. bool isHighlighted;
  55744. ItemComponent (const ItemComponent&);
  55745. ItemComponent& operator= (const ItemComponent&);
  55746. };
  55747. namespace PopupMenuSettings
  55748. {
  55749. static const int scrollZone = 24;
  55750. static const int borderSize = 2;
  55751. static const int timerInterval = 50;
  55752. static const int dismissCommandId = 0x6287345f;
  55753. }
  55754. class PopupMenu::Window : public Component,
  55755. private Timer
  55756. {
  55757. public:
  55758. Window()
  55759. : Component ("menu"),
  55760. owner (0),
  55761. currentChild (0),
  55762. activeSubMenu (0),
  55763. managerOfChosenCommand (0),
  55764. minimumWidth (0),
  55765. maximumNumColumns (7),
  55766. standardItemHeight (0),
  55767. isOver (false),
  55768. hasBeenOver (false),
  55769. isDown (false),
  55770. needsToScroll (false),
  55771. hideOnExit (false),
  55772. disableMouseMoves (false),
  55773. hasAnyJuceCompHadFocus (false),
  55774. numColumns (0),
  55775. contentHeight (0),
  55776. childYOffset (0),
  55777. timeEnteredCurrentChildComp (0),
  55778. scrollAcceleration (1.0)
  55779. {
  55780. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55781. setWantsKeyboardFocus (true);
  55782. setMouseClickGrabsKeyboardFocus (false);
  55783. setAlwaysOnTop (true);
  55784. Desktop::getInstance().addGlobalMouseListener (this);
  55785. getActiveWindows().add (this);
  55786. }
  55787. ~Window()
  55788. {
  55789. getActiveWindows().removeValue (this);
  55790. Desktop::getInstance().removeGlobalMouseListener (this);
  55791. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55792. activeSubMenu = 0;
  55793. deleteAllChildren();
  55794. }
  55795. static Window* create (const PopupMenu& menu,
  55796. const bool dismissOnMouseUp,
  55797. Window* const owner_,
  55798. const Rectangle<int>& target,
  55799. const int minimumWidth,
  55800. const int maximumNumColumns,
  55801. const int standardItemHeight,
  55802. const bool alignToRectangle,
  55803. const int itemIdThatMustBeVisible,
  55804. ApplicationCommandManager** managerOfChosenCommand,
  55805. Component* const componentAttachedTo)
  55806. {
  55807. if (menu.items.size() > 0)
  55808. {
  55809. int totalItems = 0;
  55810. ScopedPointer <Window> mw (new Window());
  55811. mw->setLookAndFeel (menu.lookAndFeel);
  55812. mw->setWantsKeyboardFocus (false);
  55813. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55814. mw->minimumWidth = minimumWidth;
  55815. mw->maximumNumColumns = maximumNumColumns;
  55816. mw->standardItemHeight = standardItemHeight;
  55817. mw->dismissOnMouseUp = dismissOnMouseUp;
  55818. for (int i = 0; i < menu.items.size(); ++i)
  55819. {
  55820. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55821. mw->addItem (*item);
  55822. ++totalItems;
  55823. }
  55824. if (totalItems > 0)
  55825. {
  55826. mw->owner = owner_;
  55827. mw->managerOfChosenCommand = managerOfChosenCommand;
  55828. mw->componentAttachedTo = componentAttachedTo;
  55829. mw->componentAttachedToOriginal = componentAttachedTo;
  55830. mw->calculateWindowPos (target, alignToRectangle);
  55831. mw->setTopLeftPosition (mw->windowPos.getX(),
  55832. mw->windowPos.getY());
  55833. mw->updateYPositions();
  55834. if (itemIdThatMustBeVisible != 0)
  55835. {
  55836. const int y = target.getY() - mw->windowPos.getY();
  55837. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55838. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55839. }
  55840. mw->resizeToBestWindowPos();
  55841. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55842. | mw->getLookAndFeel().getMenuWindowFlags());
  55843. return mw.release();
  55844. }
  55845. }
  55846. return 0;
  55847. }
  55848. void paint (Graphics& g)
  55849. {
  55850. if (isOpaque())
  55851. g.fillAll (Colours::white);
  55852. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55853. }
  55854. void paintOverChildren (Graphics& g)
  55855. {
  55856. if (isScrolling())
  55857. {
  55858. LookAndFeel& lf = getLookAndFeel();
  55859. if (isScrollZoneActive (false))
  55860. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55861. if (isScrollZoneActive (true))
  55862. {
  55863. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55864. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55865. }
  55866. }
  55867. }
  55868. bool isScrollZoneActive (bool bottomOne) const
  55869. {
  55870. return isScrolling()
  55871. && (bottomOne
  55872. ? childYOffset < contentHeight - windowPos.getHeight()
  55873. : childYOffset > 0);
  55874. }
  55875. void addItem (const PopupMenu::Item& item)
  55876. {
  55877. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55878. addAndMakeVisible (mic);
  55879. int itemW = 80;
  55880. int itemH = 16;
  55881. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55882. mic->setSize (itemW, jlimit (2, 600, itemH));
  55883. mic->addMouseListener (this, false);
  55884. }
  55885. // hide this and all sub-comps
  55886. void hide (const PopupMenu::Item* const item)
  55887. {
  55888. if (isVisible())
  55889. {
  55890. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55891. activeSubMenu = 0;
  55892. currentChild = 0;
  55893. exitModalState (item != 0 ? item->itemId : 0);
  55894. setVisible (false);
  55895. if (item != 0
  55896. && item->commandManager != 0
  55897. && item->itemId != 0)
  55898. {
  55899. *managerOfChosenCommand = item->commandManager;
  55900. }
  55901. }
  55902. }
  55903. void dismissMenu (const PopupMenu::Item* const item)
  55904. {
  55905. if (owner != 0)
  55906. {
  55907. owner->dismissMenu (item);
  55908. }
  55909. else
  55910. {
  55911. if (item != 0)
  55912. {
  55913. // need a copy of this on the stack as the one passed in will get deleted during this call
  55914. const PopupMenu::Item mi (*item);
  55915. hide (&mi);
  55916. }
  55917. else
  55918. {
  55919. hide (0);
  55920. }
  55921. }
  55922. }
  55923. void mouseMove (const MouseEvent&)
  55924. {
  55925. timerCallback();
  55926. }
  55927. void mouseDown (const MouseEvent&)
  55928. {
  55929. timerCallback();
  55930. }
  55931. void mouseDrag (const MouseEvent&)
  55932. {
  55933. timerCallback();
  55934. }
  55935. void mouseUp (const MouseEvent&)
  55936. {
  55937. timerCallback();
  55938. }
  55939. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55940. {
  55941. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55942. lastMouse = Point<int> (-1, -1);
  55943. }
  55944. bool keyPressed (const KeyPress& key)
  55945. {
  55946. if (key.isKeyCode (KeyPress::downKey))
  55947. {
  55948. selectNextItem (1);
  55949. }
  55950. else if (key.isKeyCode (KeyPress::upKey))
  55951. {
  55952. selectNextItem (-1);
  55953. }
  55954. else if (key.isKeyCode (KeyPress::leftKey))
  55955. {
  55956. if (owner != 0)
  55957. {
  55958. Component::SafePointer<Window> parentWindow (owner);
  55959. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55960. hide (0);
  55961. if (parentWindow != 0)
  55962. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55963. disableTimerUntilMouseMoves();
  55964. }
  55965. else if (componentAttachedTo != 0)
  55966. {
  55967. componentAttachedTo->keyPressed (key);
  55968. }
  55969. }
  55970. else if (key.isKeyCode (KeyPress::rightKey))
  55971. {
  55972. disableTimerUntilMouseMoves();
  55973. if (showSubMenuFor (currentChild))
  55974. {
  55975. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55976. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55977. activeSubMenu->selectNextItem (1);
  55978. }
  55979. else if (componentAttachedTo != 0)
  55980. {
  55981. componentAttachedTo->keyPressed (key);
  55982. }
  55983. }
  55984. else if (key.isKeyCode (KeyPress::returnKey))
  55985. {
  55986. triggerCurrentlyHighlightedItem();
  55987. }
  55988. else if (key.isKeyCode (KeyPress::escapeKey))
  55989. {
  55990. dismissMenu (0);
  55991. }
  55992. else
  55993. {
  55994. return false;
  55995. }
  55996. return true;
  55997. }
  55998. void inputAttemptWhenModal()
  55999. {
  56000. Component::SafePointer<Component> deletionChecker (this);
  56001. timerCallback();
  56002. if (deletionChecker != 0 && ! isOverAnyMenu())
  56003. {
  56004. if (componentAttachedTo != 0)
  56005. {
  56006. // we want to dismiss the menu, but if we do it synchronously, then
  56007. // the mouse-click will be allowed to pass through. That's good, except
  56008. // when the user clicks on the button that orginally popped the menu up,
  56009. // as they'll expect the menu to go away, and in fact it'll just
  56010. // come back. So only dismiss synchronously if they're not on the original
  56011. // comp that we're attached to.
  56012. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56013. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56014. {
  56015. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56016. return;
  56017. }
  56018. }
  56019. dismissMenu (0);
  56020. }
  56021. }
  56022. void handleCommandMessage (int commandId)
  56023. {
  56024. Component::handleCommandMessage (commandId);
  56025. if (commandId == PopupMenuSettings::dismissCommandId)
  56026. dismissMenu (0);
  56027. }
  56028. void timerCallback()
  56029. {
  56030. if (! isVisible())
  56031. return;
  56032. if (componentAttachedTo != componentAttachedToOriginal)
  56033. {
  56034. dismissMenu (0);
  56035. return;
  56036. }
  56037. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56038. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56039. return;
  56040. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56041. // move rather than a real timer callback
  56042. const Point<int> globalMousePos (Desktop::getMousePosition());
  56043. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56044. const uint32 now = Time::getMillisecondCounter();
  56045. if (now > timeEnteredCurrentChildComp + 100
  56046. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56047. && currentChild->isValidComponent()
  56048. && (! disableMouseMoves)
  56049. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56050. {
  56051. showSubMenuFor (currentChild);
  56052. }
  56053. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56054. {
  56055. highlightItemUnderMouse (globalMousePos, localMousePos);
  56056. }
  56057. bool overScrollArea = false;
  56058. if (isScrolling()
  56059. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56060. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56061. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56062. {
  56063. if (now > lastScroll + 20)
  56064. {
  56065. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56066. int amount = 0;
  56067. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56068. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56069. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56070. lastScroll = now;
  56071. }
  56072. overScrollArea = true;
  56073. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56074. }
  56075. else
  56076. {
  56077. scrollAcceleration = 1.0;
  56078. }
  56079. const bool wasDown = isDown;
  56080. bool isOverAny = isOverAnyMenu();
  56081. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56082. {
  56083. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56084. isOverAny = isOverAnyMenu();
  56085. }
  56086. if (hideOnExit && hasBeenOver && ! isOverAny)
  56087. {
  56088. hide (0);
  56089. }
  56090. else
  56091. {
  56092. isDown = hasBeenOver
  56093. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56094. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56095. bool anyFocused = Process::isForegroundProcess();
  56096. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56097. {
  56098. // because no component at all may have focus, our test here will
  56099. // only be triggered when something has focus and then loses it.
  56100. anyFocused = ! hasAnyJuceCompHadFocus;
  56101. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56102. {
  56103. if (ComponentPeer::getPeer (i)->isFocused())
  56104. {
  56105. anyFocused = true;
  56106. hasAnyJuceCompHadFocus = true;
  56107. break;
  56108. }
  56109. }
  56110. }
  56111. if (! anyFocused)
  56112. {
  56113. if (now > lastFocused + 10)
  56114. {
  56115. wasHiddenBecauseOfAppChange() = true;
  56116. dismissMenu (0);
  56117. return; // may have been deleted by the previous call..
  56118. }
  56119. }
  56120. else if (wasDown && now > menuCreationTime + 250
  56121. && ! (isDown || overScrollArea))
  56122. {
  56123. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56124. if (isOver)
  56125. {
  56126. triggerCurrentlyHighlightedItem();
  56127. }
  56128. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56129. {
  56130. dismissMenu (0);
  56131. }
  56132. return; // may have been deleted by the previous calls..
  56133. }
  56134. else
  56135. {
  56136. lastFocused = now;
  56137. }
  56138. }
  56139. }
  56140. static Array<Window*>& getActiveWindows()
  56141. {
  56142. static Array<Window*> activeMenuWindows;
  56143. return activeMenuWindows;
  56144. }
  56145. static bool& wasHiddenBecauseOfAppChange() throw()
  56146. {
  56147. static bool b = false;
  56148. return b;
  56149. }
  56150. juce_UseDebuggingNewOperator
  56151. private:
  56152. Window* owner;
  56153. PopupMenu::ItemComponent* currentChild;
  56154. ScopedPointer <Window> activeSubMenu;
  56155. ApplicationCommandManager** managerOfChosenCommand;
  56156. Component::SafePointer<Component> componentAttachedTo;
  56157. Component* componentAttachedToOriginal;
  56158. Rectangle<int> windowPos;
  56159. Point<int> lastMouse;
  56160. int minimumWidth, maximumNumColumns, standardItemHeight;
  56161. bool isOver, hasBeenOver, isDown, needsToScroll;
  56162. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56163. int numColumns, contentHeight, childYOffset;
  56164. Array <int> columnWidths;
  56165. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56166. double scrollAcceleration;
  56167. bool overlaps (const Rectangle<int>& r) const
  56168. {
  56169. return r.intersects (getBounds())
  56170. || (owner != 0 && owner->overlaps (r));
  56171. }
  56172. bool isOverAnyMenu() const
  56173. {
  56174. return (owner != 0) ? owner->isOverAnyMenu()
  56175. : isOverChildren();
  56176. }
  56177. bool isOverChildren() const
  56178. {
  56179. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56180. return isVisible()
  56181. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56182. }
  56183. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56184. {
  56185. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56186. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56187. if (activeSubMenu != 0)
  56188. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56189. }
  56190. bool treeContains (const Window* const window) const throw()
  56191. {
  56192. const Window* mw = this;
  56193. while (mw->owner != 0)
  56194. mw = mw->owner;
  56195. while (mw != 0)
  56196. {
  56197. if (mw == window)
  56198. return true;
  56199. mw = mw->activeSubMenu;
  56200. }
  56201. return false;
  56202. }
  56203. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56204. {
  56205. const Rectangle<int> mon (Desktop::getInstance()
  56206. .getMonitorAreaContaining (target.getCentre(),
  56207. #if JUCE_MAC
  56208. true));
  56209. #else
  56210. false)); // on windows, don't stop the menu overlapping the taskbar
  56211. #endif
  56212. int x, y, widthToUse, heightToUse;
  56213. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56214. if (alignToRectangle)
  56215. {
  56216. x = target.getX();
  56217. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56218. const int spaceOver = target.getY() - mon.getY();
  56219. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56220. y = target.getBottom();
  56221. else
  56222. y = target.getY() - heightToUse;
  56223. }
  56224. else
  56225. {
  56226. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56227. if (owner != 0)
  56228. {
  56229. if (owner->owner != 0)
  56230. {
  56231. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56232. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56233. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56234. tendTowardsRight = true;
  56235. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56236. tendTowardsRight = false;
  56237. }
  56238. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56239. {
  56240. tendTowardsRight = true;
  56241. }
  56242. }
  56243. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56244. target.getX() - mon.getX()) - 32;
  56245. if (biggestSpace < widthToUse)
  56246. {
  56247. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56248. if (numColumns > 1)
  56249. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56250. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56251. }
  56252. if (tendTowardsRight)
  56253. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56254. else
  56255. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56256. y = target.getY();
  56257. if (target.getCentreY() > mon.getCentreY())
  56258. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56259. }
  56260. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56261. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56262. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56263. // sets this flag if it's big enough to obscure any of its parent menus
  56264. hideOnExit = (owner != 0)
  56265. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56266. }
  56267. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56268. {
  56269. numColumns = 0;
  56270. contentHeight = 0;
  56271. const int maxMenuH = getParentHeight() - 24;
  56272. int totalW;
  56273. do
  56274. {
  56275. ++numColumns;
  56276. totalW = workOutBestSize (maxMenuW);
  56277. if (totalW > maxMenuW)
  56278. {
  56279. numColumns = jmax (1, numColumns - 1);
  56280. totalW = workOutBestSize (maxMenuW); // to update col widths
  56281. break;
  56282. }
  56283. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56284. {
  56285. break;
  56286. }
  56287. } while (numColumns < maximumNumColumns);
  56288. const int actualH = jmin (contentHeight, maxMenuH);
  56289. needsToScroll = contentHeight > actualH;
  56290. width = updateYPositions();
  56291. height = actualH + PopupMenuSettings::borderSize * 2;
  56292. }
  56293. int workOutBestSize (const int maxMenuW)
  56294. {
  56295. int totalW = 0;
  56296. contentHeight = 0;
  56297. int childNum = 0;
  56298. for (int col = 0; col < numColumns; ++col)
  56299. {
  56300. int i, colW = 50, colH = 0;
  56301. const int numChildren = jmin (getNumChildComponents() - childNum,
  56302. (getNumChildComponents() + numColumns - 1) / numColumns);
  56303. for (i = numChildren; --i >= 0;)
  56304. {
  56305. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56306. colH += getChildComponent (childNum + i)->getHeight();
  56307. }
  56308. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56309. columnWidths.set (col, colW);
  56310. totalW += colW;
  56311. contentHeight = jmax (contentHeight, colH);
  56312. childNum += numChildren;
  56313. }
  56314. if (totalW < minimumWidth)
  56315. {
  56316. totalW = minimumWidth;
  56317. for (int col = 0; col < numColumns; ++col)
  56318. columnWidths.set (0, totalW / numColumns);
  56319. }
  56320. return totalW;
  56321. }
  56322. void ensureItemIsVisible (const int itemId, int wantedY)
  56323. {
  56324. jassert (itemId != 0)
  56325. for (int i = getNumChildComponents(); --i >= 0;)
  56326. {
  56327. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56328. if (m != 0
  56329. && m->itemInfo.itemId == itemId
  56330. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56331. {
  56332. const int currentY = m->getY();
  56333. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56334. {
  56335. if (wantedY < 0)
  56336. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56337. jmax (PopupMenuSettings::scrollZone,
  56338. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56339. currentY);
  56340. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56341. int deltaY = wantedY - currentY;
  56342. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56343. jmin (windowPos.getHeight(), mon.getHeight()));
  56344. const int newY = jlimit (mon.getY(),
  56345. mon.getBottom() - windowPos.getHeight(),
  56346. windowPos.getY() + deltaY);
  56347. deltaY -= newY - windowPos.getY();
  56348. childYOffset -= deltaY;
  56349. windowPos.setPosition (windowPos.getX(), newY);
  56350. updateYPositions();
  56351. }
  56352. break;
  56353. }
  56354. }
  56355. }
  56356. void resizeToBestWindowPos()
  56357. {
  56358. Rectangle<int> r (windowPos);
  56359. if (childYOffset < 0)
  56360. {
  56361. r.setBounds (r.getX(), r.getY() - childYOffset,
  56362. r.getWidth(), r.getHeight() + childYOffset);
  56363. }
  56364. else if (childYOffset > 0)
  56365. {
  56366. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56367. if (spaceAtBottom > 0)
  56368. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56369. }
  56370. setBounds (r);
  56371. updateYPositions();
  56372. }
  56373. void alterChildYPos (const int delta)
  56374. {
  56375. if (isScrolling())
  56376. {
  56377. childYOffset += delta;
  56378. if (delta < 0)
  56379. {
  56380. childYOffset = jmax (childYOffset, 0);
  56381. }
  56382. else if (delta > 0)
  56383. {
  56384. childYOffset = jmin (childYOffset,
  56385. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56386. }
  56387. updateYPositions();
  56388. }
  56389. else
  56390. {
  56391. childYOffset = 0;
  56392. }
  56393. resizeToBestWindowPos();
  56394. repaint();
  56395. }
  56396. int updateYPositions()
  56397. {
  56398. int x = 0;
  56399. int childNum = 0;
  56400. for (int col = 0; col < numColumns; ++col)
  56401. {
  56402. const int numChildren = jmin (getNumChildComponents() - childNum,
  56403. (getNumChildComponents() + numColumns - 1) / numColumns);
  56404. const int colW = columnWidths [col];
  56405. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56406. for (int i = 0; i < numChildren; ++i)
  56407. {
  56408. Component* const c = getChildComponent (childNum + i);
  56409. c->setBounds (x, y, colW, c->getHeight());
  56410. y += c->getHeight();
  56411. }
  56412. x += colW;
  56413. childNum += numChildren;
  56414. }
  56415. return x;
  56416. }
  56417. bool isScrolling() const throw()
  56418. {
  56419. return childYOffset != 0 || needsToScroll;
  56420. }
  56421. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56422. {
  56423. if (currentChild->isValidComponent())
  56424. currentChild->setHighlighted (false);
  56425. currentChild = child;
  56426. if (currentChild != 0)
  56427. {
  56428. currentChild->setHighlighted (true);
  56429. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56430. }
  56431. }
  56432. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56433. {
  56434. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56435. activeSubMenu = 0;
  56436. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56437. {
  56438. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56439. dismissOnMouseUp,
  56440. this,
  56441. childComp->getScreenBounds(),
  56442. 0, maximumNumColumns,
  56443. standardItemHeight,
  56444. false, 0, managerOfChosenCommand,
  56445. componentAttachedTo);
  56446. if (activeSubMenu != 0)
  56447. {
  56448. activeSubMenu->setVisible (true);
  56449. activeSubMenu->enterModalState (false);
  56450. activeSubMenu->toFront (false);
  56451. return true;
  56452. }
  56453. }
  56454. return false;
  56455. }
  56456. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56457. {
  56458. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56459. if (isOver)
  56460. hasBeenOver = true;
  56461. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56462. {
  56463. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56464. if (disableMouseMoves && isOver)
  56465. disableMouseMoves = false;
  56466. }
  56467. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56468. return;
  56469. bool isMovingTowardsMenu = false;
  56470. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56471. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56472. {
  56473. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56474. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56475. // extends from the last mouse pos to the submenu's rectangle..
  56476. float subX = (float) activeSubMenu->getScreenX();
  56477. if (activeSubMenu->getX() > getX())
  56478. {
  56479. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56480. }
  56481. else
  56482. {
  56483. lastMouse += Point<int> (2, 0);
  56484. subX += activeSubMenu->getWidth();
  56485. }
  56486. Path areaTowardsSubMenu;
  56487. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56488. (float) lastMouse.getY(),
  56489. subX,
  56490. (float) activeSubMenu->getScreenY(),
  56491. subX,
  56492. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56493. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56494. }
  56495. lastMouse = globalMousePos;
  56496. if (! isMovingTowardsMenu)
  56497. {
  56498. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56499. if (c == this)
  56500. c = 0;
  56501. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56502. if (mic == 0 && c != 0)
  56503. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56504. if (mic != currentChild
  56505. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56506. {
  56507. if (isOver && (c != 0) && (activeSubMenu != 0))
  56508. {
  56509. activeSubMenu->hide (0);
  56510. }
  56511. if (! isOver)
  56512. mic = 0;
  56513. setCurrentlyHighlightedChild (mic);
  56514. }
  56515. }
  56516. }
  56517. void triggerCurrentlyHighlightedItem()
  56518. {
  56519. if (currentChild->isValidComponent()
  56520. && currentChild->itemInfo.canBeTriggered()
  56521. && (currentChild->itemInfo.customComp == 0
  56522. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56523. {
  56524. dismissMenu (&currentChild->itemInfo);
  56525. }
  56526. }
  56527. void selectNextItem (const int delta)
  56528. {
  56529. disableTimerUntilMouseMoves();
  56530. PopupMenu::ItemComponent* mic = 0;
  56531. bool wasLastOne = (currentChild == 0);
  56532. const int numItems = getNumChildComponents();
  56533. for (int i = 0; i < numItems + 1; ++i)
  56534. {
  56535. int index = (delta > 0) ? i : (numItems - 1 - i);
  56536. index = (index + numItems) % numItems;
  56537. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56538. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56539. && wasLastOne)
  56540. break;
  56541. if (mic == currentChild)
  56542. wasLastOne = true;
  56543. }
  56544. setCurrentlyHighlightedChild (mic);
  56545. }
  56546. void disableTimerUntilMouseMoves()
  56547. {
  56548. disableMouseMoves = true;
  56549. if (owner != 0)
  56550. owner->disableTimerUntilMouseMoves();
  56551. }
  56552. Window (const Window&);
  56553. Window& operator= (const Window&);
  56554. };
  56555. PopupMenu::PopupMenu()
  56556. : lookAndFeel (0),
  56557. separatorPending (false)
  56558. {
  56559. }
  56560. PopupMenu::PopupMenu (const PopupMenu& other)
  56561. : lookAndFeel (other.lookAndFeel),
  56562. separatorPending (false)
  56563. {
  56564. items.addCopiesOf (other.items);
  56565. }
  56566. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56567. {
  56568. if (this != &other)
  56569. {
  56570. lookAndFeel = other.lookAndFeel;
  56571. clear();
  56572. items.addCopiesOf (other.items);
  56573. }
  56574. return *this;
  56575. }
  56576. PopupMenu::~PopupMenu()
  56577. {
  56578. clear();
  56579. }
  56580. void PopupMenu::clear()
  56581. {
  56582. items.clear();
  56583. separatorPending = false;
  56584. }
  56585. void PopupMenu::addSeparatorIfPending()
  56586. {
  56587. if (separatorPending)
  56588. {
  56589. separatorPending = false;
  56590. if (items.size() > 0)
  56591. items.add (new Item());
  56592. }
  56593. }
  56594. void PopupMenu::addItem (const int itemResultId,
  56595. const String& itemText,
  56596. const bool isActive,
  56597. const bool isTicked,
  56598. const Image& iconToUse)
  56599. {
  56600. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56601. // didn't pick anything, so you shouldn't use it as the id
  56602. // for an item..
  56603. addSeparatorIfPending();
  56604. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56605. Colours::black, false, 0, 0, 0));
  56606. }
  56607. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56608. const int commandID,
  56609. const String& displayName)
  56610. {
  56611. jassert (commandManager != 0 && commandID != 0);
  56612. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56613. if (registeredInfo != 0)
  56614. {
  56615. ApplicationCommandInfo info (*registeredInfo);
  56616. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56617. addSeparatorIfPending();
  56618. items.add (new Item (commandID,
  56619. displayName.isNotEmpty() ? displayName
  56620. : info.shortName,
  56621. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56622. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56623. Image::null,
  56624. Colours::black,
  56625. false,
  56626. 0, 0,
  56627. commandManager));
  56628. }
  56629. }
  56630. void PopupMenu::addColouredItem (const int itemResultId,
  56631. const String& itemText,
  56632. const Colour& itemTextColour,
  56633. const bool isActive,
  56634. const bool isTicked,
  56635. const Image& iconToUse)
  56636. {
  56637. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56638. // didn't pick anything, so you shouldn't use it as the id
  56639. // for an item..
  56640. addSeparatorIfPending();
  56641. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56642. itemTextColour, true, 0, 0, 0));
  56643. }
  56644. void PopupMenu::addCustomItem (const int itemResultId,
  56645. PopupMenuCustomComponent* const customComponent)
  56646. {
  56647. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56648. // didn't pick anything, so you shouldn't use it as the id
  56649. // for an item..
  56650. addSeparatorIfPending();
  56651. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56652. Colours::black, false, customComponent, 0, 0));
  56653. }
  56654. class NormalComponentWrapper : public PopupMenuCustomComponent
  56655. {
  56656. public:
  56657. NormalComponentWrapper (Component* const comp,
  56658. const int w, const int h,
  56659. const bool triggerMenuItemAutomaticallyWhenClicked)
  56660. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56661. width (w),
  56662. height (h)
  56663. {
  56664. addAndMakeVisible (comp);
  56665. }
  56666. ~NormalComponentWrapper() {}
  56667. void getIdealSize (int& idealWidth, int& idealHeight)
  56668. {
  56669. idealWidth = width;
  56670. idealHeight = height;
  56671. }
  56672. void resized()
  56673. {
  56674. if (getChildComponent(0) != 0)
  56675. getChildComponent(0)->setBounds (getLocalBounds());
  56676. }
  56677. juce_UseDebuggingNewOperator
  56678. private:
  56679. const int width, height;
  56680. NormalComponentWrapper (const NormalComponentWrapper&);
  56681. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56682. };
  56683. void PopupMenu::addCustomItem (const int itemResultId,
  56684. Component* customComponent,
  56685. int idealWidth, int idealHeight,
  56686. const bool triggerMenuItemAutomaticallyWhenClicked)
  56687. {
  56688. addCustomItem (itemResultId,
  56689. new NormalComponentWrapper (customComponent,
  56690. idealWidth, idealHeight,
  56691. triggerMenuItemAutomaticallyWhenClicked));
  56692. }
  56693. void PopupMenu::addSubMenu (const String& subMenuName,
  56694. const PopupMenu& subMenu,
  56695. const bool isActive,
  56696. const Image& iconToUse,
  56697. const bool isTicked)
  56698. {
  56699. addSeparatorIfPending();
  56700. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56701. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56702. }
  56703. void PopupMenu::addSeparator()
  56704. {
  56705. separatorPending = true;
  56706. }
  56707. class HeaderItemComponent : public PopupMenuCustomComponent
  56708. {
  56709. public:
  56710. HeaderItemComponent (const String& name)
  56711. : PopupMenuCustomComponent (false)
  56712. {
  56713. setName (name);
  56714. }
  56715. ~HeaderItemComponent()
  56716. {
  56717. }
  56718. void paint (Graphics& g)
  56719. {
  56720. Font f (getLookAndFeel().getPopupMenuFont());
  56721. f.setBold (true);
  56722. g.setFont (f);
  56723. g.setColour (findColour (PopupMenu::headerTextColourId));
  56724. g.drawFittedText (getName(),
  56725. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56726. Justification::bottomLeft, 1);
  56727. }
  56728. void getIdealSize (int& idealWidth,
  56729. int& idealHeight)
  56730. {
  56731. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56732. idealHeight += idealHeight / 2;
  56733. idealWidth += idealWidth / 4;
  56734. }
  56735. juce_UseDebuggingNewOperator
  56736. };
  56737. void PopupMenu::addSectionHeader (const String& title)
  56738. {
  56739. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56740. }
  56741. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56742. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56743. {
  56744. public:
  56745. PopupMenuCompletionCallback()
  56746. : managerOfChosenCommand (0)
  56747. {
  56748. }
  56749. ~PopupMenuCompletionCallback() {}
  56750. void modalStateFinished (int result)
  56751. {
  56752. if (managerOfChosenCommand != 0 && result != 0)
  56753. {
  56754. ApplicationCommandTarget::InvocationInfo info (result);
  56755. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56756. managerOfChosenCommand->invoke (info, true);
  56757. }
  56758. }
  56759. ApplicationCommandManager* managerOfChosenCommand;
  56760. ScopedPointer<Component> component;
  56761. private:
  56762. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56763. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56764. };
  56765. int PopupMenu::showMenu (const Rectangle<int>& target,
  56766. const int itemIdThatMustBeVisible,
  56767. const int minimumWidth,
  56768. const int maximumNumColumns,
  56769. const int standardItemHeight,
  56770. const bool alignToRectangle,
  56771. Component* const componentAttachedTo,
  56772. ModalComponentManager::Callback* userCallback)
  56773. {
  56774. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56775. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56776. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56777. Window::wasHiddenBecauseOfAppChange() = false;
  56778. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56779. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56780. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56781. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56782. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56783. &callback->managerOfChosenCommand, componentAttachedTo);
  56784. if (callback->component == 0)
  56785. return 0;
  56786. callbackDeleter.release();
  56787. callback->component->enterModalState (false, userCallbackDeleter.release());
  56788. callback->component->toFront (false); // need to do this after making it modal, or it could
  56789. // be stuck behind other comps that are already modal..
  56790. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56791. if (userCallback != 0)
  56792. return 0;
  56793. const int result = callback->component->runModalLoop();
  56794. if (! Window::wasHiddenBecauseOfAppChange())
  56795. {
  56796. if (prevTopLevel != 0)
  56797. prevTopLevel->toFront (true);
  56798. if (prevFocused != 0)
  56799. prevFocused->grabKeyboardFocus();
  56800. }
  56801. return result;
  56802. }
  56803. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56804. const int minimumWidth,
  56805. const int maximumNumColumns,
  56806. const int standardItemHeight,
  56807. ModalComponentManager::Callback* callback)
  56808. {
  56809. const Point<int> mousePos (Desktop::getMousePosition());
  56810. return showAt (mousePos.getX(), mousePos.getY(),
  56811. itemIdThatMustBeVisible,
  56812. minimumWidth,
  56813. maximumNumColumns,
  56814. standardItemHeight,
  56815. callback);
  56816. }
  56817. int PopupMenu::showAt (const int screenX,
  56818. const int screenY,
  56819. const int itemIdThatMustBeVisible,
  56820. const int minimumWidth,
  56821. const int maximumNumColumns,
  56822. const int standardItemHeight,
  56823. ModalComponentManager::Callback* callback)
  56824. {
  56825. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56826. itemIdThatMustBeVisible,
  56827. minimumWidth, maximumNumColumns,
  56828. standardItemHeight,
  56829. false, 0, callback);
  56830. }
  56831. int PopupMenu::showAt (Component* componentToAttachTo,
  56832. const int itemIdThatMustBeVisible,
  56833. const int minimumWidth,
  56834. const int maximumNumColumns,
  56835. const int standardItemHeight,
  56836. ModalComponentManager::Callback* callback)
  56837. {
  56838. if (componentToAttachTo != 0)
  56839. {
  56840. return showMenu (componentToAttachTo->getScreenBounds(),
  56841. itemIdThatMustBeVisible,
  56842. minimumWidth,
  56843. maximumNumColumns,
  56844. standardItemHeight,
  56845. true, componentToAttachTo, callback);
  56846. }
  56847. else
  56848. {
  56849. return show (itemIdThatMustBeVisible,
  56850. minimumWidth,
  56851. maximumNumColumns,
  56852. standardItemHeight,
  56853. callback);
  56854. }
  56855. }
  56856. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56857. {
  56858. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56859. {
  56860. Window* const pmw = Window::getActiveWindows()[i];
  56861. if (pmw != 0)
  56862. pmw->dismissMenu (0);
  56863. }
  56864. }
  56865. int PopupMenu::getNumItems() const throw()
  56866. {
  56867. int num = 0;
  56868. for (int i = items.size(); --i >= 0;)
  56869. if (! (items.getUnchecked(i))->isSeparator)
  56870. ++num;
  56871. return num;
  56872. }
  56873. bool PopupMenu::containsCommandItem (const int commandID) const
  56874. {
  56875. for (int i = items.size(); --i >= 0;)
  56876. {
  56877. const Item* mi = items.getUnchecked (i);
  56878. if ((mi->itemId == commandID && mi->commandManager != 0)
  56879. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56880. {
  56881. return true;
  56882. }
  56883. }
  56884. return false;
  56885. }
  56886. bool PopupMenu::containsAnyActiveItems() const throw()
  56887. {
  56888. for (int i = items.size(); --i >= 0;)
  56889. {
  56890. const Item* const mi = items.getUnchecked (i);
  56891. if (mi->subMenu != 0)
  56892. {
  56893. if (mi->subMenu->containsAnyActiveItems())
  56894. return true;
  56895. }
  56896. else if (mi->active)
  56897. {
  56898. return true;
  56899. }
  56900. }
  56901. return false;
  56902. }
  56903. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56904. {
  56905. lookAndFeel = newLookAndFeel;
  56906. }
  56907. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56908. : isHighlighted (false),
  56909. isTriggeredAutomatically (isTriggeredAutomatically_)
  56910. {
  56911. }
  56912. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56913. {
  56914. }
  56915. void PopupMenuCustomComponent::triggerMenuItem()
  56916. {
  56917. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56918. if (mic != 0)
  56919. {
  56920. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56921. if (pmw != 0)
  56922. {
  56923. pmw->dismissMenu (&mic->itemInfo);
  56924. }
  56925. else
  56926. {
  56927. // something must have gone wrong with the component hierarchy if this happens..
  56928. jassertfalse;
  56929. }
  56930. }
  56931. else
  56932. {
  56933. // why isn't this component inside a menu? Not much point triggering the item if
  56934. // there's no menu.
  56935. jassertfalse;
  56936. }
  56937. }
  56938. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56939. : subMenu (0),
  56940. itemId (0),
  56941. isSeparator (false),
  56942. isTicked (false),
  56943. isEnabled (false),
  56944. isCustomComponent (false),
  56945. isSectionHeader (false),
  56946. customColour (0),
  56947. customImage (0),
  56948. menu (menu_),
  56949. index (0)
  56950. {
  56951. }
  56952. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56953. {
  56954. }
  56955. bool PopupMenu::MenuItemIterator::next()
  56956. {
  56957. if (index >= menu.items.size())
  56958. return false;
  56959. const Item* const item = menu.items.getUnchecked (index);
  56960. ++index;
  56961. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56962. subMenu = item->subMenu;
  56963. itemId = item->itemId;
  56964. isSeparator = item->isSeparator;
  56965. isTicked = item->isTicked;
  56966. isEnabled = item->active;
  56967. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56968. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56969. customColour = item->usesColour ? &(item->textColour) : 0;
  56970. customImage = item->image;
  56971. commandManager = item->commandManager;
  56972. return true;
  56973. }
  56974. END_JUCE_NAMESPACE
  56975. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56976. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56977. BEGIN_JUCE_NAMESPACE
  56978. ComponentDragger::ComponentDragger()
  56979. : constrainer (0)
  56980. {
  56981. }
  56982. ComponentDragger::~ComponentDragger()
  56983. {
  56984. }
  56985. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56986. ComponentBoundsConstrainer* const constrainer_)
  56987. {
  56988. jassert (componentToDrag->isValidComponent());
  56989. if (componentToDrag != 0)
  56990. {
  56991. constrainer = constrainer_;
  56992. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56993. }
  56994. }
  56995. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56996. {
  56997. jassert (componentToDrag->isValidComponent());
  56998. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56999. if (componentToDrag != 0)
  57000. {
  57001. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57002. const Component* const parentComp = componentToDrag->getParentComponent();
  57003. if (parentComp != 0)
  57004. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57005. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57006. if (constrainer != 0)
  57007. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57008. else
  57009. componentToDrag->setBounds (bounds);
  57010. }
  57011. }
  57012. END_JUCE_NAMESPACE
  57013. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57014. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57015. BEGIN_JUCE_NAMESPACE
  57016. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57017. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57018. class DragImageComponent : public Component,
  57019. public Timer
  57020. {
  57021. public:
  57022. DragImageComponent (const Image& im,
  57023. const String& desc,
  57024. Component* const sourceComponent,
  57025. Component* const mouseDragSource_,
  57026. DragAndDropContainer* const o,
  57027. const Point<int>& imageOffset_)
  57028. : image (im),
  57029. source (sourceComponent),
  57030. mouseDragSource (mouseDragSource_),
  57031. owner (o),
  57032. dragDesc (desc),
  57033. imageOffset (imageOffset_),
  57034. hasCheckedForExternalDrag (false),
  57035. drawImage (true)
  57036. {
  57037. setSize (im.getWidth(), im.getHeight());
  57038. if (mouseDragSource == 0)
  57039. mouseDragSource = source;
  57040. mouseDragSource->addMouseListener (this, false);
  57041. startTimer (200);
  57042. setInterceptsMouseClicks (false, false);
  57043. setAlwaysOnTop (true);
  57044. }
  57045. ~DragImageComponent()
  57046. {
  57047. if (owner->dragImageComponent == this)
  57048. owner->dragImageComponent.release();
  57049. if (mouseDragSource != 0)
  57050. {
  57051. mouseDragSource->removeMouseListener (this);
  57052. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57053. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57054. }
  57055. }
  57056. void paint (Graphics& g)
  57057. {
  57058. if (isOpaque())
  57059. g.fillAll (Colours::white);
  57060. if (drawImage)
  57061. {
  57062. g.setOpacity (1.0f);
  57063. g.drawImageAt (image, 0, 0);
  57064. }
  57065. }
  57066. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57067. {
  57068. Component* hit = getParentComponent();
  57069. if (hit == 0)
  57070. {
  57071. hit = Desktop::getInstance().findComponentAt (screenPos);
  57072. }
  57073. else
  57074. {
  57075. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57076. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57077. }
  57078. // (note: use a local copy of the dragDesc member in case the callback runs
  57079. // a modal loop and deletes this object before the method completes)
  57080. const String dragDescLocal (dragDesc);
  57081. while (hit != 0)
  57082. {
  57083. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57084. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57085. {
  57086. relativePos = hit->globalPositionToRelative (screenPos);
  57087. return ddt;
  57088. }
  57089. hit = hit->getParentComponent();
  57090. }
  57091. return 0;
  57092. }
  57093. void mouseUp (const MouseEvent& e)
  57094. {
  57095. if (e.originalComponent != this)
  57096. {
  57097. if (mouseDragSource != 0)
  57098. mouseDragSource->removeMouseListener (this);
  57099. bool dropAccepted = false;
  57100. DragAndDropTarget* ddt = 0;
  57101. Point<int> relPos;
  57102. if (isVisible())
  57103. {
  57104. setVisible (false);
  57105. ddt = findTarget (e.getScreenPosition(), relPos);
  57106. // fade this component and remove it - it'll be deleted later by the timer callback
  57107. dropAccepted = ddt != 0;
  57108. setVisible (true);
  57109. if (dropAccepted || source == 0)
  57110. {
  57111. fadeOutComponent (120);
  57112. }
  57113. else
  57114. {
  57115. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57116. source->getHeight() / 2)));
  57117. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57118. getHeight() / 2)));
  57119. fadeOutComponent (120,
  57120. target.getX() - ourCentre.getX(),
  57121. target.getY() - ourCentre.getY());
  57122. }
  57123. }
  57124. if (getParentComponent() != 0)
  57125. getParentComponent()->removeChildComponent (this);
  57126. if (dropAccepted && ddt != 0)
  57127. {
  57128. // (note: use a local copy of the dragDesc member in case the callback runs
  57129. // a modal loop and deletes this object before the method completes)
  57130. const String dragDescLocal (dragDesc);
  57131. currentlyOverComp = 0;
  57132. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57133. }
  57134. // careful - this object could now be deleted..
  57135. }
  57136. }
  57137. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57138. {
  57139. // (note: use a local copy of the dragDesc member in case the callback runs
  57140. // a modal loop and deletes this object before it returns)
  57141. const String dragDescLocal (dragDesc);
  57142. Point<int> newPos (screenPos + imageOffset);
  57143. if (getParentComponent() != 0)
  57144. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57145. //if (newX != getX() || newY != getY())
  57146. {
  57147. setTopLeftPosition (newPos.getX(), newPos.getY());
  57148. Point<int> relPos;
  57149. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57150. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57151. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57152. if (ddtComp != currentlyOverComp)
  57153. {
  57154. if (currentlyOverComp != 0 && source != 0
  57155. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57156. {
  57157. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57158. }
  57159. currentlyOverComp = ddtComp;
  57160. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57161. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57162. }
  57163. DragAndDropTarget* target = getCurrentlyOver();
  57164. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57165. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57166. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57167. {
  57168. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57169. {
  57170. hasCheckedForExternalDrag = true;
  57171. StringArray files;
  57172. bool canMoveFiles = false;
  57173. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57174. && files.size() > 0)
  57175. {
  57176. Component::SafePointer<Component> cdw (this);
  57177. setVisible (false);
  57178. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57179. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57180. if (cdw != 0)
  57181. delete this;
  57182. return;
  57183. }
  57184. }
  57185. }
  57186. }
  57187. }
  57188. void mouseDrag (const MouseEvent& e)
  57189. {
  57190. if (e.originalComponent != this)
  57191. updateLocation (true, e.getScreenPosition());
  57192. }
  57193. void timerCallback()
  57194. {
  57195. if (source == 0)
  57196. {
  57197. delete this;
  57198. }
  57199. else if (! isMouseButtonDownAnywhere())
  57200. {
  57201. if (mouseDragSource != 0)
  57202. mouseDragSource->removeMouseListener (this);
  57203. delete this;
  57204. }
  57205. }
  57206. private:
  57207. Image image;
  57208. Component::SafePointer<Component> source;
  57209. Component::SafePointer<Component> mouseDragSource;
  57210. DragAndDropContainer* const owner;
  57211. Component::SafePointer<Component> currentlyOverComp;
  57212. DragAndDropTarget* getCurrentlyOver()
  57213. {
  57214. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57215. }
  57216. String dragDesc;
  57217. const Point<int> imageOffset;
  57218. bool hasCheckedForExternalDrag, drawImage;
  57219. DragImageComponent (const DragImageComponent&);
  57220. DragImageComponent& operator= (const DragImageComponent&);
  57221. };
  57222. DragAndDropContainer::DragAndDropContainer()
  57223. {
  57224. }
  57225. DragAndDropContainer::~DragAndDropContainer()
  57226. {
  57227. dragImageComponent = 0;
  57228. }
  57229. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57230. Component* sourceComponent,
  57231. const Image& dragImage_,
  57232. const bool allowDraggingToExternalWindows,
  57233. const Point<int>* imageOffsetFromMouse)
  57234. {
  57235. Image dragImage (dragImage_);
  57236. if (dragImageComponent == 0)
  57237. {
  57238. Component* const thisComp = dynamic_cast <Component*> (this);
  57239. if (thisComp == 0)
  57240. {
  57241. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57242. return;
  57243. }
  57244. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57245. if (draggingSource == 0 || ! draggingSource->isDragging())
  57246. {
  57247. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57248. return;
  57249. }
  57250. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57251. Point<int> imageOffset;
  57252. if (dragImage.isNull())
  57253. {
  57254. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57255. .convertedToFormat (Image::ARGB);
  57256. dragImage.multiplyAllAlphas (0.6f);
  57257. const int lo = 150;
  57258. const int hi = 400;
  57259. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57260. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57261. for (int y = dragImage.getHeight(); --y >= 0;)
  57262. {
  57263. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57264. for (int x = dragImage.getWidth(); --x >= 0;)
  57265. {
  57266. const int dx = x - clipped.getX();
  57267. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57268. if (distance > lo)
  57269. {
  57270. const float alpha = (distance > hi) ? 0
  57271. : (hi - distance) / (float) (hi - lo)
  57272. + Random::getSystemRandom().nextFloat() * 0.008f;
  57273. dragImage.multiplyAlphaAt (x, y, alpha);
  57274. }
  57275. }
  57276. }
  57277. imageOffset = -clipped;
  57278. }
  57279. else
  57280. {
  57281. if (imageOffsetFromMouse == 0)
  57282. imageOffset = -dragImage.getBounds().getCentre();
  57283. else
  57284. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57285. }
  57286. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57287. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57288. currentDragDesc = sourceDescription;
  57289. if (allowDraggingToExternalWindows)
  57290. {
  57291. if (! Desktop::canUseSemiTransparentWindows())
  57292. dragImageComponent->setOpaque (true);
  57293. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57294. | ComponentPeer::windowIsTemporary
  57295. | ComponentPeer::windowIgnoresKeyPresses);
  57296. }
  57297. else
  57298. thisComp->addChildComponent (dragImageComponent);
  57299. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57300. dragImageComponent->setVisible (true);
  57301. }
  57302. }
  57303. bool DragAndDropContainer::isDragAndDropActive() const
  57304. {
  57305. return dragImageComponent != 0;
  57306. }
  57307. const String DragAndDropContainer::getCurrentDragDescription() const
  57308. {
  57309. return (dragImageComponent != 0) ? currentDragDesc
  57310. : String::empty;
  57311. }
  57312. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57313. {
  57314. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57315. }
  57316. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57317. {
  57318. return false;
  57319. }
  57320. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57321. {
  57322. }
  57323. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57324. {
  57325. }
  57326. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57327. {
  57328. }
  57329. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57330. {
  57331. return true;
  57332. }
  57333. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57334. {
  57335. }
  57336. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57337. {
  57338. }
  57339. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57340. {
  57341. }
  57342. END_JUCE_NAMESPACE
  57343. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57344. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57345. BEGIN_JUCE_NAMESPACE
  57346. class MouseCursor::SharedCursorHandle
  57347. {
  57348. public:
  57349. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57350. : handle (createStandardMouseCursor (type)),
  57351. refCount (1),
  57352. standardType (type),
  57353. isStandard (true)
  57354. {
  57355. }
  57356. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57357. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57358. refCount (1),
  57359. standardType (MouseCursor::NormalCursor),
  57360. isStandard (false)
  57361. {
  57362. }
  57363. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57364. {
  57365. const ScopedLock sl (getLock());
  57366. for (int i = 0; i < getCursors().size(); ++i)
  57367. {
  57368. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57369. if (sc->standardType == type)
  57370. return sc->retain();
  57371. }
  57372. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57373. getCursors().add (sc);
  57374. return sc;
  57375. }
  57376. SharedCursorHandle* retain() throw()
  57377. {
  57378. ++refCount;
  57379. return this;
  57380. }
  57381. void release()
  57382. {
  57383. if (--refCount == 0)
  57384. {
  57385. if (isStandard)
  57386. {
  57387. const ScopedLock sl (getLock());
  57388. getCursors().removeValue (this);
  57389. }
  57390. delete this;
  57391. }
  57392. }
  57393. void* getHandle() const throw() { return handle; }
  57394. juce_UseDebuggingNewOperator
  57395. private:
  57396. void* const handle;
  57397. Atomic <int> refCount;
  57398. const MouseCursor::StandardCursorType standardType;
  57399. const bool isStandard;
  57400. static CriticalSection& getLock()
  57401. {
  57402. static CriticalSection lock;
  57403. return lock;
  57404. }
  57405. static Array <SharedCursorHandle*>& getCursors()
  57406. {
  57407. static Array <SharedCursorHandle*> cursors;
  57408. return cursors;
  57409. }
  57410. ~SharedCursorHandle()
  57411. {
  57412. deleteMouseCursor (handle, isStandard);
  57413. }
  57414. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57415. };
  57416. MouseCursor::MouseCursor()
  57417. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57418. {
  57419. jassert (cursorHandle != 0);
  57420. }
  57421. MouseCursor::MouseCursor (const StandardCursorType type)
  57422. : cursorHandle (SharedCursorHandle::createStandard (type))
  57423. {
  57424. jassert (cursorHandle != 0);
  57425. }
  57426. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57427. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57428. {
  57429. }
  57430. MouseCursor::MouseCursor (const MouseCursor& other)
  57431. : cursorHandle (other.cursorHandle->retain())
  57432. {
  57433. }
  57434. MouseCursor::~MouseCursor()
  57435. {
  57436. cursorHandle->release();
  57437. }
  57438. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57439. {
  57440. other.cursorHandle->retain();
  57441. cursorHandle->release();
  57442. cursorHandle = other.cursorHandle;
  57443. return *this;
  57444. }
  57445. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57446. {
  57447. return getHandle() == other.getHandle();
  57448. }
  57449. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57450. {
  57451. return getHandle() != other.getHandle();
  57452. }
  57453. void* MouseCursor::getHandle() const throw()
  57454. {
  57455. return cursorHandle->getHandle();
  57456. }
  57457. void MouseCursor::showWaitCursor()
  57458. {
  57459. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57460. }
  57461. void MouseCursor::hideWaitCursor()
  57462. {
  57463. Desktop::getInstance().getMainMouseSource().revealCursor();
  57464. }
  57465. END_JUCE_NAMESPACE
  57466. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57467. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57468. BEGIN_JUCE_NAMESPACE
  57469. MouseEvent::MouseEvent (MouseInputSource& source_,
  57470. const Point<int>& position,
  57471. const ModifierKeys& mods_,
  57472. Component* const eventComponent_,
  57473. Component* const originator,
  57474. const Time& eventTime_,
  57475. const Point<int> mouseDownPos_,
  57476. const Time& mouseDownTime_,
  57477. const int numberOfClicks_,
  57478. const bool mouseWasDragged) throw()
  57479. : x (position.getX()),
  57480. y (position.getY()),
  57481. mods (mods_),
  57482. eventComponent (eventComponent_),
  57483. originalComponent (originator),
  57484. eventTime (eventTime_),
  57485. source (source_),
  57486. mouseDownPos (mouseDownPos_),
  57487. mouseDownTime (mouseDownTime_),
  57488. numberOfClicks (numberOfClicks_),
  57489. wasMovedSinceMouseDown (mouseWasDragged)
  57490. {
  57491. }
  57492. MouseEvent::~MouseEvent() throw()
  57493. {
  57494. }
  57495. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57496. {
  57497. if (otherComponent == 0)
  57498. {
  57499. jassertfalse;
  57500. return *this;
  57501. }
  57502. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57503. mods, otherComponent, originalComponent, eventTime,
  57504. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57505. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57506. }
  57507. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57508. {
  57509. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57510. eventTime, mouseDownPos, mouseDownTime,
  57511. numberOfClicks, wasMovedSinceMouseDown);
  57512. }
  57513. bool MouseEvent::mouseWasClicked() const throw()
  57514. {
  57515. return ! wasMovedSinceMouseDown;
  57516. }
  57517. int MouseEvent::getMouseDownX() const throw()
  57518. {
  57519. return mouseDownPos.getX();
  57520. }
  57521. int MouseEvent::getMouseDownY() const throw()
  57522. {
  57523. return mouseDownPos.getY();
  57524. }
  57525. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57526. {
  57527. return mouseDownPos;
  57528. }
  57529. int MouseEvent::getDistanceFromDragStartX() const throw()
  57530. {
  57531. return x - mouseDownPos.getX();
  57532. }
  57533. int MouseEvent::getDistanceFromDragStartY() const throw()
  57534. {
  57535. return y - mouseDownPos.getY();
  57536. }
  57537. int MouseEvent::getDistanceFromDragStart() const throw()
  57538. {
  57539. return mouseDownPos.getDistanceFrom (getPosition());
  57540. }
  57541. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57542. {
  57543. return getPosition() - mouseDownPos;
  57544. }
  57545. int MouseEvent::getLengthOfMousePress() const throw()
  57546. {
  57547. if (mouseDownTime.toMilliseconds() > 0)
  57548. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57549. return 0;
  57550. }
  57551. const Point<int> MouseEvent::getPosition() const throw()
  57552. {
  57553. return Point<int> (x, y);
  57554. }
  57555. int MouseEvent::getScreenX() const
  57556. {
  57557. return getScreenPosition().getX();
  57558. }
  57559. int MouseEvent::getScreenY() const
  57560. {
  57561. return getScreenPosition().getY();
  57562. }
  57563. const Point<int> MouseEvent::getScreenPosition() const
  57564. {
  57565. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57566. }
  57567. int MouseEvent::getMouseDownScreenX() const
  57568. {
  57569. return getMouseDownScreenPosition().getX();
  57570. }
  57571. int MouseEvent::getMouseDownScreenY() const
  57572. {
  57573. return getMouseDownScreenPosition().getY();
  57574. }
  57575. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57576. {
  57577. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57578. }
  57579. int MouseEvent::doubleClickTimeOutMs = 400;
  57580. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57581. {
  57582. doubleClickTimeOutMs = newTime;
  57583. }
  57584. int MouseEvent::getDoubleClickTimeout() throw()
  57585. {
  57586. return doubleClickTimeOutMs;
  57587. }
  57588. END_JUCE_NAMESPACE
  57589. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57590. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57591. BEGIN_JUCE_NAMESPACE
  57592. class MouseInputSourceInternal : public AsyncUpdater
  57593. {
  57594. public:
  57595. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57596. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57597. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57598. mouseEventCounter (0)
  57599. {
  57600. zerostruct (mouseDowns);
  57601. }
  57602. ~MouseInputSourceInternal()
  57603. {
  57604. }
  57605. bool isDragging() const throw()
  57606. {
  57607. return buttonState.isAnyMouseButtonDown();
  57608. }
  57609. Component* getComponentUnderMouse() const
  57610. {
  57611. return static_cast <Component*> (componentUnderMouse);
  57612. }
  57613. const ModifierKeys getCurrentModifiers() const
  57614. {
  57615. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57616. }
  57617. ComponentPeer* getPeer()
  57618. {
  57619. if (! ComponentPeer::isValidPeer (lastPeer))
  57620. lastPeer = 0;
  57621. return lastPeer;
  57622. }
  57623. Component* findComponentAt (const Point<int>& screenPos)
  57624. {
  57625. ComponentPeer* const peer = getPeer();
  57626. if (peer != 0)
  57627. {
  57628. Component* const comp = peer->getComponent();
  57629. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57630. // (the contains() call is needed to test for overlapping desktop windows)
  57631. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57632. return comp->getComponentAt (relativePos);
  57633. }
  57634. return 0;
  57635. }
  57636. const Point<int> getScreenPosition() const throw()
  57637. {
  57638. return lastScreenPos + unboundedMouseOffset;
  57639. }
  57640. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57641. {
  57642. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57643. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57644. }
  57645. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57646. {
  57647. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57648. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57649. }
  57650. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57651. {
  57652. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57653. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57654. }
  57655. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57656. {
  57657. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57658. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57659. }
  57660. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57661. {
  57662. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57663. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57664. }
  57665. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57666. {
  57667. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57668. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57669. }
  57670. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57671. {
  57672. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57673. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57674. }
  57675. // (returns true if the button change caused a modal event loop)
  57676. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57677. {
  57678. if (buttonState == newButtonState)
  57679. return false;
  57680. setScreenPos (screenPos, time, false);
  57681. // (ignore secondary clicks when there's already a button down)
  57682. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57683. {
  57684. buttonState = newButtonState;
  57685. return false;
  57686. }
  57687. const int lastCounter = mouseEventCounter;
  57688. if (buttonState.isAnyMouseButtonDown())
  57689. {
  57690. Component* const current = getComponentUnderMouse();
  57691. if (current != 0)
  57692. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57693. enableUnboundedMouseMovement (false, false);
  57694. }
  57695. buttonState = newButtonState;
  57696. if (buttonState.isAnyMouseButtonDown())
  57697. {
  57698. Desktop::getInstance().incrementMouseClickCounter();
  57699. Component* const current = getComponentUnderMouse();
  57700. if (current != 0)
  57701. {
  57702. registerMouseDown (screenPos, time, current);
  57703. sendMouseDown (current, screenPos, time);
  57704. }
  57705. }
  57706. return lastCounter != mouseEventCounter;
  57707. }
  57708. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57709. {
  57710. Component* current = getComponentUnderMouse();
  57711. if (newComponent != current)
  57712. {
  57713. Component::SafePointer<Component> safeNewComp (newComponent);
  57714. const ModifierKeys originalButtonState (buttonState);
  57715. if (current != 0)
  57716. {
  57717. setButtons (screenPos, time, ModifierKeys());
  57718. sendMouseExit (current, screenPos, time);
  57719. buttonState = originalButtonState;
  57720. }
  57721. componentUnderMouse = safeNewComp;
  57722. current = getComponentUnderMouse();
  57723. if (current != 0)
  57724. sendMouseEnter (current, screenPos, time);
  57725. revealCursor (false);
  57726. setButtons (screenPos, time, originalButtonState);
  57727. }
  57728. }
  57729. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57730. {
  57731. ModifierKeys::updateCurrentModifiers();
  57732. if (newPeer != lastPeer)
  57733. {
  57734. setComponentUnderMouse (0, screenPos, time);
  57735. lastPeer = newPeer;
  57736. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57737. }
  57738. }
  57739. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57740. {
  57741. if (! isDragging())
  57742. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57743. if (newScreenPos != lastScreenPos || forceUpdate)
  57744. {
  57745. cancelPendingUpdate();
  57746. lastScreenPos = newScreenPos;
  57747. Component* const current = getComponentUnderMouse();
  57748. if (current != 0)
  57749. {
  57750. if (isDragging())
  57751. {
  57752. registerMouseDrag (newScreenPos);
  57753. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57754. if (isUnboundedMouseModeOn)
  57755. handleUnboundedDrag (current);
  57756. }
  57757. else
  57758. {
  57759. sendMouseMove (current, newScreenPos, time);
  57760. }
  57761. }
  57762. revealCursor (false);
  57763. }
  57764. }
  57765. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57766. {
  57767. jassert (newPeer != 0);
  57768. lastTime = time;
  57769. ++mouseEventCounter;
  57770. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57771. if (isDragging() && newMods.isAnyMouseButtonDown())
  57772. {
  57773. setScreenPos (screenPos, time, false);
  57774. }
  57775. else
  57776. {
  57777. setPeer (newPeer, screenPos, time);
  57778. ComponentPeer* peer = getPeer();
  57779. if (peer != 0)
  57780. {
  57781. if (setButtons (screenPos, time, newMods))
  57782. return; // some modal events have been dispatched, so the current event is now out-of-date
  57783. peer = getPeer();
  57784. if (peer != 0)
  57785. setScreenPos (screenPos, time, false);
  57786. }
  57787. }
  57788. }
  57789. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57790. {
  57791. jassert (peer != 0);
  57792. lastTime = time;
  57793. ++mouseEventCounter;
  57794. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57795. setPeer (peer, screenPos, time);
  57796. setScreenPos (screenPos, time, false);
  57797. triggerFakeMove();
  57798. if (! isDragging())
  57799. {
  57800. Component* current = getComponentUnderMouse();
  57801. if (current != 0)
  57802. sendMouseWheel (current, screenPos, time, x, y);
  57803. }
  57804. }
  57805. const Time getLastMouseDownTime() const throw()
  57806. {
  57807. return Time (mouseDowns[0].time);
  57808. }
  57809. const Point<int> getLastMouseDownPosition() const throw()
  57810. {
  57811. return mouseDowns[0].position;
  57812. }
  57813. int getNumberOfMultipleClicks() const throw()
  57814. {
  57815. int numClicks = 0;
  57816. if (mouseDowns[0].time != 0)
  57817. {
  57818. if (! mouseMovedSignificantlySincePressed)
  57819. ++numClicks;
  57820. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57821. {
  57822. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57823. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57824. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57825. {
  57826. ++numClicks;
  57827. }
  57828. else
  57829. {
  57830. break;
  57831. }
  57832. }
  57833. }
  57834. return numClicks;
  57835. }
  57836. bool hasMouseMovedSignificantlySincePressed() const throw()
  57837. {
  57838. return mouseMovedSignificantlySincePressed
  57839. || lastTime > mouseDowns[0].time + 300;
  57840. }
  57841. void triggerFakeMove()
  57842. {
  57843. triggerAsyncUpdate();
  57844. }
  57845. void handleAsyncUpdate()
  57846. {
  57847. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57848. }
  57849. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57850. {
  57851. enable = enable && isDragging();
  57852. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57853. if (enable != isUnboundedMouseModeOn)
  57854. {
  57855. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57856. {
  57857. // when released, return the mouse to within the component's bounds
  57858. Component* current = getComponentUnderMouse();
  57859. if (current != 0)
  57860. Desktop::setMousePosition (current->getScreenBounds()
  57861. .getConstrainedPoint (lastScreenPos));
  57862. }
  57863. isUnboundedMouseModeOn = enable;
  57864. unboundedMouseOffset = Point<int>();
  57865. revealCursor (true);
  57866. }
  57867. }
  57868. void handleUnboundedDrag (Component* current)
  57869. {
  57870. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57871. if (! screenArea.contains (lastScreenPos))
  57872. {
  57873. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57874. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57875. Desktop::setMousePosition (componentCentre);
  57876. }
  57877. else if (isCursorVisibleUntilOffscreen
  57878. && (! unboundedMouseOffset.isOrigin())
  57879. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57880. {
  57881. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57882. unboundedMouseOffset = Point<int>();
  57883. }
  57884. }
  57885. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57886. {
  57887. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57888. {
  57889. cursor = MouseCursor::NoCursor;
  57890. forcedUpdate = true;
  57891. }
  57892. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57893. {
  57894. currentCursorHandle = cursor.getHandle();
  57895. cursor.showInWindow (getPeer());
  57896. }
  57897. }
  57898. void hideCursor()
  57899. {
  57900. showMouseCursor (MouseCursor::NoCursor, true);
  57901. }
  57902. void revealCursor (bool forcedUpdate)
  57903. {
  57904. MouseCursor mc (MouseCursor::NormalCursor);
  57905. Component* current = getComponentUnderMouse();
  57906. if (current != 0)
  57907. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57908. showMouseCursor (mc, forcedUpdate);
  57909. }
  57910. int index;
  57911. bool isMouseDevice;
  57912. Point<int> lastScreenPos;
  57913. ModifierKeys buttonState;
  57914. private:
  57915. MouseInputSource& source;
  57916. Component::SafePointer<Component> componentUnderMouse;
  57917. ComponentPeer* lastPeer;
  57918. Point<int> unboundedMouseOffset;
  57919. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57920. void* currentCursorHandle;
  57921. int mouseEventCounter;
  57922. struct RecentMouseDown
  57923. {
  57924. Point<int> position;
  57925. int64 time;
  57926. Component* component;
  57927. };
  57928. RecentMouseDown mouseDowns[4];
  57929. bool mouseMovedSignificantlySincePressed;
  57930. int64 lastTime;
  57931. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57932. {
  57933. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57934. mouseDowns[i] = mouseDowns[i - 1];
  57935. mouseDowns[0].position = screenPos;
  57936. mouseDowns[0].time = time;
  57937. mouseDowns[0].component = component;
  57938. mouseMovedSignificantlySincePressed = false;
  57939. }
  57940. void registerMouseDrag (const Point<int>& screenPos) throw()
  57941. {
  57942. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57943. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57944. }
  57945. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57946. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57947. };
  57948. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57949. {
  57950. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57951. }
  57952. MouseInputSource::~MouseInputSource()
  57953. {
  57954. }
  57955. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57956. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57957. bool MouseInputSource::canHover() const { return isMouse(); }
  57958. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57959. int MouseInputSource::getIndex() const { return pimpl->index; }
  57960. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57961. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57962. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57963. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57964. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57965. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57966. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57967. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57968. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57969. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57970. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57971. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57972. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57973. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57974. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57975. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57976. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57977. {
  57978. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57979. }
  57980. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57981. {
  57982. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57983. }
  57984. END_JUCE_NAMESPACE
  57985. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57986. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57987. BEGIN_JUCE_NAMESPACE
  57988. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57989. : source (0),
  57990. hoverTimeMillisecs (hoverTimeMillisecs_),
  57991. hasJustHovered (false)
  57992. {
  57993. internalTimer.owner = this;
  57994. }
  57995. MouseHoverDetector::~MouseHoverDetector()
  57996. {
  57997. setHoverComponent (0);
  57998. }
  57999. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58000. {
  58001. hoverTimeMillisecs = newTimeInMillisecs;
  58002. }
  58003. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58004. {
  58005. if (source != newSourceComponent)
  58006. {
  58007. internalTimer.stopTimer();
  58008. hasJustHovered = false;
  58009. if (source != 0)
  58010. {
  58011. // ! you need to delete the hover detector before deleting its component
  58012. jassert (source->isValidComponent());
  58013. source->removeMouseListener (&internalTimer);
  58014. }
  58015. source = newSourceComponent;
  58016. if (newSourceComponent != 0)
  58017. newSourceComponent->addMouseListener (&internalTimer, false);
  58018. }
  58019. }
  58020. void MouseHoverDetector::hoverTimerCallback()
  58021. {
  58022. internalTimer.stopTimer();
  58023. if (source != 0)
  58024. {
  58025. const Point<int> pos (source->getMouseXYRelative());
  58026. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58027. {
  58028. hasJustHovered = true;
  58029. mouseHovered (pos.getX(), pos.getY());
  58030. }
  58031. }
  58032. }
  58033. void MouseHoverDetector::checkJustHoveredCallback()
  58034. {
  58035. if (hasJustHovered)
  58036. {
  58037. hasJustHovered = false;
  58038. mouseMovedAfterHover();
  58039. }
  58040. }
  58041. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58042. {
  58043. owner->hoverTimerCallback();
  58044. }
  58045. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58046. {
  58047. stopTimer();
  58048. owner->checkJustHoveredCallback();
  58049. }
  58050. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58051. {
  58052. stopTimer();
  58053. owner->checkJustHoveredCallback();
  58054. }
  58055. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58056. {
  58057. stopTimer();
  58058. owner->checkJustHoveredCallback();
  58059. }
  58060. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58061. {
  58062. stopTimer();
  58063. owner->checkJustHoveredCallback();
  58064. }
  58065. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58066. {
  58067. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58068. {
  58069. lastX = e.x;
  58070. lastY = e.y;
  58071. if (owner->source != 0)
  58072. startTimer (owner->hoverTimeMillisecs);
  58073. owner->checkJustHoveredCallback();
  58074. }
  58075. }
  58076. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58077. {
  58078. stopTimer();
  58079. owner->checkJustHoveredCallback();
  58080. }
  58081. END_JUCE_NAMESPACE
  58082. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58083. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58084. BEGIN_JUCE_NAMESPACE
  58085. void MouseListener::mouseEnter (const MouseEvent&)
  58086. {
  58087. }
  58088. void MouseListener::mouseExit (const MouseEvent&)
  58089. {
  58090. }
  58091. void MouseListener::mouseDown (const MouseEvent&)
  58092. {
  58093. }
  58094. void MouseListener::mouseUp (const MouseEvent&)
  58095. {
  58096. }
  58097. void MouseListener::mouseDrag (const MouseEvent&)
  58098. {
  58099. }
  58100. void MouseListener::mouseMove (const MouseEvent&)
  58101. {
  58102. }
  58103. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58104. {
  58105. }
  58106. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58107. {
  58108. }
  58109. END_JUCE_NAMESPACE
  58110. /*** End of inlined file: juce_MouseListener.cpp ***/
  58111. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58112. BEGIN_JUCE_NAMESPACE
  58113. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58114. const String& buttonTextWhenTrue,
  58115. const String& buttonTextWhenFalse)
  58116. : PropertyComponent (name),
  58117. onText (buttonTextWhenTrue),
  58118. offText (buttonTextWhenFalse)
  58119. {
  58120. addAndMakeVisible (&button);
  58121. button.setClickingTogglesState (false);
  58122. button.addButtonListener (this);
  58123. }
  58124. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58125. const String& name,
  58126. const String& buttonText)
  58127. : PropertyComponent (name),
  58128. onText (buttonText),
  58129. offText (buttonText)
  58130. {
  58131. addAndMakeVisible (&button);
  58132. button.setClickingTogglesState (false);
  58133. button.setButtonText (buttonText);
  58134. button.getToggleStateValue().referTo (valueToControl);
  58135. button.setClickingTogglesState (true);
  58136. }
  58137. BooleanPropertyComponent::~BooleanPropertyComponent()
  58138. {
  58139. }
  58140. void BooleanPropertyComponent::setState (const bool newState)
  58141. {
  58142. button.setToggleState (newState, true);
  58143. }
  58144. bool BooleanPropertyComponent::getState() const
  58145. {
  58146. return button.getToggleState();
  58147. }
  58148. void BooleanPropertyComponent::paint (Graphics& g)
  58149. {
  58150. PropertyComponent::paint (g);
  58151. g.setColour (Colours::white);
  58152. g.fillRect (button.getBounds());
  58153. g.setColour (findColour (ComboBox::outlineColourId));
  58154. g.drawRect (button.getBounds());
  58155. }
  58156. void BooleanPropertyComponent::refresh()
  58157. {
  58158. button.setToggleState (getState(), false);
  58159. button.setButtonText (button.getToggleState() ? onText : offText);
  58160. }
  58161. void BooleanPropertyComponent::buttonClicked (Button*)
  58162. {
  58163. setState (! getState());
  58164. }
  58165. END_JUCE_NAMESPACE
  58166. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58167. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58168. BEGIN_JUCE_NAMESPACE
  58169. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58170. const bool triggerOnMouseDown)
  58171. : PropertyComponent (name)
  58172. {
  58173. addAndMakeVisible (&button);
  58174. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58175. button.addButtonListener (this);
  58176. }
  58177. ButtonPropertyComponent::~ButtonPropertyComponent()
  58178. {
  58179. }
  58180. void ButtonPropertyComponent::refresh()
  58181. {
  58182. button.setButtonText (getButtonText());
  58183. }
  58184. void ButtonPropertyComponent::buttonClicked (Button*)
  58185. {
  58186. buttonClicked();
  58187. }
  58188. END_JUCE_NAMESPACE
  58189. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58190. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58191. BEGIN_JUCE_NAMESPACE
  58192. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58193. public Value::Listener
  58194. {
  58195. public:
  58196. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58197. : sourceValue (sourceValue_),
  58198. mappings (mappings_)
  58199. {
  58200. sourceValue.addListener (this);
  58201. }
  58202. ~RemapperValueSource() {}
  58203. const var getValue() const
  58204. {
  58205. return mappings.indexOf (sourceValue.getValue()) + 1;
  58206. }
  58207. void setValue (const var& newValue)
  58208. {
  58209. const var remappedVal (mappings [(int) newValue - 1]);
  58210. if (remappedVal != sourceValue)
  58211. sourceValue = remappedVal;
  58212. }
  58213. void valueChanged (Value&)
  58214. {
  58215. sendChangeMessage (true);
  58216. }
  58217. juce_UseDebuggingNewOperator
  58218. protected:
  58219. Value sourceValue;
  58220. Array<var> mappings;
  58221. RemapperValueSource (const RemapperValueSource&);
  58222. const RemapperValueSource& operator= (const RemapperValueSource&);
  58223. };
  58224. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58225. : PropertyComponent (name),
  58226. isCustomClass (true)
  58227. {
  58228. }
  58229. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58230. const String& name,
  58231. const StringArray& choices_,
  58232. const Array <var>& correspondingValues)
  58233. : PropertyComponent (name),
  58234. choices (choices_),
  58235. isCustomClass (false)
  58236. {
  58237. // The array of corresponding values must contain one value for each of the items in
  58238. // the choices array!
  58239. jassert (correspondingValues.size() == choices.size());
  58240. createComboBox();
  58241. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58242. }
  58243. ChoicePropertyComponent::~ChoicePropertyComponent()
  58244. {
  58245. }
  58246. void ChoicePropertyComponent::createComboBox()
  58247. {
  58248. addAndMakeVisible (&comboBox);
  58249. for (int i = 0; i < choices.size(); ++i)
  58250. {
  58251. if (choices[i].isNotEmpty())
  58252. comboBox.addItem (choices[i], i + 1);
  58253. else
  58254. comboBox.addSeparator();
  58255. }
  58256. comboBox.setEditableText (false);
  58257. }
  58258. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58259. {
  58260. jassertfalse; // you need to override this method in your subclass!
  58261. }
  58262. int ChoicePropertyComponent::getIndex() const
  58263. {
  58264. jassertfalse; // you need to override this method in your subclass!
  58265. return -1;
  58266. }
  58267. const StringArray& ChoicePropertyComponent::getChoices() const
  58268. {
  58269. return choices;
  58270. }
  58271. void ChoicePropertyComponent::refresh()
  58272. {
  58273. if (isCustomClass)
  58274. {
  58275. if (! comboBox.isVisible())
  58276. {
  58277. createComboBox();
  58278. comboBox.addListener (this);
  58279. }
  58280. comboBox.setSelectedId (getIndex() + 1, true);
  58281. }
  58282. }
  58283. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58284. {
  58285. if (isCustomClass)
  58286. {
  58287. const int newIndex = comboBox.getSelectedId() - 1;
  58288. if (newIndex != getIndex())
  58289. setIndex (newIndex);
  58290. }
  58291. }
  58292. END_JUCE_NAMESPACE
  58293. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58294. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58295. BEGIN_JUCE_NAMESPACE
  58296. PropertyComponent::PropertyComponent (const String& name,
  58297. const int preferredHeight_)
  58298. : Component (name),
  58299. preferredHeight (preferredHeight_)
  58300. {
  58301. jassert (name.isNotEmpty());
  58302. }
  58303. PropertyComponent::~PropertyComponent()
  58304. {
  58305. }
  58306. void PropertyComponent::paint (Graphics& g)
  58307. {
  58308. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58309. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58310. }
  58311. void PropertyComponent::resized()
  58312. {
  58313. if (getNumChildComponents() > 0)
  58314. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58315. }
  58316. void PropertyComponent::enablementChanged()
  58317. {
  58318. repaint();
  58319. }
  58320. END_JUCE_NAMESPACE
  58321. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58322. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58323. BEGIN_JUCE_NAMESPACE
  58324. class PropertyPanel::PropertyHolderComponent : public Component
  58325. {
  58326. public:
  58327. PropertyHolderComponent()
  58328. {
  58329. }
  58330. ~PropertyHolderComponent()
  58331. {
  58332. deleteAllChildren();
  58333. }
  58334. void paint (Graphics&)
  58335. {
  58336. }
  58337. void updateLayout (int width);
  58338. void refreshAll() const;
  58339. private:
  58340. PropertyHolderComponent (const PropertyHolderComponent&);
  58341. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58342. };
  58343. class PropertySectionComponent : public Component
  58344. {
  58345. public:
  58346. PropertySectionComponent (const String& sectionTitle,
  58347. const Array <PropertyComponent*>& newProperties,
  58348. const bool open)
  58349. : Component (sectionTitle),
  58350. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58351. isOpen_ (open)
  58352. {
  58353. for (int i = newProperties.size(); --i >= 0;)
  58354. {
  58355. addAndMakeVisible (newProperties.getUnchecked(i));
  58356. newProperties.getUnchecked(i)->refresh();
  58357. }
  58358. }
  58359. ~PropertySectionComponent()
  58360. {
  58361. deleteAllChildren();
  58362. }
  58363. void paint (Graphics& g)
  58364. {
  58365. if (titleHeight > 0)
  58366. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58367. }
  58368. void resized()
  58369. {
  58370. int y = titleHeight;
  58371. for (int i = getNumChildComponents(); --i >= 0;)
  58372. {
  58373. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58374. if (pec != 0)
  58375. {
  58376. const int prefH = pec->getPreferredHeight();
  58377. pec->setBounds (1, y, getWidth() - 2, prefH);
  58378. y += prefH;
  58379. }
  58380. }
  58381. }
  58382. int getPreferredHeight() const
  58383. {
  58384. int y = titleHeight;
  58385. if (isOpen())
  58386. {
  58387. for (int i = 0; i < getNumChildComponents(); ++i)
  58388. {
  58389. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58390. if (pec != 0)
  58391. y += pec->getPreferredHeight();
  58392. }
  58393. }
  58394. return y;
  58395. }
  58396. void setOpen (const bool open)
  58397. {
  58398. if (isOpen_ != open)
  58399. {
  58400. isOpen_ = open;
  58401. for (int i = 0; i < getNumChildComponents(); ++i)
  58402. {
  58403. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58404. if (pec != 0)
  58405. pec->setVisible (open);
  58406. }
  58407. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58408. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58409. if (pp != 0)
  58410. pp->resized();
  58411. }
  58412. }
  58413. bool isOpen() const
  58414. {
  58415. return isOpen_;
  58416. }
  58417. void refreshAll() const
  58418. {
  58419. for (int i = 0; i < getNumChildComponents(); ++i)
  58420. {
  58421. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58422. if (pec != 0)
  58423. pec->refresh();
  58424. }
  58425. }
  58426. void mouseDown (const MouseEvent&)
  58427. {
  58428. }
  58429. void mouseUp (const MouseEvent& e)
  58430. {
  58431. if (e.getMouseDownX() < titleHeight
  58432. && e.x < titleHeight
  58433. && e.y < titleHeight
  58434. && e.getNumberOfClicks() != 2)
  58435. {
  58436. setOpen (! isOpen());
  58437. }
  58438. }
  58439. void mouseDoubleClick (const MouseEvent& e)
  58440. {
  58441. if (e.y < titleHeight)
  58442. setOpen (! isOpen());
  58443. }
  58444. private:
  58445. int titleHeight;
  58446. bool isOpen_;
  58447. PropertySectionComponent (const PropertySectionComponent&);
  58448. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58449. };
  58450. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58451. {
  58452. int y = 0;
  58453. for (int i = getNumChildComponents(); --i >= 0;)
  58454. {
  58455. PropertySectionComponent* const section
  58456. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58457. if (section != 0)
  58458. {
  58459. const int prefH = section->getPreferredHeight();
  58460. section->setBounds (0, y, width, prefH);
  58461. y += prefH;
  58462. }
  58463. }
  58464. setSize (width, y);
  58465. repaint();
  58466. }
  58467. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58468. {
  58469. for (int i = getNumChildComponents(); --i >= 0;)
  58470. {
  58471. PropertySectionComponent* const section
  58472. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58473. if (section != 0)
  58474. section->refreshAll();
  58475. }
  58476. }
  58477. PropertyPanel::PropertyPanel()
  58478. {
  58479. messageWhenEmpty = TRANS("(nothing selected)");
  58480. addAndMakeVisible (&viewport);
  58481. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58482. viewport.setFocusContainer (true);
  58483. }
  58484. PropertyPanel::~PropertyPanel()
  58485. {
  58486. clear();
  58487. }
  58488. void PropertyPanel::paint (Graphics& g)
  58489. {
  58490. if (propertyHolderComponent->getNumChildComponents() == 0)
  58491. {
  58492. g.setColour (Colours::black.withAlpha (0.5f));
  58493. g.setFont (14.0f);
  58494. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58495. Justification::centred, true);
  58496. }
  58497. }
  58498. void PropertyPanel::resized()
  58499. {
  58500. viewport.setBounds (getLocalBounds());
  58501. updatePropHolderLayout();
  58502. }
  58503. void PropertyPanel::clear()
  58504. {
  58505. if (propertyHolderComponent->getNumChildComponents() > 0)
  58506. {
  58507. propertyHolderComponent->deleteAllChildren();
  58508. repaint();
  58509. }
  58510. }
  58511. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58512. {
  58513. if (propertyHolderComponent->getNumChildComponents() == 0)
  58514. repaint();
  58515. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58516. newProperties,
  58517. true), 0);
  58518. updatePropHolderLayout();
  58519. }
  58520. void PropertyPanel::addSection (const String& sectionTitle,
  58521. const Array <PropertyComponent*>& newProperties,
  58522. const bool shouldBeOpen)
  58523. {
  58524. jassert (sectionTitle.isNotEmpty());
  58525. if (propertyHolderComponent->getNumChildComponents() == 0)
  58526. repaint();
  58527. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58528. newProperties,
  58529. shouldBeOpen), 0);
  58530. updatePropHolderLayout();
  58531. }
  58532. void PropertyPanel::updatePropHolderLayout() const
  58533. {
  58534. const int maxWidth = viewport.getMaximumVisibleWidth();
  58535. propertyHolderComponent->updateLayout (maxWidth);
  58536. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58537. if (maxWidth != newMaxWidth)
  58538. {
  58539. // need to do this twice because of scrollbars changing the size, etc.
  58540. propertyHolderComponent->updateLayout (newMaxWidth);
  58541. }
  58542. }
  58543. void PropertyPanel::refreshAll() const
  58544. {
  58545. propertyHolderComponent->refreshAll();
  58546. }
  58547. const StringArray PropertyPanel::getSectionNames() const
  58548. {
  58549. StringArray s;
  58550. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58551. {
  58552. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58553. if (section != 0 && section->getName().isNotEmpty())
  58554. s.add (section->getName());
  58555. }
  58556. return s;
  58557. }
  58558. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58559. {
  58560. int index = 0;
  58561. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58562. {
  58563. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58564. if (section != 0 && section->getName().isNotEmpty())
  58565. {
  58566. if (index == sectionIndex)
  58567. return section->isOpen();
  58568. ++index;
  58569. }
  58570. }
  58571. return false;
  58572. }
  58573. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58574. {
  58575. int index = 0;
  58576. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58577. {
  58578. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58579. if (section != 0 && section->getName().isNotEmpty())
  58580. {
  58581. if (index == sectionIndex)
  58582. {
  58583. section->setOpen (shouldBeOpen);
  58584. break;
  58585. }
  58586. ++index;
  58587. }
  58588. }
  58589. }
  58590. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58591. {
  58592. int index = 0;
  58593. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58594. {
  58595. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58596. if (section != 0 && section->getName().isNotEmpty())
  58597. {
  58598. if (index == sectionIndex)
  58599. {
  58600. section->setEnabled (shouldBeEnabled);
  58601. break;
  58602. }
  58603. ++index;
  58604. }
  58605. }
  58606. }
  58607. XmlElement* PropertyPanel::getOpennessState() const
  58608. {
  58609. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58610. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58611. const StringArray sections (getSectionNames());
  58612. for (int i = 0; i < sections.size(); ++i)
  58613. {
  58614. if (sections[i].isNotEmpty())
  58615. {
  58616. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58617. e->setAttribute ("name", sections[i]);
  58618. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58619. }
  58620. }
  58621. return xml;
  58622. }
  58623. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58624. {
  58625. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58626. {
  58627. const StringArray sections (getSectionNames());
  58628. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58629. {
  58630. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58631. e->getBoolAttribute ("open"));
  58632. }
  58633. viewport.setViewPosition (viewport.getViewPositionX(),
  58634. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58635. }
  58636. }
  58637. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58638. {
  58639. if (messageWhenEmpty != newMessage)
  58640. {
  58641. messageWhenEmpty = newMessage;
  58642. repaint();
  58643. }
  58644. }
  58645. const String& PropertyPanel::getMessageWhenEmpty() const
  58646. {
  58647. return messageWhenEmpty;
  58648. }
  58649. END_JUCE_NAMESPACE
  58650. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58651. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58652. BEGIN_JUCE_NAMESPACE
  58653. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58654. const double rangeMin,
  58655. const double rangeMax,
  58656. const double interval,
  58657. const double skewFactor)
  58658. : PropertyComponent (name)
  58659. {
  58660. addAndMakeVisible (&slider);
  58661. slider.setRange (rangeMin, rangeMax, interval);
  58662. slider.setSkewFactor (skewFactor);
  58663. slider.setSliderStyle (Slider::LinearBar);
  58664. slider.addListener (this);
  58665. }
  58666. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58667. const String& name,
  58668. const double rangeMin,
  58669. const double rangeMax,
  58670. const double interval,
  58671. const double skewFactor)
  58672. : PropertyComponent (name)
  58673. {
  58674. addAndMakeVisible (&slider);
  58675. slider.setRange (rangeMin, rangeMax, interval);
  58676. slider.setSkewFactor (skewFactor);
  58677. slider.setSliderStyle (Slider::LinearBar);
  58678. slider.getValueObject().referTo (valueToControl);
  58679. }
  58680. SliderPropertyComponent::~SliderPropertyComponent()
  58681. {
  58682. }
  58683. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58684. {
  58685. }
  58686. double SliderPropertyComponent::getValue() const
  58687. {
  58688. return slider.getValue();
  58689. }
  58690. void SliderPropertyComponent::refresh()
  58691. {
  58692. slider.setValue (getValue(), false);
  58693. }
  58694. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58695. {
  58696. if (getValue() != slider.getValue())
  58697. setValue (slider.getValue());
  58698. }
  58699. END_JUCE_NAMESPACE
  58700. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58701. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58702. BEGIN_JUCE_NAMESPACE
  58703. class TextPropLabel : public Label
  58704. {
  58705. TextPropertyComponent& owner;
  58706. int maxChars;
  58707. bool isMultiline;
  58708. public:
  58709. TextPropLabel (TextPropertyComponent& owner_,
  58710. const int maxChars_, const bool isMultiline_)
  58711. : Label (String::empty, String::empty),
  58712. owner (owner_),
  58713. maxChars (maxChars_),
  58714. isMultiline (isMultiline_)
  58715. {
  58716. setEditable (true, true, false);
  58717. setColour (backgroundColourId, Colours::white);
  58718. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58719. }
  58720. ~TextPropLabel()
  58721. {
  58722. }
  58723. TextEditor* createEditorComponent()
  58724. {
  58725. TextEditor* const textEditor = Label::createEditorComponent();
  58726. textEditor->setInputRestrictions (maxChars);
  58727. if (isMultiline)
  58728. {
  58729. textEditor->setMultiLine (true, true);
  58730. textEditor->setReturnKeyStartsNewLine (true);
  58731. }
  58732. return textEditor;
  58733. }
  58734. void textWasEdited()
  58735. {
  58736. owner.textWasEdited();
  58737. }
  58738. };
  58739. TextPropertyComponent::TextPropertyComponent (const String& name,
  58740. const int maxNumChars,
  58741. const bool isMultiLine)
  58742. : PropertyComponent (name)
  58743. {
  58744. createEditor (maxNumChars, isMultiLine);
  58745. }
  58746. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58747. const String& name,
  58748. const int maxNumChars,
  58749. const bool isMultiLine)
  58750. : PropertyComponent (name)
  58751. {
  58752. createEditor (maxNumChars, isMultiLine);
  58753. textEditor->getTextValue().referTo (valueToControl);
  58754. }
  58755. TextPropertyComponent::~TextPropertyComponent()
  58756. {
  58757. deleteAllChildren();
  58758. }
  58759. void TextPropertyComponent::setText (const String& newText)
  58760. {
  58761. textEditor->setText (newText, true);
  58762. }
  58763. const String TextPropertyComponent::getText() const
  58764. {
  58765. return textEditor->getText();
  58766. }
  58767. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58768. {
  58769. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58770. if (isMultiLine)
  58771. {
  58772. textEditor->setJustificationType (Justification::topLeft);
  58773. preferredHeight = 120;
  58774. }
  58775. }
  58776. void TextPropertyComponent::refresh()
  58777. {
  58778. textEditor->setText (getText(), false);
  58779. }
  58780. void TextPropertyComponent::textWasEdited()
  58781. {
  58782. const String newText (textEditor->getText());
  58783. if (getText() != newText)
  58784. setText (newText);
  58785. }
  58786. END_JUCE_NAMESPACE
  58787. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58788. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58789. BEGIN_JUCE_NAMESPACE
  58790. class SimpleDeviceManagerInputLevelMeter : public Component,
  58791. public Timer
  58792. {
  58793. public:
  58794. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58795. : manager (manager_),
  58796. level (0)
  58797. {
  58798. startTimer (50);
  58799. manager->enableInputLevelMeasurement (true);
  58800. }
  58801. ~SimpleDeviceManagerInputLevelMeter()
  58802. {
  58803. manager->enableInputLevelMeasurement (false);
  58804. }
  58805. void timerCallback()
  58806. {
  58807. const float newLevel = (float) manager->getCurrentInputLevel();
  58808. if (std::abs (level - newLevel) > 0.005f)
  58809. {
  58810. level = newLevel;
  58811. repaint();
  58812. }
  58813. }
  58814. void paint (Graphics& g)
  58815. {
  58816. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58817. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58818. }
  58819. private:
  58820. AudioDeviceManager* const manager;
  58821. float level;
  58822. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58823. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58824. };
  58825. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58826. public ListBoxModel
  58827. {
  58828. public:
  58829. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58830. const String& noItemsMessage_,
  58831. const int minNumber_,
  58832. const int maxNumber_)
  58833. : ListBox (String::empty, 0),
  58834. deviceManager (deviceManager_),
  58835. noItemsMessage (noItemsMessage_),
  58836. minNumber (minNumber_),
  58837. maxNumber (maxNumber_)
  58838. {
  58839. items = MidiInput::getDevices();
  58840. setModel (this);
  58841. setOutlineThickness (1);
  58842. }
  58843. ~MidiInputSelectorComponentListBox()
  58844. {
  58845. }
  58846. int getNumRows()
  58847. {
  58848. return items.size();
  58849. }
  58850. void paintListBoxItem (int row,
  58851. Graphics& g,
  58852. int width, int height,
  58853. bool rowIsSelected)
  58854. {
  58855. if (((unsigned int) row) < (unsigned int) items.size())
  58856. {
  58857. if (rowIsSelected)
  58858. g.fillAll (findColour (TextEditor::highlightColourId)
  58859. .withMultipliedAlpha (0.3f));
  58860. const String item (items [row]);
  58861. bool enabled = deviceManager.isMidiInputEnabled (item);
  58862. const int x = getTickX();
  58863. const float tickW = height * 0.75f;
  58864. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58865. enabled, true, true, false);
  58866. g.setFont (height * 0.6f);
  58867. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58868. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58869. }
  58870. }
  58871. void listBoxItemClicked (int row, const MouseEvent& e)
  58872. {
  58873. selectRow (row);
  58874. if (e.x < getTickX())
  58875. flipEnablement (row);
  58876. }
  58877. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58878. {
  58879. flipEnablement (row);
  58880. }
  58881. void returnKeyPressed (int row)
  58882. {
  58883. flipEnablement (row);
  58884. }
  58885. void paint (Graphics& g)
  58886. {
  58887. ListBox::paint (g);
  58888. if (items.size() == 0)
  58889. {
  58890. g.setColour (Colours::grey);
  58891. g.setFont (13.0f);
  58892. g.drawText (noItemsMessage,
  58893. 0, 0, getWidth(), getHeight() / 2,
  58894. Justification::centred, true);
  58895. }
  58896. }
  58897. int getBestHeight (const int preferredHeight)
  58898. {
  58899. const int extra = getOutlineThickness() * 2;
  58900. return jmax (getRowHeight() * 2 + extra,
  58901. jmin (getRowHeight() * getNumRows() + extra,
  58902. preferredHeight));
  58903. }
  58904. juce_UseDebuggingNewOperator
  58905. private:
  58906. AudioDeviceManager& deviceManager;
  58907. const String noItemsMessage;
  58908. StringArray items;
  58909. int minNumber, maxNumber;
  58910. void flipEnablement (const int row)
  58911. {
  58912. if (((unsigned int) row) < (unsigned int) items.size())
  58913. {
  58914. const String item (items [row]);
  58915. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58916. }
  58917. }
  58918. int getTickX() const
  58919. {
  58920. return getRowHeight() + 5;
  58921. }
  58922. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58923. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58924. };
  58925. class AudioDeviceSettingsPanel : public Component,
  58926. public ChangeListener,
  58927. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58928. public ButtonListener
  58929. {
  58930. public:
  58931. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58932. AudioIODeviceType::DeviceSetupDetails& setup_,
  58933. const bool hideAdvancedOptionsWithButton)
  58934. : type (type_),
  58935. setup (setup_)
  58936. {
  58937. if (hideAdvancedOptionsWithButton)
  58938. {
  58939. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58940. showAdvancedSettingsButton->addButtonListener (this);
  58941. }
  58942. type->scanForDevices();
  58943. setup.manager->addChangeListener (this);
  58944. changeListenerCallback (0);
  58945. }
  58946. ~AudioDeviceSettingsPanel()
  58947. {
  58948. setup.manager->removeChangeListener (this);
  58949. }
  58950. void resized()
  58951. {
  58952. const int lx = proportionOfWidth (0.35f);
  58953. const int w = proportionOfWidth (0.4f);
  58954. const int h = 24;
  58955. const int space = 6;
  58956. const int dh = h + space;
  58957. int y = 0;
  58958. if (outputDeviceDropDown != 0)
  58959. {
  58960. outputDeviceDropDown->setBounds (lx, y, w, h);
  58961. if (testButton != 0)
  58962. testButton->setBounds (proportionOfWidth (0.77f),
  58963. outputDeviceDropDown->getY(),
  58964. proportionOfWidth (0.18f),
  58965. h);
  58966. y += dh;
  58967. }
  58968. if (inputDeviceDropDown != 0)
  58969. {
  58970. inputDeviceDropDown->setBounds (lx, y, w, h);
  58971. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58972. inputDeviceDropDown->getY(),
  58973. proportionOfWidth (0.18f),
  58974. h);
  58975. y += dh;
  58976. }
  58977. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58978. if (outputChanList != 0)
  58979. {
  58980. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58981. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58982. y += bh + space;
  58983. }
  58984. if (inputChanList != 0)
  58985. {
  58986. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58987. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58988. y += bh + space;
  58989. }
  58990. y += space * 2;
  58991. if (showAdvancedSettingsButton != 0)
  58992. {
  58993. showAdvancedSettingsButton->changeWidthToFitText (h);
  58994. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58995. }
  58996. if (sampleRateDropDown != 0)
  58997. {
  58998. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58999. || ! showAdvancedSettingsButton->isVisible());
  59000. sampleRateDropDown->setBounds (lx, y, w, h);
  59001. y += dh;
  59002. }
  59003. if (bufferSizeDropDown != 0)
  59004. {
  59005. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59006. || ! showAdvancedSettingsButton->isVisible());
  59007. bufferSizeDropDown->setBounds (lx, y, w, h);
  59008. y += dh;
  59009. }
  59010. if (showUIButton != 0)
  59011. {
  59012. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59013. || ! showAdvancedSettingsButton->isVisible());
  59014. showUIButton->changeWidthToFitText (h);
  59015. showUIButton->setTopLeftPosition (lx, y);
  59016. }
  59017. }
  59018. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59019. {
  59020. if (comboBoxThatHasChanged == 0)
  59021. return;
  59022. AudioDeviceManager::AudioDeviceSetup config;
  59023. setup.manager->getAudioDeviceSetup (config);
  59024. String error;
  59025. if (comboBoxThatHasChanged == outputDeviceDropDown
  59026. || comboBoxThatHasChanged == inputDeviceDropDown)
  59027. {
  59028. if (outputDeviceDropDown != 0)
  59029. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59030. : outputDeviceDropDown->getText();
  59031. if (inputDeviceDropDown != 0)
  59032. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59033. : inputDeviceDropDown->getText();
  59034. if (! type->hasSeparateInputsAndOutputs())
  59035. config.inputDeviceName = config.outputDeviceName;
  59036. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59037. config.useDefaultInputChannels = true;
  59038. else
  59039. config.useDefaultOutputChannels = true;
  59040. error = setup.manager->setAudioDeviceSetup (config, true);
  59041. showCorrectDeviceName (inputDeviceDropDown, true);
  59042. showCorrectDeviceName (outputDeviceDropDown, false);
  59043. updateControlPanelButton();
  59044. resized();
  59045. }
  59046. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59047. {
  59048. if (sampleRateDropDown->getSelectedId() > 0)
  59049. {
  59050. config.sampleRate = sampleRateDropDown->getSelectedId();
  59051. error = setup.manager->setAudioDeviceSetup (config, true);
  59052. }
  59053. }
  59054. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59055. {
  59056. if (bufferSizeDropDown->getSelectedId() > 0)
  59057. {
  59058. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59059. error = setup.manager->setAudioDeviceSetup (config, true);
  59060. }
  59061. }
  59062. if (error.isNotEmpty())
  59063. {
  59064. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59065. "Error when trying to open audio device!",
  59066. error);
  59067. }
  59068. }
  59069. void buttonClicked (Button* button)
  59070. {
  59071. if (button == showAdvancedSettingsButton)
  59072. {
  59073. showAdvancedSettingsButton->setVisible (false);
  59074. resized();
  59075. }
  59076. else if (button == showUIButton)
  59077. {
  59078. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59079. if (device != 0 && device->showControlPanel())
  59080. {
  59081. setup.manager->closeAudioDevice();
  59082. setup.manager->restartLastAudioDevice();
  59083. getTopLevelComponent()->toFront (true);
  59084. }
  59085. }
  59086. else if (button == testButton && testButton != 0)
  59087. {
  59088. setup.manager->playTestSound();
  59089. }
  59090. }
  59091. void updateControlPanelButton()
  59092. {
  59093. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59094. showUIButton = 0;
  59095. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59096. {
  59097. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59098. TRANS ("opens the device's own control panel")));
  59099. showUIButton->addButtonListener (this);
  59100. }
  59101. resized();
  59102. }
  59103. void changeListenerCallback (void*)
  59104. {
  59105. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59106. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59107. {
  59108. if (outputDeviceDropDown == 0)
  59109. {
  59110. outputDeviceDropDown = new ComboBox (String::empty);
  59111. outputDeviceDropDown->addListener (this);
  59112. addAndMakeVisible (outputDeviceDropDown);
  59113. outputDeviceLabel = new Label (String::empty,
  59114. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59115. : TRANS ("device:"));
  59116. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59117. if (setup.maxNumOutputChannels > 0)
  59118. {
  59119. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59120. testButton->addButtonListener (this);
  59121. }
  59122. }
  59123. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59124. }
  59125. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59126. {
  59127. if (inputDeviceDropDown == 0)
  59128. {
  59129. inputDeviceDropDown = new ComboBox (String::empty);
  59130. inputDeviceDropDown->addListener (this);
  59131. addAndMakeVisible (inputDeviceDropDown);
  59132. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59133. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59134. addAndMakeVisible (inputLevelMeter
  59135. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59136. }
  59137. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59138. }
  59139. updateControlPanelButton();
  59140. showCorrectDeviceName (inputDeviceDropDown, true);
  59141. showCorrectDeviceName (outputDeviceDropDown, false);
  59142. if (currentDevice != 0)
  59143. {
  59144. if (setup.maxNumOutputChannels > 0
  59145. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59146. {
  59147. if (outputChanList == 0)
  59148. {
  59149. addAndMakeVisible (outputChanList
  59150. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59151. TRANS ("(no audio output channels found)")));
  59152. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59153. outputChanLabel->attachToComponent (outputChanList, true);
  59154. }
  59155. outputChanList->refresh();
  59156. }
  59157. else
  59158. {
  59159. outputChanLabel = 0;
  59160. outputChanList = 0;
  59161. }
  59162. if (setup.maxNumInputChannels > 0
  59163. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59164. {
  59165. if (inputChanList == 0)
  59166. {
  59167. addAndMakeVisible (inputChanList
  59168. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59169. TRANS ("(no audio input channels found)")));
  59170. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59171. inputChanLabel->attachToComponent (inputChanList, true);
  59172. }
  59173. inputChanList->refresh();
  59174. }
  59175. else
  59176. {
  59177. inputChanLabel = 0;
  59178. inputChanList = 0;
  59179. }
  59180. // sample rate..
  59181. {
  59182. if (sampleRateDropDown == 0)
  59183. {
  59184. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59185. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59186. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59187. }
  59188. else
  59189. {
  59190. sampleRateDropDown->clear();
  59191. sampleRateDropDown->removeListener (this);
  59192. }
  59193. const int numRates = currentDevice->getNumSampleRates();
  59194. for (int i = 0; i < numRates; ++i)
  59195. {
  59196. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59197. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59198. }
  59199. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59200. sampleRateDropDown->addListener (this);
  59201. }
  59202. // buffer size
  59203. {
  59204. if (bufferSizeDropDown == 0)
  59205. {
  59206. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59207. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59208. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59209. }
  59210. else
  59211. {
  59212. bufferSizeDropDown->clear();
  59213. bufferSizeDropDown->removeListener (this);
  59214. }
  59215. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59216. double currentRate = currentDevice->getCurrentSampleRate();
  59217. if (currentRate == 0)
  59218. currentRate = 48000.0;
  59219. for (int i = 0; i < numBufferSizes; ++i)
  59220. {
  59221. const int bs = currentDevice->getBufferSizeSamples (i);
  59222. bufferSizeDropDown->addItem (String (bs)
  59223. + " samples ("
  59224. + String (bs * 1000.0 / currentRate, 1)
  59225. + " ms)",
  59226. bs);
  59227. }
  59228. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59229. bufferSizeDropDown->addListener (this);
  59230. }
  59231. }
  59232. else
  59233. {
  59234. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59235. sampleRateLabel = 0;
  59236. bufferSizeLabel = 0;
  59237. sampleRateDropDown = 0;
  59238. bufferSizeDropDown = 0;
  59239. if (outputDeviceDropDown != 0)
  59240. outputDeviceDropDown->setSelectedId (-1, true);
  59241. if (inputDeviceDropDown != 0)
  59242. inputDeviceDropDown->setSelectedId (-1, true);
  59243. }
  59244. resized();
  59245. setSize (getWidth(), getLowestY() + 4);
  59246. }
  59247. private:
  59248. AudioIODeviceType* const type;
  59249. const AudioIODeviceType::DeviceSetupDetails setup;
  59250. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59251. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59252. ScopedPointer<TextButton> testButton;
  59253. ScopedPointer<Component> inputLevelMeter;
  59254. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59255. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59256. {
  59257. if (box != 0)
  59258. {
  59259. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59260. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59261. box->setSelectedId (index + 1, true);
  59262. if (testButton != 0 && ! isInput)
  59263. testButton->setEnabled (index >= 0);
  59264. }
  59265. }
  59266. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59267. {
  59268. const StringArray devs (type->getDeviceNames (isInputs));
  59269. combo.clear (true);
  59270. for (int i = 0; i < devs.size(); ++i)
  59271. combo.addItem (devs[i], i + 1);
  59272. combo.addItem (TRANS("<< none >>"), -1);
  59273. combo.setSelectedId (-1, true);
  59274. }
  59275. int getLowestY() const
  59276. {
  59277. int y = 0;
  59278. for (int i = getNumChildComponents(); --i >= 0;)
  59279. y = jmax (y, getChildComponent (i)->getBottom());
  59280. return y;
  59281. }
  59282. public:
  59283. class ChannelSelectorListBox : public ListBox,
  59284. public ListBoxModel
  59285. {
  59286. public:
  59287. enum BoxType
  59288. {
  59289. audioInputType,
  59290. audioOutputType
  59291. };
  59292. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59293. const BoxType type_,
  59294. const String& noItemsMessage_)
  59295. : ListBox (String::empty, 0),
  59296. setup (setup_),
  59297. type (type_),
  59298. noItemsMessage (noItemsMessage_)
  59299. {
  59300. refresh();
  59301. setModel (this);
  59302. setOutlineThickness (1);
  59303. }
  59304. ~ChannelSelectorListBox()
  59305. {
  59306. }
  59307. void refresh()
  59308. {
  59309. items.clear();
  59310. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59311. if (currentDevice != 0)
  59312. {
  59313. if (type == audioInputType)
  59314. items = currentDevice->getInputChannelNames();
  59315. else if (type == audioOutputType)
  59316. items = currentDevice->getOutputChannelNames();
  59317. if (setup.useStereoPairs)
  59318. {
  59319. StringArray pairs;
  59320. for (int i = 0; i < items.size(); i += 2)
  59321. {
  59322. const String name (items[i]);
  59323. const String name2 (items[i + 1]);
  59324. String commonBit;
  59325. for (int j = 0; j < name.length(); ++j)
  59326. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59327. commonBit = name.substring (0, j);
  59328. // Make sure we only split the name at a space, because otherwise, things
  59329. // like "input 11" + "input 12" would become "input 11 + 2"
  59330. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59331. commonBit = commonBit.dropLastCharacters (1);
  59332. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59333. }
  59334. items = pairs;
  59335. }
  59336. }
  59337. updateContent();
  59338. repaint();
  59339. }
  59340. int getNumRows()
  59341. {
  59342. return items.size();
  59343. }
  59344. void paintListBoxItem (int row,
  59345. Graphics& g,
  59346. int width, int height,
  59347. bool rowIsSelected)
  59348. {
  59349. if (((unsigned int) row) < (unsigned int) items.size())
  59350. {
  59351. if (rowIsSelected)
  59352. g.fillAll (findColour (TextEditor::highlightColourId)
  59353. .withMultipliedAlpha (0.3f));
  59354. const String item (items [row]);
  59355. bool enabled = false;
  59356. AudioDeviceManager::AudioDeviceSetup config;
  59357. setup.manager->getAudioDeviceSetup (config);
  59358. if (setup.useStereoPairs)
  59359. {
  59360. if (type == audioInputType)
  59361. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59362. else if (type == audioOutputType)
  59363. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59364. }
  59365. else
  59366. {
  59367. if (type == audioInputType)
  59368. enabled = config.inputChannels [row];
  59369. else if (type == audioOutputType)
  59370. enabled = config.outputChannels [row];
  59371. }
  59372. const int x = getTickX();
  59373. const float tickW = height * 0.75f;
  59374. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59375. enabled, true, true, false);
  59376. g.setFont (height * 0.6f);
  59377. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59378. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59379. }
  59380. }
  59381. void listBoxItemClicked (int row, const MouseEvent& e)
  59382. {
  59383. selectRow (row);
  59384. if (e.x < getTickX())
  59385. flipEnablement (row);
  59386. }
  59387. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59388. {
  59389. flipEnablement (row);
  59390. }
  59391. void returnKeyPressed (int row)
  59392. {
  59393. flipEnablement (row);
  59394. }
  59395. void paint (Graphics& g)
  59396. {
  59397. ListBox::paint (g);
  59398. if (items.size() == 0)
  59399. {
  59400. g.setColour (Colours::grey);
  59401. g.setFont (13.0f);
  59402. g.drawText (noItemsMessage,
  59403. 0, 0, getWidth(), getHeight() / 2,
  59404. Justification::centred, true);
  59405. }
  59406. }
  59407. int getBestHeight (int maxHeight)
  59408. {
  59409. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59410. getNumRows())
  59411. + getOutlineThickness() * 2;
  59412. }
  59413. juce_UseDebuggingNewOperator
  59414. private:
  59415. const AudioIODeviceType::DeviceSetupDetails setup;
  59416. const BoxType type;
  59417. const String noItemsMessage;
  59418. StringArray items;
  59419. void flipEnablement (const int row)
  59420. {
  59421. jassert (type == audioInputType || type == audioOutputType);
  59422. if (((unsigned int) row) < (unsigned int) items.size())
  59423. {
  59424. AudioDeviceManager::AudioDeviceSetup config;
  59425. setup.manager->getAudioDeviceSetup (config);
  59426. if (setup.useStereoPairs)
  59427. {
  59428. BigInteger bits;
  59429. BigInteger& original = (type == audioInputType ? config.inputChannels
  59430. : config.outputChannels);
  59431. int i;
  59432. for (i = 0; i < 256; i += 2)
  59433. bits.setBit (i / 2, original [i] || original [i + 1]);
  59434. if (type == audioInputType)
  59435. {
  59436. config.useDefaultInputChannels = false;
  59437. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59438. }
  59439. else
  59440. {
  59441. config.useDefaultOutputChannels = false;
  59442. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59443. }
  59444. for (i = 0; i < 256; ++i)
  59445. original.setBit (i, bits [i / 2]);
  59446. }
  59447. else
  59448. {
  59449. if (type == audioInputType)
  59450. {
  59451. config.useDefaultInputChannels = false;
  59452. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59453. }
  59454. else
  59455. {
  59456. config.useDefaultOutputChannels = false;
  59457. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59458. }
  59459. }
  59460. String error (setup.manager->setAudioDeviceSetup (config, true));
  59461. if (! error.isEmpty())
  59462. {
  59463. //xxx
  59464. }
  59465. }
  59466. }
  59467. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59468. {
  59469. const int numActive = chans.countNumberOfSetBits();
  59470. if (chans [index])
  59471. {
  59472. if (numActive > minNumber)
  59473. chans.setBit (index, false);
  59474. }
  59475. else
  59476. {
  59477. if (numActive >= maxNumber)
  59478. {
  59479. const int firstActiveChan = chans.findNextSetBit();
  59480. chans.setBit (index > firstActiveChan
  59481. ? firstActiveChan : chans.getHighestBit(),
  59482. false);
  59483. }
  59484. chans.setBit (index, true);
  59485. }
  59486. }
  59487. int getTickX() const
  59488. {
  59489. return getRowHeight() + 5;
  59490. }
  59491. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59492. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59493. };
  59494. private:
  59495. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59496. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59497. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59498. };
  59499. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59500. const int minInputChannels_,
  59501. const int maxInputChannels_,
  59502. const int minOutputChannels_,
  59503. const int maxOutputChannels_,
  59504. const bool showMidiInputOptions,
  59505. const bool showMidiOutputSelector,
  59506. const bool showChannelsAsStereoPairs_,
  59507. const bool hideAdvancedOptionsWithButton_)
  59508. : deviceManager (deviceManager_),
  59509. deviceTypeDropDown (0),
  59510. deviceTypeDropDownLabel (0),
  59511. minOutputChannels (minOutputChannels_),
  59512. maxOutputChannels (maxOutputChannels_),
  59513. minInputChannels (minInputChannels_),
  59514. maxInputChannels (maxInputChannels_),
  59515. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59516. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59517. {
  59518. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59519. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59520. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59521. {
  59522. deviceTypeDropDown = new ComboBox (String::empty);
  59523. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59524. {
  59525. deviceTypeDropDown
  59526. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59527. i + 1);
  59528. }
  59529. addAndMakeVisible (deviceTypeDropDown);
  59530. deviceTypeDropDown->addListener (this);
  59531. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59532. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59533. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59534. }
  59535. if (showMidiInputOptions)
  59536. {
  59537. addAndMakeVisible (midiInputsList
  59538. = new MidiInputSelectorComponentListBox (deviceManager,
  59539. TRANS("(no midi inputs available)"),
  59540. 0, 0));
  59541. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59542. midiInputsLabel->setJustificationType (Justification::topRight);
  59543. midiInputsLabel->attachToComponent (midiInputsList, true);
  59544. }
  59545. else
  59546. {
  59547. midiInputsList = 0;
  59548. midiInputsLabel = 0;
  59549. }
  59550. if (showMidiOutputSelector)
  59551. {
  59552. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59553. midiOutputSelector->addListener (this);
  59554. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59555. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59556. }
  59557. else
  59558. {
  59559. midiOutputSelector = 0;
  59560. midiOutputLabel = 0;
  59561. }
  59562. deviceManager_.addChangeListener (this);
  59563. changeListenerCallback (0);
  59564. }
  59565. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59566. {
  59567. deviceManager.removeChangeListener (this);
  59568. }
  59569. void AudioDeviceSelectorComponent::resized()
  59570. {
  59571. const int lx = proportionOfWidth (0.35f);
  59572. const int w = proportionOfWidth (0.4f);
  59573. const int h = 24;
  59574. const int space = 6;
  59575. const int dh = h + space;
  59576. int y = 15;
  59577. if (deviceTypeDropDown != 0)
  59578. {
  59579. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59580. y += dh + space * 2;
  59581. }
  59582. if (audioDeviceSettingsComp != 0)
  59583. {
  59584. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59585. y += audioDeviceSettingsComp->getHeight() + space;
  59586. }
  59587. if (midiInputsList != 0)
  59588. {
  59589. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59590. midiInputsList->setBounds (lx, y, w, bh);
  59591. y += bh + space;
  59592. }
  59593. if (midiOutputSelector != 0)
  59594. midiOutputSelector->setBounds (lx, y, w, h);
  59595. }
  59596. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59597. {
  59598. if (child == audioDeviceSettingsComp)
  59599. resized();
  59600. }
  59601. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59602. {
  59603. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59604. if (device != 0 && device->hasControlPanel())
  59605. {
  59606. if (device->showControlPanel())
  59607. deviceManager.restartLastAudioDevice();
  59608. getTopLevelComponent()->toFront (true);
  59609. }
  59610. }
  59611. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59612. {
  59613. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59614. {
  59615. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59616. if (type != 0)
  59617. {
  59618. audioDeviceSettingsComp = 0;
  59619. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59620. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59621. }
  59622. }
  59623. else if (comboBoxThatHasChanged == midiOutputSelector)
  59624. {
  59625. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59626. }
  59627. }
  59628. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59629. {
  59630. if (deviceTypeDropDown != 0)
  59631. {
  59632. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59633. }
  59634. if (audioDeviceSettingsComp == 0
  59635. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59636. {
  59637. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59638. audioDeviceSettingsComp = 0;
  59639. AudioIODeviceType* const type
  59640. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59641. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59642. if (type != 0)
  59643. {
  59644. AudioIODeviceType::DeviceSetupDetails details;
  59645. details.manager = &deviceManager;
  59646. details.minNumInputChannels = minInputChannels;
  59647. details.maxNumInputChannels = maxInputChannels;
  59648. details.minNumOutputChannels = minOutputChannels;
  59649. details.maxNumOutputChannels = maxOutputChannels;
  59650. details.useStereoPairs = showChannelsAsStereoPairs;
  59651. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59652. if (audioDeviceSettingsComp != 0)
  59653. {
  59654. addAndMakeVisible (audioDeviceSettingsComp);
  59655. audioDeviceSettingsComp->resized();
  59656. }
  59657. }
  59658. }
  59659. if (midiInputsList != 0)
  59660. {
  59661. midiInputsList->updateContent();
  59662. midiInputsList->repaint();
  59663. }
  59664. if (midiOutputSelector != 0)
  59665. {
  59666. midiOutputSelector->clear();
  59667. const StringArray midiOuts (MidiOutput::getDevices());
  59668. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59669. midiOutputSelector->addSeparator();
  59670. for (int i = 0; i < midiOuts.size(); ++i)
  59671. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59672. int current = -1;
  59673. if (deviceManager.getDefaultMidiOutput() != 0)
  59674. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59675. midiOutputSelector->setSelectedId (current, true);
  59676. }
  59677. resized();
  59678. }
  59679. END_JUCE_NAMESPACE
  59680. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59681. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59682. BEGIN_JUCE_NAMESPACE
  59683. BubbleComponent::BubbleComponent()
  59684. : side (0),
  59685. allowablePlacements (above | below | left | right),
  59686. arrowTipX (0.0f),
  59687. arrowTipY (0.0f)
  59688. {
  59689. setInterceptsMouseClicks (false, false);
  59690. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59691. setComponentEffect (&shadow);
  59692. }
  59693. BubbleComponent::~BubbleComponent()
  59694. {
  59695. }
  59696. void BubbleComponent::paint (Graphics& g)
  59697. {
  59698. int x = content.getX();
  59699. int y = content.getY();
  59700. int w = content.getWidth();
  59701. int h = content.getHeight();
  59702. int cw, ch;
  59703. getContentSize (cw, ch);
  59704. if (side == 3)
  59705. x += w - cw;
  59706. else if (side != 1)
  59707. x += (w - cw) / 2;
  59708. w = cw;
  59709. if (side == 2)
  59710. y += h - ch;
  59711. else if (side != 0)
  59712. y += (h - ch) / 2;
  59713. h = ch;
  59714. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59715. (float) x, (float) y,
  59716. (float) w, (float) h);
  59717. const int cx = x + (w - cw) / 2;
  59718. const int cy = y + (h - ch) / 2;
  59719. const int indent = 3;
  59720. g.setOrigin (cx + indent, cy + indent);
  59721. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59722. paintContent (g, cw - indent * 2, ch - indent * 2);
  59723. }
  59724. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59725. {
  59726. allowablePlacements = newPlacement;
  59727. }
  59728. void BubbleComponent::setPosition (Component* componentToPointTo)
  59729. {
  59730. jassert (componentToPointTo->isValidComponent());
  59731. Point<int> pos;
  59732. if (getParentComponent() != 0)
  59733. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59734. else
  59735. pos = componentToPointTo->relativePositionToGlobal (pos);
  59736. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59737. }
  59738. void BubbleComponent::setPosition (const int arrowTipX_,
  59739. const int arrowTipY_)
  59740. {
  59741. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59742. }
  59743. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59744. {
  59745. Rectangle<int> availableSpace;
  59746. if (getParentComponent() != 0)
  59747. {
  59748. availableSpace.setSize (getParentComponent()->getWidth(),
  59749. getParentComponent()->getHeight());
  59750. }
  59751. else
  59752. {
  59753. availableSpace = getParentMonitorArea();
  59754. }
  59755. int x = 0;
  59756. int y = 0;
  59757. int w = 150;
  59758. int h = 30;
  59759. getContentSize (w, h);
  59760. w += 30;
  59761. h += 30;
  59762. const float edgeIndent = 2.0f;
  59763. const int arrowLength = jmin (10, h / 3, w / 3);
  59764. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59765. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59766. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59767. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59768. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59769. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59770. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59771. {
  59772. spaceLeft = spaceRight = 0;
  59773. }
  59774. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59775. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59776. {
  59777. spaceAbove = spaceBelow = 0;
  59778. }
  59779. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59780. {
  59781. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59782. arrowTipX = w * 0.5f;
  59783. content.setSize (w, h - arrowLength);
  59784. if (spaceAbove >= spaceBelow)
  59785. {
  59786. // above
  59787. y = rectangleToPointTo.getY() - h;
  59788. content.setPosition (0, 0);
  59789. arrowTipY = h - edgeIndent;
  59790. side = 2;
  59791. }
  59792. else
  59793. {
  59794. // below
  59795. y = rectangleToPointTo.getBottom();
  59796. content.setPosition (0, arrowLength);
  59797. arrowTipY = edgeIndent;
  59798. side = 0;
  59799. }
  59800. }
  59801. else
  59802. {
  59803. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59804. arrowTipY = h * 0.5f;
  59805. content.setSize (w - arrowLength, h);
  59806. if (spaceLeft > spaceRight)
  59807. {
  59808. // on the left
  59809. x = rectangleToPointTo.getX() - w;
  59810. content.setPosition (0, 0);
  59811. arrowTipX = w - edgeIndent;
  59812. side = 3;
  59813. }
  59814. else
  59815. {
  59816. // on the right
  59817. x = rectangleToPointTo.getRight();
  59818. content.setPosition (arrowLength, 0);
  59819. arrowTipX = edgeIndent;
  59820. side = 1;
  59821. }
  59822. }
  59823. setBounds (x, y, w, h);
  59824. }
  59825. END_JUCE_NAMESPACE
  59826. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59827. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59828. BEGIN_JUCE_NAMESPACE
  59829. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59830. : fadeOutLength (fadeOutLengthMs),
  59831. deleteAfterUse (false)
  59832. {
  59833. }
  59834. BubbleMessageComponent::~BubbleMessageComponent()
  59835. {
  59836. fadeOutComponent (fadeOutLength);
  59837. }
  59838. void BubbleMessageComponent::showAt (int x, int y,
  59839. const String& text,
  59840. const int numMillisecondsBeforeRemoving,
  59841. const bool removeWhenMouseClicked,
  59842. const bool deleteSelfAfterUse)
  59843. {
  59844. textLayout.clear();
  59845. textLayout.setText (text, Font (14.0f));
  59846. textLayout.layout (256, Justification::centredLeft, true);
  59847. setPosition (x, y);
  59848. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59849. }
  59850. void BubbleMessageComponent::showAt (Component* const component,
  59851. const String& text,
  59852. const int numMillisecondsBeforeRemoving,
  59853. const bool removeWhenMouseClicked,
  59854. const bool deleteSelfAfterUse)
  59855. {
  59856. textLayout.clear();
  59857. textLayout.setText (text, Font (14.0f));
  59858. textLayout.layout (256, Justification::centredLeft, true);
  59859. setPosition (component);
  59860. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59861. }
  59862. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59863. const bool removeWhenMouseClicked,
  59864. const bool deleteSelfAfterUse)
  59865. {
  59866. setVisible (true);
  59867. deleteAfterUse = deleteSelfAfterUse;
  59868. if (numMillisecondsBeforeRemoving > 0)
  59869. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59870. else
  59871. expiryTime = 0;
  59872. startTimer (77);
  59873. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59874. if (! (removeWhenMouseClicked && isShowing()))
  59875. mouseClickCounter += 0xfffff;
  59876. repaint();
  59877. }
  59878. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59879. {
  59880. w = textLayout.getWidth() + 16;
  59881. h = textLayout.getHeight() + 16;
  59882. }
  59883. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59884. {
  59885. g.setColour (findColour (TooltipWindow::textColourId));
  59886. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59887. }
  59888. void BubbleMessageComponent::timerCallback()
  59889. {
  59890. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59891. {
  59892. stopTimer();
  59893. setVisible (false);
  59894. if (deleteAfterUse)
  59895. delete this;
  59896. }
  59897. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59898. {
  59899. stopTimer();
  59900. fadeOutComponent (fadeOutLength);
  59901. if (deleteAfterUse)
  59902. delete this;
  59903. }
  59904. }
  59905. END_JUCE_NAMESPACE
  59906. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59907. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59908. BEGIN_JUCE_NAMESPACE
  59909. class ColourComponentSlider : public Slider
  59910. {
  59911. public:
  59912. ColourComponentSlider (const String& name)
  59913. : Slider (name)
  59914. {
  59915. setRange (0.0, 255.0, 1.0);
  59916. }
  59917. ~ColourComponentSlider()
  59918. {
  59919. }
  59920. const String getTextFromValue (double value)
  59921. {
  59922. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59923. }
  59924. double getValueFromText (const String& text)
  59925. {
  59926. return (double) text.getHexValue32();
  59927. }
  59928. private:
  59929. ColourComponentSlider (const ColourComponentSlider&);
  59930. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59931. };
  59932. class ColourSpaceMarker : public Component
  59933. {
  59934. public:
  59935. ColourSpaceMarker()
  59936. {
  59937. setInterceptsMouseClicks (false, false);
  59938. }
  59939. ~ColourSpaceMarker()
  59940. {
  59941. }
  59942. void paint (Graphics& g)
  59943. {
  59944. g.setColour (Colour::greyLevel (0.1f));
  59945. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59946. g.setColour (Colour::greyLevel (0.9f));
  59947. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59948. }
  59949. private:
  59950. ColourSpaceMarker (const ColourSpaceMarker&);
  59951. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59952. };
  59953. class ColourSelector::ColourSpaceView : public Component
  59954. {
  59955. public:
  59956. ColourSpaceView (ColourSelector* owner_,
  59957. float& h_, float& s_, float& v_,
  59958. const int edgeSize)
  59959. : owner (owner_),
  59960. h (h_), s (s_), v (v_),
  59961. lastHue (0.0f),
  59962. edge (edgeSize)
  59963. {
  59964. addAndMakeVisible (&marker);
  59965. setMouseCursor (MouseCursor::CrosshairCursor);
  59966. }
  59967. ~ColourSpaceView()
  59968. {
  59969. }
  59970. void paint (Graphics& g)
  59971. {
  59972. if (colours.isNull())
  59973. {
  59974. const int width = getWidth() / 2;
  59975. const int height = getHeight() / 2;
  59976. colours = Image (Image::RGB, width, height, false);
  59977. Image::BitmapData pixels (colours, true);
  59978. for (int y = 0; y < height; ++y)
  59979. {
  59980. const float val = 1.0f - y / (float) height;
  59981. for (int x = 0; x < width; ++x)
  59982. {
  59983. const float sat = x / (float) width;
  59984. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59985. }
  59986. }
  59987. }
  59988. g.setOpacity (1.0f);
  59989. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59990. 0, 0, colours.getWidth(), colours.getHeight());
  59991. }
  59992. void mouseDown (const MouseEvent& e)
  59993. {
  59994. mouseDrag (e);
  59995. }
  59996. void mouseDrag (const MouseEvent& e)
  59997. {
  59998. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59999. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60000. owner->setSV (sat, val);
  60001. }
  60002. void updateIfNeeded()
  60003. {
  60004. if (lastHue != h)
  60005. {
  60006. lastHue = h;
  60007. colours = Image::null;
  60008. repaint();
  60009. }
  60010. updateMarker();
  60011. }
  60012. void resized()
  60013. {
  60014. colours = Image::null;
  60015. updateMarker();
  60016. }
  60017. private:
  60018. ColourSelector* const owner;
  60019. float& h;
  60020. float& s;
  60021. float& v;
  60022. float lastHue;
  60023. ColourSpaceMarker marker;
  60024. const int edge;
  60025. Image colours;
  60026. void updateMarker()
  60027. {
  60028. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60029. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60030. edge * 2, edge * 2);
  60031. }
  60032. ColourSpaceView (const ColourSpaceView&);
  60033. ColourSpaceView& operator= (const ColourSpaceView&);
  60034. };
  60035. class HueSelectorMarker : public Component
  60036. {
  60037. public:
  60038. HueSelectorMarker()
  60039. {
  60040. setInterceptsMouseClicks (false, false);
  60041. }
  60042. ~HueSelectorMarker()
  60043. {
  60044. }
  60045. void paint (Graphics& g)
  60046. {
  60047. Path p;
  60048. p.addTriangle (1.0f, 1.0f,
  60049. getWidth() * 0.3f, getHeight() * 0.5f,
  60050. 1.0f, getHeight() - 1.0f);
  60051. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60052. getWidth() * 0.7f, getHeight() * 0.5f,
  60053. getWidth() - 1.0f, getHeight() - 1.0f);
  60054. g.setColour (Colours::white.withAlpha (0.75f));
  60055. g.fillPath (p);
  60056. g.setColour (Colours::black.withAlpha (0.75f));
  60057. g.strokePath (p, PathStrokeType (1.2f));
  60058. }
  60059. private:
  60060. HueSelectorMarker (const HueSelectorMarker&);
  60061. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60062. };
  60063. class ColourSelector::HueSelectorComp : public Component
  60064. {
  60065. public:
  60066. HueSelectorComp (ColourSelector* owner_,
  60067. float& h_, float& s_, float& v_,
  60068. const int edgeSize)
  60069. : owner (owner_),
  60070. h (h_), s (s_), v (v_),
  60071. lastHue (0.0f),
  60072. edge (edgeSize)
  60073. {
  60074. addAndMakeVisible (&marker);
  60075. }
  60076. ~HueSelectorComp()
  60077. {
  60078. }
  60079. void paint (Graphics& g)
  60080. {
  60081. const float yScale = 1.0f / (getHeight() - edge * 2);
  60082. const Rectangle<int> clip (g.getClipBounds());
  60083. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60084. {
  60085. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60086. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60087. }
  60088. }
  60089. void resized()
  60090. {
  60091. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60092. getWidth(), edge * 2);
  60093. }
  60094. void mouseDown (const MouseEvent& e)
  60095. {
  60096. mouseDrag (e);
  60097. }
  60098. void mouseDrag (const MouseEvent& e)
  60099. {
  60100. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60101. owner->setHue (hue);
  60102. }
  60103. void updateIfNeeded()
  60104. {
  60105. resized();
  60106. }
  60107. private:
  60108. ColourSelector* const owner;
  60109. float& h;
  60110. float& s;
  60111. float& v;
  60112. float lastHue;
  60113. HueSelectorMarker marker;
  60114. const int edge;
  60115. HueSelectorComp (const HueSelectorComp&);
  60116. HueSelectorComp& operator= (const HueSelectorComp&);
  60117. };
  60118. class ColourSelector::SwatchComponent : public Component
  60119. {
  60120. public:
  60121. SwatchComponent (ColourSelector* owner_, int index_)
  60122. : owner (owner_),
  60123. index (index_)
  60124. {
  60125. }
  60126. ~SwatchComponent()
  60127. {
  60128. }
  60129. void paint (Graphics& g)
  60130. {
  60131. const Colour colour (owner->getSwatchColour (index));
  60132. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60133. Colour (0xffdddddd).overlaidWith (colour),
  60134. Colour (0xffffffff).overlaidWith (colour));
  60135. }
  60136. void mouseDown (const MouseEvent&)
  60137. {
  60138. PopupMenu m;
  60139. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60140. m.addSeparator();
  60141. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60142. const int r = m.showAt (this);
  60143. if (r == 1)
  60144. {
  60145. owner->setCurrentColour (owner->getSwatchColour (index));
  60146. }
  60147. else if (r == 2)
  60148. {
  60149. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60150. {
  60151. owner->setSwatchColour (index, owner->getCurrentColour());
  60152. repaint();
  60153. }
  60154. }
  60155. }
  60156. private:
  60157. ColourSelector* const owner;
  60158. const int index;
  60159. SwatchComponent (const SwatchComponent&);
  60160. SwatchComponent& operator= (const SwatchComponent&);
  60161. };
  60162. ColourSelector::ColourSelector (const int flags_,
  60163. const int edgeGap_,
  60164. const int gapAroundColourSpaceComponent)
  60165. : colour (Colours::white),
  60166. colourSpace (0),
  60167. hueSelector (0),
  60168. flags (flags_),
  60169. edgeGap (edgeGap_)
  60170. {
  60171. // not much point having a selector with no components in it!
  60172. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60173. updateHSV();
  60174. if ((flags & showSliders) != 0)
  60175. {
  60176. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60177. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60178. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60179. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60180. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60181. for (int i = 4; --i >= 0;)
  60182. sliders[i]->addListener (this);
  60183. }
  60184. else
  60185. {
  60186. zeromem (sliders, sizeof (sliders));
  60187. }
  60188. if ((flags & showColourspace) != 0)
  60189. {
  60190. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60191. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60192. }
  60193. update();
  60194. }
  60195. ColourSelector::~ColourSelector()
  60196. {
  60197. dispatchPendingMessages();
  60198. swatchComponents.clear();
  60199. deleteAllChildren();
  60200. }
  60201. const Colour ColourSelector::getCurrentColour() const
  60202. {
  60203. return ((flags & showAlphaChannel) != 0) ? colour
  60204. : colour.withAlpha ((uint8) 0xff);
  60205. }
  60206. void ColourSelector::setCurrentColour (const Colour& c)
  60207. {
  60208. if (c != colour)
  60209. {
  60210. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60211. updateHSV();
  60212. update();
  60213. }
  60214. }
  60215. void ColourSelector::setHue (float newH)
  60216. {
  60217. newH = jlimit (0.0f, 1.0f, newH);
  60218. if (h != newH)
  60219. {
  60220. h = newH;
  60221. colour = Colour (h, s, v, colour.getFloatAlpha());
  60222. update();
  60223. }
  60224. }
  60225. void ColourSelector::setSV (float newS, float newV)
  60226. {
  60227. newS = jlimit (0.0f, 1.0f, newS);
  60228. newV = jlimit (0.0f, 1.0f, newV);
  60229. if (s != newS || v != newV)
  60230. {
  60231. s = newS;
  60232. v = newV;
  60233. colour = Colour (h, s, v, colour.getFloatAlpha());
  60234. update();
  60235. }
  60236. }
  60237. void ColourSelector::updateHSV()
  60238. {
  60239. colour.getHSB (h, s, v);
  60240. }
  60241. void ColourSelector::update()
  60242. {
  60243. if (sliders[0] != 0)
  60244. {
  60245. sliders[0]->setValue ((int) colour.getRed());
  60246. sliders[1]->setValue ((int) colour.getGreen());
  60247. sliders[2]->setValue ((int) colour.getBlue());
  60248. sliders[3]->setValue ((int) colour.getAlpha());
  60249. }
  60250. if (colourSpace != 0)
  60251. {
  60252. colourSpace->updateIfNeeded();
  60253. hueSelector->updateIfNeeded();
  60254. }
  60255. if ((flags & showColourAtTop) != 0)
  60256. repaint (previewArea);
  60257. sendChangeMessage (this);
  60258. }
  60259. void ColourSelector::paint (Graphics& g)
  60260. {
  60261. g.fillAll (findColour (backgroundColourId));
  60262. if ((flags & showColourAtTop) != 0)
  60263. {
  60264. const Colour currentColour (getCurrentColour());
  60265. g.fillCheckerBoard (previewArea, 10, 10,
  60266. Colour (0xffdddddd).overlaidWith (currentColour),
  60267. Colour (0xffffffff).overlaidWith (currentColour));
  60268. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60269. g.setFont (14.0f, true);
  60270. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60271. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60272. Justification::centred, false);
  60273. }
  60274. if ((flags & showSliders) != 0)
  60275. {
  60276. g.setColour (findColour (labelTextColourId));
  60277. g.setFont (11.0f);
  60278. for (int i = 4; --i >= 0;)
  60279. {
  60280. if (sliders[i]->isVisible())
  60281. g.drawText (sliders[i]->getName() + ":",
  60282. 0, sliders[i]->getY(),
  60283. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60284. Justification::centredRight, false);
  60285. }
  60286. }
  60287. }
  60288. void ColourSelector::resized()
  60289. {
  60290. const int swatchesPerRow = 8;
  60291. const int swatchHeight = 22;
  60292. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60293. const int numSwatches = getNumSwatches();
  60294. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60295. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60296. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60297. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60298. int y = topSpace;
  60299. if ((flags & showColourspace) != 0)
  60300. {
  60301. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60302. colourSpace->setBounds (edgeGap, y,
  60303. getWidth() - hueWidth - edgeGap - 4,
  60304. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60305. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60306. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60307. colourSpace->getHeight());
  60308. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60309. }
  60310. if ((flags & showSliders) != 0)
  60311. {
  60312. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60313. for (int i = 0; i < numSliders; ++i)
  60314. {
  60315. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60316. proportionOfWidth (0.72f), sliderHeight - 2);
  60317. y += sliderHeight;
  60318. }
  60319. }
  60320. if (numSwatches > 0)
  60321. {
  60322. const int startX = 8;
  60323. const int xGap = 4;
  60324. const int yGap = 4;
  60325. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60326. y += edgeGap;
  60327. if (swatchComponents.size() != numSwatches)
  60328. {
  60329. swatchComponents.clear();
  60330. for (int i = 0; i < numSwatches; ++i)
  60331. {
  60332. SwatchComponent* const sc = new SwatchComponent (this, i);
  60333. swatchComponents.add (sc);
  60334. addAndMakeVisible (sc);
  60335. }
  60336. }
  60337. int x = startX;
  60338. for (int i = 0; i < swatchComponents.size(); ++i)
  60339. {
  60340. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60341. sc->setBounds (x + xGap / 2,
  60342. y + yGap / 2,
  60343. swatchWidth - xGap,
  60344. swatchHeight - yGap);
  60345. if (((i + 1) % swatchesPerRow) == 0)
  60346. {
  60347. x = startX;
  60348. y += swatchHeight;
  60349. }
  60350. else
  60351. {
  60352. x += swatchWidth;
  60353. }
  60354. }
  60355. }
  60356. }
  60357. void ColourSelector::sliderValueChanged (Slider*)
  60358. {
  60359. if (sliders[0] != 0)
  60360. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60361. (uint8) sliders[1]->getValue(),
  60362. (uint8) sliders[2]->getValue(),
  60363. (uint8) sliders[3]->getValue()));
  60364. }
  60365. int ColourSelector::getNumSwatches() const
  60366. {
  60367. return 0;
  60368. }
  60369. const Colour ColourSelector::getSwatchColour (const int) const
  60370. {
  60371. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60372. return Colours::black;
  60373. }
  60374. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60375. {
  60376. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60377. }
  60378. END_JUCE_NAMESPACE
  60379. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60380. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60381. BEGIN_JUCE_NAMESPACE
  60382. class ShadowWindow : public Component
  60383. {
  60384. Component* owner;
  60385. Image shadowImageSections [12];
  60386. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60387. public:
  60388. ShadowWindow (Component* const owner_,
  60389. const int type_,
  60390. const Image shadowImageSections_ [12])
  60391. : owner (owner_),
  60392. type (type_)
  60393. {
  60394. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60395. shadowImageSections [i] = shadowImageSections_ [i];
  60396. setInterceptsMouseClicks (false, false);
  60397. if (owner_->isOnDesktop())
  60398. {
  60399. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60400. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60401. | ComponentPeer::windowIsTemporary
  60402. | ComponentPeer::windowIgnoresKeyPresses);
  60403. }
  60404. else if (owner_->getParentComponent() != 0)
  60405. {
  60406. owner_->getParentComponent()->addChildComponent (this);
  60407. }
  60408. }
  60409. ~ShadowWindow()
  60410. {
  60411. }
  60412. void paint (Graphics& g)
  60413. {
  60414. const Image& topLeft = shadowImageSections [type * 3];
  60415. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60416. const Image& filler = shadowImageSections [type * 3 + 2];
  60417. g.setOpacity (1.0f);
  60418. if (type < 2)
  60419. {
  60420. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60421. g.drawImage (topLeft,
  60422. 0, 0, topLeft.getWidth(), imH,
  60423. 0, 0, topLeft.getWidth(), imH);
  60424. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60425. g.drawImage (bottomRight,
  60426. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60427. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60428. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60429. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60430. }
  60431. else
  60432. {
  60433. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60434. g.drawImage (topLeft,
  60435. 0, 0, imW, topLeft.getHeight(),
  60436. 0, 0, imW, topLeft.getHeight());
  60437. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60438. g.drawImage (bottomRight,
  60439. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60440. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60441. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60442. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60443. }
  60444. }
  60445. void resized()
  60446. {
  60447. repaint(); // (needed for correct repainting)
  60448. }
  60449. private:
  60450. ShadowWindow (const ShadowWindow&);
  60451. ShadowWindow& operator= (const ShadowWindow&);
  60452. };
  60453. DropShadower::DropShadower (const float alpha_,
  60454. const int xOffset_,
  60455. const int yOffset_,
  60456. const float blurRadius_)
  60457. : owner (0),
  60458. numShadows (0),
  60459. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60460. xOffset (xOffset_),
  60461. yOffset (yOffset_),
  60462. alpha (alpha_),
  60463. blurRadius (blurRadius_),
  60464. inDestructor (false),
  60465. reentrant (false)
  60466. {
  60467. }
  60468. DropShadower::~DropShadower()
  60469. {
  60470. if (owner != 0)
  60471. owner->removeComponentListener (this);
  60472. inDestructor = true;
  60473. deleteShadowWindows();
  60474. }
  60475. void DropShadower::deleteShadowWindows()
  60476. {
  60477. if (numShadows > 0)
  60478. {
  60479. int i;
  60480. for (i = numShadows; --i >= 0;)
  60481. delete shadowWindows[i];
  60482. numShadows = 0;
  60483. }
  60484. }
  60485. void DropShadower::setOwner (Component* componentToFollow)
  60486. {
  60487. if (componentToFollow != owner)
  60488. {
  60489. if (owner != 0)
  60490. owner->removeComponentListener (this);
  60491. // (the component can't be null)
  60492. jassert (componentToFollow != 0);
  60493. owner = componentToFollow;
  60494. jassert (owner != 0);
  60495. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60496. owner->addComponentListener (this);
  60497. updateShadows();
  60498. }
  60499. }
  60500. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60501. {
  60502. updateShadows();
  60503. }
  60504. void DropShadower::componentBroughtToFront (Component&)
  60505. {
  60506. bringShadowWindowsToFront();
  60507. }
  60508. void DropShadower::componentChildrenChanged (Component&)
  60509. {
  60510. }
  60511. void DropShadower::componentParentHierarchyChanged (Component&)
  60512. {
  60513. deleteShadowWindows();
  60514. updateShadows();
  60515. }
  60516. void DropShadower::componentVisibilityChanged (Component&)
  60517. {
  60518. updateShadows();
  60519. }
  60520. void DropShadower::updateShadows()
  60521. {
  60522. if (reentrant || inDestructor || (owner == 0))
  60523. return;
  60524. reentrant = true;
  60525. ComponentPeer* const nw = owner->getPeer();
  60526. const bool isOwnerVisible = owner->isVisible()
  60527. && (nw == 0 || ! nw->isMinimised());
  60528. const bool createShadowWindows = numShadows == 0
  60529. && owner->getWidth() > 0
  60530. && owner->getHeight() > 0
  60531. && isOwnerVisible
  60532. && (Desktop::canUseSemiTransparentWindows()
  60533. || owner->getParentComponent() != 0);
  60534. if (createShadowWindows)
  60535. {
  60536. // keep a cached version of the image to save doing the gaussian too often
  60537. String imageId;
  60538. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60539. const int hash = imageId.hashCode();
  60540. Image bigIm (ImageCache::getFromHashCode (hash));
  60541. if (bigIm.isNull())
  60542. {
  60543. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60544. Graphics bigG (bigIm);
  60545. bigG.setColour (Colours::black.withAlpha (alpha));
  60546. bigG.fillRect (shadowEdge + xOffset,
  60547. shadowEdge + yOffset,
  60548. bigIm.getWidth() - (shadowEdge * 2),
  60549. bigIm.getHeight() - (shadowEdge * 2));
  60550. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60551. blurKernel.createGaussianBlur (blurRadius);
  60552. blurKernel.applyToImage (bigIm, bigIm,
  60553. Rectangle<int> (xOffset, yOffset,
  60554. bigIm.getWidth(), bigIm.getHeight()));
  60555. ImageCache::addImageToCache (bigIm, hash);
  60556. }
  60557. const int iw = bigIm.getWidth();
  60558. const int ih = bigIm.getHeight();
  60559. const int shadowEdge2 = shadowEdge * 2;
  60560. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60561. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60562. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60563. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60564. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60565. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60566. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60567. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60568. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60569. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60570. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60571. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60572. for (int i = 0; i < 4; ++i)
  60573. {
  60574. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60575. ++numShadows;
  60576. }
  60577. }
  60578. if (numShadows > 0)
  60579. {
  60580. for (int i = numShadows; --i >= 0;)
  60581. {
  60582. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60583. shadowWindows[i]->setVisible (isOwnerVisible);
  60584. }
  60585. const int x = owner->getX();
  60586. const int y = owner->getY() - shadowEdge;
  60587. const int w = owner->getWidth();
  60588. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60589. shadowWindows[0]->setBounds (x - shadowEdge,
  60590. y,
  60591. shadowEdge,
  60592. h);
  60593. shadowWindows[1]->setBounds (x + w,
  60594. y,
  60595. shadowEdge,
  60596. h);
  60597. shadowWindows[2]->setBounds (x,
  60598. y,
  60599. w,
  60600. shadowEdge);
  60601. shadowWindows[3]->setBounds (x,
  60602. owner->getBottom(),
  60603. w,
  60604. shadowEdge);
  60605. }
  60606. reentrant = false;
  60607. if (createShadowWindows)
  60608. bringShadowWindowsToFront();
  60609. }
  60610. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60611. const int sx, const int sy)
  60612. {
  60613. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60614. Graphics g (shadowImageSections[num]);
  60615. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60616. }
  60617. void DropShadower::bringShadowWindowsToFront()
  60618. {
  60619. if (! (inDestructor || reentrant))
  60620. {
  60621. updateShadows();
  60622. reentrant = true;
  60623. for (int i = numShadows; --i >= 0;)
  60624. shadowWindows[i]->toBehind (owner);
  60625. reentrant = false;
  60626. }
  60627. }
  60628. END_JUCE_NAMESPACE
  60629. /*** End of inlined file: juce_DropShadower.cpp ***/
  60630. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60631. BEGIN_JUCE_NAMESPACE
  60632. class MagnifyingPeer : public ComponentPeer
  60633. {
  60634. public:
  60635. MagnifyingPeer (Component* const component_,
  60636. MagnifierComponent* const magnifierComp_)
  60637. : ComponentPeer (component_, 0),
  60638. magnifierComp (magnifierComp_)
  60639. {
  60640. }
  60641. ~MagnifyingPeer()
  60642. {
  60643. }
  60644. void* getNativeHandle() const { return 0; }
  60645. void setVisible (bool) {}
  60646. void setTitle (const String&) {}
  60647. void setPosition (int, int) {}
  60648. void setSize (int, int) {}
  60649. void setBounds (int, int, int, int, bool) {}
  60650. void setMinimised (bool) {}
  60651. bool isMinimised() const { return false; }
  60652. void setFullScreen (bool) {}
  60653. bool isFullScreen() const { return false; }
  60654. const BorderSize getFrameSize() const { return BorderSize (0); }
  60655. bool setAlwaysOnTop (bool) { return true; }
  60656. void toFront (bool) {}
  60657. void toBehind (ComponentPeer*) {}
  60658. void setIcon (const Image&) {}
  60659. bool isFocused() const
  60660. {
  60661. return magnifierComp->hasKeyboardFocus (true);
  60662. }
  60663. void grabFocus()
  60664. {
  60665. ComponentPeer* peer = magnifierComp->getPeer();
  60666. if (peer != 0)
  60667. peer->grabFocus();
  60668. }
  60669. void textInputRequired (const Point<int>& position)
  60670. {
  60671. ComponentPeer* peer = magnifierComp->getPeer();
  60672. if (peer != 0)
  60673. peer->textInputRequired (position);
  60674. }
  60675. const Rectangle<int> getBounds() const
  60676. {
  60677. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60678. component->getWidth(), component->getHeight());
  60679. }
  60680. const Point<int> getScreenPosition() const
  60681. {
  60682. return magnifierComp->getScreenPosition();
  60683. }
  60684. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60685. {
  60686. const double zoom = magnifierComp->getScaleFactor();
  60687. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60688. roundToInt (relativePosition.getY() * zoom)));
  60689. }
  60690. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60691. {
  60692. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60693. const double zoom = magnifierComp->getScaleFactor();
  60694. return Point<int> (roundToInt (p.getX() / zoom),
  60695. roundToInt (p.getY() / zoom));
  60696. }
  60697. bool contains (const Point<int>& position, bool) const
  60698. {
  60699. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60700. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60701. }
  60702. void repaint (const Rectangle<int>& area)
  60703. {
  60704. const double zoom = magnifierComp->getScaleFactor();
  60705. magnifierComp->repaint ((int) (area.getX() * zoom),
  60706. (int) (area.getY() * zoom),
  60707. roundToInt (area.getWidth() * zoom) + 1,
  60708. roundToInt (area.getHeight() * zoom) + 1);
  60709. }
  60710. void performAnyPendingRepaintsNow()
  60711. {
  60712. }
  60713. juce_UseDebuggingNewOperator
  60714. private:
  60715. MagnifierComponent* const magnifierComp;
  60716. MagnifyingPeer (const MagnifyingPeer&);
  60717. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60718. };
  60719. class PeerHolderComp : public Component
  60720. {
  60721. public:
  60722. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60723. : magnifierComp (magnifierComp_)
  60724. {
  60725. setVisible (true);
  60726. }
  60727. ~PeerHolderComp()
  60728. {
  60729. }
  60730. ComponentPeer* createNewPeer (int, void*)
  60731. {
  60732. return new MagnifyingPeer (this, magnifierComp);
  60733. }
  60734. void childBoundsChanged (Component* c)
  60735. {
  60736. if (c != 0)
  60737. {
  60738. setSize (c->getWidth(), c->getHeight());
  60739. magnifierComp->childBoundsChanged (this);
  60740. }
  60741. }
  60742. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60743. {
  60744. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60745. Component* const p = magnifierComp->getParentComponent();
  60746. if (p != 0)
  60747. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60748. }
  60749. private:
  60750. MagnifierComponent* const magnifierComp;
  60751. PeerHolderComp (const PeerHolderComp&);
  60752. PeerHolderComp& operator= (const PeerHolderComp&);
  60753. };
  60754. MagnifierComponent::MagnifierComponent (Component* const content_,
  60755. const bool deleteContentCompWhenNoLongerNeeded)
  60756. : content (content_),
  60757. scaleFactor (0.0),
  60758. peer (0),
  60759. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60760. quality (Graphics::lowResamplingQuality),
  60761. mouseSource (0, true)
  60762. {
  60763. holderComp = new PeerHolderComp (this);
  60764. setScaleFactor (1.0);
  60765. }
  60766. MagnifierComponent::~MagnifierComponent()
  60767. {
  60768. delete holderComp;
  60769. if (deleteContent)
  60770. delete content;
  60771. }
  60772. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60773. {
  60774. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60775. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60776. if (scaleFactor != newScaleFactor)
  60777. {
  60778. scaleFactor = newScaleFactor;
  60779. if (scaleFactor == 1.0)
  60780. {
  60781. holderComp->removeFromDesktop();
  60782. peer = 0;
  60783. addChildComponent (content);
  60784. childBoundsChanged (content);
  60785. }
  60786. else
  60787. {
  60788. holderComp->addAndMakeVisible (content);
  60789. holderComp->childBoundsChanged (content);
  60790. childBoundsChanged (holderComp);
  60791. holderComp->addToDesktop (0);
  60792. peer = holderComp->getPeer();
  60793. }
  60794. repaint();
  60795. }
  60796. }
  60797. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60798. {
  60799. quality = newQuality;
  60800. }
  60801. void MagnifierComponent::paint (Graphics& g)
  60802. {
  60803. const int w = holderComp->getWidth();
  60804. const int h = holderComp->getHeight();
  60805. if (w == 0 || h == 0)
  60806. return;
  60807. const Rectangle<int> r (g.getClipBounds());
  60808. const int srcX = (int) (r.getX() / scaleFactor);
  60809. const int srcY = (int) (r.getY() / scaleFactor);
  60810. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60811. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60812. if (scaleFactor >= 1.0)
  60813. {
  60814. ++srcW;
  60815. ++srcH;
  60816. }
  60817. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60818. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60819. {
  60820. Graphics g2 (temp);
  60821. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60822. holderComp->paintEntireComponent (g2);
  60823. }
  60824. g.setImageResamplingQuality (quality);
  60825. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60826. }
  60827. void MagnifierComponent::childBoundsChanged (Component* c)
  60828. {
  60829. if (c != 0)
  60830. setSize (roundToInt (c->getWidth() * scaleFactor),
  60831. roundToInt (c->getHeight() * scaleFactor));
  60832. }
  60833. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60834. {
  60835. if (peer != 0)
  60836. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60837. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60838. }
  60839. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60840. {
  60841. passOnMouseEventToPeer (e);
  60842. }
  60843. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60844. {
  60845. passOnMouseEventToPeer (e);
  60846. }
  60847. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60848. {
  60849. passOnMouseEventToPeer (e);
  60850. }
  60851. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60852. {
  60853. passOnMouseEventToPeer (e);
  60854. }
  60855. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60856. {
  60857. passOnMouseEventToPeer (e);
  60858. }
  60859. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60860. {
  60861. passOnMouseEventToPeer (e);
  60862. }
  60863. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60864. {
  60865. if (peer != 0)
  60866. peer->handleMouseWheel (e.source.getIndex(),
  60867. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60868. ix * 256.0f, iy * 256.0f);
  60869. else
  60870. Component::mouseWheelMove (e, ix, iy);
  60871. }
  60872. int MagnifierComponent::scaleInt (const int n) const
  60873. {
  60874. return roundToInt (n / scaleFactor);
  60875. }
  60876. END_JUCE_NAMESPACE
  60877. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60878. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60879. BEGIN_JUCE_NAMESPACE
  60880. class MidiKeyboardUpDownButton : public Button
  60881. {
  60882. public:
  60883. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60884. const int delta_)
  60885. : Button (String::empty),
  60886. owner (owner_),
  60887. delta (delta_)
  60888. {
  60889. setOpaque (true);
  60890. }
  60891. ~MidiKeyboardUpDownButton()
  60892. {
  60893. }
  60894. void clicked()
  60895. {
  60896. int note = owner->getLowestVisibleKey();
  60897. if (delta < 0)
  60898. note = (note - 1) / 12;
  60899. else
  60900. note = note / 12 + 1;
  60901. owner->setLowestVisibleKey (note * 12);
  60902. }
  60903. void paintButton (Graphics& g,
  60904. bool isMouseOverButton,
  60905. bool isButtonDown)
  60906. {
  60907. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60908. isMouseOverButton, isButtonDown,
  60909. delta > 0);
  60910. }
  60911. private:
  60912. MidiKeyboardComponent* const owner;
  60913. const int delta;
  60914. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60915. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60916. };
  60917. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60918. const Orientation orientation_)
  60919. : state (state_),
  60920. xOffset (0),
  60921. blackNoteLength (1),
  60922. keyWidth (16.0f),
  60923. orientation (orientation_),
  60924. midiChannel (1),
  60925. midiInChannelMask (0xffff),
  60926. velocity (1.0f),
  60927. noteUnderMouse (-1),
  60928. mouseDownNote (-1),
  60929. rangeStart (0),
  60930. rangeEnd (127),
  60931. firstKey (12 * 4),
  60932. canScroll (true),
  60933. mouseDragging (false),
  60934. useMousePositionForVelocity (true),
  60935. keyMappingOctave (6),
  60936. octaveNumForMiddleC (3)
  60937. {
  60938. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60939. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60940. // initialise with a default set of querty key-mappings..
  60941. const char* const keymap = "awsedftgyhujkolp;";
  60942. for (int i = String (keymap).length(); --i >= 0;)
  60943. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60944. setOpaque (true);
  60945. setWantsKeyboardFocus (true);
  60946. state.addListener (this);
  60947. }
  60948. MidiKeyboardComponent::~MidiKeyboardComponent()
  60949. {
  60950. state.removeListener (this);
  60951. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60952. deleteAllChildren();
  60953. }
  60954. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60955. {
  60956. keyWidth = widthInPixels;
  60957. resized();
  60958. }
  60959. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60960. {
  60961. if (orientation != newOrientation)
  60962. {
  60963. orientation = newOrientation;
  60964. resized();
  60965. }
  60966. }
  60967. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60968. const int highestNote)
  60969. {
  60970. jassert (lowestNote >= 0 && lowestNote <= 127);
  60971. jassert (highestNote >= 0 && highestNote <= 127);
  60972. jassert (lowestNote <= highestNote);
  60973. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60974. {
  60975. rangeStart = jlimit (0, 127, lowestNote);
  60976. rangeEnd = jlimit (0, 127, highestNote);
  60977. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60978. resized();
  60979. }
  60980. }
  60981. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60982. {
  60983. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60984. if (noteNumber != firstKey)
  60985. {
  60986. firstKey = noteNumber;
  60987. sendChangeMessage (this);
  60988. resized();
  60989. }
  60990. }
  60991. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60992. {
  60993. if (canScroll != canScroll_)
  60994. {
  60995. canScroll = canScroll_;
  60996. resized();
  60997. }
  60998. }
  60999. void MidiKeyboardComponent::colourChanged()
  61000. {
  61001. repaint();
  61002. }
  61003. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61004. {
  61005. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61006. if (midiChannel != midiChannelNumber)
  61007. {
  61008. resetAnyKeysInUse();
  61009. midiChannel = jlimit (1, 16, midiChannelNumber);
  61010. }
  61011. }
  61012. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61013. {
  61014. midiInChannelMask = midiChannelMask;
  61015. triggerAsyncUpdate();
  61016. }
  61017. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61018. {
  61019. velocity = jlimit (0.0f, 1.0f, velocity_);
  61020. useMousePositionForVelocity = useMousePositionForVelocity_;
  61021. }
  61022. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61023. {
  61024. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61025. static const float blackNoteWidth = 0.7f;
  61026. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61027. 1.0f, 2 - blackNoteWidth * 0.4f,
  61028. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61029. 4.0f, 5 - blackNoteWidth * 0.5f,
  61030. 5.0f, 6 - blackNoteWidth * 0.3f,
  61031. 6.0f };
  61032. static const float widths[] = { 1.0f, blackNoteWidth,
  61033. 1.0f, blackNoteWidth,
  61034. 1.0f, 1.0f, blackNoteWidth,
  61035. 1.0f, blackNoteWidth,
  61036. 1.0f, blackNoteWidth,
  61037. 1.0f };
  61038. const int octave = midiNoteNumber / 12;
  61039. const int note = midiNoteNumber % 12;
  61040. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61041. w = roundToInt (widths [note] * keyWidth_);
  61042. }
  61043. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61044. {
  61045. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61046. int rx, rw;
  61047. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61048. x -= xOffset + rx;
  61049. }
  61050. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61051. {
  61052. int x, y;
  61053. getKeyPos (midiNoteNumber, x, y);
  61054. return x;
  61055. }
  61056. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61057. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61058. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61059. {
  61060. if (! reallyContains (pos.getX(), pos.getY(), false))
  61061. return -1;
  61062. Point<int> p (pos);
  61063. if (orientation != horizontalKeyboard)
  61064. {
  61065. p = Point<int> (p.getY(), p.getX());
  61066. if (orientation == verticalKeyboardFacingLeft)
  61067. p = Point<int> (p.getX(), getWidth() - p.getY());
  61068. else
  61069. p = Point<int> (getHeight() - p.getX(), p.getY());
  61070. }
  61071. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61072. }
  61073. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61074. {
  61075. if (pos.getY() < blackNoteLength)
  61076. {
  61077. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61078. {
  61079. for (int i = 0; i < 5; ++i)
  61080. {
  61081. const int note = octaveStart + blackNotes [i];
  61082. if (note >= rangeStart && note <= rangeEnd)
  61083. {
  61084. int kx, kw;
  61085. getKeyPos (note, kx, kw);
  61086. kx += xOffset;
  61087. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61088. {
  61089. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61090. return note;
  61091. }
  61092. }
  61093. }
  61094. }
  61095. }
  61096. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61097. {
  61098. for (int i = 0; i < 7; ++i)
  61099. {
  61100. const int note = octaveStart + whiteNotes [i];
  61101. if (note >= rangeStart && note <= rangeEnd)
  61102. {
  61103. int kx, kw;
  61104. getKeyPos (note, kx, kw);
  61105. kx += xOffset;
  61106. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61107. {
  61108. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61109. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61110. return note;
  61111. }
  61112. }
  61113. }
  61114. }
  61115. mousePositionVelocity = 0;
  61116. return -1;
  61117. }
  61118. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61119. {
  61120. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61121. {
  61122. int x, w;
  61123. getKeyPos (noteNum, x, w);
  61124. if (orientation == horizontalKeyboard)
  61125. repaint (x, 0, w, getHeight());
  61126. else if (orientation == verticalKeyboardFacingLeft)
  61127. repaint (0, x, getWidth(), w);
  61128. else if (orientation == verticalKeyboardFacingRight)
  61129. repaint (0, getHeight() - x - w, getWidth(), w);
  61130. }
  61131. }
  61132. void MidiKeyboardComponent::paint (Graphics& g)
  61133. {
  61134. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61135. const Colour lineColour (findColour (keySeparatorLineColourId));
  61136. const Colour textColour (findColour (textLabelColourId));
  61137. int x, w, octave;
  61138. for (octave = 0; octave < 128; octave += 12)
  61139. {
  61140. for (int white = 0; white < 7; ++white)
  61141. {
  61142. const int noteNum = octave + whiteNotes [white];
  61143. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61144. {
  61145. getKeyPos (noteNum, x, w);
  61146. if (orientation == horizontalKeyboard)
  61147. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61148. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61149. noteUnderMouse == noteNum,
  61150. lineColour, textColour);
  61151. else if (orientation == verticalKeyboardFacingLeft)
  61152. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61153. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61154. noteUnderMouse == noteNum,
  61155. lineColour, textColour);
  61156. else if (orientation == verticalKeyboardFacingRight)
  61157. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61158. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61159. noteUnderMouse == noteNum,
  61160. lineColour, textColour);
  61161. }
  61162. }
  61163. }
  61164. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61165. if (orientation == verticalKeyboardFacingLeft)
  61166. {
  61167. x1 = getWidth() - 1.0f;
  61168. x2 = getWidth() - 5.0f;
  61169. }
  61170. else if (orientation == verticalKeyboardFacingRight)
  61171. x2 = 5.0f;
  61172. else
  61173. y2 = 5.0f;
  61174. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61175. Colours::transparentBlack, x2, y2, false));
  61176. getKeyPos (rangeEnd, x, w);
  61177. x += w;
  61178. if (orientation == verticalKeyboardFacingLeft)
  61179. g.fillRect (getWidth() - 5, 0, 5, x);
  61180. else if (orientation == verticalKeyboardFacingRight)
  61181. g.fillRect (0, 0, 5, x);
  61182. else
  61183. g.fillRect (0, 0, x, 5);
  61184. g.setColour (lineColour);
  61185. if (orientation == verticalKeyboardFacingLeft)
  61186. g.fillRect (0, 0, 1, x);
  61187. else if (orientation == verticalKeyboardFacingRight)
  61188. g.fillRect (getWidth() - 1, 0, 1, x);
  61189. else
  61190. g.fillRect (0, getHeight() - 1, x, 1);
  61191. const Colour blackNoteColour (findColour (blackNoteColourId));
  61192. for (octave = 0; octave < 128; octave += 12)
  61193. {
  61194. for (int black = 0; black < 5; ++black)
  61195. {
  61196. const int noteNum = octave + blackNotes [black];
  61197. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61198. {
  61199. getKeyPos (noteNum, x, w);
  61200. if (orientation == horizontalKeyboard)
  61201. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61202. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61203. noteUnderMouse == noteNum,
  61204. blackNoteColour);
  61205. else if (orientation == verticalKeyboardFacingLeft)
  61206. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61207. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61208. noteUnderMouse == noteNum,
  61209. blackNoteColour);
  61210. else if (orientation == verticalKeyboardFacingRight)
  61211. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61212. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61213. noteUnderMouse == noteNum,
  61214. blackNoteColour);
  61215. }
  61216. }
  61217. }
  61218. }
  61219. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61220. Graphics& g, int x, int y, int w, int h,
  61221. bool isDown, bool isOver,
  61222. const Colour& lineColour,
  61223. const Colour& textColour)
  61224. {
  61225. Colour c (Colours::transparentWhite);
  61226. if (isDown)
  61227. c = findColour (keyDownOverlayColourId);
  61228. if (isOver)
  61229. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61230. g.setColour (c);
  61231. g.fillRect (x, y, w, h);
  61232. const String text (getWhiteNoteText (midiNoteNumber));
  61233. if (! text.isEmpty())
  61234. {
  61235. g.setColour (textColour);
  61236. Font f (jmin (12.0f, keyWidth * 0.9f));
  61237. f.setHorizontalScale (0.8f);
  61238. g.setFont (f);
  61239. Justification justification (Justification::centredBottom);
  61240. if (orientation == verticalKeyboardFacingLeft)
  61241. justification = Justification::centredLeft;
  61242. else if (orientation == verticalKeyboardFacingRight)
  61243. justification = Justification::centredRight;
  61244. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61245. }
  61246. g.setColour (lineColour);
  61247. if (orientation == horizontalKeyboard)
  61248. g.fillRect (x, y, 1, h);
  61249. else if (orientation == verticalKeyboardFacingLeft)
  61250. g.fillRect (x, y, w, 1);
  61251. else if (orientation == verticalKeyboardFacingRight)
  61252. g.fillRect (x, y + h - 1, w, 1);
  61253. if (midiNoteNumber == rangeEnd)
  61254. {
  61255. if (orientation == horizontalKeyboard)
  61256. g.fillRect (x + w, y, 1, h);
  61257. else if (orientation == verticalKeyboardFacingLeft)
  61258. g.fillRect (x, y + h, w, 1);
  61259. else if (orientation == verticalKeyboardFacingRight)
  61260. g.fillRect (x, y - 1, w, 1);
  61261. }
  61262. }
  61263. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61264. Graphics& g, int x, int y, int w, int h,
  61265. bool isDown, bool isOver,
  61266. const Colour& noteFillColour)
  61267. {
  61268. Colour c (noteFillColour);
  61269. if (isDown)
  61270. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61271. if (isOver)
  61272. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61273. g.setColour (c);
  61274. g.fillRect (x, y, w, h);
  61275. if (isDown)
  61276. {
  61277. g.setColour (noteFillColour);
  61278. g.drawRect (x, y, w, h);
  61279. }
  61280. else
  61281. {
  61282. const int xIndent = jmax (1, jmin (w, h) / 8);
  61283. g.setColour (c.brighter());
  61284. if (orientation == horizontalKeyboard)
  61285. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61286. else if (orientation == verticalKeyboardFacingLeft)
  61287. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61288. else if (orientation == verticalKeyboardFacingRight)
  61289. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61290. }
  61291. }
  61292. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61293. {
  61294. octaveNumForMiddleC = octaveNumForMiddleC_;
  61295. repaint();
  61296. }
  61297. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61298. {
  61299. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61300. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61301. return String::empty;
  61302. }
  61303. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61304. const bool isMouseOver_,
  61305. const bool isButtonDown,
  61306. const bool movesOctavesUp)
  61307. {
  61308. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61309. float angle;
  61310. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61311. angle = movesOctavesUp ? 0.0f : 0.5f;
  61312. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61313. angle = movesOctavesUp ? 0.25f : 0.75f;
  61314. else
  61315. angle = movesOctavesUp ? 0.75f : 0.25f;
  61316. Path path;
  61317. path.lineTo (0.0f, 1.0f);
  61318. path.lineTo (1.0f, 0.5f);
  61319. path.closeSubPath();
  61320. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61321. g.setColour (findColour (upDownButtonArrowColourId)
  61322. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61323. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61324. w - 2.0f,
  61325. h - 2.0f,
  61326. true));
  61327. }
  61328. void MidiKeyboardComponent::resized()
  61329. {
  61330. int w = getWidth();
  61331. int h = getHeight();
  61332. if (w > 0 && h > 0)
  61333. {
  61334. if (orientation != horizontalKeyboard)
  61335. swapVariables (w, h);
  61336. blackNoteLength = roundToInt (h * 0.7f);
  61337. int kx2, kw2;
  61338. getKeyPos (rangeEnd, kx2, kw2);
  61339. kx2 += kw2;
  61340. if (firstKey != rangeStart)
  61341. {
  61342. int kx1, kw1;
  61343. getKeyPos (rangeStart, kx1, kw1);
  61344. if (kx2 - kx1 <= w)
  61345. {
  61346. firstKey = rangeStart;
  61347. sendChangeMessage (this);
  61348. repaint();
  61349. }
  61350. }
  61351. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61352. scrollDown->setVisible (showScrollButtons);
  61353. scrollUp->setVisible (showScrollButtons);
  61354. xOffset = 0;
  61355. if (showScrollButtons)
  61356. {
  61357. const int scrollButtonW = jmin (12, w / 2);
  61358. if (orientation == horizontalKeyboard)
  61359. {
  61360. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61361. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61362. }
  61363. else if (orientation == verticalKeyboardFacingLeft)
  61364. {
  61365. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61366. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61367. }
  61368. else if (orientation == verticalKeyboardFacingRight)
  61369. {
  61370. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61371. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61372. }
  61373. int endOfLastKey, kw;
  61374. getKeyPos (rangeEnd, endOfLastKey, kw);
  61375. endOfLastKey += kw;
  61376. float mousePositionVelocity;
  61377. const int spaceAvailable = w - scrollButtonW * 2;
  61378. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61379. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61380. {
  61381. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61382. sendChangeMessage (this);
  61383. }
  61384. int newOffset = 0;
  61385. getKeyPos (firstKey, newOffset, kw);
  61386. xOffset = newOffset - scrollButtonW;
  61387. }
  61388. else
  61389. {
  61390. firstKey = rangeStart;
  61391. }
  61392. timerCallback();
  61393. repaint();
  61394. }
  61395. }
  61396. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61397. {
  61398. triggerAsyncUpdate();
  61399. }
  61400. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61401. {
  61402. triggerAsyncUpdate();
  61403. }
  61404. void MidiKeyboardComponent::handleAsyncUpdate()
  61405. {
  61406. for (int i = rangeStart; i <= rangeEnd; ++i)
  61407. {
  61408. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61409. {
  61410. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61411. repaintNote (i);
  61412. }
  61413. }
  61414. }
  61415. void MidiKeyboardComponent::resetAnyKeysInUse()
  61416. {
  61417. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61418. {
  61419. state.allNotesOff (midiChannel);
  61420. keysPressed.clear();
  61421. mouseDownNote = -1;
  61422. }
  61423. }
  61424. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61425. {
  61426. float mousePositionVelocity = 0.0f;
  61427. const int newNote = (mouseDragging || isMouseOver())
  61428. ? xyToNote (pos, mousePositionVelocity) : -1;
  61429. if (noteUnderMouse != newNote)
  61430. {
  61431. if (mouseDownNote >= 0)
  61432. {
  61433. state.noteOff (midiChannel, mouseDownNote);
  61434. mouseDownNote = -1;
  61435. }
  61436. if (mouseDragging && newNote >= 0)
  61437. {
  61438. if (! useMousePositionForVelocity)
  61439. mousePositionVelocity = 1.0f;
  61440. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61441. mouseDownNote = newNote;
  61442. }
  61443. repaintNote (noteUnderMouse);
  61444. noteUnderMouse = newNote;
  61445. repaintNote (noteUnderMouse);
  61446. }
  61447. else if (mouseDownNote >= 0 && ! mouseDragging)
  61448. {
  61449. state.noteOff (midiChannel, mouseDownNote);
  61450. mouseDownNote = -1;
  61451. }
  61452. }
  61453. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61454. {
  61455. updateNoteUnderMouse (e.getPosition());
  61456. stopTimer();
  61457. }
  61458. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61459. {
  61460. float mousePositionVelocity;
  61461. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61462. if (newNote >= 0)
  61463. mouseDraggedToKey (newNote, e);
  61464. updateNoteUnderMouse (e.getPosition());
  61465. }
  61466. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61467. {
  61468. return true;
  61469. }
  61470. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61471. {
  61472. }
  61473. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61474. {
  61475. float mousePositionVelocity;
  61476. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61477. mouseDragging = false;
  61478. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61479. {
  61480. repaintNote (noteUnderMouse);
  61481. noteUnderMouse = -1;
  61482. mouseDragging = true;
  61483. updateNoteUnderMouse (e.getPosition());
  61484. startTimer (500);
  61485. }
  61486. }
  61487. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61488. {
  61489. mouseDragging = false;
  61490. updateNoteUnderMouse (e.getPosition());
  61491. stopTimer();
  61492. }
  61493. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61494. {
  61495. updateNoteUnderMouse (e.getPosition());
  61496. }
  61497. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61498. {
  61499. updateNoteUnderMouse (e.getPosition());
  61500. }
  61501. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61502. {
  61503. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61504. }
  61505. void MidiKeyboardComponent::timerCallback()
  61506. {
  61507. updateNoteUnderMouse (getMouseXYRelative());
  61508. }
  61509. void MidiKeyboardComponent::clearKeyMappings()
  61510. {
  61511. resetAnyKeysInUse();
  61512. keyPressNotes.clear();
  61513. keyPresses.clear();
  61514. }
  61515. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61516. const int midiNoteOffsetFromC)
  61517. {
  61518. removeKeyPressForNote (midiNoteOffsetFromC);
  61519. keyPressNotes.add (midiNoteOffsetFromC);
  61520. keyPresses.add (key);
  61521. }
  61522. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61523. {
  61524. for (int i = keyPressNotes.size(); --i >= 0;)
  61525. {
  61526. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61527. {
  61528. keyPressNotes.remove (i);
  61529. keyPresses.remove (i);
  61530. }
  61531. }
  61532. }
  61533. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61534. {
  61535. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61536. keyMappingOctave = newOctaveNumber;
  61537. }
  61538. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61539. {
  61540. bool keyPressUsed = false;
  61541. for (int i = keyPresses.size(); --i >= 0;)
  61542. {
  61543. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61544. if (keyPresses.getReference(i).isCurrentlyDown())
  61545. {
  61546. if (! keysPressed [note])
  61547. {
  61548. keysPressed.setBit (note);
  61549. state.noteOn (midiChannel, note, velocity);
  61550. keyPressUsed = true;
  61551. }
  61552. }
  61553. else
  61554. {
  61555. if (keysPressed [note])
  61556. {
  61557. keysPressed.clearBit (note);
  61558. state.noteOff (midiChannel, note);
  61559. keyPressUsed = true;
  61560. }
  61561. }
  61562. }
  61563. return keyPressUsed;
  61564. }
  61565. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61566. {
  61567. resetAnyKeysInUse();
  61568. }
  61569. END_JUCE_NAMESPACE
  61570. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61571. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61572. #if JUCE_OPENGL
  61573. BEGIN_JUCE_NAMESPACE
  61574. extern void juce_glViewport (const int w, const int h);
  61575. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61576. const int alphaBits_,
  61577. const int depthBufferBits_,
  61578. const int stencilBufferBits_)
  61579. : redBits (bitsPerRGBComponent),
  61580. greenBits (bitsPerRGBComponent),
  61581. blueBits (bitsPerRGBComponent),
  61582. alphaBits (alphaBits_),
  61583. depthBufferBits (depthBufferBits_),
  61584. stencilBufferBits (stencilBufferBits_),
  61585. accumulationBufferRedBits (0),
  61586. accumulationBufferGreenBits (0),
  61587. accumulationBufferBlueBits (0),
  61588. accumulationBufferAlphaBits (0),
  61589. fullSceneAntiAliasingNumSamples (0)
  61590. {
  61591. }
  61592. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61593. : redBits (other.redBits),
  61594. greenBits (other.greenBits),
  61595. blueBits (other.blueBits),
  61596. alphaBits (other.alphaBits),
  61597. depthBufferBits (other.depthBufferBits),
  61598. stencilBufferBits (other.stencilBufferBits),
  61599. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61600. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61601. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61602. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61603. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61604. {
  61605. }
  61606. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61607. {
  61608. redBits = other.redBits;
  61609. greenBits = other.greenBits;
  61610. blueBits = other.blueBits;
  61611. alphaBits = other.alphaBits;
  61612. depthBufferBits = other.depthBufferBits;
  61613. stencilBufferBits = other.stencilBufferBits;
  61614. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61615. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61616. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61617. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61618. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61619. return *this;
  61620. }
  61621. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61622. {
  61623. return redBits == other.redBits
  61624. && greenBits == other.greenBits
  61625. && blueBits == other.blueBits
  61626. && alphaBits == other.alphaBits
  61627. && depthBufferBits == other.depthBufferBits
  61628. && stencilBufferBits == other.stencilBufferBits
  61629. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61630. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61631. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61632. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61633. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61634. }
  61635. static Array<OpenGLContext*> knownContexts;
  61636. OpenGLContext::OpenGLContext() throw()
  61637. {
  61638. knownContexts.add (this);
  61639. }
  61640. OpenGLContext::~OpenGLContext()
  61641. {
  61642. knownContexts.removeValue (this);
  61643. }
  61644. OpenGLContext* OpenGLContext::getCurrentContext()
  61645. {
  61646. for (int i = knownContexts.size(); --i >= 0;)
  61647. {
  61648. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61649. if (oglc->isActive())
  61650. return oglc;
  61651. }
  61652. return 0;
  61653. }
  61654. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61655. {
  61656. public:
  61657. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61658. : ComponentMovementWatcher (owner_),
  61659. owner (owner_),
  61660. wasShowing (false)
  61661. {
  61662. }
  61663. ~OpenGLComponentWatcher() {}
  61664. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61665. {
  61666. owner->updateContextPosition();
  61667. }
  61668. void componentPeerChanged()
  61669. {
  61670. const ScopedLock sl (owner->getContextLock());
  61671. owner->deleteContext();
  61672. }
  61673. void componentVisibilityChanged (Component&)
  61674. {
  61675. const bool isShowingNow = owner->isShowing();
  61676. if (wasShowing != isShowingNow)
  61677. {
  61678. wasShowing = isShowingNow;
  61679. if (! isShowingNow)
  61680. {
  61681. const ScopedLock sl (owner->getContextLock());
  61682. owner->deleteContext();
  61683. }
  61684. }
  61685. }
  61686. juce_UseDebuggingNewOperator
  61687. private:
  61688. OpenGLComponent* const owner;
  61689. bool wasShowing;
  61690. };
  61691. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61692. : type (type_),
  61693. contextToShareListsWith (0),
  61694. needToUpdateViewport (true)
  61695. {
  61696. setOpaque (true);
  61697. componentWatcher = new OpenGLComponentWatcher (this);
  61698. }
  61699. OpenGLComponent::~OpenGLComponent()
  61700. {
  61701. deleteContext();
  61702. componentWatcher = 0;
  61703. }
  61704. void OpenGLComponent::deleteContext()
  61705. {
  61706. const ScopedLock sl (contextLock);
  61707. context = 0;
  61708. }
  61709. void OpenGLComponent::updateContextPosition()
  61710. {
  61711. needToUpdateViewport = true;
  61712. if (getWidth() > 0 && getHeight() > 0)
  61713. {
  61714. Component* const topComp = getTopLevelComponent();
  61715. if (topComp->getPeer() != 0)
  61716. {
  61717. const ScopedLock sl (contextLock);
  61718. if (context != 0)
  61719. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61720. getScreenY() - topComp->getScreenY(),
  61721. getWidth(),
  61722. getHeight(),
  61723. topComp->getHeight());
  61724. }
  61725. }
  61726. }
  61727. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61728. {
  61729. OpenGLPixelFormat pf;
  61730. const ScopedLock sl (contextLock);
  61731. if (context != 0)
  61732. pf = context->getPixelFormat();
  61733. return pf;
  61734. }
  61735. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61736. {
  61737. if (! (preferredPixelFormat == formatToUse))
  61738. {
  61739. const ScopedLock sl (contextLock);
  61740. deleteContext();
  61741. preferredPixelFormat = formatToUse;
  61742. }
  61743. }
  61744. void OpenGLComponent::shareWith (OpenGLContext* c)
  61745. {
  61746. if (contextToShareListsWith != c)
  61747. {
  61748. const ScopedLock sl (contextLock);
  61749. deleteContext();
  61750. contextToShareListsWith = c;
  61751. }
  61752. }
  61753. bool OpenGLComponent::makeCurrentContextActive()
  61754. {
  61755. if (context == 0)
  61756. {
  61757. const ScopedLock sl (contextLock);
  61758. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61759. {
  61760. context = createContext();
  61761. if (context != 0)
  61762. {
  61763. updateContextPosition();
  61764. if (context->makeActive())
  61765. newOpenGLContextCreated();
  61766. }
  61767. }
  61768. }
  61769. return context != 0 && context->makeActive();
  61770. }
  61771. void OpenGLComponent::makeCurrentContextInactive()
  61772. {
  61773. if (context != 0)
  61774. context->makeInactive();
  61775. }
  61776. bool OpenGLComponent::isActiveContext() const throw()
  61777. {
  61778. return context != 0 && context->isActive();
  61779. }
  61780. void OpenGLComponent::swapBuffers()
  61781. {
  61782. if (context != 0)
  61783. context->swapBuffers();
  61784. }
  61785. void OpenGLComponent::paint (Graphics&)
  61786. {
  61787. if (renderAndSwapBuffers())
  61788. {
  61789. ComponentPeer* const peer = getPeer();
  61790. if (peer != 0)
  61791. {
  61792. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61793. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61794. }
  61795. }
  61796. }
  61797. bool OpenGLComponent::renderAndSwapBuffers()
  61798. {
  61799. const ScopedLock sl (contextLock);
  61800. if (! makeCurrentContextActive())
  61801. return false;
  61802. if (needToUpdateViewport)
  61803. {
  61804. needToUpdateViewport = false;
  61805. juce_glViewport (getWidth(), getHeight());
  61806. }
  61807. renderOpenGL();
  61808. swapBuffers();
  61809. return true;
  61810. }
  61811. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61812. {
  61813. Component::internalRepaint (x, y, w, h);
  61814. if (context != 0)
  61815. context->repaint();
  61816. }
  61817. END_JUCE_NAMESPACE
  61818. #endif
  61819. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61820. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61821. BEGIN_JUCE_NAMESPACE
  61822. PreferencesPanel::PreferencesPanel()
  61823. : buttonSize (70)
  61824. {
  61825. }
  61826. PreferencesPanel::~PreferencesPanel()
  61827. {
  61828. currentPage = 0;
  61829. deleteAllChildren();
  61830. }
  61831. void PreferencesPanel::addSettingsPage (const String& title,
  61832. const Drawable* icon,
  61833. const Drawable* overIcon,
  61834. const Drawable* downIcon)
  61835. {
  61836. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61837. button->setImages (icon, overIcon, downIcon);
  61838. button->setRadioGroupId (1);
  61839. button->addButtonListener (this);
  61840. button->setClickingTogglesState (true);
  61841. button->setWantsKeyboardFocus (false);
  61842. addAndMakeVisible (button);
  61843. resized();
  61844. if (currentPage == 0)
  61845. setCurrentPage (title);
  61846. }
  61847. void PreferencesPanel::addSettingsPage (const String& title,
  61848. const void* imageData,
  61849. const int imageDataSize)
  61850. {
  61851. DrawableImage icon, iconOver, iconDown;
  61852. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61853. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61854. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61855. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61856. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61857. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61858. }
  61859. class PrefsDialogWindow : public DialogWindow
  61860. {
  61861. public:
  61862. PrefsDialogWindow (const String& dialogtitle,
  61863. const Colour& backgroundColour)
  61864. : DialogWindow (dialogtitle, backgroundColour, true)
  61865. {
  61866. }
  61867. ~PrefsDialogWindow()
  61868. {
  61869. }
  61870. void closeButtonPressed()
  61871. {
  61872. exitModalState (0);
  61873. }
  61874. private:
  61875. PrefsDialogWindow (const PrefsDialogWindow&);
  61876. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61877. };
  61878. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61879. int dialogWidth,
  61880. int dialogHeight,
  61881. const Colour& backgroundColour)
  61882. {
  61883. setSize (dialogWidth, dialogHeight);
  61884. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61885. dw.setContentComponent (this, true, true);
  61886. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61887. dw.runModalLoop();
  61888. dw.setContentComponent (0, false, false);
  61889. }
  61890. void PreferencesPanel::resized()
  61891. {
  61892. int x = 0;
  61893. for (int i = 0; i < getNumChildComponents(); ++i)
  61894. {
  61895. Component* c = getChildComponent (i);
  61896. if (dynamic_cast <DrawableButton*> (c) == 0)
  61897. {
  61898. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61899. }
  61900. else
  61901. {
  61902. c->setBounds (x, 0, buttonSize, buttonSize);
  61903. x += buttonSize;
  61904. }
  61905. }
  61906. }
  61907. void PreferencesPanel::paint (Graphics& g)
  61908. {
  61909. g.setColour (Colours::grey);
  61910. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61911. }
  61912. void PreferencesPanel::setCurrentPage (const String& pageName)
  61913. {
  61914. if (currentPageName != pageName)
  61915. {
  61916. currentPageName = pageName;
  61917. currentPage = 0;
  61918. currentPage = createComponentForPage (pageName);
  61919. if (currentPage != 0)
  61920. {
  61921. addAndMakeVisible (currentPage);
  61922. currentPage->toBack();
  61923. resized();
  61924. }
  61925. for (int i = 0; i < getNumChildComponents(); ++i)
  61926. {
  61927. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61928. if (db != 0 && db->getName() == pageName)
  61929. {
  61930. db->setToggleState (true, false);
  61931. break;
  61932. }
  61933. }
  61934. }
  61935. }
  61936. void PreferencesPanel::buttonClicked (Button*)
  61937. {
  61938. for (int i = 0; i < getNumChildComponents(); ++i)
  61939. {
  61940. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61941. if (db != 0 && db->getToggleState())
  61942. {
  61943. setCurrentPage (db->getName());
  61944. break;
  61945. }
  61946. }
  61947. }
  61948. END_JUCE_NAMESPACE
  61949. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61950. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61951. #if JUCE_WINDOWS || JUCE_LINUX
  61952. BEGIN_JUCE_NAMESPACE
  61953. SystemTrayIconComponent::SystemTrayIconComponent()
  61954. {
  61955. addToDesktop (0);
  61956. }
  61957. SystemTrayIconComponent::~SystemTrayIconComponent()
  61958. {
  61959. }
  61960. END_JUCE_NAMESPACE
  61961. #endif
  61962. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61963. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61964. BEGIN_JUCE_NAMESPACE
  61965. class AlertWindowTextEditor : public TextEditor
  61966. {
  61967. public:
  61968. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61969. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61970. {
  61971. setSelectAllWhenFocused (true);
  61972. }
  61973. ~AlertWindowTextEditor()
  61974. {
  61975. }
  61976. void returnPressed()
  61977. {
  61978. // pass these up the component hierarchy to be trigger the buttons
  61979. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61980. }
  61981. void escapePressed()
  61982. {
  61983. // pass these up the component hierarchy to be trigger the buttons
  61984. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61985. }
  61986. private:
  61987. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61988. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61989. static juce_wchar getDefaultPasswordChar() throw()
  61990. {
  61991. #if JUCE_LINUX
  61992. return 0x2022;
  61993. #else
  61994. return 0x25cf;
  61995. #endif
  61996. }
  61997. };
  61998. AlertWindow::AlertWindow (const String& title,
  61999. const String& message,
  62000. AlertIconType iconType,
  62001. Component* associatedComponent_)
  62002. : TopLevelWindow (title, true),
  62003. alertIconType (iconType),
  62004. associatedComponent (associatedComponent_)
  62005. {
  62006. if (message.isEmpty())
  62007. text = " "; // to force an update if the message is empty
  62008. setMessage (message);
  62009. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62010. {
  62011. Component* const c = Desktop::getInstance().getComponent (i);
  62012. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62013. {
  62014. setAlwaysOnTop (true);
  62015. break;
  62016. }
  62017. }
  62018. if (! JUCEApplication::isStandaloneApp())
  62019. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62020. lookAndFeelChanged();
  62021. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62022. }
  62023. AlertWindow::~AlertWindow()
  62024. {
  62025. for (int i = customComps.size(); --i >= 0;)
  62026. removeChildComponent ((Component*) customComps[i]);
  62027. deleteAllChildren();
  62028. }
  62029. void AlertWindow::userTriedToCloseWindow()
  62030. {
  62031. exitModalState (0);
  62032. }
  62033. void AlertWindow::setMessage (const String& message)
  62034. {
  62035. const String newMessage (message.substring (0, 2048));
  62036. if (text != newMessage)
  62037. {
  62038. text = newMessage;
  62039. font.setHeight (15.0f);
  62040. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62041. textLayout.setText (getName() + "\n\n", titleFont);
  62042. textLayout.appendText (text, font);
  62043. updateLayout (true);
  62044. repaint();
  62045. }
  62046. }
  62047. void AlertWindow::buttonClicked (Button* button)
  62048. {
  62049. for (int i = 0; i < buttons.size(); i++)
  62050. {
  62051. TextButton* const c = (TextButton*) buttons[i];
  62052. if (button->getName() == c->getName())
  62053. {
  62054. if (c->getParentComponent() != 0)
  62055. c->getParentComponent()->exitModalState (c->getCommandID());
  62056. break;
  62057. }
  62058. }
  62059. }
  62060. void AlertWindow::addButton (const String& name,
  62061. const int returnValue,
  62062. const KeyPress& shortcutKey1,
  62063. const KeyPress& shortcutKey2)
  62064. {
  62065. TextButton* const b = new TextButton (name, String::empty);
  62066. b->setWantsKeyboardFocus (true);
  62067. b->setMouseClickGrabsKeyboardFocus (false);
  62068. b->setCommandToTrigger (0, returnValue, false);
  62069. b->addShortcut (shortcutKey1);
  62070. b->addShortcut (shortcutKey2);
  62071. b->addButtonListener (this);
  62072. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62073. addAndMakeVisible (b, 0);
  62074. buttons.add (b);
  62075. updateLayout (false);
  62076. }
  62077. int AlertWindow::getNumButtons() const
  62078. {
  62079. return buttons.size();
  62080. }
  62081. void AlertWindow::triggerButtonClick (const String& buttonName)
  62082. {
  62083. for (int i = buttons.size(); --i >= 0;)
  62084. {
  62085. TextButton* const b = (TextButton*) buttons[i];
  62086. if (buttonName == b->getName())
  62087. {
  62088. b->triggerClick();
  62089. break;
  62090. }
  62091. }
  62092. }
  62093. void AlertWindow::addTextEditor (const String& name,
  62094. const String& initialContents,
  62095. const String& onScreenLabel,
  62096. const bool isPasswordBox)
  62097. {
  62098. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62099. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62100. tc->setFont (font);
  62101. tc->setText (initialContents);
  62102. tc->setCaretPosition (initialContents.length());
  62103. addAndMakeVisible (tc);
  62104. textBoxes.add (tc);
  62105. allComps.add (tc);
  62106. textboxNames.add (onScreenLabel);
  62107. updateLayout (false);
  62108. }
  62109. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62110. {
  62111. for (int i = textBoxes.size(); --i >= 0;)
  62112. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62113. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62114. return 0;
  62115. }
  62116. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62117. {
  62118. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62119. return t != 0 ? t->getText() : String::empty;
  62120. }
  62121. void AlertWindow::addComboBox (const String& name,
  62122. const StringArray& items,
  62123. const String& onScreenLabel)
  62124. {
  62125. ComboBox* const cb = new ComboBox (name);
  62126. for (int i = 0; i < items.size(); ++i)
  62127. cb->addItem (items[i], i + 1);
  62128. addAndMakeVisible (cb);
  62129. cb->setSelectedItemIndex (0);
  62130. comboBoxes.add (cb);
  62131. allComps.add (cb);
  62132. comboBoxNames.add (onScreenLabel);
  62133. updateLayout (false);
  62134. }
  62135. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62136. {
  62137. for (int i = comboBoxes.size(); --i >= 0;)
  62138. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62139. return (ComboBox*) comboBoxes[i];
  62140. return 0;
  62141. }
  62142. class AlertTextComp : public TextEditor
  62143. {
  62144. public:
  62145. AlertTextComp (const String& message,
  62146. const Font& font)
  62147. {
  62148. setReadOnly (true);
  62149. setMultiLine (true, true);
  62150. setCaretVisible (false);
  62151. setScrollbarsShown (true);
  62152. lookAndFeelChanged();
  62153. setWantsKeyboardFocus (false);
  62154. setFont (font);
  62155. setText (message, false);
  62156. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62157. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62158. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62159. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62160. }
  62161. ~AlertTextComp()
  62162. {
  62163. }
  62164. int getPreferredWidth() const throw() { return bestWidth; }
  62165. void updateLayout (const int width)
  62166. {
  62167. TextLayout text;
  62168. text.appendText (getText(), getFont());
  62169. text.layout (width - 8, Justification::topLeft, true);
  62170. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62171. }
  62172. private:
  62173. int bestWidth;
  62174. AlertTextComp (const AlertTextComp&);
  62175. AlertTextComp& operator= (const AlertTextComp&);
  62176. };
  62177. void AlertWindow::addTextBlock (const String& textBlock)
  62178. {
  62179. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62180. textBlocks.add (c);
  62181. allComps.add (c);
  62182. addAndMakeVisible (c);
  62183. updateLayout (false);
  62184. }
  62185. void AlertWindow::addProgressBarComponent (double& progressValue)
  62186. {
  62187. ProgressBar* const pb = new ProgressBar (progressValue);
  62188. progressBars.add (pb);
  62189. allComps.add (pb);
  62190. addAndMakeVisible (pb);
  62191. updateLayout (false);
  62192. }
  62193. void AlertWindow::addCustomComponent (Component* const component)
  62194. {
  62195. customComps.add (component);
  62196. allComps.add (component);
  62197. addAndMakeVisible (component);
  62198. updateLayout (false);
  62199. }
  62200. int AlertWindow::getNumCustomComponents() const
  62201. {
  62202. return customComps.size();
  62203. }
  62204. Component* AlertWindow::getCustomComponent (const int index) const
  62205. {
  62206. return (Component*) customComps [index];
  62207. }
  62208. Component* AlertWindow::removeCustomComponent (const int index)
  62209. {
  62210. Component* const c = getCustomComponent (index);
  62211. if (c != 0)
  62212. {
  62213. customComps.removeValue (c);
  62214. allComps.removeValue (c);
  62215. removeChildComponent (c);
  62216. updateLayout (false);
  62217. }
  62218. return c;
  62219. }
  62220. void AlertWindow::paint (Graphics& g)
  62221. {
  62222. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62223. g.setColour (findColour (textColourId));
  62224. g.setFont (getLookAndFeel().getAlertWindowFont());
  62225. int i;
  62226. for (i = textBoxes.size(); --i >= 0;)
  62227. {
  62228. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62229. g.drawFittedText (textboxNames[i],
  62230. te->getX(), te->getY() - 14,
  62231. te->getWidth(), 14,
  62232. Justification::centredLeft, 1);
  62233. }
  62234. for (i = comboBoxNames.size(); --i >= 0;)
  62235. {
  62236. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62237. g.drawFittedText (comboBoxNames[i],
  62238. cb->getX(), cb->getY() - 14,
  62239. cb->getWidth(), 14,
  62240. Justification::centredLeft, 1);
  62241. }
  62242. for (i = customComps.size(); --i >= 0;)
  62243. {
  62244. const Component* const c = (Component*) customComps[i];
  62245. g.drawFittedText (c->getName(),
  62246. c->getX(), c->getY() - 14,
  62247. c->getWidth(), 14,
  62248. Justification::centredLeft, 1);
  62249. }
  62250. }
  62251. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62252. {
  62253. const int titleH = 24;
  62254. const int iconWidth = 80;
  62255. const int wid = jmax (font.getStringWidth (text),
  62256. font.getStringWidth (getName()));
  62257. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62258. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62259. const int edgeGap = 10;
  62260. const int labelHeight = 18;
  62261. int iconSpace;
  62262. if (alertIconType == NoIcon)
  62263. {
  62264. textLayout.layout (w, Justification::horizontallyCentred, true);
  62265. iconSpace = 0;
  62266. }
  62267. else
  62268. {
  62269. textLayout.layout (w, Justification::left, true);
  62270. iconSpace = iconWidth;
  62271. }
  62272. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62273. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62274. const int textLayoutH = textLayout.getHeight();
  62275. const int textBottom = 16 + titleH + textLayoutH;
  62276. int h = textBottom;
  62277. int buttonW = 40;
  62278. int i;
  62279. for (i = 0; i < buttons.size(); ++i)
  62280. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62281. w = jmax (buttonW, w);
  62282. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62283. if (buttons.size() > 0)
  62284. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62285. for (i = customComps.size(); --i >= 0;)
  62286. {
  62287. Component* c = (Component*) customComps[i];
  62288. w = jmax (w, (c->getWidth() * 100) / 80);
  62289. h += 10 + c->getHeight();
  62290. if (c->getName().isNotEmpty())
  62291. h += labelHeight;
  62292. }
  62293. for (i = textBlocks.size(); --i >= 0;)
  62294. {
  62295. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62296. w = jmax (w, ac->getPreferredWidth());
  62297. }
  62298. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62299. for (i = textBlocks.size(); --i >= 0;)
  62300. {
  62301. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62302. ac->updateLayout ((int) (w * 0.8f));
  62303. h += ac->getHeight() + 10;
  62304. }
  62305. h = jmin (getParentHeight() - 50, h);
  62306. if (onlyIncreaseSize)
  62307. {
  62308. w = jmax (w, getWidth());
  62309. h = jmax (h, getHeight());
  62310. }
  62311. if (! isVisible())
  62312. {
  62313. centreAroundComponent (associatedComponent, w, h);
  62314. }
  62315. else
  62316. {
  62317. const int cx = getX() + getWidth() / 2;
  62318. const int cy = getY() + getHeight() / 2;
  62319. setBounds (cx - w / 2,
  62320. cy - h / 2,
  62321. w, h);
  62322. }
  62323. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62324. const int spacer = 16;
  62325. int totalWidth = -spacer;
  62326. for (i = buttons.size(); --i >= 0;)
  62327. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62328. int x = (w - totalWidth) / 2;
  62329. int y = (int) (getHeight() * 0.95f);
  62330. for (i = 0; i < buttons.size(); ++i)
  62331. {
  62332. TextButton* const c = (TextButton*) buttons[i];
  62333. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62334. c->setTopLeftPosition (x, ny);
  62335. if (ny < y)
  62336. y = ny;
  62337. x += c->getWidth() + spacer;
  62338. c->toFront (false);
  62339. }
  62340. y = textBottom;
  62341. for (i = 0; i < allComps.size(); ++i)
  62342. {
  62343. Component* const c = (Component*) allComps[i];
  62344. h = 22;
  62345. const int comboIndex = comboBoxes.indexOf (c);
  62346. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62347. y += labelHeight;
  62348. const int tbIndex = textBoxes.indexOf (c);
  62349. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62350. y += labelHeight;
  62351. if (customComps.contains (c))
  62352. {
  62353. if (c->getName().isNotEmpty())
  62354. y += labelHeight;
  62355. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62356. h = c->getHeight();
  62357. }
  62358. else if (textBlocks.contains (c))
  62359. {
  62360. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62361. h = c->getHeight();
  62362. }
  62363. else
  62364. {
  62365. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62366. }
  62367. y += h + 10;
  62368. }
  62369. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62370. }
  62371. bool AlertWindow::containsAnyExtraComponents() const
  62372. {
  62373. return textBoxes.size()
  62374. + comboBoxes.size()
  62375. + progressBars.size()
  62376. + customComps.size() > 0;
  62377. }
  62378. void AlertWindow::mouseDown (const MouseEvent&)
  62379. {
  62380. dragger.startDraggingComponent (this, &constrainer);
  62381. }
  62382. void AlertWindow::mouseDrag (const MouseEvent& e)
  62383. {
  62384. dragger.dragComponent (this, e);
  62385. }
  62386. bool AlertWindow::keyPressed (const KeyPress& key)
  62387. {
  62388. for (int i = buttons.size(); --i >= 0;)
  62389. {
  62390. TextButton* const b = (TextButton*) buttons[i];
  62391. if (b->isRegisteredForShortcut (key))
  62392. {
  62393. b->triggerClick();
  62394. return true;
  62395. }
  62396. }
  62397. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62398. {
  62399. exitModalState (0);
  62400. return true;
  62401. }
  62402. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62403. {
  62404. ((TextButton*) buttons.getFirst())->triggerClick();
  62405. return true;
  62406. }
  62407. return false;
  62408. }
  62409. void AlertWindow::lookAndFeelChanged()
  62410. {
  62411. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62412. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62413. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62414. }
  62415. int AlertWindow::getDesktopWindowStyleFlags() const
  62416. {
  62417. return getLookAndFeel().getAlertBoxWindowFlags();
  62418. }
  62419. struct AlertWindowInfo
  62420. {
  62421. String title, message, button1, button2, button3;
  62422. AlertWindow::AlertIconType iconType;
  62423. int numButtons;
  62424. Component::SafePointer<Component> associatedComponent;
  62425. int run() const
  62426. {
  62427. return (int) (pointer_sized_int)
  62428. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62429. }
  62430. private:
  62431. int show() const
  62432. {
  62433. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62434. : LookAndFeel::getDefaultLookAndFeel();
  62435. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62436. iconType, numButtons, associatedComponent));
  62437. jassert (alertBox != 0); // you have to return one of these!
  62438. return alertBox->runModalLoop();
  62439. }
  62440. static void* showCallback (void* userData)
  62441. {
  62442. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62443. }
  62444. };
  62445. void AlertWindow::showMessageBox (AlertIconType iconType,
  62446. const String& title,
  62447. const String& message,
  62448. const String& buttonText,
  62449. Component* associatedComponent)
  62450. {
  62451. AlertWindowInfo info;
  62452. info.title = title;
  62453. info.message = message;
  62454. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62455. info.iconType = iconType;
  62456. info.numButtons = 1;
  62457. info.associatedComponent = associatedComponent;
  62458. info.run();
  62459. }
  62460. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62461. const String& title,
  62462. const String& message,
  62463. const String& button1Text,
  62464. const String& button2Text,
  62465. Component* associatedComponent)
  62466. {
  62467. AlertWindowInfo info;
  62468. info.title = title;
  62469. info.message = message;
  62470. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62471. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62472. info.iconType = iconType;
  62473. info.numButtons = 2;
  62474. info.associatedComponent = associatedComponent;
  62475. return info.run() != 0;
  62476. }
  62477. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62478. const String& title,
  62479. const String& message,
  62480. const String& button1Text,
  62481. const String& button2Text,
  62482. const String& button3Text,
  62483. Component* associatedComponent)
  62484. {
  62485. AlertWindowInfo info;
  62486. info.title = title;
  62487. info.message = message;
  62488. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62489. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62490. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62491. info.iconType = iconType;
  62492. info.numButtons = 3;
  62493. info.associatedComponent = associatedComponent;
  62494. return info.run();
  62495. }
  62496. END_JUCE_NAMESPACE
  62497. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62498. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62499. BEGIN_JUCE_NAMESPACE
  62500. CallOutBox::CallOutBox (Component& contentComponent,
  62501. Component& componentToPointTo,
  62502. Component* const parentComponent)
  62503. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62504. {
  62505. addAndMakeVisible (&content);
  62506. if (parentComponent != 0)
  62507. {
  62508. updatePosition (parentComponent->getLocalBounds(),
  62509. componentToPointTo.getLocalBounds()
  62510. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62511. parentComponent->addAndMakeVisible (this);
  62512. }
  62513. else
  62514. {
  62515. if (! JUCEApplication::isStandaloneApp())
  62516. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62517. updatePosition (componentToPointTo.getScreenBounds(),
  62518. componentToPointTo.getParentMonitorArea());
  62519. addToDesktop (ComponentPeer::windowIsTemporary);
  62520. }
  62521. }
  62522. CallOutBox::~CallOutBox()
  62523. {
  62524. }
  62525. void CallOutBox::setArrowSize (const float newSize)
  62526. {
  62527. arrowSize = newSize;
  62528. borderSpace = jmax (20, (int) arrowSize);
  62529. refreshPath();
  62530. }
  62531. void CallOutBox::paint (Graphics& g)
  62532. {
  62533. if (background.isNull())
  62534. {
  62535. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62536. Graphics g (background);
  62537. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62538. }
  62539. g.setColour (Colours::black);
  62540. g.drawImageAt (background, 0, 0);
  62541. }
  62542. void CallOutBox::resized()
  62543. {
  62544. content.setTopLeftPosition (borderSpace, borderSpace);
  62545. refreshPath();
  62546. }
  62547. void CallOutBox::moved()
  62548. {
  62549. refreshPath();
  62550. }
  62551. void CallOutBox::childBoundsChanged (Component*)
  62552. {
  62553. updatePosition (targetArea, availableArea);
  62554. }
  62555. bool CallOutBox::hitTest (int x, int y)
  62556. {
  62557. return outline.contains ((float) x, (float) y);
  62558. }
  62559. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62560. void CallOutBox::inputAttemptWhenModal()
  62561. {
  62562. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62563. if (targetArea.contains (mousePos))
  62564. {
  62565. // if you click on the area that originally popped-up the callout, you expect it
  62566. // to get rid of the box, but deleting the box here allows the click to pass through and
  62567. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62568. postCommandMessage (callOutBoxDismissCommandId);
  62569. }
  62570. else
  62571. {
  62572. exitModalState (0);
  62573. setVisible (false);
  62574. }
  62575. }
  62576. void CallOutBox::handleCommandMessage (int commandId)
  62577. {
  62578. Component::handleCommandMessage (commandId);
  62579. if (commandId == callOutBoxDismissCommandId)
  62580. {
  62581. exitModalState (0);
  62582. setVisible (false);
  62583. }
  62584. }
  62585. bool CallOutBox::keyPressed (const KeyPress& key)
  62586. {
  62587. if (key.isKeyCode (KeyPress::escapeKey))
  62588. {
  62589. inputAttemptWhenModal();
  62590. return true;
  62591. }
  62592. return false;
  62593. }
  62594. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62595. {
  62596. targetArea = newAreaToPointTo;
  62597. availableArea = newAreaToFitIn;
  62598. Rectangle<int> bounds (0, 0,
  62599. content.getWidth() + borderSpace * 2,
  62600. content.getHeight() + borderSpace * 2);
  62601. const int hw = bounds.getWidth() / 2;
  62602. const int hh = bounds.getHeight() / 2;
  62603. const float hwReduced = (float) (hw - borderSpace * 3);
  62604. const float hhReduced = (float) (hh - borderSpace * 3);
  62605. const float arrowIndent = borderSpace - arrowSize;
  62606. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62607. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62608. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62609. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62610. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62611. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62612. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62613. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62614. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62615. float nearest = 1.0e9f;
  62616. for (int i = 0; i < 4; ++i)
  62617. {
  62618. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62619. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62620. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62621. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62622. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62623. distanceFromCentre *= 2.0f;
  62624. if (distanceFromCentre < nearest)
  62625. {
  62626. nearest = distanceFromCentre;
  62627. targetPoint = targets[i];
  62628. bounds.setPosition ((int) (centre.getX() - hw),
  62629. (int) (centre.getY() - hh));
  62630. }
  62631. }
  62632. setBounds (bounds);
  62633. }
  62634. void CallOutBox::refreshPath()
  62635. {
  62636. repaint();
  62637. background = Image::null;
  62638. outline.clear();
  62639. const float gap = 4.5f;
  62640. const float cornerSize = 9.0f;
  62641. const float cornerSize2 = 2.0f * cornerSize;
  62642. const float arrowBaseWidth = arrowSize * 0.7f;
  62643. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62644. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62645. outline.startNewSubPath (left + cornerSize, top);
  62646. if (targetY <= top)
  62647. {
  62648. outline.lineTo (targetX - arrowBaseWidth, top);
  62649. outline.lineTo (targetX, targetY);
  62650. outline.lineTo (targetX + arrowBaseWidth, top);
  62651. }
  62652. outline.lineTo (right - cornerSize, top);
  62653. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62654. if (targetX >= right)
  62655. {
  62656. outline.lineTo (right, targetY - arrowBaseWidth);
  62657. outline.lineTo (targetX, targetY);
  62658. outline.lineTo (right, targetY + arrowBaseWidth);
  62659. }
  62660. outline.lineTo (right, bottom - cornerSize);
  62661. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62662. if (targetY >= bottom)
  62663. {
  62664. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62665. outline.lineTo (targetX, targetY);
  62666. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62667. }
  62668. outline.lineTo (left + cornerSize, bottom);
  62669. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62670. if (targetX <= left)
  62671. {
  62672. outline.lineTo (left, targetY + arrowBaseWidth);
  62673. outline.lineTo (targetX, targetY);
  62674. outline.lineTo (left, targetY - arrowBaseWidth);
  62675. }
  62676. outline.lineTo (left, top + cornerSize);
  62677. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62678. outline.closeSubPath();
  62679. }
  62680. END_JUCE_NAMESPACE
  62681. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62682. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62683. BEGIN_JUCE_NAMESPACE
  62684. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62685. static Array <ComponentPeer*> heavyweightPeers;
  62686. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62687. : component (component_),
  62688. styleFlags (styleFlags_),
  62689. lastPaintTime (0),
  62690. constrainer (0),
  62691. lastDragAndDropCompUnderMouse (0),
  62692. fakeMouseMessageSent (false),
  62693. isWindowMinimised (false)
  62694. {
  62695. heavyweightPeers.add (this);
  62696. }
  62697. ComponentPeer::~ComponentPeer()
  62698. {
  62699. heavyweightPeers.removeValue (this);
  62700. Desktop::getInstance().triggerFocusCallback();
  62701. }
  62702. int ComponentPeer::getNumPeers() throw()
  62703. {
  62704. return heavyweightPeers.size();
  62705. }
  62706. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62707. {
  62708. return heavyweightPeers [index];
  62709. }
  62710. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62711. {
  62712. for (int i = heavyweightPeers.size(); --i >= 0;)
  62713. {
  62714. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62715. if (peer->getComponent() == component)
  62716. return peer;
  62717. }
  62718. return 0;
  62719. }
  62720. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62721. {
  62722. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62723. }
  62724. void ComponentPeer::updateCurrentModifiers() throw()
  62725. {
  62726. ModifierKeys::updateCurrentModifiers();
  62727. }
  62728. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62729. {
  62730. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62731. jassert (mouse != 0); // not enough sources!
  62732. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62733. }
  62734. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62735. {
  62736. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62737. jassert (mouse != 0); // not enough sources!
  62738. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62739. }
  62740. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62741. {
  62742. Graphics g (&contextToPaintTo);
  62743. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62744. g.saveState();
  62745. #endif
  62746. JUCE_TRY
  62747. {
  62748. component->paintEntireComponent (g);
  62749. }
  62750. JUCE_CATCH_EXCEPTION
  62751. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62752. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62753. // clearly when things are being repainted.
  62754. {
  62755. g.restoreState();
  62756. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62757. (uint8) Random::getSystemRandom().nextInt (255),
  62758. (uint8) Random::getSystemRandom().nextInt (255),
  62759. (uint8) 0x50));
  62760. }
  62761. #endif
  62762. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62763. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62764. mess up a lot of the calculations that the library needs to do.
  62765. */
  62766. jassert (roundToInt (10.1f) == 10);
  62767. }
  62768. bool ComponentPeer::handleKeyPress (const int keyCode,
  62769. const juce_wchar textCharacter)
  62770. {
  62771. updateCurrentModifiers();
  62772. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62773. ? Component::getCurrentlyFocusedComponent()
  62774. : component;
  62775. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62776. {
  62777. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62778. if (currentModalComp != 0)
  62779. target = currentModalComp;
  62780. }
  62781. const KeyPress keyInfo (keyCode,
  62782. ModifierKeys::getCurrentModifiers().getRawFlags()
  62783. & ModifierKeys::allKeyboardModifiers,
  62784. textCharacter);
  62785. bool keyWasUsed = false;
  62786. while (target != 0)
  62787. {
  62788. const Component::SafePointer<Component> deletionChecker (target);
  62789. if (target->keyListeners_ != 0)
  62790. {
  62791. for (int i = target->keyListeners_->size(); --i >= 0;)
  62792. {
  62793. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62794. if (keyWasUsed || deletionChecker == 0)
  62795. return keyWasUsed;
  62796. i = jmin (i, target->keyListeners_->size());
  62797. }
  62798. }
  62799. keyWasUsed = target->keyPressed (keyInfo);
  62800. if (keyWasUsed || deletionChecker == 0)
  62801. break;
  62802. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62803. {
  62804. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62805. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62806. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62807. break;
  62808. }
  62809. target = target->parentComponent_;
  62810. }
  62811. return keyWasUsed;
  62812. }
  62813. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62814. {
  62815. updateCurrentModifiers();
  62816. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62817. ? Component::getCurrentlyFocusedComponent()
  62818. : component;
  62819. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62820. {
  62821. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62822. if (currentModalComp != 0)
  62823. target = currentModalComp;
  62824. }
  62825. bool keyWasUsed = false;
  62826. while (target != 0)
  62827. {
  62828. const Component::SafePointer<Component> deletionChecker (target);
  62829. keyWasUsed = target->keyStateChanged (isKeyDown);
  62830. if (keyWasUsed || deletionChecker == 0)
  62831. break;
  62832. if (target->keyListeners_ != 0)
  62833. {
  62834. for (int i = target->keyListeners_->size(); --i >= 0;)
  62835. {
  62836. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62837. if (keyWasUsed || deletionChecker == 0)
  62838. return keyWasUsed;
  62839. i = jmin (i, target->keyListeners_->size());
  62840. }
  62841. }
  62842. target = target->parentComponent_;
  62843. }
  62844. return keyWasUsed;
  62845. }
  62846. void ComponentPeer::handleModifierKeysChange()
  62847. {
  62848. updateCurrentModifiers();
  62849. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62850. if (target == 0)
  62851. target = Component::getCurrentlyFocusedComponent();
  62852. if (target == 0)
  62853. target = component;
  62854. if (target != 0)
  62855. target->internalModifierKeysChanged();
  62856. }
  62857. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62858. {
  62859. Component* const c = Component::getCurrentlyFocusedComponent();
  62860. if (component->isParentOf (c))
  62861. {
  62862. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62863. if (ti != 0 && ti->isTextInputActive())
  62864. return ti;
  62865. }
  62866. return 0;
  62867. }
  62868. void ComponentPeer::handleBroughtToFront()
  62869. {
  62870. updateCurrentModifiers();
  62871. if (component != 0)
  62872. component->internalBroughtToFront();
  62873. }
  62874. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62875. {
  62876. constrainer = newConstrainer;
  62877. }
  62878. void ComponentPeer::handleMovedOrResized()
  62879. {
  62880. jassert (component->isValidComponent());
  62881. updateCurrentModifiers();
  62882. const bool nowMinimised = isMinimised();
  62883. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62884. {
  62885. const Component::SafePointer<Component> deletionChecker (component);
  62886. const Rectangle<int> newBounds (getBounds());
  62887. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62888. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62889. if (wasMoved || wasResized)
  62890. {
  62891. component->bounds_ = newBounds;
  62892. if (wasResized)
  62893. component->repaint();
  62894. component->sendMovedResizedMessages (wasMoved, wasResized);
  62895. if (deletionChecker == 0)
  62896. return;
  62897. }
  62898. }
  62899. if (isWindowMinimised != nowMinimised)
  62900. {
  62901. isWindowMinimised = nowMinimised;
  62902. component->minimisationStateChanged (nowMinimised);
  62903. component->sendVisibilityChangeMessage();
  62904. }
  62905. if (! isFullScreen())
  62906. lastNonFullscreenBounds = component->getBounds();
  62907. }
  62908. void ComponentPeer::handleFocusGain()
  62909. {
  62910. updateCurrentModifiers();
  62911. if (component->isParentOf (lastFocusedComponent))
  62912. {
  62913. Component::currentlyFocusedComponent = lastFocusedComponent;
  62914. Desktop::getInstance().triggerFocusCallback();
  62915. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62916. }
  62917. else
  62918. {
  62919. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62920. component->grabKeyboardFocus();
  62921. else
  62922. Component::bringModalComponentToFront();
  62923. }
  62924. }
  62925. void ComponentPeer::handleFocusLoss()
  62926. {
  62927. updateCurrentModifiers();
  62928. if (component->hasKeyboardFocus (true))
  62929. {
  62930. lastFocusedComponent = Component::currentlyFocusedComponent;
  62931. if (lastFocusedComponent != 0)
  62932. {
  62933. Component::currentlyFocusedComponent = 0;
  62934. Desktop::getInstance().triggerFocusCallback();
  62935. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62936. }
  62937. }
  62938. }
  62939. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62940. {
  62941. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62942. ? static_cast <Component*> (lastFocusedComponent)
  62943. : component;
  62944. }
  62945. void ComponentPeer::handleScreenSizeChange()
  62946. {
  62947. updateCurrentModifiers();
  62948. component->parentSizeChanged();
  62949. handleMovedOrResized();
  62950. }
  62951. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62952. {
  62953. lastNonFullscreenBounds = newBounds;
  62954. }
  62955. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62956. {
  62957. return lastNonFullscreenBounds;
  62958. }
  62959. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62960. const StringArray& files,
  62961. FileDragAndDropTarget* const lastOne)
  62962. {
  62963. while (c != 0)
  62964. {
  62965. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62966. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62967. return t;
  62968. c = c->getParentComponent();
  62969. }
  62970. return 0;
  62971. }
  62972. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62973. {
  62974. updateCurrentModifiers();
  62975. FileDragAndDropTarget* lastTarget
  62976. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62977. FileDragAndDropTarget* newTarget = 0;
  62978. Component* const compUnderMouse = component->getComponentAt (position);
  62979. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62980. {
  62981. lastDragAndDropCompUnderMouse = compUnderMouse;
  62982. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62983. if (newTarget != lastTarget)
  62984. {
  62985. if (lastTarget != 0)
  62986. lastTarget->fileDragExit (files);
  62987. dragAndDropTargetComponent = 0;
  62988. if (newTarget != 0)
  62989. {
  62990. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62991. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62992. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62993. }
  62994. }
  62995. }
  62996. else
  62997. {
  62998. newTarget = lastTarget;
  62999. }
  63000. if (newTarget != 0)
  63001. {
  63002. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63003. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63004. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63005. }
  63006. }
  63007. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63008. {
  63009. handleFileDragMove (files, Point<int> (-1, -1));
  63010. jassert (dragAndDropTargetComponent == 0);
  63011. lastDragAndDropCompUnderMouse = 0;
  63012. }
  63013. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63014. {
  63015. handleFileDragMove (files, position);
  63016. if (dragAndDropTargetComponent != 0)
  63017. {
  63018. FileDragAndDropTarget* const target
  63019. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63020. dragAndDropTargetComponent = 0;
  63021. lastDragAndDropCompUnderMouse = 0;
  63022. if (target != 0)
  63023. {
  63024. Component* const targetComp = dynamic_cast <Component*> (target);
  63025. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63026. {
  63027. targetComp->internalModalInputAttempt();
  63028. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63029. return;
  63030. }
  63031. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63032. target->filesDropped (files, pos.getX(), pos.getY());
  63033. }
  63034. }
  63035. }
  63036. void ComponentPeer::handleUserClosingWindow()
  63037. {
  63038. updateCurrentModifiers();
  63039. component->userTriedToCloseWindow();
  63040. }
  63041. void ComponentPeer::bringModalComponentToFront()
  63042. {
  63043. Component::bringModalComponentToFront();
  63044. }
  63045. void ComponentPeer::clearMaskedRegion()
  63046. {
  63047. maskedRegion.clear();
  63048. }
  63049. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63050. {
  63051. maskedRegion.add (x, y, w, h);
  63052. }
  63053. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63054. {
  63055. StringArray s;
  63056. s.add ("Software Renderer");
  63057. return s;
  63058. }
  63059. int ComponentPeer::getCurrentRenderingEngine() throw()
  63060. {
  63061. return 0;
  63062. }
  63063. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63064. {
  63065. }
  63066. END_JUCE_NAMESPACE
  63067. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63068. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63069. BEGIN_JUCE_NAMESPACE
  63070. DialogWindow::DialogWindow (const String& name,
  63071. const Colour& backgroundColour_,
  63072. const bool escapeKeyTriggersCloseButton_,
  63073. const bool addToDesktop_)
  63074. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63075. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63076. {
  63077. }
  63078. DialogWindow::~DialogWindow()
  63079. {
  63080. }
  63081. void DialogWindow::resized()
  63082. {
  63083. DocumentWindow::resized();
  63084. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63085. if (escapeKeyTriggersCloseButton
  63086. && getCloseButton() != 0
  63087. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63088. {
  63089. getCloseButton()->addShortcut (esc);
  63090. }
  63091. }
  63092. class TempDialogWindow : public DialogWindow
  63093. {
  63094. public:
  63095. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63096. : DialogWindow (title, colour, escapeCloses, true)
  63097. {
  63098. if (! JUCEApplication::isStandaloneApp())
  63099. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63100. }
  63101. ~TempDialogWindow()
  63102. {
  63103. }
  63104. void closeButtonPressed()
  63105. {
  63106. setVisible (false);
  63107. }
  63108. private:
  63109. TempDialogWindow (const TempDialogWindow&);
  63110. TempDialogWindow& operator= (const TempDialogWindow&);
  63111. };
  63112. int DialogWindow::showModalDialog (const String& dialogTitle,
  63113. Component* contentComponent,
  63114. Component* componentToCentreAround,
  63115. const Colour& colour,
  63116. const bool escapeKeyTriggersCloseButton,
  63117. const bool shouldBeResizable,
  63118. const bool useBottomRightCornerResizer)
  63119. {
  63120. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63121. dw.setContentComponent (contentComponent, true, true);
  63122. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63123. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63124. const int result = dw.runModalLoop();
  63125. dw.setContentComponent (0, false);
  63126. return result;
  63127. }
  63128. END_JUCE_NAMESPACE
  63129. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63130. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63131. BEGIN_JUCE_NAMESPACE
  63132. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63133. {
  63134. public:
  63135. ButtonListenerProxy (DocumentWindow& owner_)
  63136. : owner (owner_)
  63137. {
  63138. }
  63139. void buttonClicked (Button* button)
  63140. {
  63141. if (button == owner.getMinimiseButton())
  63142. owner.minimiseButtonPressed();
  63143. else if (button == owner.getMaximiseButton())
  63144. owner.maximiseButtonPressed();
  63145. else if (button == owner.getCloseButton())
  63146. owner.closeButtonPressed();
  63147. }
  63148. juce_UseDebuggingNewOperator
  63149. private:
  63150. DocumentWindow& owner;
  63151. ButtonListenerProxy (const ButtonListenerProxy&);
  63152. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63153. };
  63154. DocumentWindow::DocumentWindow (const String& title,
  63155. const Colour& backgroundColour,
  63156. const int requiredButtons_,
  63157. const bool addToDesktop_)
  63158. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63159. titleBarHeight (26),
  63160. menuBarHeight (24),
  63161. requiredButtons (requiredButtons_),
  63162. #if JUCE_MAC
  63163. positionTitleBarButtonsOnLeft (true),
  63164. #else
  63165. positionTitleBarButtonsOnLeft (false),
  63166. #endif
  63167. drawTitleTextCentred (true),
  63168. menuBarModel (0)
  63169. {
  63170. setResizeLimits (128, 128, 32768, 32768);
  63171. lookAndFeelChanged();
  63172. }
  63173. DocumentWindow::~DocumentWindow()
  63174. {
  63175. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63176. titleBarButtons[i] = 0;
  63177. menuBar = 0;
  63178. }
  63179. void DocumentWindow::repaintTitleBar()
  63180. {
  63181. repaint (getTitleBarArea());
  63182. }
  63183. void DocumentWindow::setName (const String& newName)
  63184. {
  63185. if (newName != getName())
  63186. {
  63187. Component::setName (newName);
  63188. repaintTitleBar();
  63189. }
  63190. }
  63191. void DocumentWindow::setIcon (const Image& imageToUse)
  63192. {
  63193. titleBarIcon = imageToUse;
  63194. repaintTitleBar();
  63195. }
  63196. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63197. {
  63198. titleBarHeight = newHeight;
  63199. resized();
  63200. repaintTitleBar();
  63201. }
  63202. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63203. const bool positionTitleBarButtonsOnLeft_)
  63204. {
  63205. requiredButtons = requiredButtons_;
  63206. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63207. lookAndFeelChanged();
  63208. }
  63209. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63210. {
  63211. drawTitleTextCentred = textShouldBeCentred;
  63212. repaintTitleBar();
  63213. }
  63214. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63215. const int menuBarHeight_)
  63216. {
  63217. if (menuBarModel != menuBarModel_)
  63218. {
  63219. menuBar = 0;
  63220. menuBarModel = menuBarModel_;
  63221. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63222. : getLookAndFeel().getDefaultMenuBarHeight();
  63223. if (menuBarModel != 0)
  63224. {
  63225. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63226. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63227. menuBar->setEnabled (isActiveWindow());
  63228. }
  63229. resized();
  63230. }
  63231. }
  63232. void DocumentWindow::closeButtonPressed()
  63233. {
  63234. /* If you've got a close button, you have to override this method to get
  63235. rid of your window!
  63236. If the window is just a pop-up, you should override this method and make
  63237. it delete the window in whatever way is appropriate for your app. E.g. you
  63238. might just want to call "delete this".
  63239. If your app is centred around this window such that the whole app should quit when
  63240. the window is closed, then you will probably want to use this method as an opportunity
  63241. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63242. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63243. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63244. or closing it via the taskbar icon on Windows).
  63245. */
  63246. jassertfalse;
  63247. }
  63248. void DocumentWindow::minimiseButtonPressed()
  63249. {
  63250. setMinimised (true);
  63251. }
  63252. void DocumentWindow::maximiseButtonPressed()
  63253. {
  63254. setFullScreen (! isFullScreen());
  63255. }
  63256. void DocumentWindow::paint (Graphics& g)
  63257. {
  63258. ResizableWindow::paint (g);
  63259. if (resizableBorder == 0)
  63260. {
  63261. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63262. const BorderSize border (getBorderThickness());
  63263. g.fillRect (0, 0, getWidth(), border.getTop());
  63264. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63265. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63266. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63267. }
  63268. const Rectangle<int> titleBarArea (getTitleBarArea());
  63269. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63270. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63271. int titleSpaceX1 = 6;
  63272. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63273. for (int i = 0; i < 3; ++i)
  63274. {
  63275. if (titleBarButtons[i] != 0)
  63276. {
  63277. if (positionTitleBarButtonsOnLeft)
  63278. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63279. else
  63280. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63281. }
  63282. }
  63283. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63284. titleBarArea.getWidth(),
  63285. titleBarArea.getHeight(),
  63286. titleSpaceX1,
  63287. jmax (1, titleSpaceX2 - titleSpaceX1),
  63288. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63289. ! drawTitleTextCentred);
  63290. }
  63291. void DocumentWindow::resized()
  63292. {
  63293. ResizableWindow::resized();
  63294. if (titleBarButtons[1] != 0)
  63295. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63296. const Rectangle<int> titleBarArea (getTitleBarArea());
  63297. getLookAndFeel()
  63298. .positionDocumentWindowButtons (*this,
  63299. titleBarArea.getX(), titleBarArea.getY(),
  63300. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63301. titleBarButtons[0],
  63302. titleBarButtons[1],
  63303. titleBarButtons[2],
  63304. positionTitleBarButtonsOnLeft);
  63305. if (menuBar != 0)
  63306. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63307. titleBarArea.getWidth(), menuBarHeight);
  63308. }
  63309. const BorderSize DocumentWindow::getBorderThickness()
  63310. {
  63311. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63312. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63313. }
  63314. const BorderSize DocumentWindow::getContentComponentBorder()
  63315. {
  63316. BorderSize border (getBorderThickness());
  63317. border.setTop (border.getTop()
  63318. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63319. + (menuBar != 0 ? menuBarHeight : 0));
  63320. return border;
  63321. }
  63322. int DocumentWindow::getTitleBarHeight() const
  63323. {
  63324. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63325. }
  63326. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63327. {
  63328. const BorderSize border (getBorderThickness());
  63329. return Rectangle<int> (border.getLeft(), border.getTop(),
  63330. getWidth() - border.getLeftAndRight(),
  63331. getTitleBarHeight());
  63332. }
  63333. Button* DocumentWindow::getCloseButton() const throw()
  63334. {
  63335. return titleBarButtons[2];
  63336. }
  63337. Button* DocumentWindow::getMinimiseButton() const throw()
  63338. {
  63339. return titleBarButtons[0];
  63340. }
  63341. Button* DocumentWindow::getMaximiseButton() const throw()
  63342. {
  63343. return titleBarButtons[1];
  63344. }
  63345. int DocumentWindow::getDesktopWindowStyleFlags() const
  63346. {
  63347. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63348. if ((requiredButtons & minimiseButton) != 0)
  63349. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63350. if ((requiredButtons & maximiseButton) != 0)
  63351. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63352. if ((requiredButtons & closeButton) != 0)
  63353. styleFlags |= ComponentPeer::windowHasCloseButton;
  63354. return styleFlags;
  63355. }
  63356. void DocumentWindow::lookAndFeelChanged()
  63357. {
  63358. int i;
  63359. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63360. titleBarButtons[i] = 0;
  63361. if (! isUsingNativeTitleBar())
  63362. {
  63363. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63364. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63365. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63366. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63367. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63368. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63369. for (i = 0; i < 3; ++i)
  63370. {
  63371. if (titleBarButtons[i] != 0)
  63372. {
  63373. if (buttonListener == 0)
  63374. buttonListener = new ButtonListenerProxy (*this);
  63375. titleBarButtons[i]->addButtonListener (buttonListener);
  63376. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63377. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63378. Component::addAndMakeVisible (titleBarButtons[i]);
  63379. }
  63380. }
  63381. if (getCloseButton() != 0)
  63382. {
  63383. #if JUCE_MAC
  63384. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63385. #else
  63386. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63387. #endif
  63388. }
  63389. }
  63390. activeWindowStatusChanged();
  63391. ResizableWindow::lookAndFeelChanged();
  63392. }
  63393. void DocumentWindow::parentHierarchyChanged()
  63394. {
  63395. lookAndFeelChanged();
  63396. }
  63397. void DocumentWindow::activeWindowStatusChanged()
  63398. {
  63399. ResizableWindow::activeWindowStatusChanged();
  63400. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63401. if (titleBarButtons[i] != 0)
  63402. titleBarButtons[i]->setEnabled (isActiveWindow());
  63403. if (menuBar != 0)
  63404. menuBar->setEnabled (isActiveWindow());
  63405. }
  63406. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63407. {
  63408. if (getTitleBarArea().contains (e.x, e.y)
  63409. && getMaximiseButton() != 0)
  63410. {
  63411. getMaximiseButton()->triggerClick();
  63412. }
  63413. }
  63414. void DocumentWindow::userTriedToCloseWindow()
  63415. {
  63416. closeButtonPressed();
  63417. }
  63418. END_JUCE_NAMESPACE
  63419. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63420. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63421. BEGIN_JUCE_NAMESPACE
  63422. ResizableWindow::ResizableWindow (const String& name,
  63423. const bool addToDesktop_)
  63424. : TopLevelWindow (name, addToDesktop_),
  63425. resizeToFitContent (false),
  63426. fullscreen (false),
  63427. lastNonFullScreenPos (50, 50, 256, 256),
  63428. constrainer (0)
  63429. #if JUCE_DEBUG
  63430. , hasBeenResized (false)
  63431. #endif
  63432. {
  63433. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63434. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63435. if (addToDesktop_)
  63436. Component::addToDesktop (getDesktopWindowStyleFlags());
  63437. }
  63438. ResizableWindow::ResizableWindow (const String& name,
  63439. const Colour& backgroundColour_,
  63440. const bool addToDesktop_)
  63441. : TopLevelWindow (name, addToDesktop_),
  63442. resizeToFitContent (false),
  63443. fullscreen (false),
  63444. lastNonFullScreenPos (50, 50, 256, 256),
  63445. constrainer (0)
  63446. #if JUCE_DEBUG
  63447. , hasBeenResized (false)
  63448. #endif
  63449. {
  63450. setBackgroundColour (backgroundColour_);
  63451. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63452. if (addToDesktop_)
  63453. Component::addToDesktop (getDesktopWindowStyleFlags());
  63454. }
  63455. ResizableWindow::~ResizableWindow()
  63456. {
  63457. resizableCorner = 0;
  63458. resizableBorder = 0;
  63459. contentComponent.deleteAndZero();
  63460. // have you been adding your own components directly to this window..? tut tut tut.
  63461. // Read the instructions for using a ResizableWindow!
  63462. jassert (getNumChildComponents() == 0);
  63463. }
  63464. int ResizableWindow::getDesktopWindowStyleFlags() const
  63465. {
  63466. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63467. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63468. styleFlags |= ComponentPeer::windowIsResizable;
  63469. return styleFlags;
  63470. }
  63471. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63472. const bool deleteOldOne,
  63473. const bool resizeToFit)
  63474. {
  63475. resizeToFitContent = resizeToFit;
  63476. if (newContentComponent != static_cast <Component*> (contentComponent))
  63477. {
  63478. if (deleteOldOne)
  63479. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63480. // external deletion of the content comp)
  63481. else
  63482. removeChildComponent (contentComponent);
  63483. contentComponent = newContentComponent;
  63484. Component::addAndMakeVisible (contentComponent);
  63485. }
  63486. if (resizeToFit)
  63487. childBoundsChanged (contentComponent);
  63488. resized(); // must always be called to position the new content comp
  63489. }
  63490. void ResizableWindow::setContentComponentSize (int width, int height)
  63491. {
  63492. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63493. const BorderSize border (getContentComponentBorder());
  63494. setSize (width + border.getLeftAndRight(),
  63495. height + border.getTopAndBottom());
  63496. }
  63497. const BorderSize ResizableWindow::getBorderThickness()
  63498. {
  63499. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63500. }
  63501. const BorderSize ResizableWindow::getContentComponentBorder()
  63502. {
  63503. return getBorderThickness();
  63504. }
  63505. void ResizableWindow::moved()
  63506. {
  63507. updateLastPos();
  63508. }
  63509. void ResizableWindow::visibilityChanged()
  63510. {
  63511. TopLevelWindow::visibilityChanged();
  63512. updateLastPos();
  63513. }
  63514. void ResizableWindow::resized()
  63515. {
  63516. if (resizableBorder != 0)
  63517. {
  63518. resizableBorder->setVisible (! isFullScreen());
  63519. resizableBorder->setBorderThickness (getBorderThickness());
  63520. resizableBorder->setSize (getWidth(), getHeight());
  63521. resizableBorder->toBack();
  63522. }
  63523. if (resizableCorner != 0)
  63524. {
  63525. resizableCorner->setVisible (! isFullScreen());
  63526. const int resizerSize = 18;
  63527. resizableCorner->setBounds (getWidth() - resizerSize,
  63528. getHeight() - resizerSize,
  63529. resizerSize, resizerSize);
  63530. }
  63531. if (contentComponent != 0)
  63532. contentComponent->setBoundsInset (getContentComponentBorder());
  63533. updateLastPos();
  63534. #if JUCE_DEBUG
  63535. hasBeenResized = true;
  63536. #endif
  63537. }
  63538. void ResizableWindow::childBoundsChanged (Component* child)
  63539. {
  63540. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63541. {
  63542. // not going to look very good if this component has a zero size..
  63543. jassert (child->getWidth() > 0);
  63544. jassert (child->getHeight() > 0);
  63545. const BorderSize borders (getContentComponentBorder());
  63546. setSize (child->getWidth() + borders.getLeftAndRight(),
  63547. child->getHeight() + borders.getTopAndBottom());
  63548. }
  63549. }
  63550. void ResizableWindow::activeWindowStatusChanged()
  63551. {
  63552. const BorderSize border (getContentComponentBorder());
  63553. Rectangle<int> area (getLocalBounds());
  63554. repaint (area.removeFromTop (border.getTop()));
  63555. repaint (area.removeFromLeft (border.getLeft()));
  63556. repaint (area.removeFromRight (border.getRight()));
  63557. repaint (area.removeFromBottom (border.getBottom()));
  63558. }
  63559. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63560. const bool useBottomRightCornerResizer)
  63561. {
  63562. if (shouldBeResizable)
  63563. {
  63564. if (useBottomRightCornerResizer)
  63565. {
  63566. resizableBorder = 0;
  63567. if (resizableCorner == 0)
  63568. {
  63569. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63570. resizableCorner->setAlwaysOnTop (true);
  63571. }
  63572. }
  63573. else
  63574. {
  63575. resizableCorner = 0;
  63576. if (resizableBorder == 0)
  63577. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63578. }
  63579. }
  63580. else
  63581. {
  63582. resizableCorner = 0;
  63583. resizableBorder = 0;
  63584. }
  63585. if (isUsingNativeTitleBar())
  63586. recreateDesktopWindow();
  63587. childBoundsChanged (contentComponent);
  63588. resized();
  63589. }
  63590. bool ResizableWindow::isResizable() const throw()
  63591. {
  63592. return resizableCorner != 0
  63593. || resizableBorder != 0;
  63594. }
  63595. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63596. const int newMinimumHeight,
  63597. const int newMaximumWidth,
  63598. const int newMaximumHeight) throw()
  63599. {
  63600. // if you've set up a custom constrainer then these settings won't have any effect..
  63601. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63602. if (constrainer == 0)
  63603. setConstrainer (&defaultConstrainer);
  63604. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63605. newMaximumWidth, newMaximumHeight);
  63606. setBoundsConstrained (getBounds());
  63607. }
  63608. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63609. {
  63610. if (constrainer != newConstrainer)
  63611. {
  63612. constrainer = newConstrainer;
  63613. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63614. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63615. resizableCorner = 0;
  63616. resizableBorder = 0;
  63617. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63618. ComponentPeer* const peer = getPeer();
  63619. if (peer != 0)
  63620. peer->setConstrainer (newConstrainer);
  63621. }
  63622. }
  63623. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63624. {
  63625. if (constrainer != 0)
  63626. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63627. else
  63628. setBounds (bounds);
  63629. }
  63630. void ResizableWindow::paint (Graphics& g)
  63631. {
  63632. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63633. getBorderThickness(), *this);
  63634. if (! isFullScreen())
  63635. {
  63636. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63637. getBorderThickness(), *this);
  63638. }
  63639. #if JUCE_DEBUG
  63640. /* If this fails, then you've probably written a subclass with a resized()
  63641. callback but forgotten to make it call its parent class's resized() method.
  63642. It's important when you override methods like resized(), moved(),
  63643. etc., that you make sure the base class methods also get called.
  63644. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63645. because your content should all be inside the content component - and it's the
  63646. content component's resized() method that you should be using to do your
  63647. layout.
  63648. */
  63649. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63650. #endif
  63651. }
  63652. void ResizableWindow::lookAndFeelChanged()
  63653. {
  63654. resized();
  63655. if (isOnDesktop())
  63656. {
  63657. Component::addToDesktop (getDesktopWindowStyleFlags());
  63658. ComponentPeer* const peer = getPeer();
  63659. if (peer != 0)
  63660. peer->setConstrainer (constrainer);
  63661. }
  63662. }
  63663. const Colour ResizableWindow::getBackgroundColour() const throw()
  63664. {
  63665. return findColour (backgroundColourId, false);
  63666. }
  63667. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63668. {
  63669. Colour backgroundColour (newColour);
  63670. if (! Desktop::canUseSemiTransparentWindows())
  63671. backgroundColour = newColour.withAlpha (1.0f);
  63672. setColour (backgroundColourId, backgroundColour);
  63673. setOpaque (backgroundColour.isOpaque());
  63674. repaint();
  63675. }
  63676. bool ResizableWindow::isFullScreen() const
  63677. {
  63678. if (isOnDesktop())
  63679. {
  63680. ComponentPeer* const peer = getPeer();
  63681. return peer != 0 && peer->isFullScreen();
  63682. }
  63683. return fullscreen;
  63684. }
  63685. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63686. {
  63687. if (shouldBeFullScreen != isFullScreen())
  63688. {
  63689. updateLastPos();
  63690. fullscreen = shouldBeFullScreen;
  63691. if (isOnDesktop())
  63692. {
  63693. ComponentPeer* const peer = getPeer();
  63694. if (peer != 0)
  63695. {
  63696. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63697. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63698. peer->setFullScreen (shouldBeFullScreen);
  63699. if (! shouldBeFullScreen)
  63700. setBounds (lastPos);
  63701. }
  63702. else
  63703. {
  63704. jassertfalse;
  63705. }
  63706. }
  63707. else
  63708. {
  63709. if (shouldBeFullScreen)
  63710. setBounds (0, 0, getParentWidth(), getParentHeight());
  63711. else
  63712. setBounds (lastNonFullScreenPos);
  63713. }
  63714. resized();
  63715. }
  63716. }
  63717. bool ResizableWindow::isMinimised() const
  63718. {
  63719. ComponentPeer* const peer = getPeer();
  63720. return (peer != 0) && peer->isMinimised();
  63721. }
  63722. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63723. {
  63724. if (shouldMinimise != isMinimised())
  63725. {
  63726. ComponentPeer* const peer = getPeer();
  63727. if (peer != 0)
  63728. {
  63729. updateLastPos();
  63730. peer->setMinimised (shouldMinimise);
  63731. }
  63732. else
  63733. {
  63734. jassertfalse;
  63735. }
  63736. }
  63737. }
  63738. void ResizableWindow::updateLastPos()
  63739. {
  63740. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63741. {
  63742. lastNonFullScreenPos = getBounds();
  63743. }
  63744. }
  63745. void ResizableWindow::parentSizeChanged()
  63746. {
  63747. if (isFullScreen() && getParentComponent() != 0)
  63748. {
  63749. setBounds (0, 0, getParentWidth(), getParentHeight());
  63750. }
  63751. }
  63752. const String ResizableWindow::getWindowStateAsString()
  63753. {
  63754. updateLastPos();
  63755. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63756. }
  63757. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63758. {
  63759. StringArray tokens;
  63760. tokens.addTokens (s, false);
  63761. tokens.removeEmptyStrings();
  63762. tokens.trim();
  63763. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63764. const int firstCoord = fs ? 1 : 0;
  63765. if (tokens.size() != firstCoord + 4)
  63766. return false;
  63767. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63768. tokens[firstCoord + 1].getIntValue(),
  63769. tokens[firstCoord + 2].getIntValue(),
  63770. tokens[firstCoord + 3].getIntValue());
  63771. if (newPos.isEmpty())
  63772. return false;
  63773. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63774. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63775. if (peer != 0)
  63776. peer->getFrameSize().addTo (newPos);
  63777. if (! screen.contains (newPos))
  63778. {
  63779. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63780. jmin (newPos.getHeight(), screen.getHeight()));
  63781. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63782. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63783. }
  63784. if (peer != 0)
  63785. {
  63786. peer->getFrameSize().subtractFrom (newPos);
  63787. peer->setNonFullScreenBounds (newPos);
  63788. }
  63789. lastNonFullScreenPos = newPos;
  63790. setFullScreen (fs);
  63791. if (! fs)
  63792. setBoundsConstrained (newPos);
  63793. return true;
  63794. }
  63795. void ResizableWindow::mouseDown (const MouseEvent&)
  63796. {
  63797. if (! isFullScreen())
  63798. dragger.startDraggingComponent (this, constrainer);
  63799. }
  63800. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63801. {
  63802. if (! isFullScreen())
  63803. dragger.dragComponent (this, e);
  63804. }
  63805. #if JUCE_DEBUG
  63806. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63807. {
  63808. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63809. manages its child components automatically, and if you add your own it'll cause
  63810. trouble. Instead, use setContentComponent() to give it a component which
  63811. will be automatically resized and kept in the right place - then you can add
  63812. subcomponents to the content comp. See the notes for the ResizableWindow class
  63813. for more info.
  63814. If you really know what you're doing and want to avoid this assertion, just call
  63815. Component::addChildComponent directly.
  63816. */
  63817. jassertfalse;
  63818. Component::addChildComponent (child, zOrder);
  63819. }
  63820. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63821. {
  63822. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63823. manages its child components automatically, and if you add your own it'll cause
  63824. trouble. Instead, use setContentComponent() to give it a component which
  63825. will be automatically resized and kept in the right place - then you can add
  63826. subcomponents to the content comp. See the notes for the ResizableWindow class
  63827. for more info.
  63828. If you really know what you're doing and want to avoid this assertion, just call
  63829. Component::addAndMakeVisible directly.
  63830. */
  63831. jassertfalse;
  63832. Component::addAndMakeVisible (child, zOrder);
  63833. }
  63834. #endif
  63835. END_JUCE_NAMESPACE
  63836. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63837. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63838. BEGIN_JUCE_NAMESPACE
  63839. SplashScreen::SplashScreen()
  63840. {
  63841. setOpaque (true);
  63842. }
  63843. SplashScreen::~SplashScreen()
  63844. {
  63845. }
  63846. void SplashScreen::show (const String& title,
  63847. const Image& backgroundImage_,
  63848. const int minimumTimeToDisplayFor,
  63849. const bool useDropShadow,
  63850. const bool removeOnMouseClick)
  63851. {
  63852. backgroundImage = backgroundImage_;
  63853. jassert (backgroundImage_.isValid());
  63854. if (backgroundImage_.isValid())
  63855. {
  63856. setOpaque (! backgroundImage_.hasAlphaChannel());
  63857. show (title,
  63858. backgroundImage_.getWidth(),
  63859. backgroundImage_.getHeight(),
  63860. minimumTimeToDisplayFor,
  63861. useDropShadow,
  63862. removeOnMouseClick);
  63863. }
  63864. }
  63865. void SplashScreen::show (const String& title,
  63866. const int width,
  63867. const int height,
  63868. const int minimumTimeToDisplayFor,
  63869. const bool useDropShadow,
  63870. const bool removeOnMouseClick)
  63871. {
  63872. setName (title);
  63873. setAlwaysOnTop (true);
  63874. setVisible (true);
  63875. centreWithSize (width, height);
  63876. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63877. toFront (false);
  63878. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63879. repaint();
  63880. originalClickCounter = removeOnMouseClick
  63881. ? Desktop::getMouseButtonClickCounter()
  63882. : std::numeric_limits<int>::max();
  63883. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63884. startTimer (50);
  63885. }
  63886. void SplashScreen::paint (Graphics& g)
  63887. {
  63888. g.setOpacity (1.0f);
  63889. g.drawImage (backgroundImage,
  63890. 0, 0, getWidth(), getHeight(),
  63891. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63892. }
  63893. void SplashScreen::timerCallback()
  63894. {
  63895. if (Time::getCurrentTime() > earliestTimeToDelete
  63896. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63897. {
  63898. delete this;
  63899. }
  63900. }
  63901. END_JUCE_NAMESPACE
  63902. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63903. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63904. BEGIN_JUCE_NAMESPACE
  63905. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63906. const bool hasProgressBar,
  63907. const bool hasCancelButton,
  63908. const int timeOutMsWhenCancelling_,
  63909. const String& cancelButtonText)
  63910. : Thread ("Juce Progress Window"),
  63911. progress (0.0),
  63912. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63913. {
  63914. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63915. .createAlertWindow (title, String::empty, cancelButtonText,
  63916. String::empty, String::empty,
  63917. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63918. if (hasProgressBar)
  63919. alertWindow->addProgressBarComponent (progress);
  63920. }
  63921. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63922. {
  63923. stopThread (timeOutMsWhenCancelling);
  63924. }
  63925. bool ThreadWithProgressWindow::runThread (const int priority)
  63926. {
  63927. startThread (priority);
  63928. startTimer (100);
  63929. {
  63930. const ScopedLock sl (messageLock);
  63931. alertWindow->setMessage (message);
  63932. }
  63933. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63934. stopThread (timeOutMsWhenCancelling);
  63935. alertWindow->setVisible (false);
  63936. return finishedNaturally;
  63937. }
  63938. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63939. {
  63940. progress = newProgress;
  63941. }
  63942. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63943. {
  63944. const ScopedLock sl (messageLock);
  63945. message = newStatusMessage;
  63946. }
  63947. void ThreadWithProgressWindow::timerCallback()
  63948. {
  63949. if (! isThreadRunning())
  63950. {
  63951. // thread has finished normally..
  63952. alertWindow->exitModalState (1);
  63953. alertWindow->setVisible (false);
  63954. }
  63955. else
  63956. {
  63957. const ScopedLock sl (messageLock);
  63958. alertWindow->setMessage (message);
  63959. }
  63960. }
  63961. END_JUCE_NAMESPACE
  63962. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63963. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63964. BEGIN_JUCE_NAMESPACE
  63965. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63966. const int millisecondsBeforeTipAppears_)
  63967. : Component ("tooltip"),
  63968. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63969. mouseClicks (0),
  63970. lastHideTime (0),
  63971. lastComponentUnderMouse (0),
  63972. changedCompsSinceShown (true)
  63973. {
  63974. if (Desktop::getInstance().getMainMouseSource().canHover())
  63975. startTimer (123);
  63976. setAlwaysOnTop (true);
  63977. setOpaque (true);
  63978. if (parentComponent != 0)
  63979. parentComponent->addChildComponent (this);
  63980. }
  63981. TooltipWindow::~TooltipWindow()
  63982. {
  63983. hide();
  63984. }
  63985. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63986. {
  63987. millisecondsBeforeTipAppears = newTimeMs;
  63988. }
  63989. void TooltipWindow::paint (Graphics& g)
  63990. {
  63991. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63992. }
  63993. void TooltipWindow::mouseEnter (const MouseEvent&)
  63994. {
  63995. hide();
  63996. }
  63997. void TooltipWindow::showFor (const String& tip)
  63998. {
  63999. jassert (tip.isNotEmpty());
  64000. if (tipShowing != tip)
  64001. repaint();
  64002. tipShowing = tip;
  64003. Point<int> mousePos (Desktop::getMousePosition());
  64004. if (getParentComponent() != 0)
  64005. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64006. int x, y, w, h;
  64007. getLookAndFeel().getTooltipSize (tip, w, h);
  64008. if (mousePos.getX() > getParentWidth() / 2)
  64009. x = mousePos.getX() - (w + 12);
  64010. else
  64011. x = mousePos.getX() + 24;
  64012. if (mousePos.getY() > getParentHeight() / 2)
  64013. y = mousePos.getY() - (h + 6);
  64014. else
  64015. y = mousePos.getY() + 6;
  64016. setBounds (x, y, w, h);
  64017. setVisible (true);
  64018. if (getParentComponent() == 0)
  64019. {
  64020. addToDesktop (ComponentPeer::windowHasDropShadow
  64021. | ComponentPeer::windowIsTemporary
  64022. | ComponentPeer::windowIgnoresKeyPresses);
  64023. }
  64024. toFront (false);
  64025. }
  64026. const String TooltipWindow::getTipFor (Component* const c)
  64027. {
  64028. if (c != 0
  64029. && Process::isForegroundProcess()
  64030. && ! Component::isMouseButtonDownAnywhere())
  64031. {
  64032. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64033. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64034. return ttc->getTooltip();
  64035. }
  64036. return String::empty;
  64037. }
  64038. void TooltipWindow::hide()
  64039. {
  64040. tipShowing = String::empty;
  64041. removeFromDesktop();
  64042. setVisible (false);
  64043. }
  64044. void TooltipWindow::timerCallback()
  64045. {
  64046. const unsigned int now = Time::getApproximateMillisecondCounter();
  64047. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64048. const String newTip (getTipFor (newComp));
  64049. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64050. lastComponentUnderMouse = newComp;
  64051. lastTipUnderMouse = newTip;
  64052. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64053. const bool mouseWasClicked = clickCount > mouseClicks;
  64054. mouseClicks = clickCount;
  64055. const Point<int> mousePos (Desktop::getMousePosition());
  64056. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64057. lastMousePos = mousePos;
  64058. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64059. lastCompChangeTime = now;
  64060. if (isVisible() || now < lastHideTime + 500)
  64061. {
  64062. // if a tip is currently visible (or has just disappeared), update to a new one
  64063. // immediately if needed..
  64064. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64065. {
  64066. if (isVisible())
  64067. {
  64068. lastHideTime = now;
  64069. hide();
  64070. }
  64071. }
  64072. else if (tipChanged)
  64073. {
  64074. showFor (newTip);
  64075. }
  64076. }
  64077. else
  64078. {
  64079. // if there isn't currently a tip, but one is needed, only let it
  64080. // appear after a timeout..
  64081. if (newTip.isNotEmpty()
  64082. && newTip != tipShowing
  64083. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64084. {
  64085. showFor (newTip);
  64086. }
  64087. }
  64088. }
  64089. END_JUCE_NAMESPACE
  64090. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64091. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64092. BEGIN_JUCE_NAMESPACE
  64093. /** Keeps track of the active top level window.
  64094. */
  64095. class TopLevelWindowManager : public Timer,
  64096. public DeletedAtShutdown
  64097. {
  64098. public:
  64099. TopLevelWindowManager()
  64100. : currentActive (0)
  64101. {
  64102. }
  64103. ~TopLevelWindowManager()
  64104. {
  64105. clearSingletonInstance();
  64106. }
  64107. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64108. void timerCallback()
  64109. {
  64110. startTimer (jmin (1731, getTimerInterval() * 2));
  64111. TopLevelWindow* active = 0;
  64112. if (Process::isForegroundProcess())
  64113. {
  64114. active = currentActive;
  64115. Component* const c = Component::getCurrentlyFocusedComponent();
  64116. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64117. if (tlw == 0 && c != 0)
  64118. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64119. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64120. if (tlw != 0)
  64121. active = tlw;
  64122. }
  64123. if (active != currentActive)
  64124. {
  64125. currentActive = active;
  64126. for (int i = windows.size(); --i >= 0;)
  64127. {
  64128. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64129. tlw->setWindowActive (isWindowActive (tlw));
  64130. i = jmin (i, windows.size() - 1);
  64131. }
  64132. Desktop::getInstance().triggerFocusCallback();
  64133. }
  64134. }
  64135. bool addWindow (TopLevelWindow* const w)
  64136. {
  64137. windows.add (w);
  64138. startTimer (10);
  64139. return isWindowActive (w);
  64140. }
  64141. void removeWindow (TopLevelWindow* const w)
  64142. {
  64143. startTimer (10);
  64144. if (currentActive == w)
  64145. currentActive = 0;
  64146. windows.removeValue (w);
  64147. if (windows.size() == 0)
  64148. deleteInstance();
  64149. }
  64150. Array <TopLevelWindow*> windows;
  64151. private:
  64152. TopLevelWindow* currentActive;
  64153. bool isWindowActive (TopLevelWindow* const tlw) const
  64154. {
  64155. return (tlw == currentActive
  64156. || tlw->isParentOf (currentActive)
  64157. || tlw->hasKeyboardFocus (true))
  64158. && tlw->isShowing();
  64159. }
  64160. TopLevelWindowManager (const TopLevelWindowManager&);
  64161. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64162. };
  64163. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64164. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64165. {
  64166. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64167. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64168. }
  64169. TopLevelWindow::TopLevelWindow (const String& name,
  64170. const bool addToDesktop_)
  64171. : Component (name),
  64172. useDropShadow (true),
  64173. useNativeTitleBar (false),
  64174. windowIsActive_ (false)
  64175. {
  64176. setOpaque (true);
  64177. if (addToDesktop_)
  64178. Component::addToDesktop (getDesktopWindowStyleFlags());
  64179. else
  64180. setDropShadowEnabled (true);
  64181. setWantsKeyboardFocus (true);
  64182. setBroughtToFrontOnMouseClick (true);
  64183. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64184. }
  64185. TopLevelWindow::~TopLevelWindow()
  64186. {
  64187. shadower = 0;
  64188. TopLevelWindowManager::getInstance()->removeWindow (this);
  64189. }
  64190. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64191. {
  64192. if (hasKeyboardFocus (true))
  64193. TopLevelWindowManager::getInstance()->timerCallback();
  64194. else
  64195. TopLevelWindowManager::getInstance()->startTimer (10);
  64196. }
  64197. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64198. {
  64199. if (windowIsActive_ != isNowActive)
  64200. {
  64201. windowIsActive_ = isNowActive;
  64202. activeWindowStatusChanged();
  64203. }
  64204. }
  64205. void TopLevelWindow::activeWindowStatusChanged()
  64206. {
  64207. }
  64208. void TopLevelWindow::parentHierarchyChanged()
  64209. {
  64210. setDropShadowEnabled (useDropShadow);
  64211. }
  64212. void TopLevelWindow::visibilityChanged()
  64213. {
  64214. if (isShowing())
  64215. toFront (true);
  64216. }
  64217. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64218. {
  64219. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64220. if (useDropShadow)
  64221. styleFlags |= ComponentPeer::windowHasDropShadow;
  64222. if (useNativeTitleBar)
  64223. styleFlags |= ComponentPeer::windowHasTitleBar;
  64224. return styleFlags;
  64225. }
  64226. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64227. {
  64228. useDropShadow = useShadow;
  64229. if (isOnDesktop())
  64230. {
  64231. shadower = 0;
  64232. Component::addToDesktop (getDesktopWindowStyleFlags());
  64233. }
  64234. else
  64235. {
  64236. if (useShadow && isOpaque())
  64237. {
  64238. if (shadower == 0)
  64239. {
  64240. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64241. if (shadower != 0)
  64242. shadower->setOwner (this);
  64243. }
  64244. }
  64245. else
  64246. {
  64247. shadower = 0;
  64248. }
  64249. }
  64250. }
  64251. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64252. {
  64253. if (useNativeTitleBar != useNativeTitleBar_)
  64254. {
  64255. useNativeTitleBar = useNativeTitleBar_;
  64256. recreateDesktopWindow();
  64257. sendLookAndFeelChange();
  64258. }
  64259. }
  64260. void TopLevelWindow::recreateDesktopWindow()
  64261. {
  64262. if (isOnDesktop())
  64263. {
  64264. Component::addToDesktop (getDesktopWindowStyleFlags());
  64265. toFront (true);
  64266. }
  64267. }
  64268. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64269. {
  64270. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64271. because this class needs to make sure its layout corresponds with settings like whether
  64272. it's got a native title bar or not.
  64273. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64274. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64275. method, then add or remove whatever flags are necessary from this value before returning it.
  64276. */
  64277. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64278. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64279. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64280. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64281. sendLookAndFeelChange();
  64282. }
  64283. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64284. {
  64285. if (c == 0)
  64286. c = TopLevelWindow::getActiveTopLevelWindow();
  64287. if (c == 0)
  64288. {
  64289. centreWithSize (width, height);
  64290. }
  64291. else
  64292. {
  64293. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64294. (c->getHeight() - height) / 2)));
  64295. Rectangle<int> parentArea (c->getParentMonitorArea());
  64296. if (getParentComponent() != 0)
  64297. {
  64298. p = getParentComponent()->globalPositionToRelative (p);
  64299. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64300. }
  64301. parentArea.reduce (12, 12);
  64302. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64303. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64304. width, height);
  64305. }
  64306. }
  64307. int TopLevelWindow::getNumTopLevelWindows() throw()
  64308. {
  64309. return TopLevelWindowManager::getInstance()->windows.size();
  64310. }
  64311. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64312. {
  64313. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64314. }
  64315. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64316. {
  64317. TopLevelWindow* best = 0;
  64318. int bestNumTWLParents = -1;
  64319. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64320. {
  64321. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64322. if (tlw->isActiveWindow())
  64323. {
  64324. int numTWLParents = 0;
  64325. const Component* c = tlw->getParentComponent();
  64326. while (c != 0)
  64327. {
  64328. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64329. ++numTWLParents;
  64330. c = c->getParentComponent();
  64331. }
  64332. if (bestNumTWLParents < numTWLParents)
  64333. {
  64334. best = tlw;
  64335. bestNumTWLParents = numTWLParents;
  64336. }
  64337. }
  64338. }
  64339. return best;
  64340. }
  64341. END_JUCE_NAMESPACE
  64342. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64343. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64344. BEGIN_JUCE_NAMESPACE
  64345. namespace RelativeCoordinateHelpers
  64346. {
  64347. static void skipComma (const juce_wchar* const s, int& i)
  64348. {
  64349. while (CharacterFunctions::isWhitespace (s[i]))
  64350. ++i;
  64351. if (s[i] == ',')
  64352. ++i;
  64353. }
  64354. }
  64355. const String RelativeCoordinate::Strings::parent ("parent");
  64356. const String RelativeCoordinate::Strings::left ("left");
  64357. const String RelativeCoordinate::Strings::right ("right");
  64358. const String RelativeCoordinate::Strings::top ("top");
  64359. const String RelativeCoordinate::Strings::bottom ("bottom");
  64360. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64361. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64362. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64363. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64364. RelativeCoordinate::RelativeCoordinate()
  64365. {
  64366. }
  64367. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64368. : term (term_)
  64369. {
  64370. }
  64371. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64372. : term (other.term)
  64373. {
  64374. }
  64375. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64376. {
  64377. term = other.term;
  64378. return *this;
  64379. }
  64380. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64381. : term (absoluteDistanceFromOrigin)
  64382. {
  64383. }
  64384. RelativeCoordinate::RelativeCoordinate (const String& s)
  64385. {
  64386. try
  64387. {
  64388. term = Expression (s);
  64389. }
  64390. catch (...)
  64391. {}
  64392. }
  64393. RelativeCoordinate::~RelativeCoordinate()
  64394. {
  64395. }
  64396. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64397. {
  64398. return term.toString() == other.term.toString();
  64399. }
  64400. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64401. {
  64402. return ! operator== (other);
  64403. }
  64404. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64405. {
  64406. try
  64407. {
  64408. if (context != 0)
  64409. return term.evaluate (*context);
  64410. else
  64411. return term.evaluate();
  64412. }
  64413. catch (...)
  64414. {}
  64415. return 0.0;
  64416. }
  64417. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64418. {
  64419. try
  64420. {
  64421. if (context != 0)
  64422. term.evaluate (*context);
  64423. else
  64424. term.evaluate();
  64425. }
  64426. catch (...)
  64427. {
  64428. return true;
  64429. }
  64430. return false;
  64431. }
  64432. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64433. {
  64434. try
  64435. {
  64436. if (context != 0)
  64437. {
  64438. term = term.adjustedToGiveNewResult (newPos, *context);
  64439. }
  64440. else
  64441. {
  64442. Expression::EvaluationContext defaultContext;
  64443. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64444. }
  64445. }
  64446. catch (...)
  64447. {}
  64448. }
  64449. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64450. {
  64451. try
  64452. {
  64453. return term.referencesSymbol (coordName, context);
  64454. }
  64455. catch (...)
  64456. {}
  64457. return false;
  64458. }
  64459. bool RelativeCoordinate::isDynamic() const
  64460. {
  64461. return term.usesAnySymbols();
  64462. }
  64463. const String RelativeCoordinate::toString() const
  64464. {
  64465. return term.toString();
  64466. }
  64467. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64468. {
  64469. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64470. if (term.referencesSymbol (oldName, 0))
  64471. term = term.withRenamedSymbol (oldName, newName);
  64472. }
  64473. RelativePoint::RelativePoint()
  64474. {
  64475. }
  64476. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64477. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64478. {
  64479. }
  64480. RelativePoint::RelativePoint (const float x_, const float y_)
  64481. : x (x_), y (y_)
  64482. {
  64483. }
  64484. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64485. : x (x_), y (y_)
  64486. {
  64487. }
  64488. RelativePoint::RelativePoint (const String& s)
  64489. {
  64490. int i = 0;
  64491. x = RelativeCoordinate (Expression::parse (s, i));
  64492. RelativeCoordinateHelpers::skipComma (s, i);
  64493. y = RelativeCoordinate (Expression::parse (s, i));
  64494. }
  64495. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64496. {
  64497. return x == other.x && y == other.y;
  64498. }
  64499. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64500. {
  64501. return ! operator== (other);
  64502. }
  64503. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64504. {
  64505. return Point<float> ((float) x.resolve (context),
  64506. (float) y.resolve (context));
  64507. }
  64508. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64509. {
  64510. x.moveToAbsolute (newPos.getX(), context);
  64511. y.moveToAbsolute (newPos.getY(), context);
  64512. }
  64513. const String RelativePoint::toString() const
  64514. {
  64515. return x.toString() + ", " + y.toString();
  64516. }
  64517. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64518. {
  64519. x.renameSymbolIfUsed (oldName, newName);
  64520. y.renameSymbolIfUsed (oldName, newName);
  64521. }
  64522. bool RelativePoint::isDynamic() const
  64523. {
  64524. return x.isDynamic() || y.isDynamic();
  64525. }
  64526. RelativeRectangle::RelativeRectangle()
  64527. {
  64528. }
  64529. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64530. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64531. : left (left_), right (right_), top (top_), bottom (bottom_)
  64532. {
  64533. }
  64534. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64535. : left (rect.getX()),
  64536. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64537. top (rect.getY()),
  64538. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64539. {
  64540. }
  64541. RelativeRectangle::RelativeRectangle (const String& s)
  64542. {
  64543. int i = 0;
  64544. left = RelativeCoordinate (Expression::parse (s, i));
  64545. RelativeCoordinateHelpers::skipComma (s, i);
  64546. top = RelativeCoordinate (Expression::parse (s, i));
  64547. RelativeCoordinateHelpers::skipComma (s, i);
  64548. right = RelativeCoordinate (Expression::parse (s, i));
  64549. RelativeCoordinateHelpers::skipComma (s, i);
  64550. bottom = RelativeCoordinate (Expression::parse (s, i));
  64551. }
  64552. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64553. {
  64554. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64555. }
  64556. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64557. {
  64558. return ! operator== (other);
  64559. }
  64560. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64561. {
  64562. const double l = left.resolve (context);
  64563. const double r = right.resolve (context);
  64564. const double t = top.resolve (context);
  64565. const double b = bottom.resolve (context);
  64566. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64567. }
  64568. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64569. {
  64570. left.moveToAbsolute (newPos.getX(), context);
  64571. right.moveToAbsolute (newPos.getRight(), context);
  64572. top.moveToAbsolute (newPos.getY(), context);
  64573. bottom.moveToAbsolute (newPos.getBottom(), context);
  64574. }
  64575. const String RelativeRectangle::toString() const
  64576. {
  64577. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64578. }
  64579. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64580. {
  64581. left.renameSymbolIfUsed (oldName, newName);
  64582. right.renameSymbolIfUsed (oldName, newName);
  64583. top.renameSymbolIfUsed (oldName, newName);
  64584. bottom.renameSymbolIfUsed (oldName, newName);
  64585. }
  64586. RelativePointPath::RelativePointPath()
  64587. : usesNonZeroWinding (true),
  64588. containsDynamicPoints (false)
  64589. {
  64590. }
  64591. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64592. : usesNonZeroWinding (true),
  64593. containsDynamicPoints (false)
  64594. {
  64595. ValueTree state (DrawablePath::valueTreeType);
  64596. other.writeTo (state, 0);
  64597. parse (state);
  64598. }
  64599. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64600. : usesNonZeroWinding (true),
  64601. containsDynamicPoints (false)
  64602. {
  64603. parse (drawable);
  64604. }
  64605. RelativePointPath::RelativePointPath (const Path& path)
  64606. {
  64607. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64608. Path::Iterator i (path);
  64609. while (i.next())
  64610. {
  64611. switch (i.elementType)
  64612. {
  64613. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64614. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64615. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64616. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64617. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64618. default: jassertfalse; break;
  64619. }
  64620. }
  64621. }
  64622. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64623. {
  64624. DrawablePath::ValueTreeWrapper wrapper (state);
  64625. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64626. ValueTree pathTree (wrapper.getPathState());
  64627. pathTree.removeAllChildren (undoManager);
  64628. for (int i = 0; i < elements.size(); ++i)
  64629. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64630. }
  64631. void RelativePointPath::parse (const ValueTree& state)
  64632. {
  64633. DrawablePath::ValueTreeWrapper wrapper (state);
  64634. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64635. RelativePoint points[3];
  64636. const ValueTree pathTree (wrapper.getPathState());
  64637. const int num = pathTree.getNumChildren();
  64638. for (int i = 0; i < num; ++i)
  64639. {
  64640. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64641. const int numCps = e.getNumControlPoints();
  64642. for (int j = 0; j < numCps; ++j)
  64643. {
  64644. points[j] = e.getControlPoint (j);
  64645. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64646. }
  64647. const Identifier type (e.getType());
  64648. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64649. elements.add (new StartSubPath (points[0]));
  64650. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64651. elements.add (new CloseSubPath());
  64652. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64653. elements.add (new LineTo (points[0]));
  64654. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64655. elements.add (new QuadraticTo (points[0], points[1]));
  64656. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64657. elements.add (new CubicTo (points[0], points[1], points[2]));
  64658. else
  64659. jassertfalse;
  64660. }
  64661. }
  64662. RelativePointPath::~RelativePointPath()
  64663. {
  64664. }
  64665. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64666. {
  64667. elements.swapWithArray (other.elements);
  64668. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64669. }
  64670. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64671. {
  64672. for (int i = 0; i < elements.size(); ++i)
  64673. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64674. }
  64675. bool RelativePointPath::containsAnyDynamicPoints() const
  64676. {
  64677. return containsDynamicPoints;
  64678. }
  64679. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64680. {
  64681. }
  64682. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64683. : ElementBase (startSubPathElement), startPos (pos)
  64684. {
  64685. }
  64686. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64687. {
  64688. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64689. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64690. return v;
  64691. }
  64692. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64693. {
  64694. path.startNewSubPath (startPos.resolve (coordFinder));
  64695. }
  64696. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64697. {
  64698. numPoints = 1;
  64699. return &startPos;
  64700. }
  64701. RelativePointPath::CloseSubPath::CloseSubPath()
  64702. : ElementBase (closeSubPathElement)
  64703. {
  64704. }
  64705. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64706. {
  64707. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64708. }
  64709. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64710. {
  64711. path.closeSubPath();
  64712. }
  64713. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64714. {
  64715. numPoints = 0;
  64716. return 0;
  64717. }
  64718. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64719. : ElementBase (lineToElement), endPoint (endPoint_)
  64720. {
  64721. }
  64722. const ValueTree RelativePointPath::LineTo::createTree() const
  64723. {
  64724. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64725. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64726. return v;
  64727. }
  64728. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64729. {
  64730. path.lineTo (endPoint.resolve (coordFinder));
  64731. }
  64732. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64733. {
  64734. numPoints = 1;
  64735. return &endPoint;
  64736. }
  64737. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64738. : ElementBase (quadraticToElement)
  64739. {
  64740. controlPoints[0] = controlPoint;
  64741. controlPoints[1] = endPoint;
  64742. }
  64743. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64744. {
  64745. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64746. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64747. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64748. return v;
  64749. }
  64750. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64751. {
  64752. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64753. controlPoints[1].resolve (coordFinder));
  64754. }
  64755. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64756. {
  64757. numPoints = 2;
  64758. return controlPoints;
  64759. }
  64760. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64761. : ElementBase (cubicToElement)
  64762. {
  64763. controlPoints[0] = controlPoint1;
  64764. controlPoints[1] = controlPoint2;
  64765. controlPoints[2] = endPoint;
  64766. }
  64767. const ValueTree RelativePointPath::CubicTo::createTree() const
  64768. {
  64769. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64770. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64771. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64772. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64773. return v;
  64774. }
  64775. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64776. {
  64777. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64778. controlPoints[1].resolve (coordFinder),
  64779. controlPoints[2].resolve (coordFinder));
  64780. }
  64781. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64782. {
  64783. numPoints = 3;
  64784. return controlPoints;
  64785. }
  64786. RelativeParallelogram::RelativeParallelogram()
  64787. {
  64788. }
  64789. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64790. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64791. {
  64792. }
  64793. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64794. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64795. {
  64796. }
  64797. RelativeParallelogram::~RelativeParallelogram()
  64798. {
  64799. }
  64800. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64801. {
  64802. points[0] = topLeft.resolve (coordFinder);
  64803. points[1] = topRight.resolve (coordFinder);
  64804. points[2] = bottomLeft.resolve (coordFinder);
  64805. }
  64806. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64807. {
  64808. resolveThreePoints (points, coordFinder);
  64809. points[3] = points[1] + (points[2] - points[0]);
  64810. }
  64811. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64812. {
  64813. Point<float> points[4];
  64814. resolveFourCorners (points, coordFinder);
  64815. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64816. }
  64817. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64818. {
  64819. Point<float> points[4];
  64820. resolveFourCorners (points, coordFinder);
  64821. path.startNewSubPath (points[0]);
  64822. path.lineTo (points[1]);
  64823. path.lineTo (points[3]);
  64824. path.lineTo (points[2]);
  64825. path.closeSubPath();
  64826. }
  64827. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64828. {
  64829. Point<float> corners[3];
  64830. resolveThreePoints (corners, coordFinder);
  64831. const Line<float> top (corners[0], corners[1]);
  64832. const Line<float> left (corners[0], corners[2]);
  64833. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64834. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64835. topRight.moveToAbsolute (newTopRight, coordFinder);
  64836. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64837. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64838. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64839. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64840. }
  64841. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64842. {
  64843. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64844. }
  64845. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64846. {
  64847. return ! operator== (other);
  64848. }
  64849. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64850. {
  64851. const Point<float> tr (corners[1] - corners[0]);
  64852. const Point<float> bl (corners[2] - corners[0]);
  64853. target -= corners[0];
  64854. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64855. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64856. }
  64857. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64858. {
  64859. return corners[0]
  64860. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64861. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64862. }
  64863. END_JUCE_NAMESPACE
  64864. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64865. #endif
  64866. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64867. /*** Start of inlined file: juce_Colour.cpp ***/
  64868. BEGIN_JUCE_NAMESPACE
  64869. namespace ColourHelpers
  64870. {
  64871. static uint8 floatAlphaToInt (const float alpha) throw()
  64872. {
  64873. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64874. }
  64875. static void convertHSBtoRGB (float h, float s, float v,
  64876. uint8& r, uint8& g, uint8& b) throw()
  64877. {
  64878. v = jlimit (0.0f, 1.0f, v);
  64879. v *= 255.0f;
  64880. const uint8 intV = (uint8) roundToInt (v);
  64881. if (s <= 0)
  64882. {
  64883. r = intV;
  64884. g = intV;
  64885. b = intV;
  64886. }
  64887. else
  64888. {
  64889. s = jmin (1.0f, s);
  64890. h = jlimit (0.0f, 1.0f, h);
  64891. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64892. const float f = h - std::floor (h);
  64893. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64894. const float y = v * (1.0f - s * f);
  64895. const float z = v * (1.0f - (s * (1.0f - f)));
  64896. if (h < 1.0f)
  64897. {
  64898. r = intV;
  64899. g = (uint8) roundToInt (z);
  64900. b = x;
  64901. }
  64902. else if (h < 2.0f)
  64903. {
  64904. r = (uint8) roundToInt (y);
  64905. g = intV;
  64906. b = x;
  64907. }
  64908. else if (h < 3.0f)
  64909. {
  64910. r = x;
  64911. g = intV;
  64912. b = (uint8) roundToInt (z);
  64913. }
  64914. else if (h < 4.0f)
  64915. {
  64916. r = x;
  64917. g = (uint8) roundToInt (y);
  64918. b = intV;
  64919. }
  64920. else if (h < 5.0f)
  64921. {
  64922. r = (uint8) roundToInt (z);
  64923. g = x;
  64924. b = intV;
  64925. }
  64926. else if (h < 6.0f)
  64927. {
  64928. r = intV;
  64929. g = x;
  64930. b = (uint8) roundToInt (y);
  64931. }
  64932. else
  64933. {
  64934. r = 0;
  64935. g = 0;
  64936. b = 0;
  64937. }
  64938. }
  64939. }
  64940. }
  64941. Colour::Colour() throw()
  64942. : argb (0)
  64943. {
  64944. }
  64945. Colour::Colour (const Colour& other) throw()
  64946. : argb (other.argb)
  64947. {
  64948. }
  64949. Colour& Colour::operator= (const Colour& other) throw()
  64950. {
  64951. argb = other.argb;
  64952. return *this;
  64953. }
  64954. bool Colour::operator== (const Colour& other) const throw()
  64955. {
  64956. return argb.getARGB() == other.argb.getARGB();
  64957. }
  64958. bool Colour::operator!= (const Colour& other) const throw()
  64959. {
  64960. return argb.getARGB() != other.argb.getARGB();
  64961. }
  64962. Colour::Colour (const uint32 argb_) throw()
  64963. : argb (argb_)
  64964. {
  64965. }
  64966. Colour::Colour (const uint8 red,
  64967. const uint8 green,
  64968. const uint8 blue) throw()
  64969. {
  64970. argb.setARGB (0xff, red, green, blue);
  64971. }
  64972. const Colour Colour::fromRGB (const uint8 red,
  64973. const uint8 green,
  64974. const uint8 blue) throw()
  64975. {
  64976. return Colour (red, green, blue);
  64977. }
  64978. Colour::Colour (const uint8 red,
  64979. const uint8 green,
  64980. const uint8 blue,
  64981. const uint8 alpha) throw()
  64982. {
  64983. argb.setARGB (alpha, red, green, blue);
  64984. }
  64985. const Colour Colour::fromRGBA (const uint8 red,
  64986. const uint8 green,
  64987. const uint8 blue,
  64988. const uint8 alpha) throw()
  64989. {
  64990. return Colour (red, green, blue, alpha);
  64991. }
  64992. Colour::Colour (const uint8 red,
  64993. const uint8 green,
  64994. const uint8 blue,
  64995. const float alpha) throw()
  64996. {
  64997. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64998. }
  64999. const Colour Colour::fromRGBAFloat (const uint8 red,
  65000. const uint8 green,
  65001. const uint8 blue,
  65002. const float alpha) throw()
  65003. {
  65004. return Colour (red, green, blue, alpha);
  65005. }
  65006. Colour::Colour (const float hue,
  65007. const float saturation,
  65008. const float brightness,
  65009. const float alpha) throw()
  65010. {
  65011. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65012. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65013. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65014. }
  65015. const Colour Colour::fromHSV (const float hue,
  65016. const float saturation,
  65017. const float brightness,
  65018. const float alpha) throw()
  65019. {
  65020. return Colour (hue, saturation, brightness, alpha);
  65021. }
  65022. Colour::Colour (const float hue,
  65023. const float saturation,
  65024. const float brightness,
  65025. const uint8 alpha) throw()
  65026. {
  65027. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65028. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65029. argb.setARGB (alpha, r, g, b);
  65030. }
  65031. Colour::~Colour() throw()
  65032. {
  65033. }
  65034. const PixelARGB Colour::getPixelARGB() const throw()
  65035. {
  65036. PixelARGB p (argb);
  65037. p.premultiply();
  65038. return p;
  65039. }
  65040. uint32 Colour::getARGB() const throw()
  65041. {
  65042. return argb.getARGB();
  65043. }
  65044. bool Colour::isTransparent() const throw()
  65045. {
  65046. return getAlpha() == 0;
  65047. }
  65048. bool Colour::isOpaque() const throw()
  65049. {
  65050. return getAlpha() == 0xff;
  65051. }
  65052. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65053. {
  65054. PixelARGB newCol (argb);
  65055. newCol.setAlpha (newAlpha);
  65056. return Colour (newCol.getARGB());
  65057. }
  65058. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65059. {
  65060. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65061. PixelARGB newCol (argb);
  65062. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65063. return Colour (newCol.getARGB());
  65064. }
  65065. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65066. {
  65067. jassert (alphaMultiplier >= 0);
  65068. PixelARGB newCol (argb);
  65069. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65070. return Colour (newCol.getARGB());
  65071. }
  65072. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65073. {
  65074. const int destAlpha = getAlpha();
  65075. if (destAlpha > 0)
  65076. {
  65077. const int invA = 0xff - (int) src.getAlpha();
  65078. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65079. if (resA > 0)
  65080. {
  65081. const int da = (invA * destAlpha) / resA;
  65082. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65083. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65084. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65085. (uint8) resA);
  65086. }
  65087. return *this;
  65088. }
  65089. else
  65090. {
  65091. return src;
  65092. }
  65093. }
  65094. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65095. {
  65096. if (proportionOfOther <= 0)
  65097. return *this;
  65098. if (proportionOfOther >= 1.0f)
  65099. return other;
  65100. PixelARGB c1 (getPixelARGB());
  65101. const PixelARGB c2 (other.getPixelARGB());
  65102. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65103. c1.unpremultiply();
  65104. return Colour (c1.getARGB());
  65105. }
  65106. float Colour::getFloatRed() const throw()
  65107. {
  65108. return getRed() / 255.0f;
  65109. }
  65110. float Colour::getFloatGreen() const throw()
  65111. {
  65112. return getGreen() / 255.0f;
  65113. }
  65114. float Colour::getFloatBlue() const throw()
  65115. {
  65116. return getBlue() / 255.0f;
  65117. }
  65118. float Colour::getFloatAlpha() const throw()
  65119. {
  65120. return getAlpha() / 255.0f;
  65121. }
  65122. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65123. {
  65124. const int r = getRed();
  65125. const int g = getGreen();
  65126. const int b = getBlue();
  65127. const int hi = jmax (r, g, b);
  65128. const int lo = jmin (r, g, b);
  65129. if (hi != 0)
  65130. {
  65131. s = (hi - lo) / (float) hi;
  65132. if (s != 0)
  65133. {
  65134. const float invDiff = 1.0f / (hi - lo);
  65135. const float red = (hi - r) * invDiff;
  65136. const float green = (hi - g) * invDiff;
  65137. const float blue = (hi - b) * invDiff;
  65138. if (r == hi)
  65139. h = blue - green;
  65140. else if (g == hi)
  65141. h = 2.0f + red - blue;
  65142. else
  65143. h = 4.0f + green - red;
  65144. h *= 1.0f / 6.0f;
  65145. if (h < 0)
  65146. ++h;
  65147. }
  65148. else
  65149. {
  65150. h = 0;
  65151. }
  65152. }
  65153. else
  65154. {
  65155. s = 0;
  65156. h = 0;
  65157. }
  65158. v = hi / 255.0f;
  65159. }
  65160. float Colour::getHue() const throw()
  65161. {
  65162. float h, s, b;
  65163. getHSB (h, s, b);
  65164. return h;
  65165. }
  65166. const Colour Colour::withHue (const float hue) const throw()
  65167. {
  65168. float h, s, b;
  65169. getHSB (h, s, b);
  65170. return Colour (hue, s, b, getAlpha());
  65171. }
  65172. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65173. {
  65174. float h, s, b;
  65175. getHSB (h, s, b);
  65176. h += amountToRotate;
  65177. h -= std::floor (h);
  65178. return Colour (h, s, b, getAlpha());
  65179. }
  65180. float Colour::getSaturation() const throw()
  65181. {
  65182. float h, s, b;
  65183. getHSB (h, s, b);
  65184. return s;
  65185. }
  65186. const Colour Colour::withSaturation (const float saturation) const throw()
  65187. {
  65188. float h, s, b;
  65189. getHSB (h, s, b);
  65190. return Colour (h, saturation, b, getAlpha());
  65191. }
  65192. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65193. {
  65194. float h, s, b;
  65195. getHSB (h, s, b);
  65196. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65197. }
  65198. float Colour::getBrightness() const throw()
  65199. {
  65200. float h, s, b;
  65201. getHSB (h, s, b);
  65202. return b;
  65203. }
  65204. const Colour Colour::withBrightness (const float brightness) const throw()
  65205. {
  65206. float h, s, b;
  65207. getHSB (h, s, b);
  65208. return Colour (h, s, brightness, getAlpha());
  65209. }
  65210. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65211. {
  65212. float h, s, b;
  65213. getHSB (h, s, b);
  65214. b *= amount;
  65215. if (b > 1.0f)
  65216. b = 1.0f;
  65217. return Colour (h, s, b, getAlpha());
  65218. }
  65219. const Colour Colour::brighter (float amount) const throw()
  65220. {
  65221. amount = 1.0f / (1.0f + amount);
  65222. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65223. (uint8) (255 - (amount * (255 - getGreen()))),
  65224. (uint8) (255 - (amount * (255 - getBlue()))),
  65225. getAlpha());
  65226. }
  65227. const Colour Colour::darker (float amount) const throw()
  65228. {
  65229. amount = 1.0f / (1.0f + amount);
  65230. return Colour ((uint8) (amount * getRed()),
  65231. (uint8) (amount * getGreen()),
  65232. (uint8) (amount * getBlue()),
  65233. getAlpha());
  65234. }
  65235. const Colour Colour::greyLevel (const float brightness) throw()
  65236. {
  65237. const uint8 level
  65238. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65239. return Colour (level, level, level);
  65240. }
  65241. const Colour Colour::contrasting (const float amount) const throw()
  65242. {
  65243. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65244. ? Colours::black
  65245. : Colours::white).withAlpha (amount));
  65246. }
  65247. const Colour Colour::contrasting (const Colour& colour1,
  65248. const Colour& colour2) throw()
  65249. {
  65250. const float b1 = colour1.getBrightness();
  65251. const float b2 = colour2.getBrightness();
  65252. float best = 0.0f;
  65253. float bestDist = 0.0f;
  65254. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65255. {
  65256. const float d1 = std::abs (i - b1);
  65257. const float d2 = std::abs (i - b2);
  65258. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65259. if (dist > bestDist)
  65260. {
  65261. best = i;
  65262. bestDist = dist;
  65263. }
  65264. }
  65265. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65266. .withBrightness (best);
  65267. }
  65268. const String Colour::toString() const
  65269. {
  65270. return String::toHexString ((int) argb.getARGB());
  65271. }
  65272. const Colour Colour::fromString (const String& encodedColourString)
  65273. {
  65274. return Colour ((uint32) encodedColourString.getHexValue32());
  65275. }
  65276. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65277. {
  65278. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65279. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65280. .toUpperCase();
  65281. }
  65282. END_JUCE_NAMESPACE
  65283. /*** End of inlined file: juce_Colour.cpp ***/
  65284. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65285. BEGIN_JUCE_NAMESPACE
  65286. ColourGradient::ColourGradient() throw()
  65287. {
  65288. #if JUCE_DEBUG
  65289. point1.setX (987654.0f);
  65290. #endif
  65291. }
  65292. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65293. const Colour& colour2, const float x2_, const float y2_,
  65294. const bool isRadial_)
  65295. : point1 (x1_, y1_),
  65296. point2 (x2_, y2_),
  65297. isRadial (isRadial_)
  65298. {
  65299. colours.add (ColourPoint (0.0, colour1));
  65300. colours.add (ColourPoint (1.0, colour2));
  65301. }
  65302. ColourGradient::~ColourGradient()
  65303. {
  65304. }
  65305. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65306. {
  65307. return point1 == other.point1 && point2 == other.point2
  65308. && isRadial == other.isRadial
  65309. && colours == other.colours;
  65310. }
  65311. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65312. {
  65313. return ! operator== (other);
  65314. }
  65315. void ColourGradient::clearColours()
  65316. {
  65317. colours.clear();
  65318. }
  65319. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65320. {
  65321. // must be within the two end-points
  65322. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65323. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65324. int i;
  65325. for (i = 0; i < colours.size(); ++i)
  65326. if (colours.getReference(i).position > pos)
  65327. break;
  65328. colours.insert (i, ColourPoint (pos, colour));
  65329. return i;
  65330. }
  65331. void ColourGradient::removeColour (int index)
  65332. {
  65333. jassert (index > 0 && index < colours.size() - 1);
  65334. colours.remove (index);
  65335. }
  65336. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65337. {
  65338. for (int i = 0; i < colours.size(); ++i)
  65339. {
  65340. Colour& c = colours.getReference(i).colour;
  65341. c = c.withMultipliedAlpha (multiplier);
  65342. }
  65343. }
  65344. int ColourGradient::getNumColours() const throw()
  65345. {
  65346. return colours.size();
  65347. }
  65348. double ColourGradient::getColourPosition (const int index) const throw()
  65349. {
  65350. if (((unsigned int) index) < (unsigned int) colours.size())
  65351. return colours.getReference (index).position;
  65352. return 0;
  65353. }
  65354. const Colour ColourGradient::getColour (const int index) const throw()
  65355. {
  65356. if (((unsigned int) index) < (unsigned int) colours.size())
  65357. return colours.getReference (index).colour;
  65358. return Colour();
  65359. }
  65360. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65361. {
  65362. if (((unsigned int) index) < (unsigned int) colours.size())
  65363. colours.getReference (index).colour = newColour;
  65364. }
  65365. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65366. {
  65367. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65368. if (position <= 0 || colours.size() <= 1)
  65369. return colours.getReference(0).colour;
  65370. int i = colours.size() - 1;
  65371. while (position < colours.getReference(i).position)
  65372. --i;
  65373. const ColourPoint& p1 = colours.getReference (i);
  65374. if (i >= colours.size() - 1)
  65375. return p1.colour;
  65376. const ColourPoint& p2 = colours.getReference (i + 1);
  65377. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65378. }
  65379. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65380. {
  65381. #if JUCE_DEBUG
  65382. // trying to use the object without setting its co-ordinates? Have a careful read of
  65383. // the comments for the constructors.
  65384. jassert (point1.getX() != 987654.0f);
  65385. #endif
  65386. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65387. 3 * (int) point1.transformedBy (transform)
  65388. .getDistanceFrom (point2.transformedBy (transform)));
  65389. lookupTable.malloc (numEntries);
  65390. if (colours.size() >= 2)
  65391. {
  65392. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65393. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65394. int index = 0;
  65395. for (int j = 1; j < colours.size(); ++j)
  65396. {
  65397. const ColourPoint& p = colours.getReference (j);
  65398. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65399. const PixelARGB pix2 (p.colour.getPixelARGB());
  65400. for (int i = 0; i < numToDo; ++i)
  65401. {
  65402. jassert (index >= 0 && index < numEntries);
  65403. lookupTable[index] = pix1;
  65404. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65405. ++index;
  65406. }
  65407. pix1 = pix2;
  65408. }
  65409. while (index < numEntries)
  65410. lookupTable [index++] = pix1;
  65411. }
  65412. else
  65413. {
  65414. jassertfalse; // no colours specified!
  65415. }
  65416. return numEntries;
  65417. }
  65418. bool ColourGradient::isOpaque() const throw()
  65419. {
  65420. for (int i = 0; i < colours.size(); ++i)
  65421. if (! colours.getReference(i).colour.isOpaque())
  65422. return false;
  65423. return true;
  65424. }
  65425. bool ColourGradient::isInvisible() const throw()
  65426. {
  65427. for (int i = 0; i < colours.size(); ++i)
  65428. if (! colours.getReference(i).colour.isTransparent())
  65429. return false;
  65430. return true;
  65431. }
  65432. END_JUCE_NAMESPACE
  65433. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65434. /*** Start of inlined file: juce_Colours.cpp ***/
  65435. BEGIN_JUCE_NAMESPACE
  65436. const Colour Colours::transparentBlack (0);
  65437. const Colour Colours::transparentWhite (0x00ffffff);
  65438. const Colour Colours::aliceblue (0xfff0f8ff);
  65439. const Colour Colours::antiquewhite (0xfffaebd7);
  65440. const Colour Colours::aqua (0xff00ffff);
  65441. const Colour Colours::aquamarine (0xff7fffd4);
  65442. const Colour Colours::azure (0xfff0ffff);
  65443. const Colour Colours::beige (0xfff5f5dc);
  65444. const Colour Colours::bisque (0xffffe4c4);
  65445. const Colour Colours::black (0xff000000);
  65446. const Colour Colours::blanchedalmond (0xffffebcd);
  65447. const Colour Colours::blue (0xff0000ff);
  65448. const Colour Colours::blueviolet (0xff8a2be2);
  65449. const Colour Colours::brown (0xffa52a2a);
  65450. const Colour Colours::burlywood (0xffdeb887);
  65451. const Colour Colours::cadetblue (0xff5f9ea0);
  65452. const Colour Colours::chartreuse (0xff7fff00);
  65453. const Colour Colours::chocolate (0xffd2691e);
  65454. const Colour Colours::coral (0xffff7f50);
  65455. const Colour Colours::cornflowerblue (0xff6495ed);
  65456. const Colour Colours::cornsilk (0xfffff8dc);
  65457. const Colour Colours::crimson (0xffdc143c);
  65458. const Colour Colours::cyan (0xff00ffff);
  65459. const Colour Colours::darkblue (0xff00008b);
  65460. const Colour Colours::darkcyan (0xff008b8b);
  65461. const Colour Colours::darkgoldenrod (0xffb8860b);
  65462. const Colour Colours::darkgrey (0xff555555);
  65463. const Colour Colours::darkgreen (0xff006400);
  65464. const Colour Colours::darkkhaki (0xffbdb76b);
  65465. const Colour Colours::darkmagenta (0xff8b008b);
  65466. const Colour Colours::darkolivegreen (0xff556b2f);
  65467. const Colour Colours::darkorange (0xffff8c00);
  65468. const Colour Colours::darkorchid (0xff9932cc);
  65469. const Colour Colours::darkred (0xff8b0000);
  65470. const Colour Colours::darksalmon (0xffe9967a);
  65471. const Colour Colours::darkseagreen (0xff8fbc8f);
  65472. const Colour Colours::darkslateblue (0xff483d8b);
  65473. const Colour Colours::darkslategrey (0xff2f4f4f);
  65474. const Colour Colours::darkturquoise (0xff00ced1);
  65475. const Colour Colours::darkviolet (0xff9400d3);
  65476. const Colour Colours::deeppink (0xffff1493);
  65477. const Colour Colours::deepskyblue (0xff00bfff);
  65478. const Colour Colours::dimgrey (0xff696969);
  65479. const Colour Colours::dodgerblue (0xff1e90ff);
  65480. const Colour Colours::firebrick (0xffb22222);
  65481. const Colour Colours::floralwhite (0xfffffaf0);
  65482. const Colour Colours::forestgreen (0xff228b22);
  65483. const Colour Colours::fuchsia (0xffff00ff);
  65484. const Colour Colours::gainsboro (0xffdcdcdc);
  65485. const Colour Colours::gold (0xffffd700);
  65486. const Colour Colours::goldenrod (0xffdaa520);
  65487. const Colour Colours::grey (0xff808080);
  65488. const Colour Colours::green (0xff008000);
  65489. const Colour Colours::greenyellow (0xffadff2f);
  65490. const Colour Colours::honeydew (0xfff0fff0);
  65491. const Colour Colours::hotpink (0xffff69b4);
  65492. const Colour Colours::indianred (0xffcd5c5c);
  65493. const Colour Colours::indigo (0xff4b0082);
  65494. const Colour Colours::ivory (0xfffffff0);
  65495. const Colour Colours::khaki (0xfff0e68c);
  65496. const Colour Colours::lavender (0xffe6e6fa);
  65497. const Colour Colours::lavenderblush (0xfffff0f5);
  65498. const Colour Colours::lemonchiffon (0xfffffacd);
  65499. const Colour Colours::lightblue (0xffadd8e6);
  65500. const Colour Colours::lightcoral (0xfff08080);
  65501. const Colour Colours::lightcyan (0xffe0ffff);
  65502. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65503. const Colour Colours::lightgreen (0xff90ee90);
  65504. const Colour Colours::lightgrey (0xffd3d3d3);
  65505. const Colour Colours::lightpink (0xffffb6c1);
  65506. const Colour Colours::lightsalmon (0xffffa07a);
  65507. const Colour Colours::lightseagreen (0xff20b2aa);
  65508. const Colour Colours::lightskyblue (0xff87cefa);
  65509. const Colour Colours::lightslategrey (0xff778899);
  65510. const Colour Colours::lightsteelblue (0xffb0c4de);
  65511. const Colour Colours::lightyellow (0xffffffe0);
  65512. const Colour Colours::lime (0xff00ff00);
  65513. const Colour Colours::limegreen (0xff32cd32);
  65514. const Colour Colours::linen (0xfffaf0e6);
  65515. const Colour Colours::magenta (0xffff00ff);
  65516. const Colour Colours::maroon (0xff800000);
  65517. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65518. const Colour Colours::mediumblue (0xff0000cd);
  65519. const Colour Colours::mediumorchid (0xffba55d3);
  65520. const Colour Colours::mediumpurple (0xff9370db);
  65521. const Colour Colours::mediumseagreen (0xff3cb371);
  65522. const Colour Colours::mediumslateblue (0xff7b68ee);
  65523. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65524. const Colour Colours::mediumturquoise (0xff48d1cc);
  65525. const Colour Colours::mediumvioletred (0xffc71585);
  65526. const Colour Colours::midnightblue (0xff191970);
  65527. const Colour Colours::mintcream (0xfff5fffa);
  65528. const Colour Colours::mistyrose (0xffffe4e1);
  65529. const Colour Colours::navajowhite (0xffffdead);
  65530. const Colour Colours::navy (0xff000080);
  65531. const Colour Colours::oldlace (0xfffdf5e6);
  65532. const Colour Colours::olive (0xff808000);
  65533. const Colour Colours::olivedrab (0xff6b8e23);
  65534. const Colour Colours::orange (0xffffa500);
  65535. const Colour Colours::orangered (0xffff4500);
  65536. const Colour Colours::orchid (0xffda70d6);
  65537. const Colour Colours::palegoldenrod (0xffeee8aa);
  65538. const Colour Colours::palegreen (0xff98fb98);
  65539. const Colour Colours::paleturquoise (0xffafeeee);
  65540. const Colour Colours::palevioletred (0xffdb7093);
  65541. const Colour Colours::papayawhip (0xffffefd5);
  65542. const Colour Colours::peachpuff (0xffffdab9);
  65543. const Colour Colours::peru (0xffcd853f);
  65544. const Colour Colours::pink (0xffffc0cb);
  65545. const Colour Colours::plum (0xffdda0dd);
  65546. const Colour Colours::powderblue (0xffb0e0e6);
  65547. const Colour Colours::purple (0xff800080);
  65548. const Colour Colours::red (0xffff0000);
  65549. const Colour Colours::rosybrown (0xffbc8f8f);
  65550. const Colour Colours::royalblue (0xff4169e1);
  65551. const Colour Colours::saddlebrown (0xff8b4513);
  65552. const Colour Colours::salmon (0xfffa8072);
  65553. const Colour Colours::sandybrown (0xfff4a460);
  65554. const Colour Colours::seagreen (0xff2e8b57);
  65555. const Colour Colours::seashell (0xfffff5ee);
  65556. const Colour Colours::sienna (0xffa0522d);
  65557. const Colour Colours::silver (0xffc0c0c0);
  65558. const Colour Colours::skyblue (0xff87ceeb);
  65559. const Colour Colours::slateblue (0xff6a5acd);
  65560. const Colour Colours::slategrey (0xff708090);
  65561. const Colour Colours::snow (0xfffffafa);
  65562. const Colour Colours::springgreen (0xff00ff7f);
  65563. const Colour Colours::steelblue (0xff4682b4);
  65564. const Colour Colours::tan (0xffd2b48c);
  65565. const Colour Colours::teal (0xff008080);
  65566. const Colour Colours::thistle (0xffd8bfd8);
  65567. const Colour Colours::tomato (0xffff6347);
  65568. const Colour Colours::turquoise (0xff40e0d0);
  65569. const Colour Colours::violet (0xffee82ee);
  65570. const Colour Colours::wheat (0xfff5deb3);
  65571. const Colour Colours::white (0xffffffff);
  65572. const Colour Colours::whitesmoke (0xfff5f5f5);
  65573. const Colour Colours::yellow (0xffffff00);
  65574. const Colour Colours::yellowgreen (0xff9acd32);
  65575. const Colour Colours::findColourForName (const String& colourName,
  65576. const Colour& defaultColour)
  65577. {
  65578. static const int presets[] =
  65579. {
  65580. // (first value is the string's hashcode, second is ARGB)
  65581. 0x05978fff, 0xff000000, /* black */
  65582. 0x06bdcc29, 0xffffffff, /* white */
  65583. 0x002e305a, 0xff0000ff, /* blue */
  65584. 0x00308adf, 0xff808080, /* grey */
  65585. 0x05e0cf03, 0xff008000, /* green */
  65586. 0x0001b891, 0xffff0000, /* red */
  65587. 0xd43c6474, 0xffffff00, /* yellow */
  65588. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65589. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65590. 0x002dcebc, 0xff00ffff, /* aqua */
  65591. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65592. 0x0590228f, 0xfff0ffff, /* azure */
  65593. 0x05947fe4, 0xfff5f5dc, /* beige */
  65594. 0xad388e35, 0xffffe4c4, /* bisque */
  65595. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65596. 0x39129959, 0xff8a2be2, /* blueviolet */
  65597. 0x059a8136, 0xffa52a2a, /* brown */
  65598. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65599. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65600. 0x6b748956, 0xff7fff00, /* chartreuse */
  65601. 0x2903623c, 0xffd2691e, /* chocolate */
  65602. 0x05a74431, 0xffff7f50, /* coral */
  65603. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65604. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65605. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65606. 0x002ed323, 0xff00ffff, /* cyan */
  65607. 0x67cc74d0, 0xff00008b, /* darkblue */
  65608. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65609. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65610. 0x67cecf55, 0xff555555, /* darkgrey */
  65611. 0x920b194d, 0xff006400, /* darkgreen */
  65612. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65613. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65614. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65615. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65616. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65617. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65618. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65619. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65620. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65621. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65622. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65623. 0xc8769375, 0xff9400d3, /* darkviolet */
  65624. 0x25832862, 0xffff1493, /* deeppink */
  65625. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65626. 0x634c8b67, 0xff696969, /* dimgrey */
  65627. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65628. 0xef19e3cb, 0xffb22222, /* firebrick */
  65629. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65630. 0xd086fd06, 0xff228b22, /* forestgreen */
  65631. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65632. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65633. 0x00308060, 0xffffd700, /* gold */
  65634. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65635. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65636. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65637. 0x41892743, 0xffff69b4, /* hotpink */
  65638. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65639. 0xb969fed2, 0xff4b0082, /* indigo */
  65640. 0x05fef6a9, 0xfffffff0, /* ivory */
  65641. 0x06149302, 0xfff0e68c, /* khaki */
  65642. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65643. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65644. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65645. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65646. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65647. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65648. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65649. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65650. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65651. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65652. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65653. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65654. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65655. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65656. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65657. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65658. 0x0032afd5, 0xff00ff00, /* lime */
  65659. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65660. 0x06234efa, 0xfffaf0e6, /* linen */
  65661. 0x316858a9, 0xffff00ff, /* magenta */
  65662. 0xbf8ca470, 0xff800000, /* maroon */
  65663. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65664. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65665. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65666. 0x07556b71, 0xff9370db, /* mediumpurple */
  65667. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65668. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65669. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65670. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65671. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65672. 0x168eb32a, 0xff191970, /* midnightblue */
  65673. 0x4306b960, 0xfff5fffa, /* mintcream */
  65674. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65675. 0xe97218a6, 0xffffdead, /* navajowhite */
  65676. 0x00337bb6, 0xff000080, /* navy */
  65677. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65678. 0x064ee1db, 0xff808000, /* olive */
  65679. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65680. 0xc3de262e, 0xffffa500, /* orange */
  65681. 0x58bebba3, 0xffff4500, /* orangered */
  65682. 0xc3def8a3, 0xffda70d6, /* orchid */
  65683. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65684. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65685. 0x74022737, 0xffafeeee, /* paleturquoise */
  65686. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65687. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65688. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65689. 0x003472f8, 0xffcd853f, /* peru */
  65690. 0x00348176, 0xffffc0cb, /* pink */
  65691. 0x00348d94, 0xffdda0dd, /* plum */
  65692. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65693. 0xc5c507bc, 0xff800080, /* purple */
  65694. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65695. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65696. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65697. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65698. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65699. 0x34636c14, 0xff2e8b57, /* seagreen */
  65700. 0x3507fb41, 0xfffff5ee, /* seashell */
  65701. 0xca348772, 0xffa0522d, /* sienna */
  65702. 0xca37d30d, 0xffc0c0c0, /* silver */
  65703. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65704. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65705. 0x44ab37f8, 0xff708090, /* slategrey */
  65706. 0x0035f183, 0xfffffafa, /* snow */
  65707. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65708. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65709. 0x0001bfa1, 0xffd2b48c, /* tan */
  65710. 0x0036425c, 0xff008080, /* teal */
  65711. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65712. 0xcc41600a, 0xffff6347, /* tomato */
  65713. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65714. 0xcf57947f, 0xffee82ee, /* violet */
  65715. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65716. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65717. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65718. };
  65719. const int hash = colourName.trim().toLowerCase().hashCode();
  65720. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65721. if (presets [i] == hash)
  65722. return Colour (presets [i + 1]);
  65723. return defaultColour;
  65724. }
  65725. END_JUCE_NAMESPACE
  65726. /*** End of inlined file: juce_Colours.cpp ***/
  65727. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65728. BEGIN_JUCE_NAMESPACE
  65729. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65730. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65731. const Path& path, const AffineTransform& transform)
  65732. : bounds (bounds_),
  65733. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65734. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65735. needToCheckEmptinesss (true)
  65736. {
  65737. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65738. int* t = table;
  65739. for (int i = bounds.getHeight(); --i >= 0;)
  65740. {
  65741. *t = 0;
  65742. t += lineStrideElements;
  65743. }
  65744. const int topLimit = bounds.getY() << 8;
  65745. const int heightLimit = bounds.getHeight() << 8;
  65746. const int leftLimit = bounds.getX() << 8;
  65747. const int rightLimit = bounds.getRight() << 8;
  65748. PathFlatteningIterator iter (path, transform);
  65749. while (iter.next())
  65750. {
  65751. int y1 = roundToInt (iter.y1 * 256.0f);
  65752. int y2 = roundToInt (iter.y2 * 256.0f);
  65753. if (y1 != y2)
  65754. {
  65755. y1 -= topLimit;
  65756. y2 -= topLimit;
  65757. const int startY = y1;
  65758. int direction = -1;
  65759. if (y1 > y2)
  65760. {
  65761. swapVariables (y1, y2);
  65762. direction = 1;
  65763. }
  65764. if (y1 < 0)
  65765. y1 = 0;
  65766. if (y2 > heightLimit)
  65767. y2 = heightLimit;
  65768. if (y1 < y2)
  65769. {
  65770. const double startX = 256.0f * iter.x1;
  65771. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65772. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65773. do
  65774. {
  65775. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65776. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65777. if (x < leftLimit)
  65778. x = leftLimit;
  65779. else if (x >= rightLimit)
  65780. x = rightLimit - 1;
  65781. addEdgePoint (x, y1 >> 8, direction * step);
  65782. y1 += step;
  65783. }
  65784. while (y1 < y2);
  65785. }
  65786. }
  65787. }
  65788. sanitiseLevels (path.isUsingNonZeroWinding());
  65789. }
  65790. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65791. : bounds (rectangleToAdd),
  65792. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65793. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65794. needToCheckEmptinesss (true)
  65795. {
  65796. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65797. table[0] = 0;
  65798. const int x1 = rectangleToAdd.getX() << 8;
  65799. const int x2 = rectangleToAdd.getRight() << 8;
  65800. int* t = table;
  65801. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65802. {
  65803. t[0] = 2;
  65804. t[1] = x1;
  65805. t[2] = 255;
  65806. t[3] = x2;
  65807. t[4] = 0;
  65808. t += lineStrideElements;
  65809. }
  65810. }
  65811. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65812. : bounds (rectanglesToAdd.getBounds()),
  65813. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65814. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65815. needToCheckEmptinesss (true)
  65816. {
  65817. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65818. int* t = table;
  65819. for (int i = bounds.getHeight(); --i >= 0;)
  65820. {
  65821. *t = 0;
  65822. t += lineStrideElements;
  65823. }
  65824. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65825. {
  65826. const Rectangle<int>* const r = iter.getRectangle();
  65827. const int x1 = r->getX() << 8;
  65828. const int x2 = r->getRight() << 8;
  65829. int y = r->getY() - bounds.getY();
  65830. for (int j = r->getHeight(); --j >= 0;)
  65831. {
  65832. addEdgePoint (x1, y, 255);
  65833. addEdgePoint (x2, y, -255);
  65834. ++y;
  65835. }
  65836. }
  65837. sanitiseLevels (true);
  65838. }
  65839. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65840. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65841. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65842. 2 + (int) rectangleToAdd.getWidth(),
  65843. 2 + (int) rectangleToAdd.getHeight())),
  65844. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65845. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65846. needToCheckEmptinesss (true)
  65847. {
  65848. jassert (! rectangleToAdd.isEmpty());
  65849. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65850. table[0] = 0;
  65851. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65852. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65853. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65854. jassert (y1 < 256);
  65855. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65856. if (x2 <= x1 || y2 <= y1)
  65857. {
  65858. bounds.setHeight (0);
  65859. return;
  65860. }
  65861. int lineY = 0;
  65862. int* t = table;
  65863. if ((y1 >> 8) == (y2 >> 8))
  65864. {
  65865. t[0] = 2;
  65866. t[1] = x1;
  65867. t[2] = y2 - y1;
  65868. t[3] = x2;
  65869. t[4] = 0;
  65870. ++lineY;
  65871. t += lineStrideElements;
  65872. }
  65873. else
  65874. {
  65875. t[0] = 2;
  65876. t[1] = x1;
  65877. t[2] = 255 - (y1 & 255);
  65878. t[3] = x2;
  65879. t[4] = 0;
  65880. ++lineY;
  65881. t += lineStrideElements;
  65882. while (lineY < (y2 >> 8))
  65883. {
  65884. t[0] = 2;
  65885. t[1] = x1;
  65886. t[2] = 255;
  65887. t[3] = x2;
  65888. t[4] = 0;
  65889. ++lineY;
  65890. t += lineStrideElements;
  65891. }
  65892. jassert (lineY < bounds.getHeight());
  65893. t[0] = 2;
  65894. t[1] = x1;
  65895. t[2] = y2 & 255;
  65896. t[3] = x2;
  65897. t[4] = 0;
  65898. ++lineY;
  65899. t += lineStrideElements;
  65900. }
  65901. while (lineY < bounds.getHeight())
  65902. {
  65903. t[0] = 0;
  65904. t += lineStrideElements;
  65905. ++lineY;
  65906. }
  65907. }
  65908. EdgeTable::EdgeTable (const EdgeTable& other)
  65909. {
  65910. operator= (other);
  65911. }
  65912. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65913. {
  65914. bounds = other.bounds;
  65915. maxEdgesPerLine = other.maxEdgesPerLine;
  65916. lineStrideElements = other.lineStrideElements;
  65917. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65918. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65919. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65920. return *this;
  65921. }
  65922. EdgeTable::~EdgeTable()
  65923. {
  65924. }
  65925. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65926. {
  65927. while (--numLines >= 0)
  65928. {
  65929. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65930. src += srcLineStride;
  65931. dest += destLineStride;
  65932. }
  65933. }
  65934. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65935. {
  65936. // Convert the table from relative windings to absolute levels..
  65937. int* lineStart = table;
  65938. for (int i = bounds.getHeight(); --i >= 0;)
  65939. {
  65940. int* line = lineStart;
  65941. lineStart += lineStrideElements;
  65942. int num = *line;
  65943. if (num == 0)
  65944. continue;
  65945. int level = 0;
  65946. if (useNonZeroWinding)
  65947. {
  65948. while (--num > 0)
  65949. {
  65950. line += 2;
  65951. level += *line;
  65952. int corrected = abs (level);
  65953. if (corrected >> 8)
  65954. corrected = 255;
  65955. *line = corrected;
  65956. }
  65957. }
  65958. else
  65959. {
  65960. while (--num > 0)
  65961. {
  65962. line += 2;
  65963. level += *line;
  65964. int corrected = abs (level);
  65965. if (corrected >> 8)
  65966. {
  65967. corrected &= 511;
  65968. if (corrected >> 8)
  65969. corrected = 511 - corrected;
  65970. }
  65971. *line = corrected;
  65972. }
  65973. }
  65974. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65975. }
  65976. }
  65977. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65978. {
  65979. if (newNumEdgesPerLine != maxEdgesPerLine)
  65980. {
  65981. maxEdgesPerLine = newNumEdgesPerLine;
  65982. jassert (bounds.getHeight() > 0);
  65983. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65984. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65985. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65986. table.swapWith (newTable);
  65987. lineStrideElements = newLineStrideElements;
  65988. }
  65989. }
  65990. void EdgeTable::optimiseTable() throw()
  65991. {
  65992. int maxLineElements = 0;
  65993. for (int i = bounds.getHeight(); --i >= 0;)
  65994. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65995. remapTableForNumEdges (maxLineElements);
  65996. }
  65997. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65998. {
  65999. jassert (y >= 0 && y < bounds.getHeight());
  66000. int* line = table + lineStrideElements * y;
  66001. const int numPoints = line[0];
  66002. int n = numPoints << 1;
  66003. if (n > 0)
  66004. {
  66005. while (n > 0)
  66006. {
  66007. const int cx = line [n - 1];
  66008. if (cx <= x)
  66009. {
  66010. if (cx == x)
  66011. {
  66012. line [n] += winding;
  66013. return;
  66014. }
  66015. break;
  66016. }
  66017. n -= 2;
  66018. }
  66019. if (numPoints >= maxEdgesPerLine)
  66020. {
  66021. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66022. jassert (numPoints < maxEdgesPerLine);
  66023. line = table + lineStrideElements * y;
  66024. }
  66025. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66026. }
  66027. line [n + 1] = x;
  66028. line [n + 2] = winding;
  66029. line[0]++;
  66030. }
  66031. void EdgeTable::translate (float dx, const int dy) throw()
  66032. {
  66033. bounds.translate ((int) std::floor (dx), dy);
  66034. int* lineStart = table;
  66035. const int intDx = (int) (dx * 256.0f);
  66036. for (int i = bounds.getHeight(); --i >= 0;)
  66037. {
  66038. int* line = lineStart;
  66039. lineStart += lineStrideElements;
  66040. int num = *line++;
  66041. while (--num >= 0)
  66042. {
  66043. *line += intDx;
  66044. line += 2;
  66045. }
  66046. }
  66047. }
  66048. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66049. {
  66050. jassert (y >= 0 && y < bounds.getHeight());
  66051. int* dest = table + lineStrideElements * y;
  66052. if (dest[0] == 0)
  66053. return;
  66054. int otherNumPoints = *otherLine;
  66055. if (otherNumPoints == 0)
  66056. {
  66057. *dest = 0;
  66058. return;
  66059. }
  66060. const int right = bounds.getRight() << 8;
  66061. // optimise for the common case where our line lies entirely within a
  66062. // single pair of points, as happens when clipping to a simple rect.
  66063. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66064. {
  66065. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66066. return;
  66067. }
  66068. ++otherLine;
  66069. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66070. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66071. memcpy (temp, dest, lineSizeBytes);
  66072. const int* src1 = temp;
  66073. int srcNum1 = *src1++;
  66074. int x1 = *src1++;
  66075. const int* src2 = otherLine;
  66076. int srcNum2 = otherNumPoints;
  66077. int x2 = *src2++;
  66078. int destIndex = 0, destTotal = 0;
  66079. int level1 = 0, level2 = 0;
  66080. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66081. while (srcNum1 > 0 && srcNum2 > 0)
  66082. {
  66083. int nextX;
  66084. if (x1 < x2)
  66085. {
  66086. nextX = x1;
  66087. level1 = *src1++;
  66088. x1 = *src1++;
  66089. --srcNum1;
  66090. }
  66091. else if (x1 == x2)
  66092. {
  66093. nextX = x1;
  66094. level1 = *src1++;
  66095. level2 = *src2++;
  66096. x1 = *src1++;
  66097. x2 = *src2++;
  66098. --srcNum1;
  66099. --srcNum2;
  66100. }
  66101. else
  66102. {
  66103. nextX = x2;
  66104. level2 = *src2++;
  66105. x2 = *src2++;
  66106. --srcNum2;
  66107. }
  66108. if (nextX > lastX)
  66109. {
  66110. if (nextX >= right)
  66111. break;
  66112. lastX = nextX;
  66113. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66114. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66115. if (nextLevel != lastLevel)
  66116. {
  66117. if (destTotal >= maxEdgesPerLine)
  66118. {
  66119. dest[0] = destTotal;
  66120. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66121. dest = table + lineStrideElements * y;
  66122. }
  66123. ++destTotal;
  66124. lastLevel = nextLevel;
  66125. dest[++destIndex] = nextX;
  66126. dest[++destIndex] = nextLevel;
  66127. }
  66128. }
  66129. }
  66130. if (lastLevel > 0)
  66131. {
  66132. if (destTotal >= maxEdgesPerLine)
  66133. {
  66134. dest[0] = destTotal;
  66135. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66136. dest = table + lineStrideElements * y;
  66137. }
  66138. ++destTotal;
  66139. dest[++destIndex] = right;
  66140. dest[++destIndex] = 0;
  66141. }
  66142. dest[0] = destTotal;
  66143. #if JUCE_DEBUG
  66144. int last = std::numeric_limits<int>::min();
  66145. for (int i = 0; i < dest[0]; ++i)
  66146. {
  66147. jassert (dest[i * 2 + 1] > last);
  66148. last = dest[i * 2 + 1];
  66149. }
  66150. jassert (dest [dest[0] * 2] == 0);
  66151. #endif
  66152. }
  66153. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66154. {
  66155. int* lastItem = dest + (dest[0] * 2 - 1);
  66156. if (x2 < lastItem[0])
  66157. {
  66158. if (x2 <= dest[1])
  66159. {
  66160. dest[0] = 0;
  66161. return;
  66162. }
  66163. while (x2 < lastItem[-2])
  66164. {
  66165. --(dest[0]);
  66166. lastItem -= 2;
  66167. }
  66168. lastItem[0] = x2;
  66169. lastItem[1] = 0;
  66170. }
  66171. if (x1 > dest[1])
  66172. {
  66173. while (lastItem[0] > x1)
  66174. lastItem -= 2;
  66175. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66176. if (itemsRemoved > 0)
  66177. {
  66178. dest[0] -= itemsRemoved;
  66179. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66180. }
  66181. dest[1] = x1;
  66182. }
  66183. }
  66184. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66185. {
  66186. const Rectangle<int> clipped (r.getIntersection (bounds));
  66187. if (clipped.isEmpty())
  66188. {
  66189. needToCheckEmptinesss = false;
  66190. bounds.setHeight (0);
  66191. }
  66192. else
  66193. {
  66194. const int top = clipped.getY() - bounds.getY();
  66195. const int bottom = clipped.getBottom() - bounds.getY();
  66196. if (bottom < bounds.getHeight())
  66197. bounds.setHeight (bottom);
  66198. if (clipped.getRight() < bounds.getRight())
  66199. bounds.setRight (clipped.getRight());
  66200. for (int i = top; --i >= 0;)
  66201. table [lineStrideElements * i] = 0;
  66202. if (clipped.getX() > bounds.getX())
  66203. {
  66204. const int x1 = clipped.getX() << 8;
  66205. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66206. int* line = table + lineStrideElements * top;
  66207. for (int i = bottom - top; --i >= 0;)
  66208. {
  66209. if (line[0] != 0)
  66210. clipEdgeTableLineToRange (line, x1, x2);
  66211. line += lineStrideElements;
  66212. }
  66213. }
  66214. needToCheckEmptinesss = true;
  66215. }
  66216. }
  66217. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66218. {
  66219. const Rectangle<int> clipped (r.getIntersection (bounds));
  66220. if (! clipped.isEmpty())
  66221. {
  66222. const int top = clipped.getY() - bounds.getY();
  66223. const int bottom = clipped.getBottom() - bounds.getY();
  66224. //XXX optimise here by shortening the table if it fills top or bottom
  66225. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66226. clipped.getX() << 8, 0,
  66227. clipped.getRight() << 8, 255,
  66228. std::numeric_limits<int>::max(), 0 };
  66229. for (int i = top; i < bottom; ++i)
  66230. intersectWithEdgeTableLine (i, rectLine);
  66231. needToCheckEmptinesss = true;
  66232. }
  66233. }
  66234. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66235. {
  66236. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66237. if (clipped.isEmpty())
  66238. {
  66239. needToCheckEmptinesss = false;
  66240. bounds.setHeight (0);
  66241. }
  66242. else
  66243. {
  66244. const int top = clipped.getY() - bounds.getY();
  66245. const int bottom = clipped.getBottom() - bounds.getY();
  66246. if (bottom < bounds.getHeight())
  66247. bounds.setHeight (bottom);
  66248. if (clipped.getRight() < bounds.getRight())
  66249. bounds.setRight (clipped.getRight());
  66250. int i = 0;
  66251. for (i = top; --i >= 0;)
  66252. table [lineStrideElements * i] = 0;
  66253. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66254. for (i = top; i < bottom; ++i)
  66255. {
  66256. intersectWithEdgeTableLine (i, otherLine);
  66257. otherLine += other.lineStrideElements;
  66258. }
  66259. needToCheckEmptinesss = true;
  66260. }
  66261. }
  66262. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66263. {
  66264. y -= bounds.getY();
  66265. if (y < 0 || y >= bounds.getHeight())
  66266. return;
  66267. needToCheckEmptinesss = true;
  66268. if (numPixels <= 0)
  66269. {
  66270. table [lineStrideElements * y] = 0;
  66271. return;
  66272. }
  66273. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66274. int destIndex = 0, lastLevel = 0;
  66275. while (--numPixels >= 0)
  66276. {
  66277. const int alpha = *mask;
  66278. mask += maskStride;
  66279. if (alpha != lastLevel)
  66280. {
  66281. tempLine[++destIndex] = (x << 8);
  66282. tempLine[++destIndex] = alpha;
  66283. lastLevel = alpha;
  66284. }
  66285. ++x;
  66286. }
  66287. if (lastLevel > 0)
  66288. {
  66289. tempLine[++destIndex] = (x << 8);
  66290. tempLine[++destIndex] = 0;
  66291. }
  66292. tempLine[0] = destIndex >> 1;
  66293. intersectWithEdgeTableLine (y, tempLine);
  66294. }
  66295. bool EdgeTable::isEmpty() throw()
  66296. {
  66297. if (needToCheckEmptinesss)
  66298. {
  66299. needToCheckEmptinesss = false;
  66300. int* t = table;
  66301. for (int i = bounds.getHeight(); --i >= 0;)
  66302. {
  66303. if (t[0] > 1)
  66304. return false;
  66305. t += lineStrideElements;
  66306. }
  66307. bounds.setHeight (0);
  66308. }
  66309. return bounds.getHeight() == 0;
  66310. }
  66311. END_JUCE_NAMESPACE
  66312. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66313. /*** Start of inlined file: juce_FillType.cpp ***/
  66314. BEGIN_JUCE_NAMESPACE
  66315. FillType::FillType() throw()
  66316. : colour (0xff000000), image (0)
  66317. {
  66318. }
  66319. FillType::FillType (const Colour& colour_) throw()
  66320. : colour (colour_), image (0)
  66321. {
  66322. }
  66323. FillType::FillType (const ColourGradient& gradient_)
  66324. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66325. {
  66326. }
  66327. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66328. : colour (0xff000000), image (image_), transform (transform_)
  66329. {
  66330. }
  66331. FillType::FillType (const FillType& other)
  66332. : colour (other.colour),
  66333. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66334. image (other.image), transform (other.transform)
  66335. {
  66336. }
  66337. FillType& FillType::operator= (const FillType& other)
  66338. {
  66339. if (this != &other)
  66340. {
  66341. colour = other.colour;
  66342. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66343. image = other.image;
  66344. transform = other.transform;
  66345. }
  66346. return *this;
  66347. }
  66348. FillType::~FillType() throw()
  66349. {
  66350. }
  66351. bool FillType::operator== (const FillType& other) const
  66352. {
  66353. return colour == other.colour && image == other.image
  66354. && transform == other.transform
  66355. && (gradient == other.gradient
  66356. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66357. }
  66358. bool FillType::operator!= (const FillType& other) const
  66359. {
  66360. return ! operator== (other);
  66361. }
  66362. void FillType::setColour (const Colour& newColour) throw()
  66363. {
  66364. gradient = 0;
  66365. image = Image::null;
  66366. colour = newColour;
  66367. }
  66368. void FillType::setGradient (const ColourGradient& newGradient)
  66369. {
  66370. if (gradient != 0)
  66371. {
  66372. *gradient = newGradient;
  66373. }
  66374. else
  66375. {
  66376. image = Image::null;
  66377. gradient = new ColourGradient (newGradient);
  66378. colour = Colours::black;
  66379. }
  66380. }
  66381. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66382. {
  66383. gradient = 0;
  66384. image = image_;
  66385. transform = transform_;
  66386. colour = Colours::black;
  66387. }
  66388. void FillType::setOpacity (const float newOpacity) throw()
  66389. {
  66390. colour = colour.withAlpha (newOpacity);
  66391. }
  66392. bool FillType::isInvisible() const throw()
  66393. {
  66394. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66395. }
  66396. END_JUCE_NAMESPACE
  66397. /*** End of inlined file: juce_FillType.cpp ***/
  66398. /*** Start of inlined file: juce_Graphics.cpp ***/
  66399. BEGIN_JUCE_NAMESPACE
  66400. template <typename Type>
  66401. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66402. {
  66403. const int maxVal = 0x3fffffff;
  66404. return (int) x >= -maxVal && (int) x <= maxVal
  66405. && (int) y >= -maxVal && (int) y <= maxVal
  66406. && (int) w >= -maxVal && (int) w <= maxVal
  66407. && (int) h >= -maxVal && (int) h <= maxVal;
  66408. }
  66409. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66410. {
  66411. }
  66412. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66413. {
  66414. }
  66415. Graphics::Graphics (const Image& imageToDrawOnto)
  66416. : context (imageToDrawOnto.createLowLevelContext()),
  66417. contextToDelete (context),
  66418. saveStatePending (false)
  66419. {
  66420. }
  66421. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66422. : context (internalContext),
  66423. saveStatePending (false)
  66424. {
  66425. }
  66426. Graphics::~Graphics()
  66427. {
  66428. }
  66429. void Graphics::resetToDefaultState()
  66430. {
  66431. saveStateIfPending();
  66432. context->setFill (FillType());
  66433. context->setFont (Font());
  66434. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66435. }
  66436. bool Graphics::isVectorDevice() const
  66437. {
  66438. return context->isVectorDevice();
  66439. }
  66440. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66441. {
  66442. saveStateIfPending();
  66443. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66444. }
  66445. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66446. {
  66447. saveStateIfPending();
  66448. return context->clipToRectangleList (clipRegion);
  66449. }
  66450. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66451. {
  66452. saveStateIfPending();
  66453. context->clipToPath (path, transform);
  66454. return ! context->isClipEmpty();
  66455. }
  66456. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66457. {
  66458. saveStateIfPending();
  66459. context->clipToImageAlpha (image, transform);
  66460. return ! context->isClipEmpty();
  66461. }
  66462. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66463. {
  66464. saveStateIfPending();
  66465. context->excludeClipRectangle (rectangleToExclude);
  66466. }
  66467. bool Graphics::isClipEmpty() const
  66468. {
  66469. return context->isClipEmpty();
  66470. }
  66471. const Rectangle<int> Graphics::getClipBounds() const
  66472. {
  66473. return context->getClipBounds();
  66474. }
  66475. void Graphics::saveState()
  66476. {
  66477. saveStateIfPending();
  66478. saveStatePending = true;
  66479. }
  66480. void Graphics::restoreState()
  66481. {
  66482. if (saveStatePending)
  66483. saveStatePending = false;
  66484. else
  66485. context->restoreState();
  66486. }
  66487. void Graphics::saveStateIfPending()
  66488. {
  66489. if (saveStatePending)
  66490. {
  66491. saveStatePending = false;
  66492. context->saveState();
  66493. }
  66494. }
  66495. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66496. {
  66497. saveStateIfPending();
  66498. context->setOrigin (newOriginX, newOriginY);
  66499. }
  66500. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66501. {
  66502. return context->clipRegionIntersects (area);
  66503. }
  66504. void Graphics::setColour (const Colour& newColour)
  66505. {
  66506. saveStateIfPending();
  66507. context->setFill (newColour);
  66508. }
  66509. void Graphics::setOpacity (const float newOpacity)
  66510. {
  66511. saveStateIfPending();
  66512. context->setOpacity (newOpacity);
  66513. }
  66514. void Graphics::setGradientFill (const ColourGradient& gradient)
  66515. {
  66516. setFillType (gradient);
  66517. }
  66518. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66519. {
  66520. saveStateIfPending();
  66521. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66522. context->setOpacity (opacity);
  66523. }
  66524. void Graphics::setFillType (const FillType& newFill)
  66525. {
  66526. saveStateIfPending();
  66527. context->setFill (newFill);
  66528. }
  66529. void Graphics::setFont (const Font& newFont)
  66530. {
  66531. saveStateIfPending();
  66532. context->setFont (newFont);
  66533. }
  66534. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66535. {
  66536. saveStateIfPending();
  66537. Font f (context->getFont());
  66538. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66539. context->setFont (f);
  66540. }
  66541. const Font Graphics::getCurrentFont() const
  66542. {
  66543. return context->getFont();
  66544. }
  66545. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66546. {
  66547. if (text.isNotEmpty()
  66548. && startX < context->getClipBounds().getRight())
  66549. {
  66550. GlyphArrangement arr;
  66551. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66552. arr.draw (*this);
  66553. }
  66554. }
  66555. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66556. {
  66557. if (text.isNotEmpty())
  66558. {
  66559. GlyphArrangement arr;
  66560. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66561. arr.draw (*this, transform);
  66562. }
  66563. }
  66564. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66565. {
  66566. if (text.isNotEmpty()
  66567. && startX < context->getClipBounds().getRight())
  66568. {
  66569. GlyphArrangement arr;
  66570. arr.addJustifiedText (context->getFont(), text,
  66571. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66572. Justification::left);
  66573. arr.draw (*this);
  66574. }
  66575. }
  66576. void Graphics::drawText (const String& text,
  66577. const int x, const int y, const int width, const int height,
  66578. const Justification& justificationType,
  66579. const bool useEllipsesIfTooBig) const
  66580. {
  66581. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66582. {
  66583. GlyphArrangement arr;
  66584. arr.addCurtailedLineOfText (context->getFont(), text,
  66585. 0.0f, 0.0f, (float) width,
  66586. useEllipsesIfTooBig);
  66587. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66588. (float) x, (float) y, (float) width, (float) height,
  66589. justificationType);
  66590. arr.draw (*this);
  66591. }
  66592. }
  66593. void Graphics::drawFittedText (const String& text,
  66594. const int x, const int y, const int width, const int height,
  66595. const Justification& justification,
  66596. const int maximumNumberOfLines,
  66597. const float minimumHorizontalScale) const
  66598. {
  66599. if (text.isNotEmpty()
  66600. && width > 0 && height > 0
  66601. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66602. {
  66603. GlyphArrangement arr;
  66604. arr.addFittedText (context->getFont(), text,
  66605. (float) x, (float) y, (float) width, (float) height,
  66606. justification,
  66607. maximumNumberOfLines,
  66608. minimumHorizontalScale);
  66609. arr.draw (*this);
  66610. }
  66611. }
  66612. void Graphics::fillRect (int x, int y, int width, int height) const
  66613. {
  66614. // passing in a silly number can cause maths problems in rendering!
  66615. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66616. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66617. }
  66618. void Graphics::fillRect (const Rectangle<int>& r) const
  66619. {
  66620. context->fillRect (r, false);
  66621. }
  66622. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66623. {
  66624. // passing in a silly number can cause maths problems in rendering!
  66625. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66626. Path p;
  66627. p.addRectangle (x, y, width, height);
  66628. fillPath (p);
  66629. }
  66630. void Graphics::setPixel (int x, int y) const
  66631. {
  66632. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66633. }
  66634. void Graphics::fillAll() const
  66635. {
  66636. fillRect (context->getClipBounds());
  66637. }
  66638. void Graphics::fillAll (const Colour& colourToUse) const
  66639. {
  66640. if (! colourToUse.isTransparent())
  66641. {
  66642. const Rectangle<int> clip (context->getClipBounds());
  66643. context->saveState();
  66644. context->setFill (colourToUse);
  66645. context->fillRect (clip, false);
  66646. context->restoreState();
  66647. }
  66648. }
  66649. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66650. {
  66651. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66652. context->fillPath (path, transform);
  66653. }
  66654. void Graphics::strokePath (const Path& path,
  66655. const PathStrokeType& strokeType,
  66656. const AffineTransform& transform) const
  66657. {
  66658. Path stroke;
  66659. strokeType.createStrokedPath (stroke, path, transform);
  66660. fillPath (stroke);
  66661. }
  66662. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66663. const int lineThickness) const
  66664. {
  66665. // passing in a silly number can cause maths problems in rendering!
  66666. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66667. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66668. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66669. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66670. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66671. }
  66672. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66673. {
  66674. // passing in a silly number can cause maths problems in rendering!
  66675. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66676. Path p;
  66677. p.addRectangle (x, y, width, lineThickness);
  66678. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66679. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66680. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66681. fillPath (p);
  66682. }
  66683. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66684. {
  66685. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66686. }
  66687. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66688. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66689. const bool useGradient, const bool sharpEdgeOnOutside) const
  66690. {
  66691. // passing in a silly number can cause maths problems in rendering!
  66692. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66693. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66694. {
  66695. context->saveState();
  66696. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66697. const float ramp = oldOpacity / bevelThickness;
  66698. for (int i = bevelThickness; --i >= 0;)
  66699. {
  66700. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66701. : oldOpacity;
  66702. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66703. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66704. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66705. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66706. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66707. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66708. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66709. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66710. }
  66711. context->restoreState();
  66712. }
  66713. }
  66714. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66715. {
  66716. // passing in a silly number can cause maths problems in rendering!
  66717. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66718. Path p;
  66719. p.addEllipse (x, y, width, height);
  66720. fillPath (p);
  66721. }
  66722. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66723. const float lineThickness) const
  66724. {
  66725. // passing in a silly number can cause maths problems in rendering!
  66726. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66727. Path p;
  66728. p.addEllipse (x, y, width, height);
  66729. strokePath (p, PathStrokeType (lineThickness));
  66730. }
  66731. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) 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.addRoundedRectangle (x, y, width, height, cornerSize);
  66737. fillPath (p);
  66738. }
  66739. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66740. {
  66741. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66742. }
  66743. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66744. const float cornerSize, const float lineThickness) const
  66745. {
  66746. // passing in a silly number can cause maths problems in rendering!
  66747. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66748. Path p;
  66749. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66750. strokePath (p, PathStrokeType (lineThickness));
  66751. }
  66752. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66753. {
  66754. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66755. }
  66756. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66757. {
  66758. Path p;
  66759. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66760. fillPath (p);
  66761. }
  66762. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66763. const int checkWidth, const int checkHeight,
  66764. const Colour& colour1, const Colour& colour2) const
  66765. {
  66766. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66767. if (checkWidth > 0 && checkHeight > 0)
  66768. {
  66769. context->saveState();
  66770. if (colour1 == colour2)
  66771. {
  66772. context->setFill (colour1);
  66773. context->fillRect (area, false);
  66774. }
  66775. else
  66776. {
  66777. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66778. if (! clipped.isEmpty())
  66779. {
  66780. context->clipToRectangle (clipped);
  66781. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66782. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66783. const int startX = area.getX() + checkNumX * checkWidth;
  66784. const int startY = area.getY() + checkNumY * checkHeight;
  66785. const int right = clipped.getRight();
  66786. const int bottom = clipped.getBottom();
  66787. for (int i = 0; i < 2; ++i)
  66788. {
  66789. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66790. int cy = i;
  66791. for (int y = startY; y < bottom; y += checkHeight)
  66792. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66793. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66794. }
  66795. }
  66796. }
  66797. context->restoreState();
  66798. }
  66799. }
  66800. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66801. {
  66802. context->drawVerticalLine (x, top, bottom);
  66803. }
  66804. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66805. {
  66806. context->drawHorizontalLine (y, left, right);
  66807. }
  66808. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66809. {
  66810. context->drawLine (Line<float> (x1, y1, x2, y2));
  66811. }
  66812. void Graphics::drawLine (const float startX, const float startY,
  66813. const float endX, const float endY,
  66814. const float lineThickness) const
  66815. {
  66816. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66817. }
  66818. void Graphics::drawLine (const Line<float>& line) const
  66819. {
  66820. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66821. }
  66822. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66823. {
  66824. Path p;
  66825. p.addLineSegment (line, lineThickness);
  66826. fillPath (p);
  66827. }
  66828. void Graphics::drawDashedLine (const float startX, const float startY,
  66829. const float endX, const float endY,
  66830. const float* const dashLengths,
  66831. const int numDashLengths,
  66832. const float lineThickness) const
  66833. {
  66834. const double dx = endX - startX;
  66835. const double dy = endY - startY;
  66836. const double totalLen = juce_hypot (dx, dy);
  66837. if (totalLen >= 0.5)
  66838. {
  66839. const double onePixAlpha = 1.0 / totalLen;
  66840. double alpha = 0.0;
  66841. float x = startX;
  66842. float y = startY;
  66843. int n = 0;
  66844. while (alpha < 1.0f)
  66845. {
  66846. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66847. n = n % numDashLengths;
  66848. const float oldX = x;
  66849. const float oldY = y;
  66850. x = (float) (startX + dx * alpha);
  66851. y = (float) (startY + dy * alpha);
  66852. if ((n & 1) != 0)
  66853. {
  66854. if (lineThickness != 1.0f)
  66855. drawLine (oldX, oldY, x, y, lineThickness);
  66856. else
  66857. drawLine (oldX, oldY, x, y);
  66858. }
  66859. }
  66860. }
  66861. }
  66862. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66863. {
  66864. saveStateIfPending();
  66865. context->setInterpolationQuality (newQuality);
  66866. }
  66867. void Graphics::drawImageAt (const Image& imageToDraw,
  66868. const int topLeftX, const int topLeftY,
  66869. const bool fillAlphaChannelWithCurrentBrush) const
  66870. {
  66871. const int imageW = imageToDraw.getWidth();
  66872. const int imageH = imageToDraw.getHeight();
  66873. drawImage (imageToDraw,
  66874. topLeftX, topLeftY, imageW, imageH,
  66875. 0, 0, imageW, imageH,
  66876. fillAlphaChannelWithCurrentBrush);
  66877. }
  66878. void Graphics::drawImageWithin (const Image& imageToDraw,
  66879. const int destX, const int destY,
  66880. const int destW, const int destH,
  66881. const RectanglePlacement& placementWithinTarget,
  66882. const bool fillAlphaChannelWithCurrentBrush) const
  66883. {
  66884. // passing in a silly number can cause maths problems in rendering!
  66885. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66886. if (imageToDraw.isValid())
  66887. {
  66888. const int imageW = imageToDraw.getWidth();
  66889. const int imageH = imageToDraw.getHeight();
  66890. if (imageW > 0 && imageH > 0)
  66891. {
  66892. double newX = 0.0, newY = 0.0;
  66893. double newW = imageW;
  66894. double newH = imageH;
  66895. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66896. destX, destY, destW, destH);
  66897. if (newW > 0 && newH > 0)
  66898. {
  66899. drawImage (imageToDraw,
  66900. roundToInt (newX), roundToInt (newY),
  66901. roundToInt (newW), roundToInt (newH),
  66902. 0, 0, imageW, imageH,
  66903. fillAlphaChannelWithCurrentBrush);
  66904. }
  66905. }
  66906. }
  66907. }
  66908. void Graphics::drawImage (const Image& imageToDraw,
  66909. int dx, int dy, int dw, int dh,
  66910. int sx, int sy, int sw, int sh,
  66911. const bool fillAlphaChannelWithCurrentBrush) const
  66912. {
  66913. // passing in a silly number can cause maths problems in rendering!
  66914. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66915. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66916. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66917. {
  66918. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66919. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66920. .translated ((float) dx, (float) dy),
  66921. fillAlphaChannelWithCurrentBrush);
  66922. }
  66923. }
  66924. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66925. const AffineTransform& transform,
  66926. const bool fillAlphaChannelWithCurrentBrush) const
  66927. {
  66928. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66929. {
  66930. if (fillAlphaChannelWithCurrentBrush)
  66931. {
  66932. context->saveState();
  66933. context->clipToImageAlpha (imageToDraw, transform);
  66934. fillAll();
  66935. context->restoreState();
  66936. }
  66937. else
  66938. {
  66939. context->drawImage (imageToDraw, transform, false);
  66940. }
  66941. }
  66942. }
  66943. END_JUCE_NAMESPACE
  66944. /*** End of inlined file: juce_Graphics.cpp ***/
  66945. /*** Start of inlined file: juce_Justification.cpp ***/
  66946. BEGIN_JUCE_NAMESPACE
  66947. Justification::Justification (const Justification& other) throw()
  66948. : flags (other.flags)
  66949. {
  66950. }
  66951. Justification& Justification::operator= (const Justification& other) throw()
  66952. {
  66953. flags = other.flags;
  66954. return *this;
  66955. }
  66956. int Justification::getOnlyVerticalFlags() const throw()
  66957. {
  66958. return flags & (top | bottom | verticallyCentred);
  66959. }
  66960. int Justification::getOnlyHorizontalFlags() const throw()
  66961. {
  66962. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66963. }
  66964. void Justification::applyToRectangle (int& x, int& y,
  66965. const int w, const int h,
  66966. const int spaceX, const int spaceY,
  66967. const int spaceW, const int spaceH) const throw()
  66968. {
  66969. if ((flags & horizontallyCentred) != 0)
  66970. x = spaceX + ((spaceW - w) >> 1);
  66971. else if ((flags & right) != 0)
  66972. x = spaceX + spaceW - w;
  66973. else
  66974. x = spaceX;
  66975. if ((flags & verticallyCentred) != 0)
  66976. y = spaceY + ((spaceH - h) >> 1);
  66977. else if ((flags & bottom) != 0)
  66978. y = spaceY + spaceH - h;
  66979. else
  66980. y = spaceY;
  66981. }
  66982. END_JUCE_NAMESPACE
  66983. /*** End of inlined file: juce_Justification.cpp ***/
  66984. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66985. BEGIN_JUCE_NAMESPACE
  66986. // this will throw an assertion if you try to draw something that's not
  66987. // possible in postscript
  66988. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66989. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66990. #define notPossibleInPostscriptAssert jassertfalse
  66991. #else
  66992. #define notPossibleInPostscriptAssert
  66993. #endif
  66994. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66995. const String& documentTitle,
  66996. const int totalWidth_,
  66997. const int totalHeight_)
  66998. : out (resultingPostScript),
  66999. totalWidth (totalWidth_),
  67000. totalHeight (totalHeight_),
  67001. needToClip (true)
  67002. {
  67003. stateStack.add (new SavedState());
  67004. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67005. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67006. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67007. "\n%%BoundingBox: 0 0 600 824"
  67008. "\n%%Pages: 0"
  67009. "\n%%Creator: Raw Material Software JUCE"
  67010. "\n%%Title: " << documentTitle <<
  67011. "\n%%CreationDate: none"
  67012. "\n%%LanguageLevel: 2"
  67013. "\n%%EndComments"
  67014. "\n%%BeginProlog"
  67015. "\n%%BeginResource: JRes"
  67016. "\n/bd {bind def} bind def"
  67017. "\n/c {setrgbcolor} bd"
  67018. "\n/m {moveto} bd"
  67019. "\n/l {lineto} bd"
  67020. "\n/rl {rlineto} bd"
  67021. "\n/ct {curveto} bd"
  67022. "\n/cp {closepath} bd"
  67023. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67024. "\n/doclip {initclip newpath} bd"
  67025. "\n/endclip {clip newpath} bd"
  67026. "\n%%EndResource"
  67027. "\n%%EndProlog"
  67028. "\n%%BeginSetup"
  67029. "\n%%EndSetup"
  67030. "\n%%Page: 1 1"
  67031. "\n%%BeginPageSetup"
  67032. "\n%%EndPageSetup\n\n"
  67033. << "40 800 translate\n"
  67034. << scale << ' ' << scale << " scale\n\n";
  67035. }
  67036. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67037. {
  67038. }
  67039. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67040. {
  67041. return true;
  67042. }
  67043. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67044. {
  67045. if (x != 0 || y != 0)
  67046. {
  67047. stateStack.getLast()->xOffset += x;
  67048. stateStack.getLast()->yOffset += y;
  67049. needToClip = true;
  67050. }
  67051. }
  67052. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67053. {
  67054. needToClip = true;
  67055. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67056. }
  67057. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67058. {
  67059. needToClip = true;
  67060. return stateStack.getLast()->clip.clipTo (clipRegion);
  67061. }
  67062. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67063. {
  67064. needToClip = true;
  67065. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67066. }
  67067. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67068. {
  67069. writeClip();
  67070. Path p (path);
  67071. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67072. writePath (p);
  67073. out << "clip\n";
  67074. }
  67075. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67076. {
  67077. needToClip = true;
  67078. jassertfalse; // xxx
  67079. }
  67080. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67081. {
  67082. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67083. }
  67084. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67085. {
  67086. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67087. -stateStack.getLast()->yOffset);
  67088. }
  67089. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67090. {
  67091. return stateStack.getLast()->clip.isEmpty();
  67092. }
  67093. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67094. : xOffset (0),
  67095. yOffset (0)
  67096. {
  67097. }
  67098. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67099. {
  67100. }
  67101. void LowLevelGraphicsPostScriptRenderer::saveState()
  67102. {
  67103. stateStack.add (new SavedState (*stateStack.getLast()));
  67104. }
  67105. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67106. {
  67107. jassert (stateStack.size() > 0);
  67108. if (stateStack.size() > 0)
  67109. stateStack.removeLast();
  67110. }
  67111. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67112. {
  67113. if (needToClip)
  67114. {
  67115. needToClip = false;
  67116. out << "doclip ";
  67117. int itemsOnLine = 0;
  67118. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67119. {
  67120. if (++itemsOnLine == 6)
  67121. {
  67122. itemsOnLine = 0;
  67123. out << '\n';
  67124. }
  67125. const Rectangle<int>& r = *i.getRectangle();
  67126. out << r.getX() << ' ' << -r.getY() << ' '
  67127. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67128. }
  67129. out << "endclip\n";
  67130. }
  67131. }
  67132. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67133. {
  67134. Colour c (Colours::white.overlaidWith (colour));
  67135. if (lastColour != c)
  67136. {
  67137. lastColour = c;
  67138. out << String (c.getFloatRed(), 3) << ' '
  67139. << String (c.getFloatGreen(), 3) << ' '
  67140. << String (c.getFloatBlue(), 3) << " c\n";
  67141. }
  67142. }
  67143. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67144. {
  67145. out << String (x, 2) << ' '
  67146. << String (-y, 2) << ' ';
  67147. }
  67148. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67149. {
  67150. out << "newpath ";
  67151. float lastX = 0.0f;
  67152. float lastY = 0.0f;
  67153. int itemsOnLine = 0;
  67154. Path::Iterator i (path);
  67155. while (i.next())
  67156. {
  67157. if (++itemsOnLine == 4)
  67158. {
  67159. itemsOnLine = 0;
  67160. out << '\n';
  67161. }
  67162. switch (i.elementType)
  67163. {
  67164. case Path::Iterator::startNewSubPath:
  67165. writeXY (i.x1, i.y1);
  67166. lastX = i.x1;
  67167. lastY = i.y1;
  67168. out << "m ";
  67169. break;
  67170. case Path::Iterator::lineTo:
  67171. writeXY (i.x1, i.y1);
  67172. lastX = i.x1;
  67173. lastY = i.y1;
  67174. out << "l ";
  67175. break;
  67176. case Path::Iterator::quadraticTo:
  67177. {
  67178. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67179. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67180. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67181. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67182. writeXY (cp1x, cp1y);
  67183. writeXY (cp2x, cp2y);
  67184. writeXY (i.x2, i.y2);
  67185. out << "ct ";
  67186. lastX = i.x2;
  67187. lastY = i.y2;
  67188. }
  67189. break;
  67190. case Path::Iterator::cubicTo:
  67191. writeXY (i.x1, i.y1);
  67192. writeXY (i.x2, i.y2);
  67193. writeXY (i.x3, i.y3);
  67194. out << "ct ";
  67195. lastX = i.x3;
  67196. lastY = i.y3;
  67197. break;
  67198. case Path::Iterator::closePath:
  67199. out << "cp ";
  67200. break;
  67201. default:
  67202. jassertfalse;
  67203. break;
  67204. }
  67205. }
  67206. out << '\n';
  67207. }
  67208. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67209. {
  67210. out << "[ "
  67211. << trans.mat00 << ' '
  67212. << trans.mat10 << ' '
  67213. << trans.mat01 << ' '
  67214. << trans.mat11 << ' '
  67215. << trans.mat02 << ' '
  67216. << trans.mat12 << " ] concat ";
  67217. }
  67218. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67219. {
  67220. stateStack.getLast()->fillType = fillType;
  67221. }
  67222. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67223. {
  67224. }
  67225. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67226. {
  67227. }
  67228. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67229. {
  67230. if (stateStack.getLast()->fillType.isColour())
  67231. {
  67232. writeClip();
  67233. writeColour (stateStack.getLast()->fillType.colour);
  67234. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67235. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67236. }
  67237. else
  67238. {
  67239. Path p;
  67240. p.addRectangle (r);
  67241. fillPath (p, AffineTransform::identity);
  67242. }
  67243. }
  67244. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67245. {
  67246. if (stateStack.getLast()->fillType.isColour())
  67247. {
  67248. writeClip();
  67249. Path p (path);
  67250. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67251. (float) stateStack.getLast()->yOffset));
  67252. writePath (p);
  67253. writeColour (stateStack.getLast()->fillType.colour);
  67254. out << "fill\n";
  67255. }
  67256. else if (stateStack.getLast()->fillType.isGradient())
  67257. {
  67258. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67259. // postscript can't do semi-transparent ones.
  67260. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67261. writeClip();
  67262. out << "gsave ";
  67263. {
  67264. Path p (path);
  67265. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67266. writePath (p);
  67267. out << "clip\n";
  67268. }
  67269. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67270. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67271. // time-being, this just fills it with the average colour..
  67272. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67273. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67274. out << "grestore\n";
  67275. }
  67276. }
  67277. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67278. const int sx, const int sy,
  67279. const int maxW, const int maxH) const
  67280. {
  67281. out << "{<\n";
  67282. const int w = jmin (maxW, im.getWidth());
  67283. const int h = jmin (maxH, im.getHeight());
  67284. int charsOnLine = 0;
  67285. const Image::BitmapData srcData (im, 0, 0, w, h);
  67286. Colour pixel;
  67287. for (int y = h; --y >= 0;)
  67288. {
  67289. for (int x = 0; x < w; ++x)
  67290. {
  67291. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67292. if (x >= sx && y >= sy)
  67293. {
  67294. if (im.isARGB())
  67295. {
  67296. PixelARGB p (*(const PixelARGB*) pixelData);
  67297. p.unpremultiply();
  67298. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67299. }
  67300. else if (im.isRGB())
  67301. {
  67302. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67303. }
  67304. else
  67305. {
  67306. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67307. }
  67308. }
  67309. else
  67310. {
  67311. pixel = Colours::transparentWhite;
  67312. }
  67313. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67314. out << String::toHexString (pixelValues, 3, 0);
  67315. charsOnLine += 3;
  67316. if (charsOnLine > 100)
  67317. {
  67318. out << '\n';
  67319. charsOnLine = 0;
  67320. }
  67321. }
  67322. }
  67323. out << "\n>}\n";
  67324. }
  67325. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67326. {
  67327. const int w = sourceImage.getWidth();
  67328. const int h = sourceImage.getHeight();
  67329. writeClip();
  67330. out << "gsave ";
  67331. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67332. .scaled (1.0f, -1.0f));
  67333. RectangleList imageClip;
  67334. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67335. out << "newpath ";
  67336. int itemsOnLine = 0;
  67337. for (RectangleList::Iterator i (imageClip); i.next();)
  67338. {
  67339. if (++itemsOnLine == 6)
  67340. {
  67341. out << '\n';
  67342. itemsOnLine = 0;
  67343. }
  67344. const Rectangle<int>& r = *i.getRectangle();
  67345. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67346. }
  67347. out << " clip newpath\n";
  67348. out << w << ' ' << h << " scale\n";
  67349. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67350. writeImage (sourceImage, 0, 0, w, h);
  67351. out << "false 3 colorimage grestore\n";
  67352. needToClip = true;
  67353. }
  67354. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67355. {
  67356. Path p;
  67357. p.addLineSegment (line, 1.0f);
  67358. fillPath (p, AffineTransform::identity);
  67359. }
  67360. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67361. {
  67362. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67363. }
  67364. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67365. {
  67366. drawLine (Line<float> (left, (float) y, right, (float) y));
  67367. }
  67368. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67369. {
  67370. stateStack.getLast()->font = newFont;
  67371. }
  67372. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67373. {
  67374. return stateStack.getLast()->font;
  67375. }
  67376. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67377. {
  67378. Path p;
  67379. Font& font = stateStack.getLast()->font;
  67380. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67381. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67382. }
  67383. END_JUCE_NAMESPACE
  67384. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67385. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67386. BEGIN_JUCE_NAMESPACE
  67387. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67388. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67389. #endif
  67390. #if JUCE_MSVC
  67391. #pragma warning (push)
  67392. #pragma warning (disable: 4127) // "expression is constant" warning
  67393. #if JUCE_DEBUG
  67394. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67395. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67396. #endif
  67397. #endif
  67398. namespace SoftwareRendererClasses
  67399. {
  67400. template <class PixelType, bool replaceExisting = false>
  67401. class SolidColourEdgeTableRenderer
  67402. {
  67403. public:
  67404. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67405. : data (data_),
  67406. sourceColour (colour)
  67407. {
  67408. if (sizeof (PixelType) == 3)
  67409. {
  67410. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67411. && sourceColour.getGreen() == sourceColour.getBlue();
  67412. filler[0].set (sourceColour);
  67413. filler[1].set (sourceColour);
  67414. filler[2].set (sourceColour);
  67415. filler[3].set (sourceColour);
  67416. }
  67417. }
  67418. forcedinline void setEdgeTableYPos (const int y) throw()
  67419. {
  67420. linePixels = (PixelType*) data.getLinePointer (y);
  67421. }
  67422. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67423. {
  67424. if (replaceExisting)
  67425. linePixels[x].set (sourceColour);
  67426. else
  67427. linePixels[x].blend (sourceColour, alphaLevel);
  67428. }
  67429. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67430. {
  67431. if (replaceExisting)
  67432. linePixels[x].set (sourceColour);
  67433. else
  67434. linePixels[x].blend (sourceColour);
  67435. }
  67436. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67437. {
  67438. PixelARGB p (sourceColour);
  67439. p.multiplyAlpha (alphaLevel);
  67440. PixelType* dest = linePixels + x;
  67441. if (replaceExisting || p.getAlpha() >= 0xff)
  67442. replaceLine (dest, p, width);
  67443. else
  67444. blendLine (dest, p, width);
  67445. }
  67446. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67447. {
  67448. PixelType* dest = linePixels + x;
  67449. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67450. replaceLine (dest, sourceColour, width);
  67451. else
  67452. blendLine (dest, sourceColour, width);
  67453. }
  67454. private:
  67455. const Image::BitmapData& data;
  67456. PixelType* linePixels;
  67457. PixelARGB sourceColour;
  67458. PixelRGB filler [4];
  67459. bool areRGBComponentsEqual;
  67460. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67461. {
  67462. do
  67463. {
  67464. dest->blend (colour);
  67465. ++dest;
  67466. } while (--width > 0);
  67467. }
  67468. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67469. {
  67470. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67471. {
  67472. memset (dest, colour.getRed(), width * 3);
  67473. }
  67474. else
  67475. {
  67476. if (width >> 5)
  67477. {
  67478. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67479. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67480. {
  67481. dest->set (colour);
  67482. ++dest;
  67483. --width;
  67484. }
  67485. while (width > 4)
  67486. {
  67487. int* d = reinterpret_cast<int*> (dest);
  67488. *d++ = intFiller[0];
  67489. *d++ = intFiller[1];
  67490. *d++ = intFiller[2];
  67491. dest = reinterpret_cast<PixelRGB*> (d);
  67492. width -= 4;
  67493. }
  67494. }
  67495. while (--width >= 0)
  67496. {
  67497. dest->set (colour);
  67498. ++dest;
  67499. }
  67500. }
  67501. }
  67502. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67503. {
  67504. memset (dest, colour.getAlpha(), width);
  67505. }
  67506. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67507. {
  67508. do
  67509. {
  67510. dest->set (colour);
  67511. ++dest;
  67512. } while (--width > 0);
  67513. }
  67514. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67515. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67516. };
  67517. class LinearGradientPixelGenerator
  67518. {
  67519. public:
  67520. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67521. : lookupTable (lookupTable_), numEntries (numEntries_)
  67522. {
  67523. jassert (numEntries_ >= 0);
  67524. Point<float> p1 (gradient.point1);
  67525. Point<float> p2 (gradient.point2);
  67526. if (! transform.isIdentity())
  67527. {
  67528. const Line<float> l (p2, p1);
  67529. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67530. p1.applyTransform (transform);
  67531. p2.applyTransform (transform);
  67532. p3.applyTransform (transform);
  67533. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67534. }
  67535. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67536. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67537. if (vertical)
  67538. {
  67539. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67540. start = roundToInt (p1.getY() * scale);
  67541. }
  67542. else if (horizontal)
  67543. {
  67544. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67545. start = roundToInt (p1.getX() * scale);
  67546. }
  67547. else
  67548. {
  67549. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67550. yTerm = p1.getY() - p1.getX() / grad;
  67551. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67552. grad *= scale;
  67553. }
  67554. }
  67555. forcedinline void setY (const int y) throw()
  67556. {
  67557. if (vertical)
  67558. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67559. else if (! horizontal)
  67560. start = roundToInt ((y - yTerm) * grad);
  67561. }
  67562. inline const PixelARGB getPixel (const int x) const throw()
  67563. {
  67564. return vertical ? linePix
  67565. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67566. }
  67567. private:
  67568. const PixelARGB* const lookupTable;
  67569. const int numEntries;
  67570. PixelARGB linePix;
  67571. int start, scale;
  67572. double grad, yTerm;
  67573. bool vertical, horizontal;
  67574. enum { numScaleBits = 12 };
  67575. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67576. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67577. };
  67578. class RadialGradientPixelGenerator
  67579. {
  67580. public:
  67581. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67582. const PixelARGB* const lookupTable_, const int numEntries_)
  67583. : lookupTable (lookupTable_),
  67584. numEntries (numEntries_),
  67585. gx1 (gradient.point1.getX()),
  67586. gy1 (gradient.point1.getY())
  67587. {
  67588. jassert (numEntries_ >= 0);
  67589. const Point<float> diff (gradient.point1 - gradient.point2);
  67590. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67591. invScale = numEntries / std::sqrt (maxDist);
  67592. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67593. }
  67594. forcedinline void setY (const int y) throw()
  67595. {
  67596. dy = y - gy1;
  67597. dy *= dy;
  67598. }
  67599. inline const PixelARGB getPixel (const int px) const throw()
  67600. {
  67601. double x = px - gx1;
  67602. x *= x;
  67603. x += dy;
  67604. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67605. }
  67606. protected:
  67607. const PixelARGB* const lookupTable;
  67608. const int numEntries;
  67609. const double gx1, gy1;
  67610. double maxDist, invScale, dy;
  67611. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67612. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67613. };
  67614. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67615. {
  67616. public:
  67617. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67618. const PixelARGB* const lookupTable_, const int numEntries_)
  67619. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67620. inverseTransform (transform.inverted())
  67621. {
  67622. tM10 = inverseTransform.mat10;
  67623. tM00 = inverseTransform.mat00;
  67624. }
  67625. forcedinline void setY (const int y) throw()
  67626. {
  67627. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67628. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67629. }
  67630. inline const PixelARGB getPixel (const int px) const throw()
  67631. {
  67632. double x = px;
  67633. const double y = tM10 * x + lineYM11;
  67634. x = tM00 * x + lineYM01;
  67635. x *= x;
  67636. x += y * y;
  67637. if (x >= maxDist)
  67638. return lookupTable [numEntries];
  67639. else
  67640. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67641. }
  67642. private:
  67643. double tM10, tM00, lineYM01, lineYM11;
  67644. const AffineTransform inverseTransform;
  67645. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67646. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67647. };
  67648. template <class PixelType, class GradientType>
  67649. class GradientEdgeTableRenderer : public GradientType
  67650. {
  67651. public:
  67652. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67653. const PixelARGB* const lookupTable_, const int numEntries_)
  67654. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67655. destData (destData_)
  67656. {
  67657. }
  67658. forcedinline void setEdgeTableYPos (const int y) throw()
  67659. {
  67660. linePixels = (PixelType*) destData.getLinePointer (y);
  67661. GradientType::setY (y);
  67662. }
  67663. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67664. {
  67665. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67666. }
  67667. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67668. {
  67669. linePixels[x].blend (GradientType::getPixel (x));
  67670. }
  67671. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67672. {
  67673. PixelType* dest = linePixels + x;
  67674. if (alphaLevel < 0xff)
  67675. {
  67676. do
  67677. {
  67678. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67679. } while (--width > 0);
  67680. }
  67681. else
  67682. {
  67683. do
  67684. {
  67685. (dest++)->blend (GradientType::getPixel (x++));
  67686. } while (--width > 0);
  67687. }
  67688. }
  67689. void handleEdgeTableLineFull (int x, int width) const throw()
  67690. {
  67691. PixelType* dest = linePixels + x;
  67692. do
  67693. {
  67694. (dest++)->blend (GradientType::getPixel (x++));
  67695. } while (--width > 0);
  67696. }
  67697. private:
  67698. const Image::BitmapData& destData;
  67699. PixelType* linePixels;
  67700. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67701. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67702. };
  67703. static forcedinline int safeModulo (int n, const int divisor) throw()
  67704. {
  67705. jassert (divisor > 0);
  67706. n %= divisor;
  67707. return (n < 0) ? (n + divisor) : n;
  67708. }
  67709. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67710. class ImageFillEdgeTableRenderer
  67711. {
  67712. public:
  67713. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67714. const Image::BitmapData& srcData_,
  67715. const int extraAlpha_,
  67716. const int x, const int y)
  67717. : destData (destData_),
  67718. srcData (srcData_),
  67719. extraAlpha (extraAlpha_ + 1),
  67720. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67721. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67722. {
  67723. }
  67724. forcedinline void setEdgeTableYPos (int y) throw()
  67725. {
  67726. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67727. y -= yOffset;
  67728. if (repeatPattern)
  67729. {
  67730. jassert (y >= 0);
  67731. y %= srcData.height;
  67732. }
  67733. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67734. }
  67735. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67736. {
  67737. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67738. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67739. }
  67740. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67741. {
  67742. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67743. }
  67744. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67745. {
  67746. DestPixelType* dest = linePixels + x;
  67747. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67748. x -= xOffset;
  67749. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67750. if (alphaLevel < 0xfe)
  67751. {
  67752. do
  67753. {
  67754. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67755. } while (--width > 0);
  67756. }
  67757. else
  67758. {
  67759. if (repeatPattern)
  67760. {
  67761. do
  67762. {
  67763. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67764. } while (--width > 0);
  67765. }
  67766. else
  67767. {
  67768. copyRow (dest, sourceLineStart + x, width);
  67769. }
  67770. }
  67771. }
  67772. void handleEdgeTableLineFull (int x, int width) const throw()
  67773. {
  67774. DestPixelType* dest = linePixels + x;
  67775. x -= xOffset;
  67776. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67777. if (extraAlpha < 0xfe)
  67778. {
  67779. do
  67780. {
  67781. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67782. } while (--width > 0);
  67783. }
  67784. else
  67785. {
  67786. if (repeatPattern)
  67787. {
  67788. do
  67789. {
  67790. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67791. } while (--width > 0);
  67792. }
  67793. else
  67794. {
  67795. copyRow (dest, sourceLineStart + x, width);
  67796. }
  67797. }
  67798. }
  67799. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67800. {
  67801. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67802. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67803. uint8* mask = (uint8*) (s + x - xOffset);
  67804. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67805. mask += PixelARGB::indexA;
  67806. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67807. }
  67808. private:
  67809. const Image::BitmapData& destData;
  67810. const Image::BitmapData& srcData;
  67811. const int extraAlpha, xOffset, yOffset;
  67812. DestPixelType* linePixels;
  67813. SrcPixelType* sourceLineStart;
  67814. template <class PixelType1, class PixelType2>
  67815. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67816. {
  67817. do
  67818. {
  67819. dest++ ->blend (*src++);
  67820. } while (--width > 0);
  67821. }
  67822. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67823. {
  67824. memcpy (dest, src, width * sizeof (PixelRGB));
  67825. }
  67826. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67827. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67828. };
  67829. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67830. class TransformedImageFillEdgeTableRenderer
  67831. {
  67832. public:
  67833. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67834. const Image::BitmapData& srcData_,
  67835. const AffineTransform& transform,
  67836. const int extraAlpha_,
  67837. const bool betterQuality_)
  67838. : interpolator (transform),
  67839. destData (destData_),
  67840. srcData (srcData_),
  67841. extraAlpha (extraAlpha_ + 1),
  67842. betterQuality (betterQuality_),
  67843. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67844. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67845. maxX (srcData_.width - 1),
  67846. maxY (srcData_.height - 1),
  67847. scratchSize (2048)
  67848. {
  67849. scratchBuffer.malloc (scratchSize);
  67850. }
  67851. ~TransformedImageFillEdgeTableRenderer()
  67852. {
  67853. }
  67854. forcedinline void setEdgeTableYPos (const int newY) throw()
  67855. {
  67856. y = newY;
  67857. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67858. }
  67859. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67860. {
  67861. alphaLevel *= extraAlpha;
  67862. alphaLevel >>= 8;
  67863. SrcPixelType p;
  67864. generate (&p, x, 1);
  67865. linePixels[x].blend (p, alphaLevel);
  67866. }
  67867. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67868. {
  67869. SrcPixelType p;
  67870. generate (&p, x, 1);
  67871. linePixels[x].blend (p, extraAlpha);
  67872. }
  67873. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67874. {
  67875. if (width > scratchSize)
  67876. {
  67877. scratchSize = width;
  67878. scratchBuffer.malloc (scratchSize);
  67879. }
  67880. SrcPixelType* span = scratchBuffer;
  67881. generate (span, x, width);
  67882. DestPixelType* dest = linePixels + x;
  67883. alphaLevel *= extraAlpha;
  67884. alphaLevel >>= 8;
  67885. if (alphaLevel < 0xfe)
  67886. {
  67887. do
  67888. {
  67889. dest++ ->blend (*span++, alphaLevel);
  67890. } while (--width > 0);
  67891. }
  67892. else
  67893. {
  67894. do
  67895. {
  67896. dest++ ->blend (*span++);
  67897. } while (--width > 0);
  67898. }
  67899. }
  67900. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67901. {
  67902. handleEdgeTableLine (x, width, 255);
  67903. }
  67904. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67905. {
  67906. if (width > scratchSize)
  67907. {
  67908. scratchSize = width;
  67909. scratchBuffer.malloc (scratchSize);
  67910. }
  67911. y = y_;
  67912. generate (scratchBuffer, x, width);
  67913. et.clipLineToMask (x, y_,
  67914. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67915. sizeof (SrcPixelType), width);
  67916. }
  67917. private:
  67918. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67919. {
  67920. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67921. do
  67922. {
  67923. int hiResX, hiResY;
  67924. this->interpolator.next (hiResX, hiResY);
  67925. hiResX += pixelOffsetInt;
  67926. hiResY += pixelOffsetInt;
  67927. int loResX = hiResX >> 8;
  67928. int loResY = hiResY >> 8;
  67929. if (repeatPattern)
  67930. {
  67931. loResX = safeModulo (loResX, srcData.width);
  67932. loResY = safeModulo (loResY, srcData.height);
  67933. }
  67934. if (betterQuality
  67935. && ((unsigned int) loResX) < (unsigned int) maxX
  67936. && ((unsigned int) loResY) < (unsigned int) maxY)
  67937. {
  67938. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67939. hiResX &= 255;
  67940. hiResY &= 255;
  67941. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67942. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67943. c[0] += weight * src[0];
  67944. c[1] += weight * src[1];
  67945. c[2] += weight * src[2];
  67946. c[3] += weight * src[3];
  67947. weight = hiResX * (256 - hiResY);
  67948. c[0] += weight * src[4];
  67949. c[1] += weight * src[5];
  67950. c[2] += weight * src[6];
  67951. c[3] += weight * src[7];
  67952. src += this->srcData.lineStride;
  67953. weight = (256 - hiResX) * hiResY;
  67954. c[0] += weight * src[0];
  67955. c[1] += weight * src[1];
  67956. c[2] += weight * src[2];
  67957. c[3] += weight * src[3];
  67958. weight = hiResX * hiResY;
  67959. c[0] += weight * src[4];
  67960. c[1] += weight * src[5];
  67961. c[2] += weight * src[6];
  67962. c[3] += weight * src[7];
  67963. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67964. (uint8) (c[PixelARGB::indexR] >> 16),
  67965. (uint8) (c[PixelARGB::indexG] >> 16),
  67966. (uint8) (c[PixelARGB::indexB] >> 16));
  67967. }
  67968. else
  67969. {
  67970. if (! repeatPattern)
  67971. {
  67972. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67973. if (loResX < 0) loResX = 0;
  67974. if (loResY < 0) loResY = 0;
  67975. if (loResX > maxX) loResX = maxX;
  67976. if (loResY > maxY) loResY = maxY;
  67977. }
  67978. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67979. }
  67980. ++dest;
  67981. } while (--numPixels > 0);
  67982. }
  67983. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67984. {
  67985. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67986. do
  67987. {
  67988. int hiResX, hiResY;
  67989. this->interpolator.next (hiResX, hiResY);
  67990. hiResX += pixelOffsetInt;
  67991. hiResY += pixelOffsetInt;
  67992. int loResX = hiResX >> 8;
  67993. int loResY = hiResY >> 8;
  67994. if (repeatPattern)
  67995. {
  67996. loResX = safeModulo (loResX, srcData.width);
  67997. loResY = safeModulo (loResY, srcData.height);
  67998. }
  67999. if (betterQuality
  68000. && ((unsigned int) loResX) < (unsigned int) maxX
  68001. && ((unsigned int) loResY) < (unsigned int) maxY)
  68002. {
  68003. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68004. hiResX &= 255;
  68005. hiResY &= 255;
  68006. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68007. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68008. c[0] += weight * src[0];
  68009. c[1] += weight * src[1];
  68010. c[2] += weight * src[2];
  68011. weight = hiResX * (256 - hiResY);
  68012. c[0] += weight * src[3];
  68013. c[1] += weight * src[4];
  68014. c[2] += weight * src[5];
  68015. src += this->srcData.lineStride;
  68016. weight = (256 - hiResX) * hiResY;
  68017. c[0] += weight * src[0];
  68018. c[1] += weight * src[1];
  68019. c[2] += weight * src[2];
  68020. weight = hiResX * hiResY;
  68021. c[0] += weight * src[3];
  68022. c[1] += weight * src[4];
  68023. c[2] += weight * src[5];
  68024. dest->setARGB ((uint8) 255,
  68025. (uint8) (c[PixelRGB::indexR] >> 16),
  68026. (uint8) (c[PixelRGB::indexG] >> 16),
  68027. (uint8) (c[PixelRGB::indexB] >> 16));
  68028. }
  68029. else
  68030. {
  68031. if (! repeatPattern)
  68032. {
  68033. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68034. if (loResX < 0) loResX = 0;
  68035. if (loResY < 0) loResY = 0;
  68036. if (loResX > maxX) loResX = maxX;
  68037. if (loResY > maxY) loResY = maxY;
  68038. }
  68039. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68040. }
  68041. ++dest;
  68042. } while (--numPixels > 0);
  68043. }
  68044. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68045. {
  68046. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68047. do
  68048. {
  68049. int hiResX, hiResY;
  68050. this->interpolator.next (hiResX, hiResY);
  68051. hiResX += pixelOffsetInt;
  68052. hiResY += pixelOffsetInt;
  68053. int loResX = hiResX >> 8;
  68054. int loResY = hiResY >> 8;
  68055. if (repeatPattern)
  68056. {
  68057. loResX = safeModulo (loResX, srcData.width);
  68058. loResY = safeModulo (loResY, srcData.height);
  68059. }
  68060. if (betterQuality
  68061. && ((unsigned int) loResX) < (unsigned int) maxX
  68062. && ((unsigned int) loResY) < (unsigned int) maxY)
  68063. {
  68064. hiResX &= 255;
  68065. hiResY &= 255;
  68066. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68067. uint32 c = 256 * 128;
  68068. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68069. c += src[1] * (hiResX * (256 - hiResY));
  68070. src += this->srcData.lineStride;
  68071. c += src[0] * ((256 - hiResX) * hiResY);
  68072. c += src[1] * (hiResX * hiResY);
  68073. *((uint8*) dest) = (uint8) c;
  68074. }
  68075. else
  68076. {
  68077. if (! repeatPattern)
  68078. {
  68079. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68080. if (loResX < 0) loResX = 0;
  68081. if (loResY < 0) loResY = 0;
  68082. if (loResX > maxX) loResX = maxX;
  68083. if (loResY > maxY) loResY = maxY;
  68084. }
  68085. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68086. }
  68087. ++dest;
  68088. } while (--numPixels > 0);
  68089. }
  68090. class TransformedImageSpanInterpolator
  68091. {
  68092. public:
  68093. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68094. : inverseTransform (transform.inverted())
  68095. {}
  68096. void setStartOfLine (float x, float y, const int numPixels) throw()
  68097. {
  68098. float x1 = x, y1 = y;
  68099. x += numPixels;
  68100. inverseTransform.transformPoints (x1, y1, x, y);
  68101. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68102. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68103. }
  68104. void next (int& x, int& y) throw()
  68105. {
  68106. x = xBresenham.n;
  68107. xBresenham.stepToNext();
  68108. y = yBresenham.n;
  68109. yBresenham.stepToNext();
  68110. }
  68111. private:
  68112. class BresenhamInterpolator
  68113. {
  68114. public:
  68115. BresenhamInterpolator() throw() {}
  68116. void set (const int n1, const int n2, const int numSteps_) throw()
  68117. {
  68118. numSteps = jmax (1, numSteps_);
  68119. step = (n2 - n1) / numSteps;
  68120. remainder = modulo = (n2 - n1) % numSteps;
  68121. n = n1;
  68122. if (modulo <= 0)
  68123. {
  68124. modulo += numSteps;
  68125. remainder += numSteps;
  68126. --step;
  68127. }
  68128. modulo -= numSteps;
  68129. }
  68130. forcedinline void stepToNext() throw()
  68131. {
  68132. modulo += remainder;
  68133. n += step;
  68134. if (modulo > 0)
  68135. {
  68136. modulo -= numSteps;
  68137. ++n;
  68138. }
  68139. }
  68140. int n;
  68141. private:
  68142. int numSteps, step, modulo, remainder;
  68143. };
  68144. const AffineTransform inverseTransform;
  68145. BresenhamInterpolator xBresenham, yBresenham;
  68146. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68147. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68148. };
  68149. TransformedImageSpanInterpolator interpolator;
  68150. const Image::BitmapData& destData;
  68151. const Image::BitmapData& srcData;
  68152. const int extraAlpha;
  68153. const bool betterQuality;
  68154. const float pixelOffset;
  68155. const int pixelOffsetInt, maxX, maxY;
  68156. int y;
  68157. DestPixelType* linePixels;
  68158. HeapBlock <SrcPixelType> scratchBuffer;
  68159. int scratchSize;
  68160. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68161. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68162. };
  68163. class ClipRegionBase : public ReferenceCountedObject
  68164. {
  68165. public:
  68166. ClipRegionBase() {}
  68167. virtual ~ClipRegionBase() {}
  68168. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68169. virtual const Ptr clone() const = 0;
  68170. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68171. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68172. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68173. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68174. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68175. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68176. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68177. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68178. virtual const Rectangle<int> getClipBounds() const = 0;
  68179. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68180. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68181. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68182. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68183. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68184. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68185. protected:
  68186. template <class Iterator>
  68187. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68188. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68189. {
  68190. switch (destData.pixelFormat)
  68191. {
  68192. case Image::ARGB:
  68193. switch (srcData.pixelFormat)
  68194. {
  68195. case Image::ARGB:
  68196. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68197. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68198. break;
  68199. case Image::RGB:
  68200. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68201. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68202. break;
  68203. default:
  68204. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68205. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68206. break;
  68207. }
  68208. break;
  68209. case Image::RGB:
  68210. switch (srcData.pixelFormat)
  68211. {
  68212. case Image::ARGB:
  68213. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68214. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68215. break;
  68216. case Image::RGB:
  68217. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68218. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68219. break;
  68220. default:
  68221. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68222. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68223. break;
  68224. }
  68225. break;
  68226. default:
  68227. switch (srcData.pixelFormat)
  68228. {
  68229. case Image::ARGB:
  68230. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68231. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68232. break;
  68233. case Image::RGB:
  68234. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68235. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68236. break;
  68237. default:
  68238. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68239. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68240. break;
  68241. }
  68242. break;
  68243. }
  68244. }
  68245. template <class Iterator>
  68246. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68247. {
  68248. switch (destData.pixelFormat)
  68249. {
  68250. case Image::ARGB:
  68251. switch (srcData.pixelFormat)
  68252. {
  68253. case Image::ARGB:
  68254. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68255. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68256. break;
  68257. case Image::RGB:
  68258. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68259. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68260. break;
  68261. default:
  68262. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68263. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68264. break;
  68265. }
  68266. break;
  68267. case Image::RGB:
  68268. switch (srcData.pixelFormat)
  68269. {
  68270. case Image::ARGB:
  68271. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68272. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68273. break;
  68274. case Image::RGB:
  68275. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68276. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68277. break;
  68278. default:
  68279. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68280. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68281. break;
  68282. }
  68283. break;
  68284. default:
  68285. switch (srcData.pixelFormat)
  68286. {
  68287. case Image::ARGB:
  68288. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68289. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68290. break;
  68291. case Image::RGB:
  68292. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68293. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68294. break;
  68295. default:
  68296. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68297. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68298. break;
  68299. }
  68300. break;
  68301. }
  68302. }
  68303. template <class Iterator, class DestPixelType>
  68304. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68305. {
  68306. jassert (destData.pixelStride == sizeof (DestPixelType));
  68307. if (replaceContents)
  68308. {
  68309. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68310. iter.iterate (r);
  68311. }
  68312. else
  68313. {
  68314. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68315. iter.iterate (r);
  68316. }
  68317. }
  68318. template <class Iterator, class DestPixelType>
  68319. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68320. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68321. {
  68322. jassert (destData.pixelStride == sizeof (DestPixelType));
  68323. if (g.isRadial)
  68324. {
  68325. if (isIdentity)
  68326. {
  68327. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68328. iter.iterate (renderer);
  68329. }
  68330. else
  68331. {
  68332. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68333. iter.iterate (renderer);
  68334. }
  68335. }
  68336. else
  68337. {
  68338. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68339. iter.iterate (renderer);
  68340. }
  68341. }
  68342. };
  68343. class ClipRegion_EdgeTable : public ClipRegionBase
  68344. {
  68345. public:
  68346. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68347. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68348. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68349. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68350. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68351. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68352. ~ClipRegion_EdgeTable() {}
  68353. const Ptr clone() const
  68354. {
  68355. return new ClipRegion_EdgeTable (*this);
  68356. }
  68357. const Ptr applyClipTo (const Ptr& target) const
  68358. {
  68359. return target->clipToEdgeTable (edgeTable);
  68360. }
  68361. const Ptr clipToRectangle (const Rectangle<int>& r)
  68362. {
  68363. edgeTable.clipToRectangle (r);
  68364. return edgeTable.isEmpty() ? 0 : this;
  68365. }
  68366. const Ptr clipToRectangleList (const RectangleList& r)
  68367. {
  68368. RectangleList inverse (edgeTable.getMaximumBounds());
  68369. if (inverse.subtract (r))
  68370. for (RectangleList::Iterator iter (inverse); iter.next();)
  68371. edgeTable.excludeRectangle (*iter.getRectangle());
  68372. return edgeTable.isEmpty() ? 0 : this;
  68373. }
  68374. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68375. {
  68376. edgeTable.excludeRectangle (r);
  68377. return edgeTable.isEmpty() ? 0 : this;
  68378. }
  68379. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68380. {
  68381. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68382. edgeTable.clipToEdgeTable (et);
  68383. return edgeTable.isEmpty() ? 0 : this;
  68384. }
  68385. const Ptr clipToEdgeTable (const EdgeTable& et)
  68386. {
  68387. edgeTable.clipToEdgeTable (et);
  68388. return edgeTable.isEmpty() ? 0 : this;
  68389. }
  68390. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68391. {
  68392. const Image::BitmapData srcData (image, false);
  68393. if (transform.isOnlyTranslation())
  68394. {
  68395. // If our translation doesn't involve any distortion, just use a simple blit..
  68396. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68397. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68398. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68399. {
  68400. const int imageX = ((tx + 128) >> 8);
  68401. const int imageY = ((ty + 128) >> 8);
  68402. if (image.getFormat() == Image::ARGB)
  68403. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68404. else
  68405. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68406. return edgeTable.isEmpty() ? 0 : this;
  68407. }
  68408. }
  68409. if (transform.isSingularity())
  68410. return 0;
  68411. {
  68412. Path p;
  68413. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68414. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68415. edgeTable.clipToEdgeTable (et2);
  68416. }
  68417. if (! edgeTable.isEmpty())
  68418. {
  68419. if (image.getFormat() == Image::ARGB)
  68420. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68421. else
  68422. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68423. }
  68424. return edgeTable.isEmpty() ? 0 : this;
  68425. }
  68426. bool clipRegionIntersects (const Rectangle<int>& r) const
  68427. {
  68428. return edgeTable.getMaximumBounds().intersects (r);
  68429. }
  68430. const Rectangle<int> getClipBounds() const
  68431. {
  68432. return edgeTable.getMaximumBounds();
  68433. }
  68434. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68435. {
  68436. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68437. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68438. if (! clipped.isEmpty())
  68439. {
  68440. ClipRegion_EdgeTable et (clipped);
  68441. et.edgeTable.clipToEdgeTable (edgeTable);
  68442. et.fillAllWithColour (destData, colour, replaceContents);
  68443. }
  68444. }
  68445. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68446. {
  68447. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68448. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68449. if (! clipped.isEmpty())
  68450. {
  68451. ClipRegion_EdgeTable et (clipped);
  68452. et.edgeTable.clipToEdgeTable (edgeTable);
  68453. et.fillAllWithColour (destData, colour, false);
  68454. }
  68455. }
  68456. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68457. {
  68458. switch (destData.pixelFormat)
  68459. {
  68460. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68461. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68462. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68463. }
  68464. }
  68465. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68466. {
  68467. HeapBlock <PixelARGB> lookupTable;
  68468. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68469. jassert (numLookupEntries > 0);
  68470. switch (destData.pixelFormat)
  68471. {
  68472. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68473. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68474. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68475. }
  68476. }
  68477. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68478. {
  68479. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68480. }
  68481. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68482. {
  68483. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68484. }
  68485. EdgeTable edgeTable;
  68486. private:
  68487. template <class SrcPixelType>
  68488. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68489. {
  68490. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68491. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68492. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68493. edgeTable.getMaximumBounds().getWidth());
  68494. }
  68495. template <class SrcPixelType>
  68496. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68497. {
  68498. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68499. edgeTable.clipToRectangle (r);
  68500. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68501. for (int y = 0; y < r.getHeight(); ++y)
  68502. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68503. }
  68504. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68505. };
  68506. class ClipRegion_RectangleList : public ClipRegionBase
  68507. {
  68508. public:
  68509. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68510. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68511. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68512. ~ClipRegion_RectangleList() {}
  68513. const Ptr clone() const
  68514. {
  68515. return new ClipRegion_RectangleList (*this);
  68516. }
  68517. const Ptr applyClipTo (const Ptr& target) const
  68518. {
  68519. return target->clipToRectangleList (clip);
  68520. }
  68521. const Ptr clipToRectangle (const Rectangle<int>& r)
  68522. {
  68523. clip.clipTo (r);
  68524. return clip.isEmpty() ? 0 : this;
  68525. }
  68526. const Ptr clipToRectangleList (const RectangleList& r)
  68527. {
  68528. clip.clipTo (r);
  68529. return clip.isEmpty() ? 0 : this;
  68530. }
  68531. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68532. {
  68533. clip.subtract (r);
  68534. return clip.isEmpty() ? 0 : this;
  68535. }
  68536. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68537. {
  68538. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68539. }
  68540. const Ptr clipToEdgeTable (const EdgeTable& et)
  68541. {
  68542. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68543. }
  68544. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68545. {
  68546. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68547. }
  68548. bool clipRegionIntersects (const Rectangle<int>& r) const
  68549. {
  68550. return clip.intersects (r);
  68551. }
  68552. const Rectangle<int> getClipBounds() const
  68553. {
  68554. return clip.getBounds();
  68555. }
  68556. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68557. {
  68558. SubRectangleIterator iter (clip, area);
  68559. switch (destData.pixelFormat)
  68560. {
  68561. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68562. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68563. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68564. }
  68565. }
  68566. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68567. {
  68568. SubRectangleIteratorFloat iter (clip, area);
  68569. switch (destData.pixelFormat)
  68570. {
  68571. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68572. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68573. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68574. }
  68575. }
  68576. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68577. {
  68578. switch (destData.pixelFormat)
  68579. {
  68580. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68581. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68582. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68583. }
  68584. }
  68585. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68586. {
  68587. HeapBlock <PixelARGB> lookupTable;
  68588. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68589. jassert (numLookupEntries > 0);
  68590. switch (destData.pixelFormat)
  68591. {
  68592. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68593. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68594. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68595. }
  68596. }
  68597. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68598. {
  68599. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68600. }
  68601. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68602. {
  68603. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68604. }
  68605. RectangleList clip;
  68606. template <class Renderer>
  68607. void iterate (Renderer& r) const throw()
  68608. {
  68609. RectangleList::Iterator iter (clip);
  68610. while (iter.next())
  68611. {
  68612. const Rectangle<int> rect (*iter.getRectangle());
  68613. const int x = rect.getX();
  68614. const int w = rect.getWidth();
  68615. jassert (w > 0);
  68616. const int bottom = rect.getBottom();
  68617. for (int y = rect.getY(); y < bottom; ++y)
  68618. {
  68619. r.setEdgeTableYPos (y);
  68620. r.handleEdgeTableLineFull (x, w);
  68621. }
  68622. }
  68623. }
  68624. private:
  68625. class SubRectangleIterator
  68626. {
  68627. public:
  68628. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68629. : clip (clip_), area (area_)
  68630. {
  68631. }
  68632. template <class Renderer>
  68633. void iterate (Renderer& r) const throw()
  68634. {
  68635. RectangleList::Iterator iter (clip);
  68636. while (iter.next())
  68637. {
  68638. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68639. if (! rect.isEmpty())
  68640. {
  68641. const int x = rect.getX();
  68642. const int w = rect.getWidth();
  68643. const int bottom = rect.getBottom();
  68644. for (int y = rect.getY(); y < bottom; ++y)
  68645. {
  68646. r.setEdgeTableYPos (y);
  68647. r.handleEdgeTableLineFull (x, w);
  68648. }
  68649. }
  68650. }
  68651. }
  68652. private:
  68653. const RectangleList& clip;
  68654. const Rectangle<int> area;
  68655. SubRectangleIterator (const SubRectangleIterator&);
  68656. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68657. };
  68658. class SubRectangleIteratorFloat
  68659. {
  68660. public:
  68661. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68662. : clip (clip_), area (area_)
  68663. {
  68664. }
  68665. template <class Renderer>
  68666. void iterate (Renderer& r) const throw()
  68667. {
  68668. int left = roundToInt (area.getX() * 256.0f);
  68669. int top = roundToInt (area.getY() * 256.0f);
  68670. int right = roundToInt (area.getRight() * 256.0f);
  68671. int bottom = roundToInt (area.getBottom() * 256.0f);
  68672. int totalTop, totalLeft, totalBottom, totalRight;
  68673. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68674. if ((top >> 8) == (bottom >> 8))
  68675. {
  68676. topAlpha = bottom - top;
  68677. bottomAlpha = 0;
  68678. totalTop = top >> 8;
  68679. totalBottom = bottom = top = totalTop + 1;
  68680. }
  68681. else
  68682. {
  68683. if ((top & 255) == 0)
  68684. {
  68685. topAlpha = 0;
  68686. top = totalTop = (top >> 8);
  68687. }
  68688. else
  68689. {
  68690. topAlpha = 255 - (top & 255);
  68691. totalTop = (top >> 8);
  68692. top = totalTop + 1;
  68693. }
  68694. bottomAlpha = bottom & 255;
  68695. bottom >>= 8;
  68696. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68697. }
  68698. if ((left >> 8) == (right >> 8))
  68699. {
  68700. leftAlpha = right - left;
  68701. rightAlpha = 0;
  68702. totalLeft = (left >> 8);
  68703. totalRight = right = left = totalLeft + 1;
  68704. }
  68705. else
  68706. {
  68707. if ((left & 255) == 0)
  68708. {
  68709. leftAlpha = 0;
  68710. left = totalLeft = (left >> 8);
  68711. }
  68712. else
  68713. {
  68714. leftAlpha = 255 - (left & 255);
  68715. totalLeft = (left >> 8);
  68716. left = totalLeft + 1;
  68717. }
  68718. rightAlpha = right & 255;
  68719. right >>= 8;
  68720. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68721. }
  68722. RectangleList::Iterator iter (clip);
  68723. while (iter.next())
  68724. {
  68725. const int clipLeft = iter.getRectangle()->getX();
  68726. const int clipRight = iter.getRectangle()->getRight();
  68727. const int clipTop = iter.getRectangle()->getY();
  68728. const int clipBottom = iter.getRectangle()->getBottom();
  68729. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68730. {
  68731. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68732. {
  68733. if (topAlpha != 0 && totalTop >= clipTop)
  68734. {
  68735. r.setEdgeTableYPos (totalTop);
  68736. r.handleEdgeTablePixel (left, topAlpha);
  68737. }
  68738. const int endY = jmin (bottom, clipBottom);
  68739. for (int y = jmax (clipTop, top); y < endY; ++y)
  68740. {
  68741. r.setEdgeTableYPos (y);
  68742. r.handleEdgeTablePixelFull (left);
  68743. }
  68744. if (bottomAlpha != 0 && bottom < clipBottom)
  68745. {
  68746. r.setEdgeTableYPos (bottom);
  68747. r.handleEdgeTablePixel (left, bottomAlpha);
  68748. }
  68749. }
  68750. else
  68751. {
  68752. const int clippedLeft = jmax (left, clipLeft);
  68753. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68754. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68755. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68756. if (topAlpha != 0 && totalTop >= clipTop)
  68757. {
  68758. r.setEdgeTableYPos (totalTop);
  68759. if (doLeftAlpha)
  68760. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68761. if (clippedWidth > 0)
  68762. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68763. if (doRightAlpha)
  68764. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68765. }
  68766. const int endY = jmin (bottom, clipBottom);
  68767. for (int y = jmax (clipTop, top); y < endY; ++y)
  68768. {
  68769. r.setEdgeTableYPos (y);
  68770. if (doLeftAlpha)
  68771. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68772. if (clippedWidth > 0)
  68773. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68774. if (doRightAlpha)
  68775. r.handleEdgeTablePixel (right, rightAlpha);
  68776. }
  68777. if (bottomAlpha != 0 && bottom < clipBottom)
  68778. {
  68779. r.setEdgeTableYPos (bottom);
  68780. if (doLeftAlpha)
  68781. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68782. if (clippedWidth > 0)
  68783. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68784. if (doRightAlpha)
  68785. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68786. }
  68787. }
  68788. }
  68789. }
  68790. }
  68791. private:
  68792. const RectangleList& clip;
  68793. const Rectangle<float>& area;
  68794. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68795. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68796. };
  68797. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68798. };
  68799. }
  68800. class LowLevelGraphicsSoftwareRenderer::SavedState
  68801. {
  68802. public:
  68803. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68804. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68805. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68806. {
  68807. }
  68808. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68809. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68810. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68811. {
  68812. }
  68813. SavedState (const SavedState& other)
  68814. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68815. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68816. {
  68817. }
  68818. ~SavedState()
  68819. {
  68820. }
  68821. void setOrigin (const int x, const int y) throw()
  68822. {
  68823. xOffset += x;
  68824. yOffset += y;
  68825. }
  68826. bool clipToRectangle (const Rectangle<int>& r)
  68827. {
  68828. if (clip != 0)
  68829. {
  68830. cloneClipIfMultiplyReferenced();
  68831. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68832. }
  68833. return clip != 0;
  68834. }
  68835. bool clipToRectangleList (const RectangleList& r)
  68836. {
  68837. if (clip != 0)
  68838. {
  68839. cloneClipIfMultiplyReferenced();
  68840. RectangleList offsetList (r);
  68841. offsetList.offsetAll (xOffset, yOffset);
  68842. clip = clip->clipToRectangleList (offsetList);
  68843. }
  68844. return clip != 0;
  68845. }
  68846. bool excludeClipRectangle (const Rectangle<int>& r)
  68847. {
  68848. if (clip != 0)
  68849. {
  68850. cloneClipIfMultiplyReferenced();
  68851. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68852. }
  68853. return clip != 0;
  68854. }
  68855. void clipToPath (const Path& p, const AffineTransform& transform)
  68856. {
  68857. if (clip != 0)
  68858. {
  68859. cloneClipIfMultiplyReferenced();
  68860. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68861. }
  68862. }
  68863. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68864. {
  68865. if (clip != 0)
  68866. {
  68867. if (image.hasAlphaChannel())
  68868. {
  68869. cloneClipIfMultiplyReferenced();
  68870. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68871. interpolationQuality != Graphics::lowResamplingQuality);
  68872. }
  68873. else
  68874. {
  68875. Path p;
  68876. p.addRectangle (image.getBounds());
  68877. clipToPath (p, t);
  68878. }
  68879. }
  68880. }
  68881. bool clipRegionIntersects (const Rectangle<int>& r) const
  68882. {
  68883. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68884. }
  68885. const Rectangle<int> getClipBounds() const
  68886. {
  68887. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68888. }
  68889. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68890. {
  68891. if (clip != 0)
  68892. {
  68893. if (fillType.isColour())
  68894. {
  68895. Image::BitmapData destData (image, true);
  68896. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68897. }
  68898. else
  68899. {
  68900. const Rectangle<int> totalClip (clip->getClipBounds());
  68901. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68902. if (! clipped.isEmpty())
  68903. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68904. }
  68905. }
  68906. }
  68907. void fillRect (Image& image, const Rectangle<float>& r)
  68908. {
  68909. if (clip != 0)
  68910. {
  68911. if (fillType.isColour())
  68912. {
  68913. Image::BitmapData destData (image, true);
  68914. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68915. }
  68916. else
  68917. {
  68918. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68919. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68920. if (! clipped.isEmpty())
  68921. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68922. }
  68923. }
  68924. }
  68925. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68926. {
  68927. if (clip != 0)
  68928. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68929. }
  68930. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68931. {
  68932. if (clip != 0)
  68933. {
  68934. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68935. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68936. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68937. fillShape (image, shapeToFill, false);
  68938. }
  68939. }
  68940. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68941. {
  68942. jassert (clip != 0);
  68943. shapeToFill = clip->applyClipTo (shapeToFill);
  68944. if (shapeToFill != 0)
  68945. {
  68946. Image::BitmapData destData (image, true);
  68947. if (fillType.isGradient())
  68948. {
  68949. jassert (! replaceContents); // that option is just for solid colours
  68950. ColourGradient g2 (*(fillType.gradient));
  68951. g2.multiplyOpacity (fillType.getOpacity());
  68952. g2.point1.addXY (-0.5f, -0.5f);
  68953. g2.point2.addXY (-0.5f, -0.5f);
  68954. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68955. const bool isIdentity = transform.isOnlyTranslation();
  68956. if (isIdentity)
  68957. {
  68958. // If our translation doesn't involve any distortion, we can speed it up..
  68959. g2.point1.applyTransform (transform);
  68960. g2.point2.applyTransform (transform);
  68961. transform = AffineTransform::identity;
  68962. }
  68963. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68964. }
  68965. else if (fillType.isTiledImage())
  68966. {
  68967. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68968. }
  68969. else
  68970. {
  68971. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68972. }
  68973. }
  68974. }
  68975. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68976. {
  68977. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68978. const Image::BitmapData destData (destImage, true);
  68979. const Image::BitmapData srcData (sourceImage, false);
  68980. const int alpha = fillType.colour.getAlpha();
  68981. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68982. if (transform.isOnlyTranslation())
  68983. {
  68984. // If our translation doesn't involve any distortion, just use a simple blit..
  68985. int tx = (int) (transform.getTranslationX() * 256.0f);
  68986. int ty = (int) (transform.getTranslationY() * 256.0f);
  68987. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68988. {
  68989. tx = ((tx + 128) >> 8);
  68990. ty = ((ty + 128) >> 8);
  68991. if (tiledFillClipRegion != 0)
  68992. {
  68993. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68994. }
  68995. else
  68996. {
  68997. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68998. c = clip->applyClipTo (c);
  68999. if (c != 0)
  69000. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69001. }
  69002. return;
  69003. }
  69004. }
  69005. if (transform.isSingularity())
  69006. return;
  69007. if (tiledFillClipRegion != 0)
  69008. {
  69009. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69010. }
  69011. else
  69012. {
  69013. Path p;
  69014. p.addRectangle (sourceImage.getBounds());
  69015. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69016. c = c->clipToPath (p, transform);
  69017. if (c != 0)
  69018. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69019. }
  69020. }
  69021. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69022. int xOffset, yOffset;
  69023. Font font;
  69024. FillType fillType;
  69025. Graphics::ResamplingQuality interpolationQuality;
  69026. private:
  69027. void cloneClipIfMultiplyReferenced()
  69028. {
  69029. if (clip->getReferenceCount() > 1)
  69030. clip = clip->clone();
  69031. }
  69032. SavedState& operator= (const SavedState&);
  69033. };
  69034. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69035. : image (image_)
  69036. {
  69037. currentState = new SavedState (image_.getBounds(), 0, 0);
  69038. }
  69039. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69040. const RectangleList& initialClip)
  69041. : image (image_)
  69042. {
  69043. currentState = new SavedState (initialClip, xOffset, yOffset);
  69044. }
  69045. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69046. {
  69047. }
  69048. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69049. {
  69050. return false;
  69051. }
  69052. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69053. {
  69054. currentState->setOrigin (x, y);
  69055. }
  69056. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69057. {
  69058. return currentState->clipToRectangle (r);
  69059. }
  69060. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69061. {
  69062. return currentState->clipToRectangleList (clipRegion);
  69063. }
  69064. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69065. {
  69066. currentState->excludeClipRectangle (r);
  69067. }
  69068. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69069. {
  69070. currentState->clipToPath (path, transform);
  69071. }
  69072. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69073. {
  69074. currentState->clipToImageAlpha (sourceImage, transform);
  69075. }
  69076. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69077. {
  69078. return currentState->clipRegionIntersects (r);
  69079. }
  69080. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69081. {
  69082. return currentState->getClipBounds();
  69083. }
  69084. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69085. {
  69086. return currentState->clip == 0;
  69087. }
  69088. void LowLevelGraphicsSoftwareRenderer::saveState()
  69089. {
  69090. stateStack.add (new SavedState (*currentState));
  69091. }
  69092. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69093. {
  69094. SavedState* const top = stateStack.getLast();
  69095. if (top != 0)
  69096. {
  69097. currentState = top;
  69098. stateStack.removeLast (1, false);
  69099. }
  69100. else
  69101. {
  69102. jassertfalse; // trying to pop with an empty stack!
  69103. }
  69104. }
  69105. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69106. {
  69107. currentState->fillType = fillType;
  69108. }
  69109. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69110. {
  69111. currentState->fillType.setOpacity (newOpacity);
  69112. }
  69113. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69114. {
  69115. currentState->interpolationQuality = quality;
  69116. }
  69117. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69118. {
  69119. currentState->fillRect (image, r, replaceExistingContents);
  69120. }
  69121. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69122. {
  69123. currentState->fillPath (image, path, transform);
  69124. }
  69125. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69126. {
  69127. currentState->renderImage (image, sourceImage, transform,
  69128. fillEntireClipAsTiles ? currentState->clip : 0);
  69129. }
  69130. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69131. {
  69132. Path p;
  69133. p.addLineSegment (line, 1.0f);
  69134. fillPath (p, AffineTransform::identity);
  69135. }
  69136. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69137. {
  69138. if (bottom > top)
  69139. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69140. }
  69141. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69142. {
  69143. if (right > left)
  69144. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69145. }
  69146. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69147. {
  69148. public:
  69149. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69150. ~CachedGlyph() {}
  69151. void draw (SavedState& state, Image& image, const float x, const float y) const
  69152. {
  69153. if (edgeTable != 0)
  69154. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69155. }
  69156. void generate (const Font& newFont, const int glyphNumber)
  69157. {
  69158. font = newFont;
  69159. glyph = glyphNumber;
  69160. edgeTable = 0;
  69161. Path glyphPath;
  69162. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69163. if (! glyphPath.isEmpty())
  69164. {
  69165. const float fontHeight = font.getHeight();
  69166. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69167. #if JUCE_MAC || JUCE_IOS
  69168. .translated (0.0f, -0.5f)
  69169. #endif
  69170. );
  69171. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69172. glyphPath, transform);
  69173. }
  69174. }
  69175. int glyph, lastAccessCount;
  69176. Font font;
  69177. juce_UseDebuggingNewOperator
  69178. private:
  69179. ScopedPointer <EdgeTable> edgeTable;
  69180. CachedGlyph (const CachedGlyph&);
  69181. CachedGlyph& operator= (const CachedGlyph&);
  69182. };
  69183. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69184. {
  69185. public:
  69186. GlyphCache()
  69187. : accessCounter (0), hits (0), misses (0)
  69188. {
  69189. for (int i = 120; --i >= 0;)
  69190. glyphs.add (new CachedGlyph());
  69191. }
  69192. ~GlyphCache()
  69193. {
  69194. clearSingletonInstance();
  69195. }
  69196. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69197. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69198. {
  69199. ++accessCounter;
  69200. int oldestCounter = std::numeric_limits<int>::max();
  69201. CachedGlyph* oldest = 0;
  69202. for (int i = glyphs.size(); --i >= 0;)
  69203. {
  69204. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69205. if (glyph->glyph == glyphNumber && glyph->font == font)
  69206. {
  69207. ++hits;
  69208. glyph->lastAccessCount = accessCounter;
  69209. glyph->draw (state, image, x, y);
  69210. return;
  69211. }
  69212. if (glyph->lastAccessCount <= oldestCounter)
  69213. {
  69214. oldestCounter = glyph->lastAccessCount;
  69215. oldest = glyph;
  69216. }
  69217. }
  69218. if (hits + ++misses > (glyphs.size() << 4))
  69219. {
  69220. if (misses * 2 > hits)
  69221. {
  69222. for (int i = 32; --i >= 0;)
  69223. glyphs.add (new CachedGlyph());
  69224. }
  69225. hits = misses = 0;
  69226. oldest = glyphs.getLast();
  69227. }
  69228. jassert (oldest != 0);
  69229. oldest->lastAccessCount = accessCounter;
  69230. oldest->generate (font, glyphNumber);
  69231. oldest->draw (state, image, x, y);
  69232. }
  69233. juce_UseDebuggingNewOperator
  69234. private:
  69235. friend class OwnedArray <CachedGlyph>;
  69236. OwnedArray <CachedGlyph> glyphs;
  69237. int accessCounter, hits, misses;
  69238. GlyphCache (const GlyphCache&);
  69239. GlyphCache& operator= (const GlyphCache&);
  69240. };
  69241. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69242. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69243. {
  69244. currentState->font = newFont;
  69245. }
  69246. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69247. {
  69248. return currentState->font;
  69249. }
  69250. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69251. {
  69252. Font& f = currentState->font;
  69253. if (transform.isOnlyTranslation())
  69254. {
  69255. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69256. transform.getTranslationX(),
  69257. transform.getTranslationY());
  69258. }
  69259. else
  69260. {
  69261. Path p;
  69262. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69263. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69264. }
  69265. }
  69266. #if JUCE_MSVC
  69267. #pragma warning (pop)
  69268. #if JUCE_DEBUG
  69269. #pragma optimize ("", on) // resets optimisations to the project defaults
  69270. #endif
  69271. #endif
  69272. END_JUCE_NAMESPACE
  69273. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69274. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69275. BEGIN_JUCE_NAMESPACE
  69276. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69277. : flags (other.flags)
  69278. {
  69279. }
  69280. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69281. {
  69282. flags = other.flags;
  69283. return *this;
  69284. }
  69285. void RectanglePlacement::applyTo (double& x, double& y,
  69286. double& w, double& h,
  69287. const double dx, const double dy,
  69288. const double dw, const double dh) const throw()
  69289. {
  69290. if (w == 0 || h == 0)
  69291. return;
  69292. if ((flags & stretchToFit) != 0)
  69293. {
  69294. x = dx;
  69295. y = dy;
  69296. w = dw;
  69297. h = dh;
  69298. }
  69299. else
  69300. {
  69301. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69302. : jmin (dw / w, dh / h);
  69303. if ((flags & onlyReduceInSize) != 0)
  69304. scale = jmin (scale, 1.0);
  69305. if ((flags & onlyIncreaseInSize) != 0)
  69306. scale = jmax (scale, 1.0);
  69307. w *= scale;
  69308. h *= scale;
  69309. if ((flags & xLeft) != 0)
  69310. x = dx;
  69311. else if ((flags & xRight) != 0)
  69312. x = dx + dw - w;
  69313. else
  69314. x = dx + (dw - w) * 0.5;
  69315. if ((flags & yTop) != 0)
  69316. y = dy;
  69317. else if ((flags & yBottom) != 0)
  69318. y = dy + dh - h;
  69319. else
  69320. y = dy + (dh - h) * 0.5;
  69321. }
  69322. }
  69323. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69324. float w, float h,
  69325. const float dx, const float dy,
  69326. const float dw, const float dh) const throw()
  69327. {
  69328. if (w == 0 || h == 0)
  69329. return AffineTransform::identity;
  69330. const float scaleX = dw / w;
  69331. const float scaleY = dh / h;
  69332. if ((flags & stretchToFit) != 0)
  69333. return AffineTransform::translation (-x, -y)
  69334. .scaled (scaleX, scaleY)
  69335. .translated (dx, dy);
  69336. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69337. : jmin (scaleX, scaleY);
  69338. if ((flags & onlyReduceInSize) != 0)
  69339. scale = jmin (scale, 1.0f);
  69340. if ((flags & onlyIncreaseInSize) != 0)
  69341. scale = jmax (scale, 1.0f);
  69342. w *= scale;
  69343. h *= scale;
  69344. float newX = dx;
  69345. if ((flags & xRight) != 0)
  69346. newX += dw - w; // right
  69347. else if ((flags & xLeft) == 0)
  69348. newX += (dw - w) / 2.0f; // centre
  69349. float newY = dy;
  69350. if ((flags & yBottom) != 0)
  69351. newY += dh - h; // bottom
  69352. else if ((flags & yTop) == 0)
  69353. newY += (dh - h) / 2.0f; // centre
  69354. return AffineTransform::translation (-x, -y)
  69355. .scaled (scale, scale)
  69356. .translated (newX, newY);
  69357. }
  69358. END_JUCE_NAMESPACE
  69359. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69360. /*** Start of inlined file: juce_Drawable.cpp ***/
  69361. BEGIN_JUCE_NAMESPACE
  69362. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69363. const AffineTransform& transform_,
  69364. const float opacity_) throw()
  69365. : g (g_),
  69366. transform (transform_),
  69367. opacity (opacity_)
  69368. {
  69369. }
  69370. Drawable::Drawable()
  69371. : parent (0)
  69372. {
  69373. }
  69374. Drawable::~Drawable()
  69375. {
  69376. }
  69377. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69378. {
  69379. render (RenderingContext (g, transform, opacity));
  69380. }
  69381. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69382. {
  69383. draw (g, opacity, AffineTransform::translation (x, y));
  69384. }
  69385. void Drawable::drawWithin (Graphics& g,
  69386. const int destX,
  69387. const int destY,
  69388. const int destW,
  69389. const int destH,
  69390. const RectanglePlacement& placement,
  69391. const float opacity) const
  69392. {
  69393. if (destW > 0 && destH > 0)
  69394. {
  69395. Rectangle<float> bounds (getBounds());
  69396. draw (g, opacity,
  69397. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69398. (float) destX, (float) destY,
  69399. (float) destW, (float) destH));
  69400. }
  69401. }
  69402. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69403. {
  69404. Drawable* result = 0;
  69405. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69406. if (image.isValid())
  69407. {
  69408. DrawableImage* const di = new DrawableImage();
  69409. di->setImage (image);
  69410. result = di;
  69411. }
  69412. else
  69413. {
  69414. const String asString (String::createStringFromData (data, (int) numBytes));
  69415. XmlDocument doc (asString);
  69416. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69417. if (outer != 0 && outer->hasTagName ("svg"))
  69418. {
  69419. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69420. if (svg != 0)
  69421. result = Drawable::createFromSVG (*svg);
  69422. }
  69423. }
  69424. return result;
  69425. }
  69426. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69427. {
  69428. MemoryOutputStream mo;
  69429. mo.writeFromInputStream (dataSource, -1);
  69430. return createFromImageData (mo.getData(), mo.getDataSize());
  69431. }
  69432. Drawable* Drawable::createFromImageFile (const File& file)
  69433. {
  69434. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69435. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69436. }
  69437. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69438. {
  69439. return createChildFromValueTree (0, tree, imageProvider);
  69440. }
  69441. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69442. {
  69443. const Identifier type (tree.getType());
  69444. Drawable* d = 0;
  69445. if (type == DrawablePath::valueTreeType)
  69446. d = new DrawablePath();
  69447. else if (type == DrawableComposite::valueTreeType)
  69448. d = new DrawableComposite();
  69449. else if (type == DrawableImage::valueTreeType)
  69450. d = new DrawableImage();
  69451. else if (type == DrawableText::valueTreeType)
  69452. d = new DrawableText();
  69453. if (d != 0)
  69454. {
  69455. d->parent = parent;
  69456. d->refreshFromValueTree (tree, imageProvider);
  69457. }
  69458. return d;
  69459. }
  69460. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69461. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69462. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69463. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69464. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69465. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69466. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69467. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69468. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69469. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69470. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69471. : state (state_)
  69472. {
  69473. }
  69474. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69475. {
  69476. }
  69477. const String Drawable::ValueTreeWrapperBase::getID() const
  69478. {
  69479. return state [idProperty];
  69480. }
  69481. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69482. {
  69483. if (newID.isEmpty())
  69484. state.removeProperty (idProperty, undoManager);
  69485. else
  69486. state.setProperty (idProperty, newID, undoManager);
  69487. }
  69488. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69489. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69490. {
  69491. const String newType (v[type].toString());
  69492. if (newType == "solid")
  69493. {
  69494. const String colourString (v [colour].toString());
  69495. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69496. : (uint32) colourString.getHexValue32()));
  69497. }
  69498. else if (newType == "gradient")
  69499. {
  69500. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69501. ColourGradient g;
  69502. if (gp1 != 0) *gp1 = p1;
  69503. if (gp2 != 0) *gp2 = p2;
  69504. if (gp3 != 0) *gp3 = p3;
  69505. g.point1 = p1.resolve (nameFinder);
  69506. g.point2 = p2.resolve (nameFinder);
  69507. g.isRadial = v[radial];
  69508. StringArray colourSteps;
  69509. colourSteps.addTokens (v[colours].toString(), false);
  69510. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69511. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69512. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69513. FillType fillType (g);
  69514. if (g.isRadial)
  69515. {
  69516. const Point<float> point3 (p3.resolve (nameFinder));
  69517. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69518. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69519. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69520. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69521. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69522. }
  69523. return fillType;
  69524. }
  69525. else if (newType == "image")
  69526. {
  69527. Image im;
  69528. if (imageProvider != 0)
  69529. im = imageProvider->getImageForIdentifier (v[imageId]);
  69530. FillType f (im, AffineTransform::identity);
  69531. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69532. return f;
  69533. }
  69534. jassertfalse;
  69535. return FillType();
  69536. }
  69537. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69538. {
  69539. const ColourGradient& g = *fillType.gradient;
  69540. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69541. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69542. return point3Source.transformedBy (fillType.transform);
  69543. }
  69544. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69545. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69546. ImageProvider* imageProvider, UndoManager* const undoManager)
  69547. {
  69548. if (fillType.isColour())
  69549. {
  69550. v.setProperty (type, "solid", undoManager);
  69551. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69552. }
  69553. else if (fillType.isGradient())
  69554. {
  69555. v.setProperty (type, "gradient", undoManager);
  69556. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69557. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69558. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69559. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69560. String s;
  69561. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69562. s << ' ' << fillType.gradient->getColourPosition (i)
  69563. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69564. v.setProperty (colours, s.trimStart(), undoManager);
  69565. }
  69566. else if (fillType.isTiledImage())
  69567. {
  69568. v.setProperty (type, "image", undoManager);
  69569. if (imageProvider != 0)
  69570. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69571. if (fillType.getOpacity() < 1.0f)
  69572. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69573. else
  69574. v.removeProperty (imageOpacity, undoManager);
  69575. }
  69576. else
  69577. {
  69578. jassertfalse;
  69579. }
  69580. }
  69581. END_JUCE_NAMESPACE
  69582. /*** End of inlined file: juce_Drawable.cpp ***/
  69583. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69584. BEGIN_JUCE_NAMESPACE
  69585. DrawableComposite::DrawableComposite()
  69586. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69587. {
  69588. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69589. RelativeCoordinate (100.0),
  69590. RelativeCoordinate (0.0),
  69591. RelativeCoordinate (100.0)));
  69592. }
  69593. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69594. {
  69595. bounds = other.bounds;
  69596. for (int i = 0; i < other.drawables.size(); ++i)
  69597. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69598. markersX.addCopiesOf (other.markersX);
  69599. markersY.addCopiesOf (other.markersY);
  69600. }
  69601. DrawableComposite::~DrawableComposite()
  69602. {
  69603. }
  69604. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69605. {
  69606. if (drawable != 0)
  69607. {
  69608. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69609. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69610. drawables.insert (index, drawable);
  69611. drawable->parent = this;
  69612. }
  69613. }
  69614. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69615. {
  69616. insertDrawable (drawable.createCopy(), index);
  69617. }
  69618. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69619. {
  69620. drawables.remove (index, deleteDrawable);
  69621. }
  69622. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69623. {
  69624. for (int i = drawables.size(); --i >= 0;)
  69625. if (drawables.getUnchecked(i)->getName() == name)
  69626. return drawables.getUnchecked(i);
  69627. return 0;
  69628. }
  69629. void DrawableComposite::bringToFront (const int index)
  69630. {
  69631. if (index >= 0 && index < drawables.size() - 1)
  69632. drawables.move (index, -1);
  69633. }
  69634. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69635. {
  69636. bounds = newBoundingBox;
  69637. }
  69638. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69639. : name (other.name), position (other.position)
  69640. {
  69641. }
  69642. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69643. : name (name_), position (position_)
  69644. {
  69645. }
  69646. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69647. {
  69648. return name != other.name || position != other.position;
  69649. }
  69650. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69651. const char* const DrawableComposite::contentRightMarkerName ("right");
  69652. const char* const DrawableComposite::contentTopMarkerName ("top");
  69653. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69654. const RelativeRectangle DrawableComposite::getContentArea() const
  69655. {
  69656. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69657. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69658. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69659. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69660. }
  69661. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69662. {
  69663. setMarker (contentLeftMarkerName, true, newArea.left);
  69664. setMarker (contentRightMarkerName, true, newArea.right);
  69665. setMarker (contentTopMarkerName, false, newArea.top);
  69666. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69667. }
  69668. void DrawableComposite::resetBoundingBoxToContentArea()
  69669. {
  69670. const RelativeRectangle content (getContentArea());
  69671. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69672. RelativePoint (content.right, content.top),
  69673. RelativePoint (content.left, content.bottom)));
  69674. }
  69675. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69676. {
  69677. const Rectangle<float> bounds (getUntransformedBounds (false));
  69678. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69679. RelativeCoordinate (bounds.getRight()),
  69680. RelativeCoordinate (bounds.getY()),
  69681. RelativeCoordinate (bounds.getBottom())));
  69682. resetBoundingBoxToContentArea();
  69683. }
  69684. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69685. {
  69686. return (xAxis ? markersX : markersY).size();
  69687. }
  69688. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69689. {
  69690. return (xAxis ? markersX : markersY) [index];
  69691. }
  69692. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69693. {
  69694. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69695. for (int i = 0; i < markers.size(); ++i)
  69696. {
  69697. Marker* const m = markers.getUnchecked(i);
  69698. if (m->name == name)
  69699. {
  69700. if (m->position != position)
  69701. {
  69702. m->position = position;
  69703. invalidatePoints();
  69704. }
  69705. return;
  69706. }
  69707. }
  69708. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69709. invalidatePoints();
  69710. }
  69711. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69712. {
  69713. jassert (index >= 2);
  69714. if (index >= 2)
  69715. (xAxis ? markersX : markersY).remove (index);
  69716. }
  69717. const AffineTransform DrawableComposite::calculateTransform() const
  69718. {
  69719. Point<float> resolved[3];
  69720. bounds.resolveThreePoints (resolved, parent);
  69721. const Rectangle<float> content (getContentArea().resolve (parent));
  69722. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69723. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69724. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69725. }
  69726. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69727. {
  69728. if (drawables.size() > 0 && context.opacity > 0)
  69729. {
  69730. if (context.opacity >= 1.0f || drawables.size() == 1)
  69731. {
  69732. Drawable::RenderingContext contextCopy (context);
  69733. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69734. for (int i = 0; i < drawables.size(); ++i)
  69735. drawables.getUnchecked(i)->render (contextCopy);
  69736. }
  69737. else
  69738. {
  69739. // To correctly render a whole composite layer with an overall transparency,
  69740. // we need to render everything opaquely into a temp buffer, then blend that
  69741. // with the target opacity...
  69742. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69743. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69744. {
  69745. Graphics tempG (tempImage);
  69746. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69747. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69748. render (tempContext);
  69749. }
  69750. context.g.setOpacity (context.opacity);
  69751. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69752. }
  69753. }
  69754. }
  69755. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69756. {
  69757. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69758. int i;
  69759. for (i = 0; i < markersX.size(); ++i)
  69760. {
  69761. Marker* const m = markersX.getUnchecked(i);
  69762. if (m->name == symbol)
  69763. return m->position.getExpression();
  69764. }
  69765. for (i = 0; i < markersY.size(); ++i)
  69766. {
  69767. Marker* const m = markersY.getUnchecked(i);
  69768. if (m->name == symbol)
  69769. return m->position.getExpression();
  69770. }
  69771. throw Expression::EvaluationError (symbol, member);
  69772. }
  69773. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69774. {
  69775. Rectangle<float> bounds;
  69776. int i;
  69777. for (i = 0; i < drawables.size(); ++i)
  69778. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69779. if (includeMarkers)
  69780. {
  69781. if (markersX.size() > 0)
  69782. {
  69783. float minX = std::numeric_limits<float>::max();
  69784. float maxX = std::numeric_limits<float>::min();
  69785. for (i = markersX.size(); --i >= 0;)
  69786. {
  69787. const Marker* m = markersX.getUnchecked(i);
  69788. const float pos = (float) m->position.resolve (this);
  69789. minX = jmin (minX, pos);
  69790. maxX = jmax (maxX, pos);
  69791. }
  69792. if (minX <= maxX)
  69793. {
  69794. if (bounds.getHeight() > 0)
  69795. {
  69796. minX = jmin (minX, bounds.getX());
  69797. maxX = jmax (maxX, bounds.getRight());
  69798. }
  69799. bounds.setLeft (minX);
  69800. bounds.setWidth (maxX - minX);
  69801. }
  69802. }
  69803. if (markersY.size() > 0)
  69804. {
  69805. float minY = std::numeric_limits<float>::max();
  69806. float maxY = std::numeric_limits<float>::min();
  69807. for (i = markersY.size(); --i >= 0;)
  69808. {
  69809. const Marker* m = markersY.getUnchecked(i);
  69810. const float pos = (float) m->position.resolve (this);
  69811. minY = jmin (minY, pos);
  69812. maxY = jmax (maxY, pos);
  69813. }
  69814. if (minY <= maxY)
  69815. {
  69816. if (bounds.getHeight() > 0)
  69817. {
  69818. minY = jmin (minY, bounds.getY());
  69819. maxY = jmax (maxY, bounds.getBottom());
  69820. }
  69821. bounds.setTop (minY);
  69822. bounds.setHeight (maxY - minY);
  69823. }
  69824. }
  69825. }
  69826. return bounds;
  69827. }
  69828. const Rectangle<float> DrawableComposite::getBounds() const
  69829. {
  69830. return getUntransformedBounds (true).transformed (calculateTransform());
  69831. }
  69832. bool DrawableComposite::hitTest (float x, float y) const
  69833. {
  69834. calculateTransform().inverted().transformPoint (x, y);
  69835. for (int i = 0; i < drawables.size(); ++i)
  69836. if (drawables.getUnchecked(i)->hitTest (x, y))
  69837. return true;
  69838. return false;
  69839. }
  69840. Drawable* DrawableComposite::createCopy() const
  69841. {
  69842. return new DrawableComposite (*this);
  69843. }
  69844. void DrawableComposite::invalidatePoints()
  69845. {
  69846. for (int i = 0; i < drawables.size(); ++i)
  69847. drawables.getUnchecked(i)->invalidatePoints();
  69848. }
  69849. const Identifier DrawableComposite::valueTreeType ("Group");
  69850. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69851. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69852. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69853. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69854. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69855. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69856. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69857. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69858. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69859. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69860. : ValueTreeWrapperBase (state_)
  69861. {
  69862. jassert (state.hasType (valueTreeType));
  69863. }
  69864. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69865. {
  69866. return state.getChildWithName (childGroupTag);
  69867. }
  69868. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69869. {
  69870. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69871. }
  69872. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69873. {
  69874. return getChildList().getNumChildren();
  69875. }
  69876. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69877. {
  69878. return getChildList().getChild (index);
  69879. }
  69880. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69881. {
  69882. if (getID() == objectId)
  69883. return state;
  69884. if (! recursive)
  69885. {
  69886. return getChildList().getChildWithProperty (idProperty, objectId);
  69887. }
  69888. else
  69889. {
  69890. const ValueTree childList (getChildList());
  69891. for (int i = getNumDrawables(); --i >= 0;)
  69892. {
  69893. const ValueTree& child = childList.getChild (i);
  69894. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69895. return child;
  69896. if (child.hasType (DrawableComposite::valueTreeType))
  69897. {
  69898. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69899. if (v.isValid())
  69900. return v;
  69901. }
  69902. }
  69903. return ValueTree::invalid;
  69904. }
  69905. }
  69906. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69907. {
  69908. return getChildList().indexOf (item);
  69909. }
  69910. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69911. {
  69912. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69913. }
  69914. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69915. {
  69916. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69917. }
  69918. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69919. {
  69920. getChildList().removeChild (child, undoManager);
  69921. }
  69922. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69923. {
  69924. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69925. state.getProperty (topRight, "100, 0"),
  69926. state.getProperty (bottomLeft, "0, 100"));
  69927. }
  69928. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69929. {
  69930. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69931. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69932. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69933. }
  69934. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69935. {
  69936. const RelativeRectangle content (getContentArea());
  69937. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69938. RelativePoint (content.right, content.top),
  69939. RelativePoint (content.left, content.bottom)), undoManager);
  69940. }
  69941. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69942. {
  69943. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69944. getMarker (true, getMarkerState (true, 1)).position,
  69945. getMarker (false, getMarkerState (false, 0)).position,
  69946. getMarker (false, getMarkerState (false, 1)).position);
  69947. }
  69948. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69949. {
  69950. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69951. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69952. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69953. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69954. }
  69955. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69956. {
  69957. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69958. }
  69959. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69960. {
  69961. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69962. }
  69963. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69964. {
  69965. return getMarkerList (xAxis).getNumChildren();
  69966. }
  69967. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69968. {
  69969. return getMarkerList (xAxis).getChild (index);
  69970. }
  69971. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69972. {
  69973. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69974. }
  69975. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69976. {
  69977. return state.isAChildOf (getMarkerList (xAxis));
  69978. }
  69979. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69980. {
  69981. (void) xAxis;
  69982. jassert (containsMarker (xAxis, state));
  69983. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  69984. }
  69985. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69986. {
  69987. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69988. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69989. if (marker.isValid())
  69990. {
  69991. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69992. }
  69993. else
  69994. {
  69995. marker = ValueTree (markerTag);
  69996. marker.setProperty (nameProperty, m.name, 0);
  69997. marker.setProperty (posProperty, m.position.toString(), 0);
  69998. markerList.addChild (marker, -1, undoManager);
  69999. }
  70000. }
  70001. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70002. {
  70003. if (state [nameProperty].toString() != contentLeftMarkerName
  70004. && state [nameProperty].toString() != contentRightMarkerName
  70005. && state [nameProperty].toString() != contentTopMarkerName
  70006. && state [nameProperty].toString() != contentBottomMarkerName)
  70007. return getMarkerList (xAxis).removeChild (state, undoManager);
  70008. }
  70009. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70010. {
  70011. const ValueTreeWrapper wrapper (tree);
  70012. setName (wrapper.getID());
  70013. Rectangle<float> damage;
  70014. bool redrawAll = false;
  70015. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70016. if (bounds != newBounds)
  70017. {
  70018. redrawAll = true;
  70019. damage = getBounds();
  70020. bounds = newBounds;
  70021. }
  70022. const int numMarkersX = wrapper.getNumMarkers (true);
  70023. const int numMarkersY = wrapper.getNumMarkers (false);
  70024. // Remove deleted markers...
  70025. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70026. {
  70027. if (! redrawAll)
  70028. {
  70029. redrawAll = true;
  70030. damage = getBounds();
  70031. }
  70032. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70033. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70034. }
  70035. // Update markers and add new ones..
  70036. int i;
  70037. for (i = 0; i < numMarkersX; ++i)
  70038. {
  70039. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70040. Marker* m = markersX[i];
  70041. if (m == 0 || newMarker != *m)
  70042. {
  70043. if (! redrawAll)
  70044. {
  70045. redrawAll = true;
  70046. damage = getBounds();
  70047. }
  70048. if (m == 0)
  70049. markersX.add (new Marker (newMarker));
  70050. else
  70051. *m = newMarker;
  70052. }
  70053. }
  70054. for (i = 0; i < numMarkersY; ++i)
  70055. {
  70056. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70057. Marker* m = markersY[i];
  70058. if (m == 0 || newMarker != *m)
  70059. {
  70060. if (! redrawAll)
  70061. {
  70062. redrawAll = true;
  70063. damage = getBounds();
  70064. }
  70065. if (m == 0)
  70066. markersY.add (new Marker (newMarker));
  70067. else
  70068. *m = newMarker;
  70069. }
  70070. }
  70071. // Remove deleted drawables..
  70072. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70073. {
  70074. Drawable* const d = drawables.getUnchecked(i);
  70075. if (! redrawAll)
  70076. damage = damage.getUnion (d->getBounds());
  70077. d->parent = 0;
  70078. drawables.remove (i);
  70079. }
  70080. // Update drawables and add new ones..
  70081. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70082. {
  70083. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70084. Drawable* d = drawables[i];
  70085. if (d != 0)
  70086. {
  70087. if (newDrawable.hasType (d->getValueTreeType()))
  70088. {
  70089. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70090. if (! redrawAll)
  70091. damage = damage.getUnion (area);
  70092. }
  70093. else
  70094. {
  70095. if (! redrawAll)
  70096. damage = damage.getUnion (d->getBounds());
  70097. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70098. drawables.set (i, d);
  70099. if (! redrawAll)
  70100. damage = damage.getUnion (d->getBounds());
  70101. }
  70102. }
  70103. else
  70104. {
  70105. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70106. drawables.set (i, d);
  70107. if (! redrawAll)
  70108. damage = damage.getUnion (d->getBounds());
  70109. }
  70110. }
  70111. if (redrawAll)
  70112. damage = damage.getUnion (getBounds());
  70113. else if (! damage.isEmpty())
  70114. damage = damage.transformed (calculateTransform());
  70115. return damage;
  70116. }
  70117. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70118. {
  70119. ValueTree tree (valueTreeType);
  70120. ValueTreeWrapper v (tree);
  70121. v.setID (getName(), 0);
  70122. v.setBoundingBox (bounds, 0);
  70123. int i;
  70124. for (i = 0; i < drawables.size(); ++i)
  70125. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70126. for (i = 0; i < markersX.size(); ++i)
  70127. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70128. for (i = 0; i < markersY.size(); ++i)
  70129. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70130. return tree;
  70131. }
  70132. END_JUCE_NAMESPACE
  70133. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70134. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70135. BEGIN_JUCE_NAMESPACE
  70136. DrawableImage::DrawableImage()
  70137. : image (0),
  70138. opacity (1.0f),
  70139. overlayColour (0x00000000)
  70140. {
  70141. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70142. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70143. }
  70144. DrawableImage::DrawableImage (const DrawableImage& other)
  70145. : image (other.image),
  70146. opacity (other.opacity),
  70147. overlayColour (other.overlayColour),
  70148. bounds (other.bounds)
  70149. {
  70150. }
  70151. DrawableImage::~DrawableImage()
  70152. {
  70153. }
  70154. void DrawableImage::setImage (const Image& imageToUse)
  70155. {
  70156. image = imageToUse;
  70157. if (image.isValid())
  70158. {
  70159. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70160. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70161. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70162. }
  70163. }
  70164. void DrawableImage::setOpacity (const float newOpacity)
  70165. {
  70166. opacity = newOpacity;
  70167. }
  70168. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70169. {
  70170. overlayColour = newOverlayColour;
  70171. }
  70172. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70173. {
  70174. bounds = newBounds;
  70175. }
  70176. const AffineTransform DrawableImage::calculateTransform() const
  70177. {
  70178. if (image.isNull())
  70179. return AffineTransform::identity;
  70180. Point<float> resolved[3];
  70181. bounds.resolveThreePoints (resolved, parent);
  70182. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70183. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70184. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70185. tr.getX(), tr.getY(),
  70186. bl.getX(), bl.getY());
  70187. }
  70188. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70189. {
  70190. if (image.isValid())
  70191. {
  70192. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70193. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70194. {
  70195. context.g.setOpacity (context.opacity * opacity);
  70196. context.g.drawImageTransformed (image, t, false);
  70197. }
  70198. if (! overlayColour.isTransparent())
  70199. {
  70200. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70201. context.g.drawImageTransformed (image, t, true);
  70202. }
  70203. }
  70204. }
  70205. const Rectangle<float> DrawableImage::getBounds() const
  70206. {
  70207. if (image.isNull())
  70208. return Rectangle<float>();
  70209. return bounds.getBounds (parent);
  70210. }
  70211. bool DrawableImage::hitTest (float x, float y) const
  70212. {
  70213. if (image.isNull())
  70214. return false;
  70215. calculateTransform().inverted().transformPoint (x, y);
  70216. const int ix = roundToInt (x);
  70217. const int iy = roundToInt (y);
  70218. return ix >= 0
  70219. && iy >= 0
  70220. && ix < image.getWidth()
  70221. && iy < image.getHeight()
  70222. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70223. }
  70224. Drawable* DrawableImage::createCopy() const
  70225. {
  70226. return new DrawableImage (*this);
  70227. }
  70228. void DrawableImage::invalidatePoints()
  70229. {
  70230. }
  70231. const Identifier DrawableImage::valueTreeType ("Image");
  70232. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70233. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70234. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70235. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70236. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70237. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70238. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70239. : ValueTreeWrapperBase (state_)
  70240. {
  70241. jassert (state.hasType (valueTreeType));
  70242. }
  70243. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70244. {
  70245. return state [image];
  70246. }
  70247. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70248. {
  70249. return state.getPropertyAsValue (image, undoManager);
  70250. }
  70251. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70252. {
  70253. state.setProperty (image, newIdentifier, undoManager);
  70254. }
  70255. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70256. {
  70257. return (float) state.getProperty (opacity, 1.0);
  70258. }
  70259. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70260. {
  70261. if (! state.hasProperty (opacity))
  70262. state.setProperty (opacity, 1.0, undoManager);
  70263. return state.getPropertyAsValue (opacity, undoManager);
  70264. }
  70265. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70266. {
  70267. state.setProperty (opacity, newOpacity, undoManager);
  70268. }
  70269. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70270. {
  70271. return Colour (state [overlay].toString().getHexValue32());
  70272. }
  70273. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70274. {
  70275. if (newColour.isTransparent())
  70276. state.removeProperty (overlay, undoManager);
  70277. else
  70278. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70279. }
  70280. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70281. {
  70282. return state.getPropertyAsValue (overlay, undoManager);
  70283. }
  70284. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70285. {
  70286. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70287. state.getProperty (topRight, "100, 0"),
  70288. state.getProperty (bottomLeft, "0, 100"));
  70289. }
  70290. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70291. {
  70292. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70293. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70294. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70295. }
  70296. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70297. {
  70298. const ValueTreeWrapper controller (tree);
  70299. setName (controller.getID());
  70300. const float newOpacity = controller.getOpacity();
  70301. const Colour newOverlayColour (controller.getOverlayColour());
  70302. Image newImage;
  70303. const var imageIdentifier (controller.getImageIdentifier());
  70304. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70305. if (imageProvider != 0)
  70306. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70307. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70308. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70309. {
  70310. const Rectangle<float> damage (getBounds());
  70311. opacity = newOpacity;
  70312. overlayColour = newOverlayColour;
  70313. bounds = newBounds;
  70314. image = newImage;
  70315. return damage.getUnion (getBounds());
  70316. }
  70317. return Rectangle<float>();
  70318. }
  70319. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70320. {
  70321. ValueTree tree (valueTreeType);
  70322. ValueTreeWrapper v (tree);
  70323. v.setID (getName(), 0);
  70324. v.setOpacity (opacity, 0);
  70325. v.setOverlayColour (overlayColour, 0);
  70326. v.setBoundingBox (bounds, 0);
  70327. if (image.isValid())
  70328. {
  70329. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70330. if (imageProvider != 0)
  70331. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70332. }
  70333. return tree;
  70334. }
  70335. END_JUCE_NAMESPACE
  70336. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70337. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70338. BEGIN_JUCE_NAMESPACE
  70339. DrawablePath::DrawablePath()
  70340. : mainFill (Colours::black),
  70341. strokeFill (Colours::black),
  70342. strokeType (0.0f),
  70343. pathNeedsUpdating (true),
  70344. strokeNeedsUpdating (true)
  70345. {
  70346. }
  70347. DrawablePath::DrawablePath (const DrawablePath& other)
  70348. : mainFill (other.mainFill),
  70349. strokeFill (other.strokeFill),
  70350. strokeType (other.strokeType),
  70351. pathNeedsUpdating (true),
  70352. strokeNeedsUpdating (true)
  70353. {
  70354. if (other.relativePath != 0)
  70355. relativePath = new RelativePointPath (*other.relativePath);
  70356. else
  70357. path = other.path;
  70358. }
  70359. DrawablePath::~DrawablePath()
  70360. {
  70361. }
  70362. void DrawablePath::setPath (const Path& newPath)
  70363. {
  70364. path = newPath;
  70365. strokeNeedsUpdating = true;
  70366. }
  70367. void DrawablePath::setFill (const FillType& newFill)
  70368. {
  70369. mainFill = newFill;
  70370. }
  70371. void DrawablePath::setStrokeFill (const FillType& newFill)
  70372. {
  70373. strokeFill = newFill;
  70374. }
  70375. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70376. {
  70377. strokeType = newStrokeType;
  70378. strokeNeedsUpdating = true;
  70379. }
  70380. void DrawablePath::setStrokeThickness (const float newThickness)
  70381. {
  70382. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70383. }
  70384. void DrawablePath::updatePath() const
  70385. {
  70386. if (pathNeedsUpdating)
  70387. {
  70388. pathNeedsUpdating = false;
  70389. if (relativePath != 0)
  70390. {
  70391. path.clear();
  70392. relativePath->createPath (path, parent);
  70393. strokeNeedsUpdating = true;
  70394. }
  70395. }
  70396. }
  70397. void DrawablePath::updateStroke() const
  70398. {
  70399. if (strokeNeedsUpdating)
  70400. {
  70401. strokeNeedsUpdating = false;
  70402. updatePath();
  70403. stroke.clear();
  70404. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70405. }
  70406. }
  70407. const Path& DrawablePath::getPath() const
  70408. {
  70409. updatePath();
  70410. return path;
  70411. }
  70412. const Path& DrawablePath::getStrokePath() const
  70413. {
  70414. updateStroke();
  70415. return stroke;
  70416. }
  70417. bool DrawablePath::isStrokeVisible() const throw()
  70418. {
  70419. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70420. }
  70421. void DrawablePath::invalidatePoints()
  70422. {
  70423. pathNeedsUpdating = true;
  70424. strokeNeedsUpdating = true;
  70425. }
  70426. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70427. {
  70428. {
  70429. FillType f (mainFill);
  70430. if (f.isGradient())
  70431. f.gradient->multiplyOpacity (context.opacity);
  70432. else
  70433. f.setOpacity (f.getOpacity() * context.opacity);
  70434. f.transform = f.transform.followedBy (context.transform);
  70435. context.g.setFillType (f);
  70436. context.g.fillPath (getPath(), context.transform);
  70437. }
  70438. if (isStrokeVisible())
  70439. {
  70440. FillType f (strokeFill);
  70441. if (f.isGradient())
  70442. f.gradient->multiplyOpacity (context.opacity);
  70443. else
  70444. f.setOpacity (f.getOpacity() * context.opacity);
  70445. f.transform = f.transform.followedBy (context.transform);
  70446. context.g.setFillType (f);
  70447. context.g.fillPath (getStrokePath(), context.transform);
  70448. }
  70449. }
  70450. const Rectangle<float> DrawablePath::getBounds() const
  70451. {
  70452. if (isStrokeVisible())
  70453. return getStrokePath().getBounds();
  70454. else
  70455. return getPath().getBounds();
  70456. }
  70457. bool DrawablePath::hitTest (float x, float y) const
  70458. {
  70459. return getPath().contains (x, y)
  70460. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70461. }
  70462. Drawable* DrawablePath::createCopy() const
  70463. {
  70464. return new DrawablePath (*this);
  70465. }
  70466. const Identifier DrawablePath::valueTreeType ("Path");
  70467. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70468. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70469. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70470. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70471. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70472. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70473. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70474. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70475. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70476. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70477. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70478. : ValueTreeWrapperBase (state_)
  70479. {
  70480. jassert (state.hasType (valueTreeType));
  70481. }
  70482. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70483. {
  70484. return state.getOrCreateChildWithName (path, 0);
  70485. }
  70486. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70487. {
  70488. ValueTree v (state.getChildWithName (fill));
  70489. if (v.isValid())
  70490. return v;
  70491. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70492. return getMainFillState();
  70493. }
  70494. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70495. {
  70496. ValueTree v (state.getChildWithName (stroke));
  70497. if (v.isValid())
  70498. return v;
  70499. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70500. return getStrokeFillState();
  70501. }
  70502. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70503. ImageProvider* imageProvider) const
  70504. {
  70505. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70506. }
  70507. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70508. const RelativePoint* gp2, const RelativePoint* gp3,
  70509. ImageProvider* imageProvider, UndoManager* undoManager)
  70510. {
  70511. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70512. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70513. }
  70514. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70515. ImageProvider* imageProvider) const
  70516. {
  70517. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70518. }
  70519. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70520. const RelativePoint* gp2, const RelativePoint* gp3,
  70521. ImageProvider* imageProvider, UndoManager* undoManager)
  70522. {
  70523. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70524. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70525. }
  70526. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70527. {
  70528. const String jointStyleString (state [jointStyle].toString());
  70529. const String capStyleString (state [capStyle].toString());
  70530. return PathStrokeType (state [strokeWidth],
  70531. jointStyleString == "curved" ? PathStrokeType::curved
  70532. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70533. : PathStrokeType::mitered),
  70534. capStyleString == "square" ? PathStrokeType::square
  70535. : (capStyleString == "round" ? PathStrokeType::rounded
  70536. : PathStrokeType::butt));
  70537. }
  70538. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70539. {
  70540. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70541. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70542. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70543. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70544. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70545. }
  70546. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70547. {
  70548. return state [nonZeroWinding];
  70549. }
  70550. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70551. {
  70552. state.setProperty (nonZeroWinding, b, undoManager);
  70553. }
  70554. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70555. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70556. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70557. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70558. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70559. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70560. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70561. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70562. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70563. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70564. : state (state_)
  70565. {
  70566. }
  70567. DrawablePath::ValueTreeWrapper::Element::~Element()
  70568. {
  70569. }
  70570. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70571. {
  70572. return ValueTreeWrapper (state.getParent().getParent());
  70573. }
  70574. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70575. {
  70576. return Element (state.getSibling (-1));
  70577. }
  70578. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70579. {
  70580. const Identifier i (state.getType());
  70581. if (i == startSubPathElement || i == lineToElement) return 1;
  70582. if (i == quadraticToElement) return 2;
  70583. if (i == cubicToElement) return 3;
  70584. return 0;
  70585. }
  70586. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70587. {
  70588. jassert (index >= 0 && index < getNumControlPoints());
  70589. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70590. }
  70591. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70592. {
  70593. jassert (index >= 0 && index < getNumControlPoints());
  70594. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70595. }
  70596. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70597. {
  70598. jassert (index >= 0 && index < getNumControlPoints());
  70599. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70600. }
  70601. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70602. {
  70603. const Identifier i (state.getType());
  70604. if (i == startSubPathElement)
  70605. return getControlPoint (0);
  70606. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70607. return getPreviousElement().getEndPoint();
  70608. }
  70609. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70610. {
  70611. const Identifier i (state.getType());
  70612. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70613. if (i == quadraticToElement) return getControlPoint (1);
  70614. if (i == cubicToElement) return getControlPoint (2);
  70615. jassert (i == closeSubPathElement);
  70616. return RelativePoint();
  70617. }
  70618. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70619. {
  70620. const Identifier i (state.getType());
  70621. if (i == lineToElement || i == closeSubPathElement)
  70622. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70623. if (i == cubicToElement)
  70624. {
  70625. Path p;
  70626. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70627. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70628. return p.getLength();
  70629. }
  70630. if (i == quadraticToElement)
  70631. {
  70632. Path p;
  70633. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70634. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70635. return p.getLength();
  70636. }
  70637. jassert (i == startSubPathElement);
  70638. return 0;
  70639. }
  70640. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70641. {
  70642. return state [mode].toString();
  70643. }
  70644. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70645. {
  70646. if (state.hasType (cubicToElement))
  70647. state.setProperty (mode, newMode, undoManager);
  70648. }
  70649. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70650. {
  70651. const Identifier i (state.getType());
  70652. if (i == quadraticToElement || i == cubicToElement)
  70653. {
  70654. ValueTree newState (lineToElement);
  70655. Element e (newState);
  70656. e.setControlPoint (0, getEndPoint(), undoManager);
  70657. state = newState;
  70658. }
  70659. }
  70660. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70661. {
  70662. const Identifier i (state.getType());
  70663. if (i == lineToElement || i == quadraticToElement)
  70664. {
  70665. ValueTree newState (cubicToElement);
  70666. Element e (newState);
  70667. const RelativePoint start (getStartPoint());
  70668. const RelativePoint end (getEndPoint());
  70669. const Point<float> startResolved (start.resolve (nameFinder));
  70670. const Point<float> endResolved (end.resolve (nameFinder));
  70671. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70672. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70673. e.setControlPoint (2, end, undoManager);
  70674. state = newState;
  70675. }
  70676. }
  70677. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70678. {
  70679. const Identifier i (state.getType());
  70680. if (i != startSubPathElement)
  70681. {
  70682. ValueTree newState (startSubPathElement);
  70683. Element e (newState);
  70684. e.setControlPoint (0, getEndPoint(), undoManager);
  70685. state = newState;
  70686. }
  70687. }
  70688. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70689. {
  70690. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70691. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70692. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70693. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70694. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70695. return newCp1 + (newCp2 - newCp1) * proportion;
  70696. }
  70697. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70698. {
  70699. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70700. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70701. return mid1 + (mid2 - mid1) * proportion;
  70702. }
  70703. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70704. {
  70705. const Identifier i (state.getType());
  70706. float bestProp = 0;
  70707. if (i == cubicToElement)
  70708. {
  70709. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70710. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70711. float bestDistance = std::numeric_limits<float>::max();
  70712. for (int i = 110; --i >= 0;)
  70713. {
  70714. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70715. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70716. const float distance = centre.getDistanceFrom (targetPoint);
  70717. if (distance < bestDistance)
  70718. {
  70719. bestProp = prop;
  70720. bestDistance = distance;
  70721. }
  70722. }
  70723. }
  70724. else if (i == quadraticToElement)
  70725. {
  70726. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70727. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.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 (findQuadraticSubdivisionPoint ((float) 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 == lineToElement)
  70742. {
  70743. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70744. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70745. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70746. }
  70747. return bestProp;
  70748. }
  70749. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70750. {
  70751. ValueTree newTree;
  70752. const Identifier i (state.getType());
  70753. if (i == cubicToElement)
  70754. {
  70755. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70756. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70757. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70758. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70759. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70760. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70761. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70762. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70763. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70764. setControlPoint (0, mid1, undoManager);
  70765. setControlPoint (1, newCp1, undoManager);
  70766. setControlPoint (2, newCentre, undoManager);
  70767. setModeOfEndPoint (roundedMode, undoManager);
  70768. Element newElement (newTree = ValueTree (cubicToElement));
  70769. newElement.setControlPoint (0, newCp2, 0);
  70770. newElement.setControlPoint (1, mid3, 0);
  70771. newElement.setControlPoint (2, rp4, 0);
  70772. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70773. }
  70774. else if (i == quadraticToElement)
  70775. {
  70776. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70777. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70778. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70779. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70780. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70781. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70782. setControlPoint (0, mid1, undoManager);
  70783. setControlPoint (1, newCentre, undoManager);
  70784. setModeOfEndPoint (roundedMode, undoManager);
  70785. Element newElement (newTree = ValueTree (quadraticToElement));
  70786. newElement.setControlPoint (0, mid2, 0);
  70787. newElement.setControlPoint (1, rp3, 0);
  70788. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70789. }
  70790. else if (i == lineToElement)
  70791. {
  70792. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70793. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70794. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70795. setControlPoint (0, newPoint, undoManager);
  70796. Element newElement (newTree = ValueTree (lineToElement));
  70797. newElement.setControlPoint (0, rp2, 0);
  70798. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70799. }
  70800. else if (i == closeSubPathElement)
  70801. {
  70802. }
  70803. return newTree;
  70804. }
  70805. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70806. {
  70807. state.getParent().removeChild (state, undoManager);
  70808. }
  70809. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70810. {
  70811. Rectangle<float> damageRect;
  70812. ValueTreeWrapper v (tree);
  70813. setName (v.getID());
  70814. bool needsRedraw = false;
  70815. const FillType newFill (v.getMainFill (parent, imageProvider));
  70816. if (mainFill != newFill)
  70817. {
  70818. needsRedraw = true;
  70819. mainFill = newFill;
  70820. }
  70821. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70822. if (strokeFill != newStrokeFill)
  70823. {
  70824. needsRedraw = true;
  70825. strokeFill = newStrokeFill;
  70826. }
  70827. const PathStrokeType newStroke (v.getStrokeType());
  70828. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70829. Path newPath;
  70830. newRelativePath->createPath (newPath, parent);
  70831. if (! newRelativePath->containsAnyDynamicPoints())
  70832. newRelativePath = 0;
  70833. if (strokeType != newStroke || path != newPath)
  70834. {
  70835. damageRect = getBounds();
  70836. path.swapWithPath (newPath);
  70837. strokeNeedsUpdating = true;
  70838. strokeType = newStroke;
  70839. needsRedraw = true;
  70840. }
  70841. relativePath = newRelativePath;
  70842. if (needsRedraw)
  70843. damageRect = damageRect.getUnion (getBounds());
  70844. return damageRect;
  70845. }
  70846. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70847. {
  70848. ValueTree tree (valueTreeType);
  70849. ValueTreeWrapper v (tree);
  70850. v.setID (getName(), 0);
  70851. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70852. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70853. v.setStrokeType (strokeType, 0);
  70854. if (relativePath != 0)
  70855. {
  70856. relativePath->writeTo (tree, 0);
  70857. }
  70858. else
  70859. {
  70860. RelativePointPath rp (path);
  70861. rp.writeTo (tree, 0);
  70862. }
  70863. return tree;
  70864. }
  70865. END_JUCE_NAMESPACE
  70866. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70867. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70868. BEGIN_JUCE_NAMESPACE
  70869. DrawableText::DrawableText()
  70870. : colour (Colours::black),
  70871. justification (Justification::centredLeft)
  70872. {
  70873. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70874. RelativePoint (50.0f, 0.0f),
  70875. RelativePoint (0.0f, 20.0f)));
  70876. setFont (Font (15.0f), true);
  70877. }
  70878. DrawableText::DrawableText (const DrawableText& other)
  70879. : text (other.text),
  70880. font (other.font),
  70881. colour (other.colour),
  70882. justification (other.justification),
  70883. bounds (other.bounds),
  70884. fontSizeControlPoint (other.fontSizeControlPoint)
  70885. {
  70886. }
  70887. DrawableText::~DrawableText()
  70888. {
  70889. }
  70890. void DrawableText::setText (const String& newText)
  70891. {
  70892. text = newText;
  70893. }
  70894. void DrawableText::setColour (const Colour& newColour)
  70895. {
  70896. colour = newColour;
  70897. }
  70898. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70899. {
  70900. font = newFont;
  70901. if (applySizeAndScale)
  70902. {
  70903. Point<float> corners[3];
  70904. bounds.resolveThreePoints (corners, parent);
  70905. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70906. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70907. }
  70908. }
  70909. void DrawableText::setJustification (const Justification& newJustification)
  70910. {
  70911. justification = newJustification;
  70912. }
  70913. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70914. {
  70915. bounds = newBounds;
  70916. }
  70917. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70918. {
  70919. fontSizeControlPoint = newPoint;
  70920. }
  70921. void DrawableText::render (const Drawable::RenderingContext& context) const
  70922. {
  70923. Point<float> points[3];
  70924. bounds.resolveThreePoints (points, parent);
  70925. const float w = Line<float> (points[0], points[1]).getLength();
  70926. const float h = Line<float> (points[0], points[2]).getLength();
  70927. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70928. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70929. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70930. Font f (font);
  70931. f.setHeight (fontHeight);
  70932. f.setHorizontalScale (fontWidth / fontHeight);
  70933. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70934. GlyphArrangement ga;
  70935. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70936. ga.draw (context.g,
  70937. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70938. w, 0, points[1].getX(), points[1].getY(),
  70939. 0, h, points[2].getX(), points[2].getY())
  70940. .followedBy (context.transform));
  70941. }
  70942. const Rectangle<float> DrawableText::getBounds() const
  70943. {
  70944. return bounds.getBounds (parent);
  70945. }
  70946. bool DrawableText::hitTest (float x, float y) const
  70947. {
  70948. Path p;
  70949. bounds.getPath (p, parent);
  70950. return p.contains (x, y);
  70951. }
  70952. Drawable* DrawableText::createCopy() const
  70953. {
  70954. return new DrawableText (*this);
  70955. }
  70956. void DrawableText::invalidatePoints()
  70957. {
  70958. }
  70959. const Identifier DrawableText::valueTreeType ("Text");
  70960. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70961. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70962. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70963. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70964. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70965. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70966. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70967. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70968. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70969. : ValueTreeWrapperBase (state_)
  70970. {
  70971. jassert (state.hasType (valueTreeType));
  70972. }
  70973. const String DrawableText::ValueTreeWrapper::getText() const
  70974. {
  70975. return state [text].toString();
  70976. }
  70977. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70978. {
  70979. state.setProperty (text, newText, undoManager);
  70980. }
  70981. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70982. {
  70983. return state.getPropertyAsValue (text, undoManager);
  70984. }
  70985. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70986. {
  70987. return Colour::fromString (state [colour].toString());
  70988. }
  70989. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70990. {
  70991. state.setProperty (colour, newColour.toString(), undoManager);
  70992. }
  70993. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70994. {
  70995. return Justification ((int) state [justification]);
  70996. }
  70997. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70998. {
  70999. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71000. }
  71001. const Font DrawableText::ValueTreeWrapper::getFont() const
  71002. {
  71003. return Font::fromString (state [font]);
  71004. }
  71005. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71006. {
  71007. state.setProperty (font, newFont.toString(), undoManager);
  71008. }
  71009. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71010. {
  71011. return state.getPropertyAsValue (font, undoManager);
  71012. }
  71013. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71014. {
  71015. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71016. }
  71017. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71018. {
  71019. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71020. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71021. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71022. }
  71023. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71024. {
  71025. return state [fontSizeAnchor].toString();
  71026. }
  71027. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71028. {
  71029. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71030. }
  71031. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71032. {
  71033. ValueTreeWrapper v (tree);
  71034. setName (v.getID());
  71035. const RelativeParallelogram newBounds (v.getBoundingBox());
  71036. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71037. const Colour newColour (v.getColour());
  71038. const Justification newJustification (v.getJustification());
  71039. const String newText (v.getText());
  71040. const Font newFont (v.getFont());
  71041. if (text != newText || font != newFont || justification != newJustification
  71042. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71043. {
  71044. const Rectangle<float> damage (getBounds());
  71045. setBoundingBox (newBounds);
  71046. setFontSizeControlPoint (newFontPoint);
  71047. setColour (newColour);
  71048. setFont (newFont, false);
  71049. setJustification (newJustification);
  71050. setText (newText);
  71051. return damage.getUnion (getBounds());
  71052. }
  71053. return Rectangle<float>();
  71054. }
  71055. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71056. {
  71057. ValueTree tree (valueTreeType);
  71058. ValueTreeWrapper v (tree);
  71059. v.setID (getName(), 0);
  71060. v.setText (text, 0);
  71061. v.setFont (font, 0);
  71062. v.setJustification (justification, 0);
  71063. v.setColour (colour, 0);
  71064. v.setBoundingBox (bounds, 0);
  71065. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71066. return tree;
  71067. }
  71068. END_JUCE_NAMESPACE
  71069. /*** End of inlined file: juce_DrawableText.cpp ***/
  71070. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71071. BEGIN_JUCE_NAMESPACE
  71072. class SVGState
  71073. {
  71074. public:
  71075. SVGState (const XmlElement* const topLevel)
  71076. : topLevelXml (topLevel),
  71077. elementX (0), elementY (0),
  71078. width (512), height (512),
  71079. viewBoxW (0), viewBoxH (0)
  71080. {
  71081. }
  71082. ~SVGState()
  71083. {
  71084. }
  71085. Drawable* parseSVGElement (const XmlElement& xml)
  71086. {
  71087. if (! xml.hasTagName ("svg"))
  71088. return 0;
  71089. DrawableComposite* const drawable = new DrawableComposite();
  71090. drawable->setName (xml.getStringAttribute ("id"));
  71091. SVGState newState (*this);
  71092. if (xml.hasAttribute ("transform"))
  71093. newState.addTransform (xml);
  71094. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71095. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71096. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71097. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71098. if (xml.hasAttribute ("viewBox"))
  71099. {
  71100. const String viewParams (xml.getStringAttribute ("viewBox"));
  71101. int i = 0;
  71102. float vx, vy, vw, vh;
  71103. if (parseCoords (viewParams, vx, vy, i, true)
  71104. && parseCoords (viewParams, vw, vh, i, true)
  71105. && vw > 0
  71106. && vh > 0)
  71107. {
  71108. newState.viewBoxW = vw;
  71109. newState.viewBoxH = vh;
  71110. int placementFlags = 0;
  71111. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71112. if (aspect.containsIgnoreCase ("none"))
  71113. {
  71114. placementFlags = RectanglePlacement::stretchToFit;
  71115. }
  71116. else
  71117. {
  71118. if (aspect.containsIgnoreCase ("slice"))
  71119. placementFlags |= RectanglePlacement::fillDestination;
  71120. if (aspect.containsIgnoreCase ("xMin"))
  71121. placementFlags |= RectanglePlacement::xLeft;
  71122. else if (aspect.containsIgnoreCase ("xMax"))
  71123. placementFlags |= RectanglePlacement::xRight;
  71124. else
  71125. placementFlags |= RectanglePlacement::xMid;
  71126. if (aspect.containsIgnoreCase ("yMin"))
  71127. placementFlags |= RectanglePlacement::yTop;
  71128. else if (aspect.containsIgnoreCase ("yMax"))
  71129. placementFlags |= RectanglePlacement::yBottom;
  71130. else
  71131. placementFlags |= RectanglePlacement::yMid;
  71132. }
  71133. const RectanglePlacement placement (placementFlags);
  71134. newState.transform
  71135. = placement.getTransformToFit (vx, vy, vw, vh,
  71136. 0.0f, 0.0f, newState.width, newState.height)
  71137. .followedBy (newState.transform);
  71138. }
  71139. }
  71140. else
  71141. {
  71142. if (viewBoxW == 0)
  71143. newState.viewBoxW = newState.width;
  71144. if (viewBoxH == 0)
  71145. newState.viewBoxH = newState.height;
  71146. }
  71147. newState.parseSubElements (xml, drawable);
  71148. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71149. return drawable;
  71150. }
  71151. private:
  71152. const XmlElement* const topLevelXml;
  71153. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71154. AffineTransform transform;
  71155. String cssStyleText;
  71156. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71157. {
  71158. forEachXmlChildElement (xml, e)
  71159. {
  71160. Drawable* d = 0;
  71161. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71162. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71163. else if (e->hasTagName ("path")) d = parsePath (*e);
  71164. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71165. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71166. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71167. else if (e->hasTagName ("line")) d = parseLine (*e);
  71168. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71169. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71170. else if (e->hasTagName ("text")) d = parseText (*e);
  71171. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71172. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71173. parentDrawable->insertDrawable (d);
  71174. }
  71175. }
  71176. DrawableComposite* parseSwitch (const XmlElement& xml)
  71177. {
  71178. const XmlElement* const group = xml.getChildByName ("g");
  71179. if (group != 0)
  71180. return parseGroupElement (*group);
  71181. return 0;
  71182. }
  71183. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71184. {
  71185. DrawableComposite* const drawable = new DrawableComposite();
  71186. drawable->setName (xml.getStringAttribute ("id"));
  71187. if (xml.hasAttribute ("transform"))
  71188. {
  71189. SVGState newState (*this);
  71190. newState.addTransform (xml);
  71191. newState.parseSubElements (xml, drawable);
  71192. }
  71193. else
  71194. {
  71195. parseSubElements (xml, drawable);
  71196. }
  71197. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71198. return drawable;
  71199. }
  71200. Drawable* parsePath (const XmlElement& xml) const
  71201. {
  71202. const String d (xml.getStringAttribute ("d").trimStart());
  71203. Path path;
  71204. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71205. path.setUsingNonZeroWinding (false);
  71206. int index = 0;
  71207. float lastX = 0, lastY = 0;
  71208. float lastX2 = 0, lastY2 = 0;
  71209. juce_wchar lastCommandChar = 0;
  71210. bool isRelative = true;
  71211. bool carryOn = true;
  71212. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71213. while (d[index] != 0)
  71214. {
  71215. float x, y, x2, y2, x3, y3;
  71216. if (validCommandChars.containsChar (d[index]))
  71217. {
  71218. lastCommandChar = d [index++];
  71219. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71220. }
  71221. switch (lastCommandChar)
  71222. {
  71223. case 'M':
  71224. case 'm':
  71225. case 'L':
  71226. case 'l':
  71227. if (parseCoords (d, x, y, index, false))
  71228. {
  71229. if (isRelative)
  71230. {
  71231. x += lastX;
  71232. y += lastY;
  71233. }
  71234. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71235. {
  71236. path.startNewSubPath (x, y);
  71237. lastCommandChar = 'l';
  71238. }
  71239. else
  71240. path.lineTo (x, y);
  71241. lastX2 = lastX;
  71242. lastY2 = lastY;
  71243. lastX = x;
  71244. lastY = y;
  71245. }
  71246. else
  71247. {
  71248. ++index;
  71249. }
  71250. break;
  71251. case 'H':
  71252. case 'h':
  71253. if (parseCoord (d, x, index, false, true))
  71254. {
  71255. if (isRelative)
  71256. x += lastX;
  71257. path.lineTo (x, lastY);
  71258. lastX2 = lastX;
  71259. lastX = x;
  71260. }
  71261. else
  71262. {
  71263. ++index;
  71264. }
  71265. break;
  71266. case 'V':
  71267. case 'v':
  71268. if (parseCoord (d, y, index, false, false))
  71269. {
  71270. if (isRelative)
  71271. y += lastY;
  71272. path.lineTo (lastX, y);
  71273. lastY2 = lastY;
  71274. lastY = y;
  71275. }
  71276. else
  71277. {
  71278. ++index;
  71279. }
  71280. break;
  71281. case 'C':
  71282. case 'c':
  71283. if (parseCoords (d, x, y, index, false)
  71284. && parseCoords (d, x2, y2, index, false)
  71285. && parseCoords (d, x3, y3, index, false))
  71286. {
  71287. if (isRelative)
  71288. {
  71289. x += lastX;
  71290. y += lastY;
  71291. x2 += lastX;
  71292. y2 += lastY;
  71293. x3 += lastX;
  71294. y3 += lastY;
  71295. }
  71296. path.cubicTo (x, y, x2, y2, x3, y3);
  71297. lastX2 = x2;
  71298. lastY2 = y2;
  71299. lastX = x3;
  71300. lastY = y3;
  71301. }
  71302. else
  71303. {
  71304. ++index;
  71305. }
  71306. break;
  71307. case 'S':
  71308. case 's':
  71309. if (parseCoords (d, x, y, index, false)
  71310. && parseCoords (d, x3, y3, index, false))
  71311. {
  71312. if (isRelative)
  71313. {
  71314. x += lastX;
  71315. y += lastY;
  71316. x3 += lastX;
  71317. y3 += lastY;
  71318. }
  71319. x2 = lastX + (lastX - lastX2);
  71320. y2 = lastY + (lastY - lastY2);
  71321. path.cubicTo (x2, y2, x, y, x3, y3);
  71322. lastX2 = x;
  71323. lastY2 = y;
  71324. lastX = x3;
  71325. lastY = y3;
  71326. }
  71327. else
  71328. {
  71329. ++index;
  71330. }
  71331. break;
  71332. case 'Q':
  71333. case 'q':
  71334. if (parseCoords (d, x, y, index, false)
  71335. && parseCoords (d, x2, y2, index, false))
  71336. {
  71337. if (isRelative)
  71338. {
  71339. x += lastX;
  71340. y += lastY;
  71341. x2 += lastX;
  71342. y2 += lastY;
  71343. }
  71344. path.quadraticTo (x, y, x2, y2);
  71345. lastX2 = x;
  71346. lastY2 = y;
  71347. lastX = x2;
  71348. lastY = y2;
  71349. }
  71350. else
  71351. {
  71352. ++index;
  71353. }
  71354. break;
  71355. case 'T':
  71356. case 't':
  71357. if (parseCoords (d, x, y, index, false))
  71358. {
  71359. if (isRelative)
  71360. {
  71361. x += lastX;
  71362. y += lastY;
  71363. }
  71364. x2 = lastX + (lastX - lastX2);
  71365. y2 = lastY + (lastY - lastY2);
  71366. path.quadraticTo (x2, y2, x, y);
  71367. lastX2 = x2;
  71368. lastY2 = y2;
  71369. lastX = x;
  71370. lastY = y;
  71371. }
  71372. else
  71373. {
  71374. ++index;
  71375. }
  71376. break;
  71377. case 'A':
  71378. case 'a':
  71379. if (parseCoords (d, x, y, index, false))
  71380. {
  71381. String num;
  71382. if (parseNextNumber (d, num, index, false))
  71383. {
  71384. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71385. if (parseNextNumber (d, num, index, false))
  71386. {
  71387. const bool largeArc = num.getIntValue() != 0;
  71388. if (parseNextNumber (d, num, index, false))
  71389. {
  71390. const bool sweep = num.getIntValue() != 0;
  71391. if (parseCoords (d, x2, y2, index, false))
  71392. {
  71393. if (isRelative)
  71394. {
  71395. x2 += lastX;
  71396. y2 += lastY;
  71397. }
  71398. if (lastX != x2 || lastY != y2)
  71399. {
  71400. double centreX, centreY, startAngle, deltaAngle;
  71401. double rx = x, ry = y;
  71402. endpointToCentreParameters (lastX, lastY, x2, y2,
  71403. angle, largeArc, sweep,
  71404. rx, ry, centreX, centreY,
  71405. startAngle, deltaAngle);
  71406. path.addCentredArc ((float) centreX, (float) centreY,
  71407. (float) rx, (float) ry,
  71408. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71409. false);
  71410. path.lineTo (x2, y2);
  71411. }
  71412. lastX2 = lastX;
  71413. lastY2 = lastY;
  71414. lastX = x2;
  71415. lastY = y2;
  71416. }
  71417. }
  71418. }
  71419. }
  71420. }
  71421. else
  71422. {
  71423. ++index;
  71424. }
  71425. break;
  71426. case 'Z':
  71427. case 'z':
  71428. path.closeSubPath();
  71429. while (CharacterFunctions::isWhitespace (d [index]))
  71430. ++index;
  71431. break;
  71432. default:
  71433. carryOn = false;
  71434. break;
  71435. }
  71436. if (! carryOn)
  71437. break;
  71438. }
  71439. return parseShape (xml, path);
  71440. }
  71441. Drawable* parseRect (const XmlElement& xml) const
  71442. {
  71443. Path rect;
  71444. const bool hasRX = xml.hasAttribute ("rx");
  71445. const bool hasRY = xml.hasAttribute ("ry");
  71446. if (hasRX || hasRY)
  71447. {
  71448. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71449. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71450. if (! hasRX)
  71451. rx = ry;
  71452. else if (! hasRY)
  71453. ry = rx;
  71454. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71455. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71456. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71457. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71458. rx, ry);
  71459. }
  71460. else
  71461. {
  71462. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71463. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71464. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71465. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71466. }
  71467. return parseShape (xml, rect);
  71468. }
  71469. Drawable* parseCircle (const XmlElement& xml) const
  71470. {
  71471. Path circle;
  71472. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71473. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71474. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71475. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71476. return parseShape (xml, circle);
  71477. }
  71478. Drawable* parseEllipse (const XmlElement& xml) const
  71479. {
  71480. Path ellipse;
  71481. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71482. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71483. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71484. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71485. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71486. return parseShape (xml, ellipse);
  71487. }
  71488. Drawable* parseLine (const XmlElement& xml) const
  71489. {
  71490. Path line;
  71491. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71492. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71493. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71494. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71495. line.startNewSubPath (x1, y1);
  71496. line.lineTo (x2, y2);
  71497. return parseShape (xml, line);
  71498. }
  71499. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71500. {
  71501. const String points (xml.getStringAttribute ("points"));
  71502. Path path;
  71503. int index = 0;
  71504. float x, y;
  71505. if (parseCoords (points, x, y, index, true))
  71506. {
  71507. float firstX = x;
  71508. float firstY = y;
  71509. float lastX = 0, lastY = 0;
  71510. path.startNewSubPath (x, y);
  71511. while (parseCoords (points, x, y, index, true))
  71512. {
  71513. lastX = x;
  71514. lastY = y;
  71515. path.lineTo (x, y);
  71516. }
  71517. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71518. path.closeSubPath();
  71519. }
  71520. return parseShape (xml, path);
  71521. }
  71522. Drawable* parseShape (const XmlElement& xml, Path& path,
  71523. const bool shouldParseTransform = true) const
  71524. {
  71525. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71526. {
  71527. SVGState newState (*this);
  71528. newState.addTransform (xml);
  71529. return newState.parseShape (xml, path, false);
  71530. }
  71531. DrawablePath* dp = new DrawablePath();
  71532. dp->setName (xml.getStringAttribute ("id"));
  71533. dp->setFill (Colours::transparentBlack);
  71534. path.applyTransform (transform);
  71535. dp->setPath (path);
  71536. Path::Iterator iter (path);
  71537. bool containsClosedSubPath = false;
  71538. while (iter.next())
  71539. {
  71540. if (iter.elementType == Path::Iterator::closePath)
  71541. {
  71542. containsClosedSubPath = true;
  71543. break;
  71544. }
  71545. }
  71546. dp->setFill (getPathFillType (path,
  71547. getStyleAttribute (&xml, "fill"),
  71548. getStyleAttribute (&xml, "fill-opacity"),
  71549. getStyleAttribute (&xml, "opacity"),
  71550. containsClosedSubPath ? Colours::black
  71551. : Colours::transparentBlack));
  71552. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71553. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71554. {
  71555. dp->setStrokeFill (getPathFillType (path, strokeType,
  71556. getStyleAttribute (&xml, "stroke-opacity"),
  71557. getStyleAttribute (&xml, "opacity"),
  71558. Colours::transparentBlack));
  71559. dp->setStrokeType (getStrokeFor (&xml));
  71560. }
  71561. return dp;
  71562. }
  71563. const XmlElement* findLinkedElement (const XmlElement* e) const
  71564. {
  71565. const String id (e->getStringAttribute ("xlink:href"));
  71566. if (! id.startsWithChar ('#'))
  71567. return 0;
  71568. return findElementForId (topLevelXml, id.substring (1));
  71569. }
  71570. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71571. {
  71572. if (fillXml == 0)
  71573. return;
  71574. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71575. {
  71576. int index = 0;
  71577. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71578. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71579. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71580. double offset = e->getDoubleAttribute ("offset");
  71581. if (e->getStringAttribute ("offset").containsChar ('%'))
  71582. offset *= 0.01;
  71583. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71584. }
  71585. }
  71586. const FillType getPathFillType (const Path& path,
  71587. const String& fill,
  71588. const String& fillOpacity,
  71589. const String& overallOpacity,
  71590. const Colour& defaultColour) const
  71591. {
  71592. float opacity = 1.0f;
  71593. if (overallOpacity.isNotEmpty())
  71594. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71595. if (fillOpacity.isNotEmpty())
  71596. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71597. if (fill.startsWithIgnoreCase ("url"))
  71598. {
  71599. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71600. .upToLastOccurrenceOf (")", false, false).trim());
  71601. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71602. if (fillXml != 0
  71603. && (fillXml->hasTagName ("linearGradient")
  71604. || fillXml->hasTagName ("radialGradient")))
  71605. {
  71606. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71607. ColourGradient gradient;
  71608. addGradientStopsIn (gradient, inheritedFrom);
  71609. addGradientStopsIn (gradient, fillXml);
  71610. if (gradient.getNumColours() > 0)
  71611. {
  71612. gradient.addColour (0.0, gradient.getColour (0));
  71613. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71614. }
  71615. else
  71616. {
  71617. gradient.addColour (0.0, Colours::black);
  71618. gradient.addColour (1.0, Colours::black);
  71619. }
  71620. if (overallOpacity.isNotEmpty())
  71621. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71622. jassert (gradient.getNumColours() > 0);
  71623. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71624. float gradientWidth = viewBoxW;
  71625. float gradientHeight = viewBoxH;
  71626. float dx = 0.0f;
  71627. float dy = 0.0f;
  71628. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71629. if (! userSpace)
  71630. {
  71631. const Rectangle<float> bounds (path.getBounds());
  71632. dx = bounds.getX();
  71633. dy = bounds.getY();
  71634. gradientWidth = bounds.getWidth();
  71635. gradientHeight = bounds.getHeight();
  71636. }
  71637. if (gradient.isRadial)
  71638. {
  71639. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71640. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71641. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71642. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71643. //xxx (the fx, fy focal point isn't handled properly here..)
  71644. }
  71645. else
  71646. {
  71647. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71648. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71649. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71650. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71651. if (gradient.point1 == gradient.point2)
  71652. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71653. }
  71654. FillType type (gradient);
  71655. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71656. .followedBy (transform);
  71657. return type;
  71658. }
  71659. }
  71660. if (fill.equalsIgnoreCase ("none"))
  71661. return Colours::transparentBlack;
  71662. int i = 0;
  71663. const Colour colour (parseColour (fill, i, defaultColour));
  71664. return colour.withMultipliedAlpha (opacity);
  71665. }
  71666. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71667. {
  71668. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71669. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71670. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71671. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71672. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71673. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71674. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71675. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71676. if (join.equalsIgnoreCase ("round"))
  71677. joinStyle = PathStrokeType::curved;
  71678. else if (join.equalsIgnoreCase ("bevel"))
  71679. joinStyle = PathStrokeType::beveled;
  71680. if (cap.equalsIgnoreCase ("round"))
  71681. capStyle = PathStrokeType::rounded;
  71682. else if (cap.equalsIgnoreCase ("square"))
  71683. capStyle = PathStrokeType::square;
  71684. float ox = 0.0f, oy = 0.0f;
  71685. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71686. transform.transformPoints (ox, oy, x, y);
  71687. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71688. joinStyle, capStyle);
  71689. }
  71690. Drawable* parseText (const XmlElement& xml)
  71691. {
  71692. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71693. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71694. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71695. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71696. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71697. //xxx not done text yet!
  71698. forEachXmlChildElement (xml, e)
  71699. {
  71700. if (e->isTextElement())
  71701. {
  71702. const String text (e->getText());
  71703. Path path;
  71704. Drawable* s = parseShape (*e, path);
  71705. delete s; // xxx not finished!
  71706. }
  71707. else if (e->hasTagName ("tspan"))
  71708. {
  71709. Drawable* s = parseText (*e);
  71710. delete s; // xxx not finished!
  71711. }
  71712. }
  71713. return 0;
  71714. }
  71715. void addTransform (const XmlElement& xml)
  71716. {
  71717. transform = parseTransform (xml.getStringAttribute ("transform"))
  71718. .followedBy (transform);
  71719. }
  71720. bool parseCoord (const String& s, float& value, int& index,
  71721. const bool allowUnits, const bool isX) const
  71722. {
  71723. String number;
  71724. if (! parseNextNumber (s, number, index, allowUnits))
  71725. {
  71726. value = 0;
  71727. return false;
  71728. }
  71729. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71730. return true;
  71731. }
  71732. bool parseCoords (const String& s, float& x, float& y,
  71733. int& index, const bool allowUnits) const
  71734. {
  71735. return parseCoord (s, x, index, allowUnits, true)
  71736. && parseCoord (s, y, index, allowUnits, false);
  71737. }
  71738. float getCoordLength (const String& s, const float sizeForProportions) const
  71739. {
  71740. float n = s.getFloatValue();
  71741. const int len = s.length();
  71742. if (len > 2)
  71743. {
  71744. const float dpi = 96.0f;
  71745. const juce_wchar n1 = s [len - 2];
  71746. const juce_wchar n2 = s [len - 1];
  71747. if (n1 == 'i' && n2 == 'n')
  71748. n *= dpi;
  71749. else if (n1 == 'm' && n2 == 'm')
  71750. n *= dpi / 25.4f;
  71751. else if (n1 == 'c' && n2 == 'm')
  71752. n *= dpi / 2.54f;
  71753. else if (n1 == 'p' && n2 == 'c')
  71754. n *= 15.0f;
  71755. else if (n2 == '%')
  71756. n *= 0.01f * sizeForProportions;
  71757. }
  71758. return n;
  71759. }
  71760. void getCoordList (Array <float>& coords, const String& list,
  71761. const bool allowUnits, const bool isX) const
  71762. {
  71763. int index = 0;
  71764. float value;
  71765. while (parseCoord (list, value, index, allowUnits, isX))
  71766. coords.add (value);
  71767. }
  71768. void parseCSSStyle (const XmlElement& xml)
  71769. {
  71770. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71771. }
  71772. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71773. const String& defaultValue = String::empty) const
  71774. {
  71775. if (xml->hasAttribute (attributeName))
  71776. return xml->getStringAttribute (attributeName, defaultValue);
  71777. const String styleAtt (xml->getStringAttribute ("style"));
  71778. if (styleAtt.isNotEmpty())
  71779. {
  71780. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71781. if (value.isNotEmpty())
  71782. return value;
  71783. }
  71784. else if (xml->hasAttribute ("class"))
  71785. {
  71786. const String className ("." + xml->getStringAttribute ("class"));
  71787. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71788. if (index < 0)
  71789. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71790. if (index >= 0)
  71791. {
  71792. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71793. if (openBracket > index)
  71794. {
  71795. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71796. if (closeBracket > openBracket)
  71797. {
  71798. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71799. if (value.isNotEmpty())
  71800. return value;
  71801. }
  71802. }
  71803. }
  71804. }
  71805. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71806. if (xml != 0)
  71807. return getStyleAttribute (xml, attributeName, defaultValue);
  71808. return defaultValue;
  71809. }
  71810. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71811. {
  71812. if (xml->hasAttribute (attributeName))
  71813. return xml->getStringAttribute (attributeName);
  71814. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71815. if (xml != 0)
  71816. return getInheritedAttribute (xml, attributeName);
  71817. return String::empty;
  71818. }
  71819. static bool isIdentifierChar (const juce_wchar c)
  71820. {
  71821. return CharacterFunctions::isLetter (c) || c == '-';
  71822. }
  71823. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71824. {
  71825. int i = 0;
  71826. for (;;)
  71827. {
  71828. i = list.indexOf (i, attributeName);
  71829. if (i < 0)
  71830. break;
  71831. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71832. && ! isIdentifierChar (list [i + attributeName.length()]))
  71833. {
  71834. i = list.indexOfChar (i, ':');
  71835. if (i < 0)
  71836. break;
  71837. int end = list.indexOfChar (i, ';');
  71838. if (end < 0)
  71839. end = 0x7ffff;
  71840. return list.substring (i + 1, end).trim();
  71841. }
  71842. ++i;
  71843. }
  71844. return defaultValue;
  71845. }
  71846. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71847. {
  71848. const juce_wchar* const s = source;
  71849. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71850. ++index;
  71851. int start = index;
  71852. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71853. ++index;
  71854. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71855. ++index;
  71856. if ((s[index] == 'e' || s[index] == 'E')
  71857. && (CharacterFunctions::isDigit (s[index + 1])
  71858. || s[index + 1] == '-'
  71859. || s[index + 1] == '+'))
  71860. {
  71861. index += 2;
  71862. while (CharacterFunctions::isDigit (s[index]))
  71863. ++index;
  71864. }
  71865. if (allowUnits)
  71866. {
  71867. while (CharacterFunctions::isLetter (s[index]))
  71868. ++index;
  71869. }
  71870. if (index == start)
  71871. return false;
  71872. value = String (s + start, index - start);
  71873. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71874. ++index;
  71875. return true;
  71876. }
  71877. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71878. {
  71879. if (s [index] == '#')
  71880. {
  71881. uint32 hex [6];
  71882. zeromem (hex, sizeof (hex));
  71883. int numChars = 0;
  71884. for (int i = 6; --i >= 0;)
  71885. {
  71886. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71887. if (hexValue >= 0)
  71888. hex [numChars++] = hexValue;
  71889. else
  71890. break;
  71891. }
  71892. if (numChars <= 3)
  71893. return Colour ((uint8) (hex [0] * 0x11),
  71894. (uint8) (hex [1] * 0x11),
  71895. (uint8) (hex [2] * 0x11));
  71896. else
  71897. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71898. (uint8) ((hex [2] << 4) + hex [3]),
  71899. (uint8) ((hex [4] << 4) + hex [5]));
  71900. }
  71901. else if (s [index] == 'r'
  71902. && s [index + 1] == 'g'
  71903. && s [index + 2] == 'b')
  71904. {
  71905. const int openBracket = s.indexOfChar (index, '(');
  71906. const int closeBracket = s.indexOfChar (openBracket, ')');
  71907. if (openBracket >= 3 && closeBracket > openBracket)
  71908. {
  71909. index = closeBracket;
  71910. StringArray tokens;
  71911. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71912. tokens.trim();
  71913. tokens.removeEmptyStrings();
  71914. if (tokens[0].containsChar ('%'))
  71915. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71916. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71917. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71918. else
  71919. return Colour ((uint8) tokens[0].getIntValue(),
  71920. (uint8) tokens[1].getIntValue(),
  71921. (uint8) tokens[2].getIntValue());
  71922. }
  71923. }
  71924. return Colours::findColourForName (s, defaultColour);
  71925. }
  71926. static const AffineTransform parseTransform (String t)
  71927. {
  71928. AffineTransform result;
  71929. while (t.isNotEmpty())
  71930. {
  71931. StringArray tokens;
  71932. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71933. .upToFirstOccurrenceOf (")", false, false),
  71934. ", ", String::empty);
  71935. tokens.removeEmptyStrings (true);
  71936. float numbers [6];
  71937. for (int i = 0; i < 6; ++i)
  71938. numbers[i] = tokens[i].getFloatValue();
  71939. AffineTransform trans;
  71940. if (t.startsWithIgnoreCase ("matrix"))
  71941. {
  71942. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71943. numbers[1], numbers[3], numbers[5]);
  71944. }
  71945. else if (t.startsWithIgnoreCase ("translate"))
  71946. {
  71947. jassert (tokens.size() == 2);
  71948. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71949. }
  71950. else if (t.startsWithIgnoreCase ("scale"))
  71951. {
  71952. if (tokens.size() == 1)
  71953. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71954. else
  71955. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71956. }
  71957. else if (t.startsWithIgnoreCase ("rotate"))
  71958. {
  71959. if (tokens.size() != 3)
  71960. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71961. else
  71962. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71963. numbers[1], numbers[2]);
  71964. }
  71965. else if (t.startsWithIgnoreCase ("skewX"))
  71966. {
  71967. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71968. 0.0f, 1.0f, 0.0f);
  71969. }
  71970. else if (t.startsWithIgnoreCase ("skewY"))
  71971. {
  71972. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71973. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71974. }
  71975. result = trans.followedBy (result);
  71976. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71977. }
  71978. return result;
  71979. }
  71980. static void endpointToCentreParameters (const double x1, const double y1,
  71981. const double x2, const double y2,
  71982. const double angle,
  71983. const bool largeArc, const bool sweep,
  71984. double& rx, double& ry,
  71985. double& centreX, double& centreY,
  71986. double& startAngle, double& deltaAngle)
  71987. {
  71988. const double midX = (x1 - x2) * 0.5;
  71989. const double midY = (y1 - y2) * 0.5;
  71990. const double cosAngle = cos (angle);
  71991. const double sinAngle = sin (angle);
  71992. const double xp = cosAngle * midX + sinAngle * midY;
  71993. const double yp = cosAngle * midY - sinAngle * midX;
  71994. const double xp2 = xp * xp;
  71995. const double yp2 = yp * yp;
  71996. double rx2 = rx * rx;
  71997. double ry2 = ry * ry;
  71998. const double s = (xp2 / rx2) + (yp2 / ry2);
  71999. double c;
  72000. if (s <= 1.0)
  72001. {
  72002. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72003. / (( rx2 * yp2) + (ry2 * xp2))));
  72004. if (largeArc == sweep)
  72005. c = -c;
  72006. }
  72007. else
  72008. {
  72009. const double s2 = std::sqrt (s);
  72010. rx *= s2;
  72011. ry *= s2;
  72012. rx2 = rx * rx;
  72013. ry2 = ry * ry;
  72014. c = 0;
  72015. }
  72016. const double cpx = ((rx * yp) / ry) * c;
  72017. const double cpy = ((-ry * xp) / rx) * c;
  72018. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72019. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72020. const double ux = (xp - cpx) / rx;
  72021. const double uy = (yp - cpy) / ry;
  72022. const double vx = (-xp - cpx) / rx;
  72023. const double vy = (-yp - cpy) / ry;
  72024. const double length = juce_hypot (ux, uy);
  72025. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72026. if (uy < 0)
  72027. startAngle = -startAngle;
  72028. startAngle += double_Pi * 0.5;
  72029. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72030. / (length * juce_hypot (vx, vy))));
  72031. if ((ux * vy) - (uy * vx) < 0)
  72032. deltaAngle = -deltaAngle;
  72033. if (sweep)
  72034. {
  72035. if (deltaAngle < 0)
  72036. deltaAngle += double_Pi * 2.0;
  72037. }
  72038. else
  72039. {
  72040. if (deltaAngle > 0)
  72041. deltaAngle -= double_Pi * 2.0;
  72042. }
  72043. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72044. }
  72045. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72046. {
  72047. forEachXmlChildElement (*parent, e)
  72048. {
  72049. if (e->compareAttribute ("id", id))
  72050. return e;
  72051. const XmlElement* const found = findElementForId (e, id);
  72052. if (found != 0)
  72053. return found;
  72054. }
  72055. return 0;
  72056. }
  72057. SVGState& operator= (const SVGState&);
  72058. };
  72059. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72060. {
  72061. SVGState state (&svgDocument);
  72062. return state.parseSVGElement (svgDocument);
  72063. }
  72064. END_JUCE_NAMESPACE
  72065. /*** End of inlined file: juce_SVGParser.cpp ***/
  72066. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72067. BEGIN_JUCE_NAMESPACE
  72068. #if JUCE_MSVC && JUCE_DEBUG
  72069. #pragma optimize ("t", on)
  72070. #endif
  72071. DropShadowEffect::DropShadowEffect()
  72072. : offsetX (0),
  72073. offsetY (0),
  72074. radius (4),
  72075. opacity (0.6f)
  72076. {
  72077. }
  72078. DropShadowEffect::~DropShadowEffect()
  72079. {
  72080. }
  72081. void DropShadowEffect::setShadowProperties (const float newRadius,
  72082. const float newOpacity,
  72083. const int newShadowOffsetX,
  72084. const int newShadowOffsetY)
  72085. {
  72086. radius = jmax (1.1f, newRadius);
  72087. offsetX = newShadowOffsetX;
  72088. offsetY = newShadowOffsetY;
  72089. opacity = newOpacity;
  72090. }
  72091. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72092. {
  72093. const int w = image.getWidth();
  72094. const int h = image.getHeight();
  72095. Image shadowImage (Image::SingleChannel, w, h, false);
  72096. const Image::BitmapData srcData (image, false);
  72097. const Image::BitmapData destData (shadowImage, true);
  72098. const int filter = roundToInt (63.0f / radius);
  72099. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72100. for (int x = w; --x >= 0;)
  72101. {
  72102. int shadowAlpha = 0;
  72103. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72104. uint8* shadowPix = destData.data + x;
  72105. for (int y = h; --y >= 0;)
  72106. {
  72107. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72108. *shadowPix = (uint8) shadowAlpha;
  72109. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72110. shadowPix += destData.lineStride;
  72111. }
  72112. }
  72113. for (int y = h; --y >= 0;)
  72114. {
  72115. int shadowAlpha = 0;
  72116. uint8* shadowPix = destData.getLinePointer (y);
  72117. for (int x = w; --x >= 0;)
  72118. {
  72119. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72120. *shadowPix++ = (uint8) shadowAlpha;
  72121. }
  72122. }
  72123. g.setColour (Colours::black.withAlpha (opacity));
  72124. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72125. g.setOpacity (1.0f);
  72126. g.drawImageAt (image, 0, 0);
  72127. }
  72128. #if JUCE_MSVC && JUCE_DEBUG
  72129. #pragma optimize ("", on) // resets optimisations to the project defaults
  72130. #endif
  72131. END_JUCE_NAMESPACE
  72132. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72133. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72134. BEGIN_JUCE_NAMESPACE
  72135. GlowEffect::GlowEffect()
  72136. : radius (2.0f),
  72137. colour (Colours::white)
  72138. {
  72139. }
  72140. GlowEffect::~GlowEffect()
  72141. {
  72142. }
  72143. void GlowEffect::setGlowProperties (const float newRadius,
  72144. const Colour& newColour)
  72145. {
  72146. radius = newRadius;
  72147. colour = newColour;
  72148. }
  72149. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72150. {
  72151. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72152. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72153. blurKernel.createGaussianBlur (radius);
  72154. blurKernel.rescaleAllValues (radius);
  72155. blurKernel.applyToImage (temp, image, image.getBounds());
  72156. g.setColour (colour);
  72157. g.drawImageAt (temp, 0, 0, true);
  72158. g.setOpacity (1.0f);
  72159. g.drawImageAt (image, 0, 0, false);
  72160. }
  72161. END_JUCE_NAMESPACE
  72162. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72163. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72164. BEGIN_JUCE_NAMESPACE
  72165. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72166. : opacity (opacity_)
  72167. {
  72168. }
  72169. ReduceOpacityEffect::~ReduceOpacityEffect()
  72170. {
  72171. }
  72172. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72173. {
  72174. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72175. }
  72176. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72177. {
  72178. g.setOpacity (opacity);
  72179. g.drawImageAt (image, 0, 0);
  72180. }
  72181. END_JUCE_NAMESPACE
  72182. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72183. /*** Start of inlined file: juce_Font.cpp ***/
  72184. BEGIN_JUCE_NAMESPACE
  72185. namespace FontValues
  72186. {
  72187. static float limitFontHeight (const float height) throw()
  72188. {
  72189. return jlimit (0.1f, 10000.0f, height);
  72190. }
  72191. static const float defaultFontHeight = 14.0f;
  72192. static String fallbackFont;
  72193. }
  72194. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72195. const float kerning_, const float ascent_, const int styleFlags_,
  72196. Typeface* const typeface_) throw()
  72197. : typefaceName (typefaceName_),
  72198. height (height_),
  72199. horizontalScale (horizontalScale_),
  72200. kerning (kerning_),
  72201. ascent (ascent_),
  72202. styleFlags (styleFlags_),
  72203. typeface (typeface_)
  72204. {
  72205. }
  72206. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72207. : typefaceName (other.typefaceName),
  72208. height (other.height),
  72209. horizontalScale (other.horizontalScale),
  72210. kerning (other.kerning),
  72211. ascent (other.ascent),
  72212. styleFlags (other.styleFlags),
  72213. typeface (other.typeface)
  72214. {
  72215. }
  72216. Font::Font()
  72217. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72218. 1.0f, 0, 0, Font::plain, 0))
  72219. {
  72220. }
  72221. Font::Font (const float fontHeight, const int styleFlags_)
  72222. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72223. 1.0f, 0, 0, styleFlags_, 0))
  72224. {
  72225. }
  72226. Font::Font (const String& typefaceName_,
  72227. const float fontHeight,
  72228. const int styleFlags_)
  72229. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72230. 1.0f, 0, 0, styleFlags_, 0))
  72231. {
  72232. }
  72233. Font::Font (const Font& other) throw()
  72234. : font (other.font)
  72235. {
  72236. }
  72237. Font& Font::operator= (const Font& other) throw()
  72238. {
  72239. font = other.font;
  72240. return *this;
  72241. }
  72242. Font::~Font() throw()
  72243. {
  72244. }
  72245. Font::Font (const Typeface::Ptr& typeface)
  72246. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72247. 1.0f, 0, 0, Font::plain, typeface))
  72248. {
  72249. }
  72250. bool Font::operator== (const Font& other) const throw()
  72251. {
  72252. return font == other.font
  72253. || (font->height == other.font->height
  72254. && font->styleFlags == other.font->styleFlags
  72255. && font->horizontalScale == other.font->horizontalScale
  72256. && font->kerning == other.font->kerning
  72257. && font->typefaceName == other.font->typefaceName);
  72258. }
  72259. bool Font::operator!= (const Font& other) const throw()
  72260. {
  72261. return ! operator== (other);
  72262. }
  72263. void Font::dupeInternalIfShared()
  72264. {
  72265. if (font->getReferenceCount() > 1)
  72266. font = new SharedFontInternal (*font);
  72267. }
  72268. const String Font::getDefaultSansSerifFontName()
  72269. {
  72270. static const String name ("<Sans-Serif>");
  72271. return name;
  72272. }
  72273. const String Font::getDefaultSerifFontName()
  72274. {
  72275. static const String name ("<Serif>");
  72276. return name;
  72277. }
  72278. const String Font::getDefaultMonospacedFontName()
  72279. {
  72280. static const String name ("<Monospaced>");
  72281. return name;
  72282. }
  72283. void Font::setTypefaceName (const String& faceName)
  72284. {
  72285. if (faceName != font->typefaceName)
  72286. {
  72287. dupeInternalIfShared();
  72288. font->typefaceName = faceName;
  72289. font->typeface = 0;
  72290. font->ascent = 0;
  72291. }
  72292. }
  72293. const String Font::getFallbackFontName()
  72294. {
  72295. return FontValues::fallbackFont;
  72296. }
  72297. void Font::setFallbackFontName (const String& name)
  72298. {
  72299. FontValues::fallbackFont = name;
  72300. }
  72301. void Font::setHeight (float newHeight)
  72302. {
  72303. newHeight = FontValues::limitFontHeight (newHeight);
  72304. if (font->height != newHeight)
  72305. {
  72306. dupeInternalIfShared();
  72307. font->height = newHeight;
  72308. }
  72309. }
  72310. void Font::setHeightWithoutChangingWidth (float newHeight)
  72311. {
  72312. newHeight = FontValues::limitFontHeight (newHeight);
  72313. if (font->height != newHeight)
  72314. {
  72315. dupeInternalIfShared();
  72316. font->horizontalScale *= (font->height / newHeight);
  72317. font->height = newHeight;
  72318. }
  72319. }
  72320. void Font::setStyleFlags (const int newFlags)
  72321. {
  72322. if (font->styleFlags != newFlags)
  72323. {
  72324. dupeInternalIfShared();
  72325. font->styleFlags = newFlags;
  72326. font->typeface = 0;
  72327. font->ascent = 0;
  72328. }
  72329. }
  72330. void Font::setSizeAndStyle (float newHeight,
  72331. const int newStyleFlags,
  72332. const float newHorizontalScale,
  72333. const float newKerningAmount)
  72334. {
  72335. newHeight = FontValues::limitFontHeight (newHeight);
  72336. if (font->height != newHeight
  72337. || font->horizontalScale != newHorizontalScale
  72338. || font->kerning != newKerningAmount)
  72339. {
  72340. dupeInternalIfShared();
  72341. font->height = newHeight;
  72342. font->horizontalScale = newHorizontalScale;
  72343. font->kerning = newKerningAmount;
  72344. }
  72345. setStyleFlags (newStyleFlags);
  72346. }
  72347. void Font::setHorizontalScale (const float scaleFactor)
  72348. {
  72349. dupeInternalIfShared();
  72350. font->horizontalScale = scaleFactor;
  72351. }
  72352. void Font::setExtraKerningFactor (const float extraKerning)
  72353. {
  72354. dupeInternalIfShared();
  72355. font->kerning = extraKerning;
  72356. }
  72357. void Font::setBold (const bool shouldBeBold)
  72358. {
  72359. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72360. : (font->styleFlags & ~bold));
  72361. }
  72362. const Font Font::boldened() const
  72363. {
  72364. Font f (*this);
  72365. f.setBold (true);
  72366. return f;
  72367. }
  72368. bool Font::isBold() const throw()
  72369. {
  72370. return (font->styleFlags & bold) != 0;
  72371. }
  72372. void Font::setItalic (const bool shouldBeItalic)
  72373. {
  72374. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72375. : (font->styleFlags & ~italic));
  72376. }
  72377. const Font Font::italicised() const
  72378. {
  72379. Font f (*this);
  72380. f.setItalic (true);
  72381. return f;
  72382. }
  72383. bool Font::isItalic() const throw()
  72384. {
  72385. return (font->styleFlags & italic) != 0;
  72386. }
  72387. void Font::setUnderline (const bool shouldBeUnderlined)
  72388. {
  72389. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72390. : (font->styleFlags & ~underlined));
  72391. }
  72392. bool Font::isUnderlined() const throw()
  72393. {
  72394. return (font->styleFlags & underlined) != 0;
  72395. }
  72396. float Font::getAscent() const
  72397. {
  72398. if (font->ascent == 0)
  72399. font->ascent = getTypeface()->getAscent();
  72400. return font->height * font->ascent;
  72401. }
  72402. float Font::getDescent() const
  72403. {
  72404. return font->height - getAscent();
  72405. }
  72406. int Font::getStringWidth (const String& text) const
  72407. {
  72408. return roundToInt (getStringWidthFloat (text));
  72409. }
  72410. float Font::getStringWidthFloat (const String& text) const
  72411. {
  72412. float w = getTypeface()->getStringWidth (text);
  72413. if (font->kerning != 0)
  72414. w += font->kerning * text.length();
  72415. return w * font->height * font->horizontalScale;
  72416. }
  72417. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72418. {
  72419. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72420. const float scale = font->height * font->horizontalScale;
  72421. const int num = xOffsets.size();
  72422. if (num > 0)
  72423. {
  72424. float* const x = &(xOffsets.getReference(0));
  72425. if (font->kerning != 0)
  72426. {
  72427. for (int i = 0; i < num; ++i)
  72428. x[i] = (x[i] + i * font->kerning) * scale;
  72429. }
  72430. else
  72431. {
  72432. for (int i = 0; i < num; ++i)
  72433. x[i] *= scale;
  72434. }
  72435. }
  72436. }
  72437. void Font::findFonts (Array<Font>& destArray)
  72438. {
  72439. const StringArray names (findAllTypefaceNames());
  72440. for (int i = 0; i < names.size(); ++i)
  72441. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72442. }
  72443. const String Font::toString() const
  72444. {
  72445. String s (getTypefaceName());
  72446. if (s == getDefaultSansSerifFontName())
  72447. s = String::empty;
  72448. else
  72449. s += "; ";
  72450. s += String (getHeight(), 1);
  72451. if (isBold())
  72452. s += " bold";
  72453. if (isItalic())
  72454. s += " italic";
  72455. return s;
  72456. }
  72457. const Font Font::fromString (const String& fontDescription)
  72458. {
  72459. String name;
  72460. const int separator = fontDescription.indexOfChar (';');
  72461. if (separator > 0)
  72462. name = fontDescription.substring (0, separator).trim();
  72463. if (name.isEmpty())
  72464. name = getDefaultSansSerifFontName();
  72465. String sizeAndStyle (fontDescription.substring (separator + 1));
  72466. float height = sizeAndStyle.getFloatValue();
  72467. if (height <= 0)
  72468. height = 10.0f;
  72469. int flags = Font::plain;
  72470. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72471. flags |= Font::bold;
  72472. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72473. flags |= Font::italic;
  72474. return Font (name, height, flags);
  72475. }
  72476. class TypefaceCache : public DeletedAtShutdown
  72477. {
  72478. public:
  72479. TypefaceCache (int numToCache = 10)
  72480. : counter (1)
  72481. {
  72482. while (--numToCache >= 0)
  72483. faces.add (new CachedFace());
  72484. }
  72485. ~TypefaceCache()
  72486. {
  72487. clearSingletonInstance();
  72488. }
  72489. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72490. const Typeface::Ptr findTypefaceFor (const Font& font)
  72491. {
  72492. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72493. const String faceName (font.getTypefaceName());
  72494. int i;
  72495. for (i = faces.size(); --i >= 0;)
  72496. {
  72497. CachedFace* const face = faces.getUnchecked(i);
  72498. if (face->flags == flags
  72499. && face->typefaceName == faceName)
  72500. {
  72501. face->lastUsageCount = ++counter;
  72502. return face->typeFace;
  72503. }
  72504. }
  72505. int replaceIndex = 0;
  72506. int bestLastUsageCount = std::numeric_limits<int>::max();
  72507. for (i = faces.size(); --i >= 0;)
  72508. {
  72509. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72510. if (bestLastUsageCount > lu)
  72511. {
  72512. bestLastUsageCount = lu;
  72513. replaceIndex = i;
  72514. }
  72515. }
  72516. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72517. face->typefaceName = faceName;
  72518. face->flags = flags;
  72519. face->lastUsageCount = ++counter;
  72520. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72521. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72522. return face->typeFace;
  72523. }
  72524. juce_UseDebuggingNewOperator
  72525. private:
  72526. struct CachedFace
  72527. {
  72528. CachedFace() throw()
  72529. : lastUsageCount (0), flags (-1)
  72530. {
  72531. }
  72532. String typefaceName;
  72533. int lastUsageCount;
  72534. int flags;
  72535. Typeface::Ptr typeFace;
  72536. };
  72537. int counter;
  72538. OwnedArray <CachedFace> faces;
  72539. TypefaceCache (const TypefaceCache&);
  72540. TypefaceCache& operator= (const TypefaceCache&);
  72541. };
  72542. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72543. Typeface* Font::getTypeface() const
  72544. {
  72545. if (font->typeface == 0)
  72546. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72547. return font->typeface;
  72548. }
  72549. END_JUCE_NAMESPACE
  72550. /*** End of inlined file: juce_Font.cpp ***/
  72551. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72552. BEGIN_JUCE_NAMESPACE
  72553. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72554. const juce_wchar character_, const int glyph_)
  72555. : x (x_),
  72556. y (y_),
  72557. w (w_),
  72558. font (font_),
  72559. character (character_),
  72560. glyph (glyph_)
  72561. {
  72562. }
  72563. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72564. : x (other.x),
  72565. y (other.y),
  72566. w (other.w),
  72567. font (other.font),
  72568. character (other.character),
  72569. glyph (other.glyph)
  72570. {
  72571. }
  72572. void PositionedGlyph::draw (const Graphics& g) const
  72573. {
  72574. if (! isWhitespace())
  72575. {
  72576. g.getInternalContext()->setFont (font);
  72577. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72578. }
  72579. }
  72580. void PositionedGlyph::draw (const Graphics& g,
  72581. const AffineTransform& transform) const
  72582. {
  72583. if (! isWhitespace())
  72584. {
  72585. g.getInternalContext()->setFont (font);
  72586. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72587. .followedBy (transform));
  72588. }
  72589. }
  72590. void PositionedGlyph::createPath (Path& path) const
  72591. {
  72592. if (! isWhitespace())
  72593. {
  72594. Typeface* const t = font.getTypeface();
  72595. if (t != 0)
  72596. {
  72597. Path p;
  72598. t->getOutlineForGlyph (glyph, p);
  72599. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72600. .translated (x, y));
  72601. }
  72602. }
  72603. }
  72604. bool PositionedGlyph::hitTest (float px, float py) const
  72605. {
  72606. if (getBounds().contains (px, py) && ! isWhitespace())
  72607. {
  72608. Typeface* const t = font.getTypeface();
  72609. if (t != 0)
  72610. {
  72611. Path p;
  72612. t->getOutlineForGlyph (glyph, p);
  72613. AffineTransform::translation (-x, -y)
  72614. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72615. .transformPoint (px, py);
  72616. return p.contains (px, py);
  72617. }
  72618. }
  72619. return false;
  72620. }
  72621. void PositionedGlyph::moveBy (const float deltaX,
  72622. const float deltaY)
  72623. {
  72624. x += deltaX;
  72625. y += deltaY;
  72626. }
  72627. GlyphArrangement::GlyphArrangement()
  72628. {
  72629. glyphs.ensureStorageAllocated (128);
  72630. }
  72631. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72632. {
  72633. addGlyphArrangement (other);
  72634. }
  72635. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72636. {
  72637. if (this != &other)
  72638. {
  72639. clear();
  72640. addGlyphArrangement (other);
  72641. }
  72642. return *this;
  72643. }
  72644. GlyphArrangement::~GlyphArrangement()
  72645. {
  72646. }
  72647. void GlyphArrangement::clear()
  72648. {
  72649. glyphs.clear();
  72650. }
  72651. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72652. {
  72653. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72654. return *glyphs [index];
  72655. }
  72656. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72657. {
  72658. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72659. glyphs.addCopiesOf (other.glyphs);
  72660. }
  72661. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72662. {
  72663. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72664. }
  72665. void GlyphArrangement::addLineOfText (const Font& font,
  72666. const String& text,
  72667. const float xOffset,
  72668. const float yOffset)
  72669. {
  72670. addCurtailedLineOfText (font, text,
  72671. xOffset, yOffset,
  72672. 1.0e10f, false);
  72673. }
  72674. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72675. const String& text,
  72676. float xOffset,
  72677. const float yOffset,
  72678. const float maxWidthPixels,
  72679. const bool useEllipsis)
  72680. {
  72681. if (text.isNotEmpty())
  72682. {
  72683. Array <int> newGlyphs;
  72684. Array <float> xOffsets;
  72685. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72686. const int textLen = newGlyphs.size();
  72687. const juce_wchar* const unicodeText = text;
  72688. for (int i = 0; i < textLen; ++i)
  72689. {
  72690. const float thisX = xOffsets.getUnchecked (i);
  72691. const float nextX = xOffsets.getUnchecked (i + 1);
  72692. if (nextX > maxWidthPixels + 1.0f)
  72693. {
  72694. // curtail the string if it's too wide..
  72695. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72696. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72697. break;
  72698. }
  72699. else
  72700. {
  72701. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72702. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72703. }
  72704. }
  72705. }
  72706. }
  72707. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72708. const int startIndex, int endIndex)
  72709. {
  72710. int numDeleted = 0;
  72711. if (glyphs.size() > 0)
  72712. {
  72713. Array<int> dotGlyphs;
  72714. Array<float> dotXs;
  72715. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72716. const float dx = dotXs[1];
  72717. float xOffset = 0.0f, yOffset = 0.0f;
  72718. while (endIndex > startIndex)
  72719. {
  72720. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72721. xOffset = pg->x;
  72722. yOffset = pg->y;
  72723. glyphs.remove (endIndex);
  72724. ++numDeleted;
  72725. if (xOffset + dx * 3 <= maxXPos)
  72726. break;
  72727. }
  72728. for (int i = 3; --i >= 0;)
  72729. {
  72730. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72731. font, '.', dotGlyphs.getFirst()));
  72732. --numDeleted;
  72733. xOffset += dx;
  72734. if (xOffset > maxXPos)
  72735. break;
  72736. }
  72737. }
  72738. return numDeleted;
  72739. }
  72740. void GlyphArrangement::addJustifiedText (const Font& font,
  72741. const String& text,
  72742. float x, float y,
  72743. const float maxLineWidth,
  72744. const Justification& horizontalLayout)
  72745. {
  72746. int lineStartIndex = glyphs.size();
  72747. addLineOfText (font, text, x, y);
  72748. const float originalY = y;
  72749. while (lineStartIndex < glyphs.size())
  72750. {
  72751. int i = lineStartIndex;
  72752. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72753. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72754. ++i;
  72755. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72756. int lastWordBreakIndex = -1;
  72757. while (i < glyphs.size())
  72758. {
  72759. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72760. const juce_wchar c = pg->getCharacter();
  72761. if (c == '\r' || c == '\n')
  72762. {
  72763. ++i;
  72764. if (c == '\r' && i < glyphs.size()
  72765. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72766. ++i;
  72767. break;
  72768. }
  72769. else if (pg->isWhitespace())
  72770. {
  72771. lastWordBreakIndex = i + 1;
  72772. }
  72773. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72774. {
  72775. if (lastWordBreakIndex >= 0)
  72776. i = lastWordBreakIndex;
  72777. break;
  72778. }
  72779. ++i;
  72780. }
  72781. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72782. float currentLineEndX = currentLineStartX;
  72783. for (int j = i; --j >= lineStartIndex;)
  72784. {
  72785. if (! glyphs.getUnchecked (j)->isWhitespace())
  72786. {
  72787. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72788. break;
  72789. }
  72790. }
  72791. float deltaX = 0.0f;
  72792. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72793. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72794. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72795. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72796. else if (horizontalLayout.testFlags (Justification::right))
  72797. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72798. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72799. x + deltaX - currentLineStartX, y - originalY);
  72800. lineStartIndex = i;
  72801. y += font.getHeight();
  72802. }
  72803. }
  72804. void GlyphArrangement::addFittedText (const Font& f,
  72805. const String& text,
  72806. const float x, const float y,
  72807. const float width, const float height,
  72808. const Justification& layout,
  72809. int maximumLines,
  72810. const float minimumHorizontalScale)
  72811. {
  72812. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72813. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72814. if (text.containsAnyOf ("\r\n"))
  72815. {
  72816. GlyphArrangement ga;
  72817. ga.addJustifiedText (f, text, x, y, width, layout);
  72818. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72819. float dy = y - bb.getY();
  72820. if (layout.testFlags (Justification::verticallyCentred))
  72821. dy += (height - bb.getHeight()) * 0.5f;
  72822. else if (layout.testFlags (Justification::bottom))
  72823. dy += height - bb.getHeight();
  72824. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72825. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72826. for (int i = 0; i < ga.glyphs.size(); ++i)
  72827. glyphs.add (ga.glyphs.getUnchecked (i));
  72828. ga.glyphs.clear (false);
  72829. return;
  72830. }
  72831. int startIndex = glyphs.size();
  72832. addLineOfText (f, text.trim(), x, y);
  72833. if (glyphs.size() > startIndex)
  72834. {
  72835. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72836. - glyphs.getUnchecked (startIndex)->getLeft();
  72837. if (lineWidth <= 0)
  72838. return;
  72839. if (lineWidth * minimumHorizontalScale < width)
  72840. {
  72841. if (lineWidth > width)
  72842. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72843. width / lineWidth);
  72844. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72845. x, y, width, height, layout);
  72846. }
  72847. else if (maximumLines <= 1)
  72848. {
  72849. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72850. x, y, width, height, f, layout, minimumHorizontalScale);
  72851. }
  72852. else
  72853. {
  72854. Font font (f);
  72855. String txt (text.trim());
  72856. const int length = txt.length();
  72857. const int originalStartIndex = startIndex;
  72858. int numLines = 1;
  72859. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72860. maximumLines = 1;
  72861. maximumLines = jmin (maximumLines, length);
  72862. while (numLines < maximumLines)
  72863. {
  72864. ++numLines;
  72865. const float newFontHeight = height / (float) numLines;
  72866. if (newFontHeight < font.getHeight())
  72867. {
  72868. font.setHeight (jmax (8.0f, newFontHeight));
  72869. removeRangeOfGlyphs (startIndex, -1);
  72870. addLineOfText (font, txt, x, y);
  72871. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72872. - glyphs.getUnchecked (startIndex)->getLeft();
  72873. }
  72874. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72875. break;
  72876. }
  72877. if (numLines < 1)
  72878. numLines = 1;
  72879. float lineY = y;
  72880. float widthPerLine = lineWidth / numLines;
  72881. int lastLineStartIndex = 0;
  72882. for (int line = 0; line < numLines; ++line)
  72883. {
  72884. int i = startIndex;
  72885. lastLineStartIndex = i;
  72886. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72887. if (line == numLines - 1)
  72888. {
  72889. widthPerLine = width;
  72890. i = glyphs.size();
  72891. }
  72892. else
  72893. {
  72894. while (i < glyphs.size())
  72895. {
  72896. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72897. if (lineWidth > widthPerLine)
  72898. {
  72899. // got to a point where the line's too long, so skip forward to find a
  72900. // good place to break it..
  72901. const int searchStartIndex = i;
  72902. while (i < glyphs.size())
  72903. {
  72904. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72905. {
  72906. if (glyphs.getUnchecked (i)->isWhitespace()
  72907. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72908. {
  72909. ++i;
  72910. break;
  72911. }
  72912. }
  72913. else
  72914. {
  72915. // can't find a suitable break, so try looking backwards..
  72916. i = searchStartIndex;
  72917. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72918. {
  72919. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72920. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72921. {
  72922. i -= back - 1;
  72923. break;
  72924. }
  72925. }
  72926. break;
  72927. }
  72928. ++i;
  72929. }
  72930. break;
  72931. }
  72932. ++i;
  72933. }
  72934. int wsStart = i;
  72935. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72936. --wsStart;
  72937. int wsEnd = i;
  72938. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72939. ++wsEnd;
  72940. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72941. i = jmax (wsStart, startIndex + 1);
  72942. }
  72943. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72944. x, lineY, width, font.getHeight(), font,
  72945. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72946. minimumHorizontalScale);
  72947. startIndex = i;
  72948. lineY += font.getHeight();
  72949. if (startIndex >= glyphs.size())
  72950. break;
  72951. }
  72952. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72953. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72954. }
  72955. }
  72956. }
  72957. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72958. const float dx, const float dy)
  72959. {
  72960. jassert (startIndex >= 0);
  72961. if (dx != 0.0f || dy != 0.0f)
  72962. {
  72963. if (num < 0 || startIndex + num > glyphs.size())
  72964. num = glyphs.size() - startIndex;
  72965. while (--num >= 0)
  72966. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72967. }
  72968. }
  72969. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72970. const Justification& justification, float minimumHorizontalScale)
  72971. {
  72972. int numDeleted = 0;
  72973. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72974. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72975. if (lineWidth > w)
  72976. {
  72977. if (minimumHorizontalScale < 1.0f)
  72978. {
  72979. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72980. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72981. }
  72982. if (lineWidth > w)
  72983. {
  72984. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72985. numGlyphs -= numDeleted;
  72986. }
  72987. }
  72988. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72989. return numDeleted;
  72990. }
  72991. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72992. const float horizontalScaleFactor)
  72993. {
  72994. jassert (startIndex >= 0);
  72995. if (num < 0 || startIndex + num > glyphs.size())
  72996. num = glyphs.size() - startIndex;
  72997. if (num > 0)
  72998. {
  72999. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73000. while (--num >= 0)
  73001. {
  73002. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73003. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73004. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73005. pg->w *= horizontalScaleFactor;
  73006. }
  73007. }
  73008. }
  73009. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73010. {
  73011. jassert (startIndex >= 0);
  73012. if (num < 0 || startIndex + num > glyphs.size())
  73013. num = glyphs.size() - startIndex;
  73014. Rectangle<float> result;
  73015. while (--num >= 0)
  73016. {
  73017. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73018. if (includeWhitespace || ! pg->isWhitespace())
  73019. result = result.getUnion (pg->getBounds());
  73020. }
  73021. return result;
  73022. }
  73023. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73024. const float x, const float y, const float width, const float height,
  73025. const Justification& justification)
  73026. {
  73027. jassert (num >= 0 && startIndex >= 0);
  73028. if (glyphs.size() > 0 && num > 0)
  73029. {
  73030. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73031. | Justification::horizontallyCentred)));
  73032. float deltaX = 0.0f;
  73033. if (justification.testFlags (Justification::horizontallyJustified))
  73034. deltaX = x - bb.getX();
  73035. else if (justification.testFlags (Justification::horizontallyCentred))
  73036. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73037. else if (justification.testFlags (Justification::right))
  73038. deltaX = (x + width) - bb.getRight();
  73039. else
  73040. deltaX = x - bb.getX();
  73041. float deltaY = 0.0f;
  73042. if (justification.testFlags (Justification::top))
  73043. deltaY = y - bb.getY();
  73044. else if (justification.testFlags (Justification::bottom))
  73045. deltaY = (y + height) - bb.getBottom();
  73046. else
  73047. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73048. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73049. if (justification.testFlags (Justification::horizontallyJustified))
  73050. {
  73051. int lineStart = 0;
  73052. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73053. int i;
  73054. for (i = 0; i < num; ++i)
  73055. {
  73056. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73057. if (glyphY != baseY)
  73058. {
  73059. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73060. lineStart = i;
  73061. baseY = glyphY;
  73062. }
  73063. }
  73064. if (i > lineStart)
  73065. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73066. }
  73067. }
  73068. }
  73069. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73070. {
  73071. if (start + num < glyphs.size()
  73072. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73073. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73074. {
  73075. int numSpaces = 0;
  73076. int spacesAtEnd = 0;
  73077. for (int i = 0; i < num; ++i)
  73078. {
  73079. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73080. {
  73081. ++spacesAtEnd;
  73082. ++numSpaces;
  73083. }
  73084. else
  73085. {
  73086. spacesAtEnd = 0;
  73087. }
  73088. }
  73089. numSpaces -= spacesAtEnd;
  73090. if (numSpaces > 0)
  73091. {
  73092. const float startX = glyphs.getUnchecked (start)->getLeft();
  73093. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73094. const float extraPaddingBetweenWords
  73095. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73096. float deltaX = 0.0f;
  73097. for (int i = 0; i < num; ++i)
  73098. {
  73099. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73100. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73101. deltaX += extraPaddingBetweenWords;
  73102. }
  73103. }
  73104. }
  73105. }
  73106. void GlyphArrangement::draw (const Graphics& g) const
  73107. {
  73108. for (int i = 0; i < glyphs.size(); ++i)
  73109. {
  73110. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73111. if (pg->font.isUnderlined())
  73112. {
  73113. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73114. float nextX = pg->x + pg->w;
  73115. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73116. nextX = glyphs.getUnchecked (i + 1)->x;
  73117. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73118. nextX - pg->x, lineThickness);
  73119. }
  73120. pg->draw (g);
  73121. }
  73122. }
  73123. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) 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. Path p;
  73135. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73136. nextX, pg->y + lineThickness * 2.0f),
  73137. lineThickness);
  73138. g.fillPath (p, transform);
  73139. }
  73140. pg->draw (g, transform);
  73141. }
  73142. }
  73143. void GlyphArrangement::createPath (Path& path) const
  73144. {
  73145. for (int i = 0; i < glyphs.size(); ++i)
  73146. glyphs.getUnchecked (i)->createPath (path);
  73147. }
  73148. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73149. {
  73150. for (int i = 0; i < glyphs.size(); ++i)
  73151. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73152. return i;
  73153. return -1;
  73154. }
  73155. END_JUCE_NAMESPACE
  73156. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73157. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73158. BEGIN_JUCE_NAMESPACE
  73159. class TextLayout::Token
  73160. {
  73161. public:
  73162. String text;
  73163. Font font;
  73164. int x, y, w, h;
  73165. int line, lineHeight;
  73166. bool isWhitespace, isNewLine;
  73167. Token (const String& t,
  73168. const Font& f,
  73169. const bool isWhitespace_)
  73170. : text (t),
  73171. font (f),
  73172. x(0),
  73173. y(0),
  73174. isWhitespace (isWhitespace_)
  73175. {
  73176. w = font.getStringWidth (t);
  73177. h = roundToInt (f.getHeight());
  73178. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73179. }
  73180. Token (const Token& other)
  73181. : text (other.text),
  73182. font (other.font),
  73183. x (other.x),
  73184. y (other.y),
  73185. w (other.w),
  73186. h (other.h),
  73187. line (other.line),
  73188. lineHeight (other.lineHeight),
  73189. isWhitespace (other.isWhitespace),
  73190. isNewLine (other.isNewLine)
  73191. {
  73192. }
  73193. ~Token()
  73194. {
  73195. }
  73196. void draw (Graphics& g,
  73197. const int xOffset,
  73198. const int yOffset)
  73199. {
  73200. if (! isWhitespace)
  73201. {
  73202. g.setFont (font);
  73203. g.drawSingleLineText (text.trimEnd(),
  73204. xOffset + x,
  73205. yOffset + y + (lineHeight - h)
  73206. + roundToInt (font.getAscent()));
  73207. }
  73208. }
  73209. juce_UseDebuggingNewOperator
  73210. };
  73211. TextLayout::TextLayout()
  73212. : totalLines (0)
  73213. {
  73214. tokens.ensureStorageAllocated (64);
  73215. }
  73216. TextLayout::TextLayout (const String& text, const Font& font)
  73217. : totalLines (0)
  73218. {
  73219. tokens.ensureStorageAllocated (64);
  73220. appendText (text, font);
  73221. }
  73222. TextLayout::TextLayout (const TextLayout& other)
  73223. : totalLines (0)
  73224. {
  73225. *this = other;
  73226. }
  73227. TextLayout& TextLayout::operator= (const TextLayout& other)
  73228. {
  73229. if (this != &other)
  73230. {
  73231. clear();
  73232. totalLines = other.totalLines;
  73233. tokens.addCopiesOf (other.tokens);
  73234. }
  73235. return *this;
  73236. }
  73237. TextLayout::~TextLayout()
  73238. {
  73239. clear();
  73240. }
  73241. void TextLayout::clear()
  73242. {
  73243. tokens.clear();
  73244. totalLines = 0;
  73245. }
  73246. bool TextLayout::isEmpty() const
  73247. {
  73248. return tokens.size() == 0;
  73249. }
  73250. void TextLayout::appendText (const String& text, const Font& font)
  73251. {
  73252. const juce_wchar* t = text;
  73253. String currentString;
  73254. int lastCharType = 0;
  73255. for (;;)
  73256. {
  73257. const juce_wchar c = *t++;
  73258. if (c == 0)
  73259. break;
  73260. int charType;
  73261. if (c == '\r' || c == '\n')
  73262. {
  73263. charType = 0;
  73264. }
  73265. else if (CharacterFunctions::isWhitespace (c))
  73266. {
  73267. charType = 2;
  73268. }
  73269. else
  73270. {
  73271. charType = 1;
  73272. }
  73273. if (charType == 0 || charType != lastCharType)
  73274. {
  73275. if (currentString.isNotEmpty())
  73276. {
  73277. tokens.add (new Token (currentString, font,
  73278. lastCharType == 2 || lastCharType == 0));
  73279. }
  73280. currentString = String::charToString (c);
  73281. if (c == '\r' && *t == '\n')
  73282. currentString += *t++;
  73283. }
  73284. else
  73285. {
  73286. currentString += c;
  73287. }
  73288. lastCharType = charType;
  73289. }
  73290. if (currentString.isNotEmpty())
  73291. tokens.add (new Token (currentString, font, lastCharType == 2));
  73292. }
  73293. void TextLayout::setText (const String& text, const Font& font)
  73294. {
  73295. clear();
  73296. appendText (text, font);
  73297. }
  73298. void TextLayout::layout (int maxWidth,
  73299. const Justification& justification,
  73300. const bool attemptToBalanceLineLengths)
  73301. {
  73302. if (attemptToBalanceLineLengths)
  73303. {
  73304. const int originalW = maxWidth;
  73305. int bestWidth = maxWidth;
  73306. float bestLineProportion = 0.0f;
  73307. while (maxWidth > originalW / 2)
  73308. {
  73309. layout (maxWidth, justification, false);
  73310. if (getNumLines() <= 1)
  73311. return;
  73312. const int lastLineW = getLineWidth (getNumLines() - 1);
  73313. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73314. const float prop = lastLineW / (float) lastButOneLineW;
  73315. if (prop > 0.9f)
  73316. return;
  73317. if (prop > bestLineProportion)
  73318. {
  73319. bestLineProportion = prop;
  73320. bestWidth = maxWidth;
  73321. }
  73322. maxWidth -= 10;
  73323. }
  73324. layout (bestWidth, justification, false);
  73325. }
  73326. else
  73327. {
  73328. int x = 0;
  73329. int y = 0;
  73330. int h = 0;
  73331. totalLines = 0;
  73332. int i;
  73333. for (i = 0; i < tokens.size(); ++i)
  73334. {
  73335. Token* const t = tokens.getUnchecked(i);
  73336. t->x = x;
  73337. t->y = y;
  73338. t->line = totalLines;
  73339. x += t->w;
  73340. h = jmax (h, t->h);
  73341. const Token* nextTok = tokens [i + 1];
  73342. if (nextTok == 0)
  73343. break;
  73344. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73345. {
  73346. // finished a line, so go back and update the heights of the things on it
  73347. for (int j = i; j >= 0; --j)
  73348. {
  73349. Token* const tok = tokens.getUnchecked(j);
  73350. if (tok->line == totalLines)
  73351. tok->lineHeight = h;
  73352. else
  73353. break;
  73354. }
  73355. x = 0;
  73356. y += h;
  73357. h = 0;
  73358. ++totalLines;
  73359. }
  73360. }
  73361. // finished a line, so go back and update the heights of the things on it
  73362. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73363. {
  73364. Token* const t = tokens.getUnchecked(j);
  73365. if (t->line == totalLines)
  73366. t->lineHeight = h;
  73367. else
  73368. break;
  73369. }
  73370. ++totalLines;
  73371. if (! justification.testFlags (Justification::left))
  73372. {
  73373. int totalW = getWidth();
  73374. for (i = totalLines; --i >= 0;)
  73375. {
  73376. const int lineW = getLineWidth (i);
  73377. int dx = 0;
  73378. if (justification.testFlags (Justification::horizontallyCentred))
  73379. dx = (totalW - lineW) / 2;
  73380. else if (justification.testFlags (Justification::right))
  73381. dx = totalW - lineW;
  73382. for (int j = tokens.size(); --j >= 0;)
  73383. {
  73384. Token* const t = tokens.getUnchecked(j);
  73385. if (t->line == i)
  73386. t->x += dx;
  73387. }
  73388. }
  73389. }
  73390. }
  73391. }
  73392. int TextLayout::getLineWidth (const int lineNumber) const
  73393. {
  73394. int maxW = 0;
  73395. for (int i = tokens.size(); --i >= 0;)
  73396. {
  73397. const Token* const t = tokens.getUnchecked(i);
  73398. if (t->line == lineNumber && ! t->isWhitespace)
  73399. maxW = jmax (maxW, t->x + t->w);
  73400. }
  73401. return maxW;
  73402. }
  73403. int TextLayout::getWidth() const
  73404. {
  73405. int maxW = 0;
  73406. for (int i = tokens.size(); --i >= 0;)
  73407. {
  73408. const Token* const t = tokens.getUnchecked(i);
  73409. if (! t->isWhitespace)
  73410. maxW = jmax (maxW, t->x + t->w);
  73411. }
  73412. return maxW;
  73413. }
  73414. int TextLayout::getHeight() const
  73415. {
  73416. int maxH = 0;
  73417. for (int i = tokens.size(); --i >= 0;)
  73418. {
  73419. const Token* const t = tokens.getUnchecked(i);
  73420. if (! t->isWhitespace)
  73421. maxH = jmax (maxH, t->y + t->h);
  73422. }
  73423. return maxH;
  73424. }
  73425. void TextLayout::draw (Graphics& g,
  73426. const int xOffset,
  73427. const int yOffset) const
  73428. {
  73429. for (int i = tokens.size(); --i >= 0;)
  73430. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73431. }
  73432. void TextLayout::drawWithin (Graphics& g,
  73433. int x, int y, int w, int h,
  73434. const Justification& justification) const
  73435. {
  73436. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73437. x, y, w, h);
  73438. draw (g, x, y);
  73439. }
  73440. END_JUCE_NAMESPACE
  73441. /*** End of inlined file: juce_TextLayout.cpp ***/
  73442. /*** Start of inlined file: juce_Typeface.cpp ***/
  73443. BEGIN_JUCE_NAMESPACE
  73444. Typeface::Typeface (const String& name_) throw()
  73445. : name (name_)
  73446. {
  73447. }
  73448. Typeface::~Typeface()
  73449. {
  73450. }
  73451. class CustomTypeface::GlyphInfo
  73452. {
  73453. public:
  73454. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73455. : character (character_), path (path_), width (width_)
  73456. {
  73457. }
  73458. ~GlyphInfo() throw()
  73459. {
  73460. }
  73461. struct KerningPair
  73462. {
  73463. juce_wchar character2;
  73464. float kerningAmount;
  73465. };
  73466. void addKerningPair (const juce_wchar subsequentCharacter,
  73467. const float extraKerningAmount) throw()
  73468. {
  73469. KerningPair kp;
  73470. kp.character2 = subsequentCharacter;
  73471. kp.kerningAmount = extraKerningAmount;
  73472. kerningPairs.add (kp);
  73473. }
  73474. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73475. {
  73476. if (subsequentCharacter != 0)
  73477. {
  73478. for (int i = kerningPairs.size(); --i >= 0;)
  73479. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73480. return width + kerningPairs.getReference(i).kerningAmount;
  73481. }
  73482. return width;
  73483. }
  73484. const juce_wchar character;
  73485. const Path path;
  73486. float width;
  73487. Array <KerningPair> kerningPairs;
  73488. juce_UseDebuggingNewOperator
  73489. private:
  73490. GlyphInfo (const GlyphInfo&);
  73491. GlyphInfo& operator= (const GlyphInfo&);
  73492. };
  73493. CustomTypeface::CustomTypeface()
  73494. : Typeface (String::empty)
  73495. {
  73496. clear();
  73497. }
  73498. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73499. : Typeface (String::empty)
  73500. {
  73501. clear();
  73502. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73503. BufferedInputStream in (&gzin, 32768, false);
  73504. name = in.readString();
  73505. isBold = in.readBool();
  73506. isItalic = in.readBool();
  73507. ascent = in.readFloat();
  73508. defaultCharacter = (juce_wchar) in.readShort();
  73509. int i, numChars = in.readInt();
  73510. for (i = 0; i < numChars; ++i)
  73511. {
  73512. const juce_wchar c = (juce_wchar) in.readShort();
  73513. const float width = in.readFloat();
  73514. Path p;
  73515. p.loadPathFromStream (in);
  73516. addGlyph (c, p, width);
  73517. }
  73518. const int numKerningPairs = in.readInt();
  73519. for (i = 0; i < numKerningPairs; ++i)
  73520. {
  73521. const juce_wchar char1 = (juce_wchar) in.readShort();
  73522. const juce_wchar char2 = (juce_wchar) in.readShort();
  73523. addKerningPair (char1, char2, in.readFloat());
  73524. }
  73525. }
  73526. CustomTypeface::~CustomTypeface()
  73527. {
  73528. }
  73529. void CustomTypeface::clear()
  73530. {
  73531. defaultCharacter = 0;
  73532. ascent = 1.0f;
  73533. isBold = isItalic = false;
  73534. zeromem (lookupTable, sizeof (lookupTable));
  73535. glyphs.clear();
  73536. }
  73537. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73538. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73539. {
  73540. name = name_;
  73541. defaultCharacter = defaultCharacter_;
  73542. ascent = ascent_;
  73543. isBold = isBold_;
  73544. isItalic = isItalic_;
  73545. }
  73546. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73547. {
  73548. // Check that you're not trying to add the same character twice..
  73549. jassert (findGlyph (character, false) == 0);
  73550. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73551. lookupTable [character] = (short) glyphs.size();
  73552. glyphs.add (new GlyphInfo (character, path, width));
  73553. }
  73554. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73555. {
  73556. if (extraAmount != 0)
  73557. {
  73558. GlyphInfo* const g = findGlyph (char1, true);
  73559. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73560. if (g != 0)
  73561. g->addKerningPair (char2, extraAmount);
  73562. }
  73563. }
  73564. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73565. {
  73566. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73567. return glyphs [(int) lookupTable [(int) character]];
  73568. for (int i = 0; i < glyphs.size(); ++i)
  73569. {
  73570. GlyphInfo* const g = glyphs.getUnchecked(i);
  73571. if (g->character == character)
  73572. return g;
  73573. }
  73574. if (loadIfNeeded && loadGlyphIfPossible (character))
  73575. return findGlyph (character, false);
  73576. return 0;
  73577. }
  73578. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73579. {
  73580. GlyphInfo* glyph = findGlyph (character, true);
  73581. if (glyph == 0)
  73582. {
  73583. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73584. glyph = findGlyph (L' ', true);
  73585. if (glyph == 0)
  73586. {
  73587. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73588. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73589. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73590. {
  73591. //xxx
  73592. }
  73593. if (glyph == 0)
  73594. glyph = findGlyph (defaultCharacter, true);
  73595. }
  73596. }
  73597. return glyph;
  73598. }
  73599. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73600. {
  73601. return false;
  73602. }
  73603. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73604. {
  73605. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73606. for (int i = 0; i < numCharacters; ++i)
  73607. {
  73608. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73609. Array <int> glyphIndexes;
  73610. Array <float> offsets;
  73611. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73612. const int glyphIndex = glyphIndexes.getFirst();
  73613. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73614. {
  73615. const float glyphWidth = offsets[1];
  73616. Path p;
  73617. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73618. addGlyph (c, p, glyphWidth);
  73619. for (int j = glyphs.size() - 1; --j >= 0;)
  73620. {
  73621. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73622. glyphIndexes.clearQuick();
  73623. offsets.clearQuick();
  73624. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73625. if (offsets.size() > 1)
  73626. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73627. }
  73628. }
  73629. }
  73630. }
  73631. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73632. {
  73633. GZIPCompressorOutputStream out (&outputStream);
  73634. out.writeString (name);
  73635. out.writeBool (isBold);
  73636. out.writeBool (isItalic);
  73637. out.writeFloat (ascent);
  73638. out.writeShort ((short) (unsigned short) defaultCharacter);
  73639. out.writeInt (glyphs.size());
  73640. int i, numKerningPairs = 0;
  73641. for (i = 0; i < glyphs.size(); ++i)
  73642. {
  73643. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73644. out.writeShort ((short) (unsigned short) g->character);
  73645. out.writeFloat (g->width);
  73646. g->path.writePathToStream (out);
  73647. numKerningPairs += g->kerningPairs.size();
  73648. }
  73649. out.writeInt (numKerningPairs);
  73650. for (i = 0; i < glyphs.size(); ++i)
  73651. {
  73652. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73653. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73654. {
  73655. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73656. out.writeShort ((short) (unsigned short) g->character);
  73657. out.writeShort ((short) (unsigned short) p.character2);
  73658. out.writeFloat (p.kerningAmount);
  73659. }
  73660. }
  73661. return true;
  73662. }
  73663. float CustomTypeface::getAscent() const
  73664. {
  73665. return ascent;
  73666. }
  73667. float CustomTypeface::getDescent() const
  73668. {
  73669. return 1.0f - ascent;
  73670. }
  73671. float CustomTypeface::getStringWidth (const String& text)
  73672. {
  73673. float x = 0;
  73674. const juce_wchar* t = text;
  73675. while (*t != 0)
  73676. {
  73677. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73678. if (glyph != 0)
  73679. x += glyph->getHorizontalSpacing (*t);
  73680. }
  73681. return x;
  73682. }
  73683. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73684. {
  73685. xOffsets.add (0);
  73686. float x = 0;
  73687. const juce_wchar* t = text;
  73688. while (*t != 0)
  73689. {
  73690. const juce_wchar c = *t++;
  73691. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73692. if (glyph != 0)
  73693. {
  73694. x += glyph->getHorizontalSpacing (*t);
  73695. resultGlyphs.add ((int) glyph->character);
  73696. xOffsets.add (x);
  73697. }
  73698. }
  73699. }
  73700. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73701. {
  73702. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73703. if (glyph != 0)
  73704. {
  73705. path = glyph->path;
  73706. return true;
  73707. }
  73708. return false;
  73709. }
  73710. END_JUCE_NAMESPACE
  73711. /*** End of inlined file: juce_Typeface.cpp ***/
  73712. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73713. BEGIN_JUCE_NAMESPACE
  73714. AffineTransform::AffineTransform() throw()
  73715. : mat00 (1.0f),
  73716. mat01 (0),
  73717. mat02 (0),
  73718. mat10 (0),
  73719. mat11 (1.0f),
  73720. mat12 (0)
  73721. {
  73722. }
  73723. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73724. : mat00 (other.mat00),
  73725. mat01 (other.mat01),
  73726. mat02 (other.mat02),
  73727. mat10 (other.mat10),
  73728. mat11 (other.mat11),
  73729. mat12 (other.mat12)
  73730. {
  73731. }
  73732. AffineTransform::AffineTransform (const float mat00_,
  73733. const float mat01_,
  73734. const float mat02_,
  73735. const float mat10_,
  73736. const float mat11_,
  73737. const float mat12_) throw()
  73738. : mat00 (mat00_),
  73739. mat01 (mat01_),
  73740. mat02 (mat02_),
  73741. mat10 (mat10_),
  73742. mat11 (mat11_),
  73743. mat12 (mat12_)
  73744. {
  73745. }
  73746. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73747. {
  73748. mat00 = other.mat00;
  73749. mat01 = other.mat01;
  73750. mat02 = other.mat02;
  73751. mat10 = other.mat10;
  73752. mat11 = other.mat11;
  73753. mat12 = other.mat12;
  73754. return *this;
  73755. }
  73756. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73757. {
  73758. return mat00 == other.mat00
  73759. && mat01 == other.mat01
  73760. && mat02 == other.mat02
  73761. && mat10 == other.mat10
  73762. && mat11 == other.mat11
  73763. && mat12 == other.mat12;
  73764. }
  73765. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73766. {
  73767. return ! operator== (other);
  73768. }
  73769. bool AffineTransform::isIdentity() const throw()
  73770. {
  73771. return (mat01 == 0)
  73772. && (mat02 == 0)
  73773. && (mat10 == 0)
  73774. && (mat12 == 0)
  73775. && (mat00 == 1.0f)
  73776. && (mat11 == 1.0f);
  73777. }
  73778. const AffineTransform AffineTransform::identity;
  73779. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73780. {
  73781. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73782. other.mat00 * mat01 + other.mat01 * mat11,
  73783. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73784. other.mat10 * mat00 + other.mat11 * mat10,
  73785. other.mat10 * mat01 + other.mat11 * mat11,
  73786. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73787. }
  73788. const AffineTransform AffineTransform::followedBy (const float omat00,
  73789. const float omat01,
  73790. const float omat02,
  73791. const float omat10,
  73792. const float omat11,
  73793. const float omat12) const throw()
  73794. {
  73795. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73796. omat00 * mat01 + omat01 * mat11,
  73797. omat00 * mat02 + omat01 * mat12 + omat02,
  73798. omat10 * mat00 + omat11 * mat10,
  73799. omat10 * mat01 + omat11 * mat11,
  73800. omat10 * mat02 + omat11 * mat12 + omat12);
  73801. }
  73802. const AffineTransform AffineTransform::translated (const float dx,
  73803. const float dy) const throw()
  73804. {
  73805. return AffineTransform (mat00, mat01, mat02 + dx,
  73806. mat10, mat11, mat12 + dy);
  73807. }
  73808. const AffineTransform AffineTransform::translation (const float dx,
  73809. const float dy) throw()
  73810. {
  73811. return AffineTransform (1.0f, 0, dx,
  73812. 0, 1.0f, dy);
  73813. }
  73814. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73815. {
  73816. const float cosRad = std::cos (rad);
  73817. const float sinRad = std::sin (rad);
  73818. return followedBy (cosRad, -sinRad, 0,
  73819. sinRad, cosRad, 0);
  73820. }
  73821. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73822. {
  73823. const float cosRad = std::cos (rad);
  73824. const float sinRad = std::sin (rad);
  73825. return AffineTransform (cosRad, -sinRad, 0,
  73826. sinRad, cosRad, 0);
  73827. }
  73828. const AffineTransform AffineTransform::rotated (const float angle,
  73829. const float pivotX,
  73830. const float pivotY) const throw()
  73831. {
  73832. return translated (-pivotX, -pivotY)
  73833. .rotated (angle)
  73834. .translated (pivotX, pivotY);
  73835. }
  73836. const AffineTransform AffineTransform::rotation (const float angle,
  73837. const float pivotX,
  73838. const float pivotY) throw()
  73839. {
  73840. return translation (-pivotX, -pivotY)
  73841. .rotated (angle)
  73842. .translated (pivotX, pivotY);
  73843. }
  73844. const AffineTransform AffineTransform::scaled (const float factorX,
  73845. const float factorY) const throw()
  73846. {
  73847. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73848. factorY * mat10, factorY * mat11, factorY * mat12);
  73849. }
  73850. const AffineTransform AffineTransform::scale (const float factorX,
  73851. const float factorY) throw()
  73852. {
  73853. return AffineTransform (factorX, 0, 0,
  73854. 0, factorY, 0);
  73855. }
  73856. const AffineTransform AffineTransform::sheared (const float shearX,
  73857. const float shearY) const throw()
  73858. {
  73859. return followedBy (1.0f, shearX, 0,
  73860. shearY, 1.0f, 0);
  73861. }
  73862. const AffineTransform AffineTransform::inverted() const throw()
  73863. {
  73864. double determinant = (mat00 * mat11 - mat10 * mat01);
  73865. if (determinant != 0.0)
  73866. {
  73867. determinant = 1.0 / determinant;
  73868. const float dst00 = (float) (mat11 * determinant);
  73869. const float dst10 = (float) (-mat10 * determinant);
  73870. const float dst01 = (float) (-mat01 * determinant);
  73871. const float dst11 = (float) (mat00 * determinant);
  73872. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73873. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73874. }
  73875. else
  73876. {
  73877. // singularity..
  73878. return *this;
  73879. }
  73880. }
  73881. bool AffineTransform::isSingularity() const throw()
  73882. {
  73883. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73884. }
  73885. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73886. const float x10, const float y10,
  73887. const float x01, const float y01) throw()
  73888. {
  73889. return AffineTransform (x10 - x00, x01 - x00, x00,
  73890. y10 - y00, y01 - y00, y00);
  73891. }
  73892. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73893. const float sx2, const float sy2, const float tx2, const float ty2,
  73894. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73895. {
  73896. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73897. .inverted()
  73898. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73899. }
  73900. bool AffineTransform::isOnlyTranslation() const throw()
  73901. {
  73902. return (mat01 == 0)
  73903. && (mat10 == 0)
  73904. && (mat00 == 1.0f)
  73905. && (mat11 == 1.0f);
  73906. }
  73907. END_JUCE_NAMESPACE
  73908. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73909. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73910. BEGIN_JUCE_NAMESPACE
  73911. BorderSize::BorderSize() throw()
  73912. : top (0),
  73913. left (0),
  73914. bottom (0),
  73915. right (0)
  73916. {
  73917. }
  73918. BorderSize::BorderSize (const BorderSize& other) throw()
  73919. : top (other.top),
  73920. left (other.left),
  73921. bottom (other.bottom),
  73922. right (other.right)
  73923. {
  73924. }
  73925. BorderSize::BorderSize (const int topGap,
  73926. const int leftGap,
  73927. const int bottomGap,
  73928. const int rightGap) throw()
  73929. : top (topGap),
  73930. left (leftGap),
  73931. bottom (bottomGap),
  73932. right (rightGap)
  73933. {
  73934. }
  73935. BorderSize::BorderSize (const int allGaps) throw()
  73936. : top (allGaps),
  73937. left (allGaps),
  73938. bottom (allGaps),
  73939. right (allGaps)
  73940. {
  73941. }
  73942. BorderSize::~BorderSize() throw()
  73943. {
  73944. }
  73945. void BorderSize::setTop (const int newTopGap) throw()
  73946. {
  73947. top = newTopGap;
  73948. }
  73949. void BorderSize::setLeft (const int newLeftGap) throw()
  73950. {
  73951. left = newLeftGap;
  73952. }
  73953. void BorderSize::setBottom (const int newBottomGap) throw()
  73954. {
  73955. bottom = newBottomGap;
  73956. }
  73957. void BorderSize::setRight (const int newRightGap) throw()
  73958. {
  73959. right = newRightGap;
  73960. }
  73961. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73962. {
  73963. return Rectangle<int> (r.getX() + left,
  73964. r.getY() + top,
  73965. r.getWidth() - (left + right),
  73966. r.getHeight() - (top + bottom));
  73967. }
  73968. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73969. {
  73970. r.setBounds (r.getX() + left,
  73971. r.getY() + top,
  73972. r.getWidth() - (left + right),
  73973. r.getHeight() - (top + bottom));
  73974. }
  73975. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73976. {
  73977. return Rectangle<int> (r.getX() - left,
  73978. r.getY() - top,
  73979. r.getWidth() + (left + right),
  73980. r.getHeight() + (top + bottom));
  73981. }
  73982. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73983. {
  73984. r.setBounds (r.getX() - left,
  73985. r.getY() - top,
  73986. r.getWidth() + (left + right),
  73987. r.getHeight() + (top + bottom));
  73988. }
  73989. bool BorderSize::operator== (const BorderSize& other) const throw()
  73990. {
  73991. return top == other.top
  73992. && left == other.left
  73993. && bottom == other.bottom
  73994. && right == other.right;
  73995. }
  73996. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73997. {
  73998. return ! operator== (other);
  73999. }
  74000. END_JUCE_NAMESPACE
  74001. /*** End of inlined file: juce_BorderSize.cpp ***/
  74002. /*** Start of inlined file: juce_Path.cpp ***/
  74003. BEGIN_JUCE_NAMESPACE
  74004. // tests that some co-ords aren't NaNs
  74005. #define CHECK_COORDS_ARE_VALID(x, y) \
  74006. jassert (x == x && y == y);
  74007. namespace PathHelpers
  74008. {
  74009. static const float ellipseAngularIncrement = 0.05f;
  74010. static const String nextToken (const juce_wchar*& t)
  74011. {
  74012. while (CharacterFunctions::isWhitespace (*t))
  74013. ++t;
  74014. const juce_wchar* const start = t;
  74015. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74016. ++t;
  74017. return String (start, (int) (t - start));
  74018. }
  74019. }
  74020. const float Path::lineMarker = 100001.0f;
  74021. const float Path::moveMarker = 100002.0f;
  74022. const float Path::quadMarker = 100003.0f;
  74023. const float Path::cubicMarker = 100004.0f;
  74024. const float Path::closeSubPathMarker = 100005.0f;
  74025. Path::Path()
  74026. : numElements (0),
  74027. pathXMin (0),
  74028. pathXMax (0),
  74029. pathYMin (0),
  74030. pathYMax (0),
  74031. useNonZeroWinding (true)
  74032. {
  74033. }
  74034. Path::~Path()
  74035. {
  74036. }
  74037. Path::Path (const Path& other)
  74038. : numElements (other.numElements),
  74039. pathXMin (other.pathXMin),
  74040. pathXMax (other.pathXMax),
  74041. pathYMin (other.pathYMin),
  74042. pathYMax (other.pathYMax),
  74043. useNonZeroWinding (other.useNonZeroWinding)
  74044. {
  74045. if (numElements > 0)
  74046. {
  74047. data.setAllocatedSize ((int) numElements);
  74048. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74049. }
  74050. }
  74051. Path& Path::operator= (const Path& other)
  74052. {
  74053. if (this != &other)
  74054. {
  74055. data.ensureAllocatedSize ((int) other.numElements);
  74056. numElements = other.numElements;
  74057. pathXMin = other.pathXMin;
  74058. pathXMax = other.pathXMax;
  74059. pathYMin = other.pathYMin;
  74060. pathYMax = other.pathYMax;
  74061. useNonZeroWinding = other.useNonZeroWinding;
  74062. if (numElements > 0)
  74063. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74064. }
  74065. return *this;
  74066. }
  74067. bool Path::operator== (const Path& other) const throw()
  74068. {
  74069. return ! operator!= (other);
  74070. }
  74071. bool Path::operator!= (const Path& other) const throw()
  74072. {
  74073. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74074. return true;
  74075. for (size_t i = 0; i < numElements; ++i)
  74076. if (data.elements[i] != other.data.elements[i])
  74077. return true;
  74078. return false;
  74079. }
  74080. void Path::clear() throw()
  74081. {
  74082. numElements = 0;
  74083. pathXMin = 0;
  74084. pathYMin = 0;
  74085. pathYMax = 0;
  74086. pathXMax = 0;
  74087. }
  74088. void Path::swapWithPath (Path& other) throw()
  74089. {
  74090. data.swapWith (other.data);
  74091. swapVariables <size_t> (numElements, other.numElements);
  74092. swapVariables <float> (pathXMin, other.pathXMin);
  74093. swapVariables <float> (pathXMax, other.pathXMax);
  74094. swapVariables <float> (pathYMin, other.pathYMin);
  74095. swapVariables <float> (pathYMax, other.pathYMax);
  74096. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74097. }
  74098. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74099. {
  74100. useNonZeroWinding = isNonZero;
  74101. }
  74102. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74103. const bool preserveProportions) throw()
  74104. {
  74105. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74106. }
  74107. bool Path::isEmpty() const throw()
  74108. {
  74109. size_t i = 0;
  74110. while (i < numElements)
  74111. {
  74112. const float type = data.elements [i++];
  74113. if (type == moveMarker)
  74114. {
  74115. i += 2;
  74116. }
  74117. else if (type == lineMarker
  74118. || type == quadMarker
  74119. || type == cubicMarker)
  74120. {
  74121. return false;
  74122. }
  74123. }
  74124. return true;
  74125. }
  74126. const Rectangle<float> Path::getBounds() const throw()
  74127. {
  74128. return Rectangle<float> (pathXMin, pathYMin,
  74129. pathXMax - pathXMin,
  74130. pathYMax - pathYMin);
  74131. }
  74132. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74133. {
  74134. return getBounds().transformed (transform);
  74135. }
  74136. void Path::startNewSubPath (const float x, const float y)
  74137. {
  74138. CHECK_COORDS_ARE_VALID (x, y);
  74139. if (numElements == 0)
  74140. {
  74141. pathXMin = pathXMax = x;
  74142. pathYMin = pathYMax = y;
  74143. }
  74144. else
  74145. {
  74146. pathXMin = jmin (pathXMin, x);
  74147. pathXMax = jmax (pathXMax, x);
  74148. pathYMin = jmin (pathYMin, y);
  74149. pathYMax = jmax (pathYMax, y);
  74150. }
  74151. data.ensureAllocatedSize ((int) numElements + 3);
  74152. data.elements [numElements++] = moveMarker;
  74153. data.elements [numElements++] = x;
  74154. data.elements [numElements++] = y;
  74155. }
  74156. void Path::startNewSubPath (const Point<float>& start)
  74157. {
  74158. startNewSubPath (start.getX(), start.getY());
  74159. }
  74160. void Path::lineTo (const float x, const float y)
  74161. {
  74162. CHECK_COORDS_ARE_VALID (x, y);
  74163. if (numElements == 0)
  74164. startNewSubPath (0, 0);
  74165. data.ensureAllocatedSize ((int) numElements + 3);
  74166. data.elements [numElements++] = lineMarker;
  74167. data.elements [numElements++] = x;
  74168. data.elements [numElements++] = y;
  74169. pathXMin = jmin (pathXMin, x);
  74170. pathXMax = jmax (pathXMax, x);
  74171. pathYMin = jmin (pathYMin, y);
  74172. pathYMax = jmax (pathYMax, y);
  74173. }
  74174. void Path::lineTo (const Point<float>& end)
  74175. {
  74176. lineTo (end.getX(), end.getY());
  74177. }
  74178. void Path::quadraticTo (const float x1, const float y1,
  74179. const float x2, const float y2)
  74180. {
  74181. CHECK_COORDS_ARE_VALID (x1, y1);
  74182. CHECK_COORDS_ARE_VALID (x2, y2);
  74183. if (numElements == 0)
  74184. startNewSubPath (0, 0);
  74185. data.ensureAllocatedSize ((int) numElements + 5);
  74186. data.elements [numElements++] = quadMarker;
  74187. data.elements [numElements++] = x1;
  74188. data.elements [numElements++] = y1;
  74189. data.elements [numElements++] = x2;
  74190. data.elements [numElements++] = y2;
  74191. pathXMin = jmin (pathXMin, x1, x2);
  74192. pathXMax = jmax (pathXMax, x1, x2);
  74193. pathYMin = jmin (pathYMin, y1, y2);
  74194. pathYMax = jmax (pathYMax, y1, y2);
  74195. }
  74196. void Path::quadraticTo (const Point<float>& controlPoint,
  74197. const Point<float>& endPoint)
  74198. {
  74199. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74200. endPoint.getX(), endPoint.getY());
  74201. }
  74202. void Path::cubicTo (const float x1, const float y1,
  74203. const float x2, const float y2,
  74204. const float x3, const float y3)
  74205. {
  74206. CHECK_COORDS_ARE_VALID (x1, y1);
  74207. CHECK_COORDS_ARE_VALID (x2, y2);
  74208. CHECK_COORDS_ARE_VALID (x3, y3);
  74209. if (numElements == 0)
  74210. startNewSubPath (0, 0);
  74211. data.ensureAllocatedSize ((int) numElements + 7);
  74212. data.elements [numElements++] = cubicMarker;
  74213. data.elements [numElements++] = x1;
  74214. data.elements [numElements++] = y1;
  74215. data.elements [numElements++] = x2;
  74216. data.elements [numElements++] = y2;
  74217. data.elements [numElements++] = x3;
  74218. data.elements [numElements++] = y3;
  74219. pathXMin = jmin (pathXMin, x1, x2, x3);
  74220. pathXMax = jmax (pathXMax, x1, x2, x3);
  74221. pathYMin = jmin (pathYMin, y1, y2, y3);
  74222. pathYMax = jmax (pathYMax, y1, y2, y3);
  74223. }
  74224. void Path::cubicTo (const Point<float>& controlPoint1,
  74225. const Point<float>& controlPoint2,
  74226. const Point<float>& endPoint)
  74227. {
  74228. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74229. controlPoint2.getX(), controlPoint2.getY(),
  74230. endPoint.getX(), endPoint.getY());
  74231. }
  74232. void Path::closeSubPath()
  74233. {
  74234. if (numElements > 0
  74235. && data.elements [numElements - 1] != closeSubPathMarker)
  74236. {
  74237. data.ensureAllocatedSize ((int) numElements + 1);
  74238. data.elements [numElements++] = closeSubPathMarker;
  74239. }
  74240. }
  74241. const Point<float> Path::getCurrentPosition() const
  74242. {
  74243. size_t i = numElements - 1;
  74244. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74245. {
  74246. while (i >= 0)
  74247. {
  74248. if (data.elements[i] == moveMarker)
  74249. {
  74250. i += 2;
  74251. break;
  74252. }
  74253. --i;
  74254. }
  74255. }
  74256. if (i > 0)
  74257. return Point<float> (data.elements [i - 1], data.elements [i]);
  74258. return Point<float>();
  74259. }
  74260. void Path::addRectangle (const float x, const float y,
  74261. const float w, const float h)
  74262. {
  74263. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74264. if (w < 0)
  74265. swapVariables (x1, x2);
  74266. if (h < 0)
  74267. swapVariables (y1, y2);
  74268. data.ensureAllocatedSize ((int) numElements + 13);
  74269. if (numElements == 0)
  74270. {
  74271. pathXMin = x1;
  74272. pathXMax = x2;
  74273. pathYMin = y1;
  74274. pathYMax = y2;
  74275. }
  74276. else
  74277. {
  74278. pathXMin = jmin (pathXMin, x1);
  74279. pathXMax = jmax (pathXMax, x2);
  74280. pathYMin = jmin (pathYMin, y1);
  74281. pathYMax = jmax (pathYMax, y2);
  74282. }
  74283. data.elements [numElements++] = moveMarker;
  74284. data.elements [numElements++] = x1;
  74285. data.elements [numElements++] = y2;
  74286. data.elements [numElements++] = lineMarker;
  74287. data.elements [numElements++] = x1;
  74288. data.elements [numElements++] = y1;
  74289. data.elements [numElements++] = lineMarker;
  74290. data.elements [numElements++] = x2;
  74291. data.elements [numElements++] = y1;
  74292. data.elements [numElements++] = lineMarker;
  74293. data.elements [numElements++] = x2;
  74294. data.elements [numElements++] = y2;
  74295. data.elements [numElements++] = closeSubPathMarker;
  74296. }
  74297. void Path::addRoundedRectangle (const float x, const float y,
  74298. const float w, const float h,
  74299. float csx,
  74300. float csy)
  74301. {
  74302. csx = jmin (csx, w * 0.5f);
  74303. csy = jmin (csy, h * 0.5f);
  74304. const float cs45x = csx * 0.45f;
  74305. const float cs45y = csy * 0.45f;
  74306. const float x2 = x + w;
  74307. const float y2 = y + h;
  74308. startNewSubPath (x + csx, y);
  74309. lineTo (x2 - csx, y);
  74310. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74311. lineTo (x2, y2 - csy);
  74312. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74313. lineTo (x + csx, y2);
  74314. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74315. lineTo (x, y + csy);
  74316. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74317. closeSubPath();
  74318. }
  74319. void Path::addRoundedRectangle (const float x, const float y,
  74320. const float w, const float h,
  74321. float cs)
  74322. {
  74323. addRoundedRectangle (x, y, w, h, cs, cs);
  74324. }
  74325. void Path::addTriangle (const float x1, const float y1,
  74326. const float x2, const float y2,
  74327. const float x3, const float y3)
  74328. {
  74329. startNewSubPath (x1, y1);
  74330. lineTo (x2, y2);
  74331. lineTo (x3, y3);
  74332. closeSubPath();
  74333. }
  74334. void Path::addQuadrilateral (const float x1, const float y1,
  74335. const float x2, const float y2,
  74336. const float x3, const float y3,
  74337. const float x4, const float y4)
  74338. {
  74339. startNewSubPath (x1, y1);
  74340. lineTo (x2, y2);
  74341. lineTo (x3, y3);
  74342. lineTo (x4, y4);
  74343. closeSubPath();
  74344. }
  74345. void Path::addEllipse (const float x, const float y,
  74346. const float w, const float h)
  74347. {
  74348. const float hw = w * 0.5f;
  74349. const float hw55 = hw * 0.55f;
  74350. const float hh = h * 0.5f;
  74351. const float hh45 = hh * 0.55f;
  74352. const float cx = x + hw;
  74353. const float cy = y + hh;
  74354. startNewSubPath (cx, cy - hh);
  74355. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74356. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74357. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74358. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74359. closeSubPath();
  74360. }
  74361. void Path::addArc (const float x, const float y,
  74362. const float w, const float h,
  74363. const float fromRadians,
  74364. const float toRadians,
  74365. const bool startAsNewSubPath)
  74366. {
  74367. const float radiusX = w / 2.0f;
  74368. const float radiusY = h / 2.0f;
  74369. addCentredArc (x + radiusX,
  74370. y + radiusY,
  74371. radiusX, radiusY,
  74372. 0.0f,
  74373. fromRadians, toRadians,
  74374. startAsNewSubPath);
  74375. }
  74376. void Path::addCentredArc (const float centreX, const float centreY,
  74377. const float radiusX, const float radiusY,
  74378. const float rotationOfEllipse,
  74379. const float fromRadians,
  74380. const float toRadians,
  74381. const bool startAsNewSubPath)
  74382. {
  74383. if (radiusX > 0.0f && radiusY > 0.0f)
  74384. {
  74385. const Point<float> centre (centreX, centreY);
  74386. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74387. float angle = fromRadians;
  74388. if (startAsNewSubPath)
  74389. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74390. if (fromRadians < toRadians)
  74391. {
  74392. if (startAsNewSubPath)
  74393. angle += PathHelpers::ellipseAngularIncrement;
  74394. while (angle < toRadians)
  74395. {
  74396. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74397. angle += PathHelpers::ellipseAngularIncrement;
  74398. }
  74399. }
  74400. else
  74401. {
  74402. if (startAsNewSubPath)
  74403. angle -= PathHelpers::ellipseAngularIncrement;
  74404. while (angle > toRadians)
  74405. {
  74406. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74407. angle -= PathHelpers::ellipseAngularIncrement;
  74408. }
  74409. }
  74410. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74411. }
  74412. }
  74413. void Path::addPieSegment (const float x, const float y,
  74414. const float width, const float height,
  74415. const float fromRadians,
  74416. const float toRadians,
  74417. const float innerCircleProportionalSize)
  74418. {
  74419. float radiusX = width * 0.5f;
  74420. float radiusY = height * 0.5f;
  74421. const Point<float> centre (x + radiusX, y + radiusY);
  74422. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74423. addArc (x, y, width, height, fromRadians, toRadians);
  74424. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74425. {
  74426. closeSubPath();
  74427. if (innerCircleProportionalSize > 0)
  74428. {
  74429. radiusX *= innerCircleProportionalSize;
  74430. radiusY *= innerCircleProportionalSize;
  74431. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74432. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74433. }
  74434. }
  74435. else
  74436. {
  74437. if (innerCircleProportionalSize > 0)
  74438. {
  74439. radiusX *= innerCircleProportionalSize;
  74440. radiusY *= innerCircleProportionalSize;
  74441. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74442. }
  74443. else
  74444. {
  74445. lineTo (centre);
  74446. }
  74447. }
  74448. closeSubPath();
  74449. }
  74450. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74451. {
  74452. const Line<float> reversed (line.reversed());
  74453. lineThickness *= 0.5f;
  74454. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74455. lineTo (line.getPointAlongLine (0, -lineThickness));
  74456. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74457. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74458. closeSubPath();
  74459. }
  74460. void Path::addArrow (const Line<float>& line, float lineThickness,
  74461. float arrowheadWidth, float arrowheadLength)
  74462. {
  74463. const Line<float> reversed (line.reversed());
  74464. lineThickness *= 0.5f;
  74465. arrowheadWidth *= 0.5f;
  74466. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74467. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74468. lineTo (line.getPointAlongLine (0, -lineThickness));
  74469. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74470. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74471. lineTo (line.getEnd());
  74472. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74473. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74474. closeSubPath();
  74475. }
  74476. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74477. const float radius, const float startAngle)
  74478. {
  74479. jassert (numberOfSides > 1); // this would be silly.
  74480. if (numberOfSides > 1)
  74481. {
  74482. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74483. for (int i = 0; i < numberOfSides; ++i)
  74484. {
  74485. const float angle = startAngle + i * angleBetweenPoints;
  74486. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74487. if (i == 0)
  74488. startNewSubPath (p);
  74489. else
  74490. lineTo (p);
  74491. }
  74492. closeSubPath();
  74493. }
  74494. }
  74495. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74496. const float innerRadius, const float outerRadius, const float startAngle)
  74497. {
  74498. jassert (numberOfPoints > 1); // this would be silly.
  74499. if (numberOfPoints > 1)
  74500. {
  74501. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74502. for (int i = 0; i < numberOfPoints; ++i)
  74503. {
  74504. const float angle = startAngle + i * angleBetweenPoints;
  74505. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74506. if (i == 0)
  74507. startNewSubPath (p);
  74508. else
  74509. lineTo (p);
  74510. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74511. }
  74512. closeSubPath();
  74513. }
  74514. }
  74515. void Path::addBubble (float x, float y,
  74516. float w, float h,
  74517. float cs,
  74518. float tipX,
  74519. float tipY,
  74520. int whichSide,
  74521. float arrowPos,
  74522. float arrowWidth)
  74523. {
  74524. if (w > 1.0f && h > 1.0f)
  74525. {
  74526. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74527. const float cs2 = 2.0f * cs;
  74528. startNewSubPath (x + cs, y);
  74529. if (whichSide == 0)
  74530. {
  74531. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74532. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74533. lineTo (arrowX1, y);
  74534. lineTo (tipX, tipY);
  74535. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74536. }
  74537. lineTo (x + w - cs, y);
  74538. if (cs > 0.0f)
  74539. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74540. if (whichSide == 3)
  74541. {
  74542. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74543. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74544. lineTo (x + w, arrowY1);
  74545. lineTo (tipX, tipY);
  74546. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74547. }
  74548. lineTo (x + w, y + h - cs);
  74549. if (cs > 0.0f)
  74550. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74551. if (whichSide == 2)
  74552. {
  74553. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74554. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74555. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74556. lineTo (tipX, tipY);
  74557. lineTo (arrowX1, y + h);
  74558. }
  74559. lineTo (x + cs, y + h);
  74560. if (cs > 0.0f)
  74561. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74562. if (whichSide == 1)
  74563. {
  74564. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74565. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74566. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74567. lineTo (tipX, tipY);
  74568. lineTo (x, arrowY1);
  74569. }
  74570. lineTo (x, y + cs);
  74571. if (cs > 0.0f)
  74572. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74573. closeSubPath();
  74574. }
  74575. }
  74576. void Path::addPath (const Path& other)
  74577. {
  74578. size_t i = 0;
  74579. while (i < other.numElements)
  74580. {
  74581. const float type = other.data.elements [i++];
  74582. if (type == moveMarker)
  74583. {
  74584. startNewSubPath (other.data.elements [i],
  74585. other.data.elements [i + 1]);
  74586. i += 2;
  74587. }
  74588. else if (type == lineMarker)
  74589. {
  74590. lineTo (other.data.elements [i],
  74591. other.data.elements [i + 1]);
  74592. i += 2;
  74593. }
  74594. else if (type == quadMarker)
  74595. {
  74596. quadraticTo (other.data.elements [i],
  74597. other.data.elements [i + 1],
  74598. other.data.elements [i + 2],
  74599. other.data.elements [i + 3]);
  74600. i += 4;
  74601. }
  74602. else if (type == cubicMarker)
  74603. {
  74604. cubicTo (other.data.elements [i],
  74605. other.data.elements [i + 1],
  74606. other.data.elements [i + 2],
  74607. other.data.elements [i + 3],
  74608. other.data.elements [i + 4],
  74609. other.data.elements [i + 5]);
  74610. i += 6;
  74611. }
  74612. else if (type == closeSubPathMarker)
  74613. {
  74614. closeSubPath();
  74615. }
  74616. else
  74617. {
  74618. // something's gone wrong with the element list!
  74619. jassertfalse;
  74620. }
  74621. }
  74622. }
  74623. void Path::addPath (const Path& other,
  74624. const AffineTransform& transformToApply)
  74625. {
  74626. size_t i = 0;
  74627. while (i < other.numElements)
  74628. {
  74629. const float type = other.data.elements [i++];
  74630. if (type == closeSubPathMarker)
  74631. {
  74632. closeSubPath();
  74633. }
  74634. else
  74635. {
  74636. float x = other.data.elements [i++];
  74637. float y = other.data.elements [i++];
  74638. transformToApply.transformPoint (x, y);
  74639. if (type == moveMarker)
  74640. {
  74641. startNewSubPath (x, y);
  74642. }
  74643. else if (type == lineMarker)
  74644. {
  74645. lineTo (x, y);
  74646. }
  74647. else if (type == quadMarker)
  74648. {
  74649. float x2 = other.data.elements [i++];
  74650. float y2 = other.data.elements [i++];
  74651. transformToApply.transformPoint (x2, y2);
  74652. quadraticTo (x, y, x2, y2);
  74653. }
  74654. else if (type == cubicMarker)
  74655. {
  74656. float x2 = other.data.elements [i++];
  74657. float y2 = other.data.elements [i++];
  74658. float x3 = other.data.elements [i++];
  74659. float y3 = other.data.elements [i++];
  74660. transformToApply.transformPoints (x2, y2, x3, y3);
  74661. cubicTo (x, y, x2, y2, x3, y3);
  74662. }
  74663. else
  74664. {
  74665. // something's gone wrong with the element list!
  74666. jassertfalse;
  74667. }
  74668. }
  74669. }
  74670. }
  74671. void Path::applyTransform (const AffineTransform& transform) throw()
  74672. {
  74673. size_t i = 0;
  74674. pathYMin = pathXMin = 0;
  74675. pathYMax = pathXMax = 0;
  74676. bool setMaxMin = false;
  74677. while (i < numElements)
  74678. {
  74679. const float type = data.elements [i++];
  74680. if (type == moveMarker)
  74681. {
  74682. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74683. if (setMaxMin)
  74684. {
  74685. pathXMin = jmin (pathXMin, data.elements [i]);
  74686. pathXMax = jmax (pathXMax, data.elements [i]);
  74687. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74688. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74689. }
  74690. else
  74691. {
  74692. pathXMin = pathXMax = data.elements [i];
  74693. pathYMin = pathYMax = data.elements [i + 1];
  74694. setMaxMin = true;
  74695. }
  74696. i += 2;
  74697. }
  74698. else if (type == lineMarker)
  74699. {
  74700. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74701. pathXMin = jmin (pathXMin, data.elements [i]);
  74702. pathXMax = jmax (pathXMax, data.elements [i]);
  74703. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74704. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74705. i += 2;
  74706. }
  74707. else if (type == quadMarker)
  74708. {
  74709. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74710. data.elements [i + 2], data.elements [i + 3]);
  74711. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74712. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74713. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74714. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74715. i += 4;
  74716. }
  74717. else if (type == cubicMarker)
  74718. {
  74719. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74720. data.elements [i + 2], data.elements [i + 3],
  74721. data.elements [i + 4], data.elements [i + 5]);
  74722. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74723. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74724. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74725. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74726. i += 6;
  74727. }
  74728. }
  74729. }
  74730. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74731. const float w, const float h,
  74732. const bool preserveProportions,
  74733. const Justification& justification) const
  74734. {
  74735. Rectangle<float> bounds (getBounds());
  74736. if (preserveProportions)
  74737. {
  74738. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74739. return AffineTransform::identity;
  74740. float newW, newH;
  74741. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74742. if (srcRatio > h / w)
  74743. {
  74744. newW = h / srcRatio;
  74745. newH = h;
  74746. }
  74747. else
  74748. {
  74749. newW = w;
  74750. newH = w * srcRatio;
  74751. }
  74752. float newXCentre = x;
  74753. float newYCentre = y;
  74754. if (justification.testFlags (Justification::left))
  74755. newXCentre += newW * 0.5f;
  74756. else if (justification.testFlags (Justification::right))
  74757. newXCentre += w - newW * 0.5f;
  74758. else
  74759. newXCentre += w * 0.5f;
  74760. if (justification.testFlags (Justification::top))
  74761. newYCentre += newH * 0.5f;
  74762. else if (justification.testFlags (Justification::bottom))
  74763. newYCentre += h - newH * 0.5f;
  74764. else
  74765. newYCentre += h * 0.5f;
  74766. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74767. bounds.getHeight() * -0.5f - bounds.getY())
  74768. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74769. .translated (newXCentre, newYCentre);
  74770. }
  74771. else
  74772. {
  74773. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74774. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74775. .translated (x, y);
  74776. }
  74777. }
  74778. bool Path::contains (const float x, const float y, const float tolerence) const
  74779. {
  74780. if (x <= pathXMin || x >= pathXMax
  74781. || y <= pathYMin || y >= pathYMax)
  74782. return false;
  74783. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74784. int positiveCrossings = 0;
  74785. int negativeCrossings = 0;
  74786. while (i.next())
  74787. {
  74788. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74789. {
  74790. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74791. if (intersectX <= x)
  74792. {
  74793. if (i.y1 < i.y2)
  74794. ++positiveCrossings;
  74795. else
  74796. ++negativeCrossings;
  74797. }
  74798. }
  74799. }
  74800. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74801. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74802. }
  74803. bool Path::contains (const Point<float>& point, const float tolerence) const
  74804. {
  74805. return contains (point.getX(), point.getY(), tolerence);
  74806. }
  74807. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74808. {
  74809. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74810. Point<float> intersection;
  74811. while (i.next())
  74812. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74813. return true;
  74814. return false;
  74815. }
  74816. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74817. {
  74818. Line<float> result (line);
  74819. const bool startInside = contains (line.getStart());
  74820. const bool endInside = contains (line.getEnd());
  74821. if (startInside == endInside)
  74822. {
  74823. if (keepSectionOutsidePath == startInside)
  74824. result = Line<float>();
  74825. }
  74826. else
  74827. {
  74828. PathFlatteningIterator i (*this, AffineTransform::identity);
  74829. Point<float> intersection;
  74830. while (i.next())
  74831. {
  74832. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74833. {
  74834. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74835. result.setStart (intersection);
  74836. else
  74837. result.setEnd (intersection);
  74838. }
  74839. }
  74840. }
  74841. return result;
  74842. }
  74843. float Path::getLength (const AffineTransform& transform) const
  74844. {
  74845. float length = 0;
  74846. PathFlatteningIterator i (*this, transform);
  74847. while (i.next())
  74848. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74849. return length;
  74850. }
  74851. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74852. {
  74853. PathFlatteningIterator i (*this, transform);
  74854. while (i.next())
  74855. {
  74856. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74857. const float lineLength = line.getLength();
  74858. if (distanceFromStart <= lineLength)
  74859. return line.getPointAlongLine (distanceFromStart);
  74860. distanceFromStart -= lineLength;
  74861. }
  74862. return Point<float> (i.x2, i.y2);
  74863. }
  74864. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74865. const AffineTransform& transform) const
  74866. {
  74867. PathFlatteningIterator i (*this, transform);
  74868. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74869. float length = 0;
  74870. Point<float> pointOnLine;
  74871. while (i.next())
  74872. {
  74873. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74874. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74875. if (distance < bestDistance)
  74876. {
  74877. bestDistance = distance;
  74878. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74879. pointOnPath = pointOnLine;
  74880. }
  74881. length += line.getLength();
  74882. }
  74883. return bestPosition;
  74884. }
  74885. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74886. {
  74887. if (cornerRadius <= 0.01f)
  74888. return *this;
  74889. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74890. size_t n = 0;
  74891. bool lastWasLine = false, firstWasLine = false;
  74892. Path p;
  74893. while (n < numElements)
  74894. {
  74895. const float type = data.elements [n++];
  74896. if (type == moveMarker)
  74897. {
  74898. indexOfPathStart = p.numElements;
  74899. indexOfPathStartThis = n - 1;
  74900. const float x = data.elements [n++];
  74901. const float y = data.elements [n++];
  74902. p.startNewSubPath (x, y);
  74903. lastWasLine = false;
  74904. firstWasLine = (data.elements [n] == lineMarker);
  74905. }
  74906. else if (type == lineMarker || type == closeSubPathMarker)
  74907. {
  74908. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74909. if (type == lineMarker)
  74910. {
  74911. endX = data.elements [n++];
  74912. endY = data.elements [n++];
  74913. if (n > 8)
  74914. {
  74915. startX = data.elements [n - 8];
  74916. startY = data.elements [n - 7];
  74917. joinX = data.elements [n - 5];
  74918. joinY = data.elements [n - 4];
  74919. }
  74920. }
  74921. else
  74922. {
  74923. endX = data.elements [indexOfPathStartThis + 1];
  74924. endY = data.elements [indexOfPathStartThis + 2];
  74925. if (n > 6)
  74926. {
  74927. startX = data.elements [n - 6];
  74928. startY = data.elements [n - 5];
  74929. joinX = data.elements [n - 3];
  74930. joinY = data.elements [n - 2];
  74931. }
  74932. }
  74933. if (lastWasLine)
  74934. {
  74935. const double len1 = juce_hypot (startX - joinX,
  74936. startY - joinY);
  74937. if (len1 > 0)
  74938. {
  74939. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74940. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74941. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74942. }
  74943. const double len2 = juce_hypot (endX - joinX,
  74944. endY - joinY);
  74945. if (len2 > 0)
  74946. {
  74947. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74948. p.quadraticTo (joinX, joinY,
  74949. (float) (joinX + (endX - joinX) * propNeeded),
  74950. (float) (joinY + (endY - joinY) * propNeeded));
  74951. }
  74952. p.lineTo (endX, endY);
  74953. }
  74954. else if (type == lineMarker)
  74955. {
  74956. p.lineTo (endX, endY);
  74957. lastWasLine = true;
  74958. }
  74959. if (type == closeSubPathMarker)
  74960. {
  74961. if (firstWasLine)
  74962. {
  74963. startX = data.elements [n - 3];
  74964. startY = data.elements [n - 2];
  74965. joinX = endX;
  74966. joinY = endY;
  74967. endX = data.elements [indexOfPathStartThis + 4];
  74968. endY = data.elements [indexOfPathStartThis + 5];
  74969. const double len1 = juce_hypot (startX - joinX,
  74970. startY - joinY);
  74971. if (len1 > 0)
  74972. {
  74973. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74974. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74975. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74976. }
  74977. const double len2 = juce_hypot (endX - joinX,
  74978. endY - joinY);
  74979. if (len2 > 0)
  74980. {
  74981. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74982. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74983. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74984. p.quadraticTo (joinX, joinY, endX, endY);
  74985. p.data.elements [indexOfPathStart + 1] = endX;
  74986. p.data.elements [indexOfPathStart + 2] = endY;
  74987. }
  74988. }
  74989. p.closeSubPath();
  74990. }
  74991. }
  74992. else if (type == quadMarker)
  74993. {
  74994. lastWasLine = false;
  74995. const float x1 = data.elements [n++];
  74996. const float y1 = data.elements [n++];
  74997. const float x2 = data.elements [n++];
  74998. const float y2 = data.elements [n++];
  74999. p.quadraticTo (x1, y1, x2, y2);
  75000. }
  75001. else if (type == cubicMarker)
  75002. {
  75003. lastWasLine = false;
  75004. const float x1 = data.elements [n++];
  75005. const float y1 = data.elements [n++];
  75006. const float x2 = data.elements [n++];
  75007. const float y2 = data.elements [n++];
  75008. const float x3 = data.elements [n++];
  75009. const float y3 = data.elements [n++];
  75010. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75011. }
  75012. }
  75013. return p;
  75014. }
  75015. void Path::loadPathFromStream (InputStream& source)
  75016. {
  75017. while (! source.isExhausted())
  75018. {
  75019. switch (source.readByte())
  75020. {
  75021. case 'm':
  75022. {
  75023. const float x = source.readFloat();
  75024. const float y = source.readFloat();
  75025. startNewSubPath (x, y);
  75026. break;
  75027. }
  75028. case 'l':
  75029. {
  75030. const float x = source.readFloat();
  75031. const float y = source.readFloat();
  75032. lineTo (x, y);
  75033. break;
  75034. }
  75035. case 'q':
  75036. {
  75037. const float x1 = source.readFloat();
  75038. const float y1 = source.readFloat();
  75039. const float x2 = source.readFloat();
  75040. const float y2 = source.readFloat();
  75041. quadraticTo (x1, y1, x2, y2);
  75042. break;
  75043. }
  75044. case 'b':
  75045. {
  75046. const float x1 = source.readFloat();
  75047. const float y1 = source.readFloat();
  75048. const float x2 = source.readFloat();
  75049. const float y2 = source.readFloat();
  75050. const float x3 = source.readFloat();
  75051. const float y3 = source.readFloat();
  75052. cubicTo (x1, y1, x2, y2, x3, y3);
  75053. break;
  75054. }
  75055. case 'c':
  75056. closeSubPath();
  75057. break;
  75058. case 'n':
  75059. useNonZeroWinding = true;
  75060. break;
  75061. case 'z':
  75062. useNonZeroWinding = false;
  75063. break;
  75064. case 'e':
  75065. return; // end of path marker
  75066. default:
  75067. jassertfalse; // illegal char in the stream
  75068. break;
  75069. }
  75070. }
  75071. }
  75072. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75073. {
  75074. MemoryInputStream in (pathData, numberOfBytes, false);
  75075. loadPathFromStream (in);
  75076. }
  75077. void Path::writePathToStream (OutputStream& dest) const
  75078. {
  75079. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75080. size_t i = 0;
  75081. while (i < numElements)
  75082. {
  75083. const float type = data.elements [i++];
  75084. if (type == moveMarker)
  75085. {
  75086. dest.writeByte ('m');
  75087. dest.writeFloat (data.elements [i++]);
  75088. dest.writeFloat (data.elements [i++]);
  75089. }
  75090. else if (type == lineMarker)
  75091. {
  75092. dest.writeByte ('l');
  75093. dest.writeFloat (data.elements [i++]);
  75094. dest.writeFloat (data.elements [i++]);
  75095. }
  75096. else if (type == quadMarker)
  75097. {
  75098. dest.writeByte ('q');
  75099. dest.writeFloat (data.elements [i++]);
  75100. dest.writeFloat (data.elements [i++]);
  75101. dest.writeFloat (data.elements [i++]);
  75102. dest.writeFloat (data.elements [i++]);
  75103. }
  75104. else if (type == cubicMarker)
  75105. {
  75106. dest.writeByte ('b');
  75107. dest.writeFloat (data.elements [i++]);
  75108. dest.writeFloat (data.elements [i++]);
  75109. dest.writeFloat (data.elements [i++]);
  75110. dest.writeFloat (data.elements [i++]);
  75111. dest.writeFloat (data.elements [i++]);
  75112. dest.writeFloat (data.elements [i++]);
  75113. }
  75114. else if (type == closeSubPathMarker)
  75115. {
  75116. dest.writeByte ('c');
  75117. }
  75118. }
  75119. dest.writeByte ('e'); // marks the end-of-path
  75120. }
  75121. const String Path::toString() const
  75122. {
  75123. MemoryOutputStream s (2048);
  75124. if (! useNonZeroWinding)
  75125. s << 'a';
  75126. size_t i = 0;
  75127. float lastMarker = 0.0f;
  75128. while (i < numElements)
  75129. {
  75130. const float marker = data.elements [i++];
  75131. char markerChar = 0;
  75132. int numCoords = 0;
  75133. if (marker == moveMarker)
  75134. {
  75135. markerChar = 'm';
  75136. numCoords = 2;
  75137. }
  75138. else if (marker == lineMarker)
  75139. {
  75140. markerChar = 'l';
  75141. numCoords = 2;
  75142. }
  75143. else if (marker == quadMarker)
  75144. {
  75145. markerChar = 'q';
  75146. numCoords = 4;
  75147. }
  75148. else if (marker == cubicMarker)
  75149. {
  75150. markerChar = 'c';
  75151. numCoords = 6;
  75152. }
  75153. else
  75154. {
  75155. jassert (marker == closeSubPathMarker);
  75156. markerChar = 'z';
  75157. }
  75158. if (marker != lastMarker)
  75159. {
  75160. if (s.getDataSize() != 0)
  75161. s << ' ';
  75162. s << markerChar;
  75163. lastMarker = marker;
  75164. }
  75165. while (--numCoords >= 0 && i < numElements)
  75166. {
  75167. String coord (data.elements [i++], 3);
  75168. while (coord.endsWithChar ('0') && coord != "0")
  75169. coord = coord.dropLastCharacters (1);
  75170. if (coord.endsWithChar ('.'))
  75171. coord = coord.dropLastCharacters (1);
  75172. if (s.getDataSize() != 0)
  75173. s << ' ';
  75174. s << coord;
  75175. }
  75176. }
  75177. return s.toUTF8();
  75178. }
  75179. void Path::restoreFromString (const String& stringVersion)
  75180. {
  75181. clear();
  75182. setUsingNonZeroWinding (true);
  75183. const juce_wchar* t = stringVersion;
  75184. juce_wchar marker = 'm';
  75185. int numValues = 2;
  75186. float values [6];
  75187. for (;;)
  75188. {
  75189. const String token (PathHelpers::nextToken (t));
  75190. const juce_wchar firstChar = token[0];
  75191. int startNum = 0;
  75192. if (firstChar == 0)
  75193. break;
  75194. if (firstChar == 'm' || firstChar == 'l')
  75195. {
  75196. marker = firstChar;
  75197. numValues = 2;
  75198. }
  75199. else if (firstChar == 'q')
  75200. {
  75201. marker = firstChar;
  75202. numValues = 4;
  75203. }
  75204. else if (firstChar == 'c')
  75205. {
  75206. marker = firstChar;
  75207. numValues = 6;
  75208. }
  75209. else if (firstChar == 'z')
  75210. {
  75211. marker = firstChar;
  75212. numValues = 0;
  75213. }
  75214. else if (firstChar == 'a')
  75215. {
  75216. setUsingNonZeroWinding (false);
  75217. continue;
  75218. }
  75219. else
  75220. {
  75221. ++startNum;
  75222. values [0] = token.getFloatValue();
  75223. }
  75224. for (int i = startNum; i < numValues; ++i)
  75225. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75226. switch (marker)
  75227. {
  75228. case 'm': startNewSubPath (values[0], values[1]); break;
  75229. case 'l': lineTo (values[0], values[1]); break;
  75230. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75231. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75232. case 'z': closeSubPath(); break;
  75233. default: jassertfalse; break; // illegal string format?
  75234. }
  75235. }
  75236. }
  75237. Path::Iterator::Iterator (const Path& path_)
  75238. : path (path_),
  75239. index (0)
  75240. {
  75241. }
  75242. Path::Iterator::~Iterator()
  75243. {
  75244. }
  75245. bool Path::Iterator::next()
  75246. {
  75247. const float* const elements = path.data.elements;
  75248. if (index < path.numElements)
  75249. {
  75250. const float type = elements [index++];
  75251. if (type == moveMarker)
  75252. {
  75253. elementType = startNewSubPath;
  75254. x1 = elements [index++];
  75255. y1 = elements [index++];
  75256. }
  75257. else if (type == lineMarker)
  75258. {
  75259. elementType = lineTo;
  75260. x1 = elements [index++];
  75261. y1 = elements [index++];
  75262. }
  75263. else if (type == quadMarker)
  75264. {
  75265. elementType = quadraticTo;
  75266. x1 = elements [index++];
  75267. y1 = elements [index++];
  75268. x2 = elements [index++];
  75269. y2 = elements [index++];
  75270. }
  75271. else if (type == cubicMarker)
  75272. {
  75273. elementType = cubicTo;
  75274. x1 = elements [index++];
  75275. y1 = elements [index++];
  75276. x2 = elements [index++];
  75277. y2 = elements [index++];
  75278. x3 = elements [index++];
  75279. y3 = elements [index++];
  75280. }
  75281. else if (type == closeSubPathMarker)
  75282. {
  75283. elementType = closePath;
  75284. }
  75285. return true;
  75286. }
  75287. return false;
  75288. }
  75289. END_JUCE_NAMESPACE
  75290. /*** End of inlined file: juce_Path.cpp ***/
  75291. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75292. BEGIN_JUCE_NAMESPACE
  75293. #if JUCE_MSVC && JUCE_DEBUG
  75294. #pragma optimize ("t", on)
  75295. #endif
  75296. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75297. const AffineTransform& transform_,
  75298. float tolerence_)
  75299. : x2 (0),
  75300. y2 (0),
  75301. closesSubPath (false),
  75302. subPathIndex (-1),
  75303. path (path_),
  75304. transform (transform_),
  75305. points (path_.data.elements),
  75306. tolerence (tolerence_ * tolerence_),
  75307. subPathCloseX (0),
  75308. subPathCloseY (0),
  75309. isIdentityTransform (transform_.isIdentity()),
  75310. stackBase (32),
  75311. index (0),
  75312. stackSize (32)
  75313. {
  75314. stackPos = stackBase;
  75315. }
  75316. PathFlatteningIterator::~PathFlatteningIterator()
  75317. {
  75318. }
  75319. bool PathFlatteningIterator::next()
  75320. {
  75321. x1 = x2;
  75322. y1 = y2;
  75323. float x3 = 0;
  75324. float y3 = 0;
  75325. float x4 = 0;
  75326. float y4 = 0;
  75327. float type;
  75328. for (;;)
  75329. {
  75330. if (stackPos == stackBase)
  75331. {
  75332. if (index >= path.numElements)
  75333. {
  75334. return false;
  75335. }
  75336. else
  75337. {
  75338. type = points [index++];
  75339. if (type != Path::closeSubPathMarker)
  75340. {
  75341. x2 = points [index++];
  75342. y2 = points [index++];
  75343. if (type == Path::quadMarker)
  75344. {
  75345. x3 = points [index++];
  75346. y3 = points [index++];
  75347. if (! isIdentityTransform)
  75348. transform.transformPoints (x2, y2, x3, y3);
  75349. }
  75350. else if (type == Path::cubicMarker)
  75351. {
  75352. x3 = points [index++];
  75353. y3 = points [index++];
  75354. x4 = points [index++];
  75355. y4 = points [index++];
  75356. if (! isIdentityTransform)
  75357. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75358. }
  75359. else
  75360. {
  75361. if (! isIdentityTransform)
  75362. transform.transformPoint (x2, y2);
  75363. }
  75364. }
  75365. }
  75366. }
  75367. else
  75368. {
  75369. type = *--stackPos;
  75370. if (type != Path::closeSubPathMarker)
  75371. {
  75372. x2 = *--stackPos;
  75373. y2 = *--stackPos;
  75374. if (type == Path::quadMarker)
  75375. {
  75376. x3 = *--stackPos;
  75377. y3 = *--stackPos;
  75378. }
  75379. else if (type == Path::cubicMarker)
  75380. {
  75381. x3 = *--stackPos;
  75382. y3 = *--stackPos;
  75383. x4 = *--stackPos;
  75384. y4 = *--stackPos;
  75385. }
  75386. }
  75387. }
  75388. if (type == Path::lineMarker)
  75389. {
  75390. ++subPathIndex;
  75391. closesSubPath = (stackPos == stackBase)
  75392. && (index < path.numElements)
  75393. && (points [index] == Path::closeSubPathMarker)
  75394. && x2 == subPathCloseX
  75395. && y2 == subPathCloseY;
  75396. return true;
  75397. }
  75398. else if (type == Path::quadMarker)
  75399. {
  75400. const size_t offset = (size_t) (stackPos - stackBase);
  75401. if (offset >= stackSize - 10)
  75402. {
  75403. stackSize <<= 1;
  75404. stackBase.realloc (stackSize);
  75405. stackPos = stackBase + offset;
  75406. }
  75407. const float dx1 = x1 - x2;
  75408. const float dy1 = y1 - y2;
  75409. const float dx2 = x2 - x3;
  75410. const float dy2 = y2 - y3;
  75411. const float m1x = (x1 + x2) * 0.5f;
  75412. const float m1y = (y1 + y2) * 0.5f;
  75413. const float m2x = (x2 + x3) * 0.5f;
  75414. const float m2y = (y2 + y3) * 0.5f;
  75415. const float m3x = (m1x + m2x) * 0.5f;
  75416. const float m3y = (m1y + m2y) * 0.5f;
  75417. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75418. {
  75419. *stackPos++ = y3;
  75420. *stackPos++ = x3;
  75421. *stackPos++ = m2y;
  75422. *stackPos++ = m2x;
  75423. *stackPos++ = Path::quadMarker;
  75424. *stackPos++ = m3y;
  75425. *stackPos++ = m3x;
  75426. *stackPos++ = m1y;
  75427. *stackPos++ = m1x;
  75428. *stackPos++ = Path::quadMarker;
  75429. }
  75430. else
  75431. {
  75432. *stackPos++ = y3;
  75433. *stackPos++ = x3;
  75434. *stackPos++ = Path::lineMarker;
  75435. *stackPos++ = m3y;
  75436. *stackPos++ = m3x;
  75437. *stackPos++ = Path::lineMarker;
  75438. }
  75439. jassert (stackPos < stackBase + stackSize);
  75440. }
  75441. else if (type == Path::cubicMarker)
  75442. {
  75443. const size_t offset = (size_t) (stackPos - stackBase);
  75444. if (offset >= stackSize - 16)
  75445. {
  75446. stackSize <<= 1;
  75447. stackBase.realloc (stackSize);
  75448. stackPos = stackBase + offset;
  75449. }
  75450. const float dx1 = x1 - x2;
  75451. const float dy1 = y1 - y2;
  75452. const float dx2 = x2 - x3;
  75453. const float dy2 = y2 - y3;
  75454. const float dx3 = x3 - x4;
  75455. const float dy3 = y3 - y4;
  75456. const float m1x = (x1 + x2) * 0.5f;
  75457. const float m1y = (y1 + y2) * 0.5f;
  75458. const float m2x = (x3 + x2) * 0.5f;
  75459. const float m2y = (y3 + y2) * 0.5f;
  75460. const float m3x = (x3 + x4) * 0.5f;
  75461. const float m3y = (y3 + y4) * 0.5f;
  75462. const float m4x = (m1x + m2x) * 0.5f;
  75463. const float m4y = (m1y + m2y) * 0.5f;
  75464. const float m5x = (m3x + m2x) * 0.5f;
  75465. const float m5y = (m3y + m2y) * 0.5f;
  75466. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75467. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75468. {
  75469. *stackPos++ = y4;
  75470. *stackPos++ = x4;
  75471. *stackPos++ = m3y;
  75472. *stackPos++ = m3x;
  75473. *stackPos++ = m5y;
  75474. *stackPos++ = m5x;
  75475. *stackPos++ = Path::cubicMarker;
  75476. *stackPos++ = (m4y + m5y) * 0.5f;
  75477. *stackPos++ = (m4x + m5x) * 0.5f;
  75478. *stackPos++ = m4y;
  75479. *stackPos++ = m4x;
  75480. *stackPos++ = m1y;
  75481. *stackPos++ = m1x;
  75482. *stackPos++ = Path::cubicMarker;
  75483. }
  75484. else
  75485. {
  75486. *stackPos++ = y4;
  75487. *stackPos++ = x4;
  75488. *stackPos++ = Path::lineMarker;
  75489. *stackPos++ = m5y;
  75490. *stackPos++ = m5x;
  75491. *stackPos++ = Path::lineMarker;
  75492. *stackPos++ = m4y;
  75493. *stackPos++ = m4x;
  75494. *stackPos++ = Path::lineMarker;
  75495. }
  75496. }
  75497. else if (type == Path::closeSubPathMarker)
  75498. {
  75499. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75500. {
  75501. x1 = x2;
  75502. y1 = y2;
  75503. x2 = subPathCloseX;
  75504. y2 = subPathCloseY;
  75505. closesSubPath = true;
  75506. return true;
  75507. }
  75508. }
  75509. else
  75510. {
  75511. jassert (type == Path::moveMarker);
  75512. subPathIndex = -1;
  75513. subPathCloseX = x1 = x2;
  75514. subPathCloseY = y1 = y2;
  75515. }
  75516. }
  75517. }
  75518. #if JUCE_MSVC && JUCE_DEBUG
  75519. #pragma optimize ("", on) // resets optimisations to the project defaults
  75520. #endif
  75521. END_JUCE_NAMESPACE
  75522. /*** End of inlined file: juce_PathIterator.cpp ***/
  75523. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75524. BEGIN_JUCE_NAMESPACE
  75525. PathStrokeType::PathStrokeType (const float strokeThickness,
  75526. const JointStyle jointStyle_,
  75527. const EndCapStyle endStyle_) throw()
  75528. : thickness (strokeThickness),
  75529. jointStyle (jointStyle_),
  75530. endStyle (endStyle_)
  75531. {
  75532. }
  75533. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75534. : thickness (other.thickness),
  75535. jointStyle (other.jointStyle),
  75536. endStyle (other.endStyle)
  75537. {
  75538. }
  75539. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75540. {
  75541. thickness = other.thickness;
  75542. jointStyle = other.jointStyle;
  75543. endStyle = other.endStyle;
  75544. return *this;
  75545. }
  75546. PathStrokeType::~PathStrokeType() throw()
  75547. {
  75548. }
  75549. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75550. {
  75551. return thickness == other.thickness
  75552. && jointStyle == other.jointStyle
  75553. && endStyle == other.endStyle;
  75554. }
  75555. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75556. {
  75557. return ! operator== (other);
  75558. }
  75559. namespace PathStrokeHelpers
  75560. {
  75561. static bool lineIntersection (const float x1, const float y1,
  75562. const float x2, const float y2,
  75563. const float x3, const float y3,
  75564. const float x4, const float y4,
  75565. float& intersectionX,
  75566. float& intersectionY,
  75567. float& distanceBeyondLine1EndSquared) throw()
  75568. {
  75569. if (x2 != x3 || y2 != y3)
  75570. {
  75571. const float dx1 = x2 - x1;
  75572. const float dy1 = y2 - y1;
  75573. const float dx2 = x4 - x3;
  75574. const float dy2 = y4 - y3;
  75575. const float divisor = dx1 * dy2 - dx2 * dy1;
  75576. if (divisor == 0)
  75577. {
  75578. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75579. {
  75580. if (dy1 == 0 && dy2 != 0)
  75581. {
  75582. const float along = (y1 - y3) / dy2;
  75583. intersectionX = x3 + along * dx2;
  75584. intersectionY = y1;
  75585. distanceBeyondLine1EndSquared = intersectionX - x2;
  75586. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75587. if ((x2 > x1) == (intersectionX < x2))
  75588. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75589. return along >= 0 && along <= 1.0f;
  75590. }
  75591. else if (dy2 == 0 && dy1 != 0)
  75592. {
  75593. const float along = (y3 - y1) / dy1;
  75594. intersectionX = x1 + along * dx1;
  75595. intersectionY = y3;
  75596. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75597. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75598. if (along < 1.0f)
  75599. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75600. return along >= 0 && along <= 1.0f;
  75601. }
  75602. else if (dx1 == 0 && dx2 != 0)
  75603. {
  75604. const float along = (x1 - x3) / dx2;
  75605. intersectionX = x1;
  75606. intersectionY = y3 + along * dy2;
  75607. distanceBeyondLine1EndSquared = intersectionY - y2;
  75608. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75609. if ((y2 > y1) == (intersectionY < y2))
  75610. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75611. return along >= 0 && along <= 1.0f;
  75612. }
  75613. else if (dx2 == 0 && dx1 != 0)
  75614. {
  75615. const float along = (x3 - x1) / dx1;
  75616. intersectionX = x3;
  75617. intersectionY = y1 + along * dy1;
  75618. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75619. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75620. if (along < 1.0f)
  75621. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75622. return along >= 0 && along <= 1.0f;
  75623. }
  75624. }
  75625. intersectionX = 0.5f * (x2 + x3);
  75626. intersectionY = 0.5f * (y2 + y3);
  75627. distanceBeyondLine1EndSquared = 0.0f;
  75628. return false;
  75629. }
  75630. else
  75631. {
  75632. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75633. intersectionX = x1 + along1 * dx1;
  75634. intersectionY = y1 + along1 * dy1;
  75635. if (along1 >= 0 && along1 <= 1.0f)
  75636. {
  75637. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75638. if (along2 >= 0 && along2 <= divisor)
  75639. {
  75640. distanceBeyondLine1EndSquared = 0.0f;
  75641. return true;
  75642. }
  75643. }
  75644. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75645. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75646. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75647. if (along1 < 1.0f)
  75648. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75649. return false;
  75650. }
  75651. }
  75652. intersectionX = x2;
  75653. intersectionY = y2;
  75654. distanceBeyondLine1EndSquared = 0.0f;
  75655. return true;
  75656. }
  75657. static void addEdgeAndJoint (Path& destPath,
  75658. const PathStrokeType::JointStyle style,
  75659. const float maxMiterExtensionSquared, const float width,
  75660. const float x1, const float y1,
  75661. const float x2, const float y2,
  75662. const float x3, const float y3,
  75663. const float x4, const float y4,
  75664. const float midX, const float midY)
  75665. {
  75666. if (style == PathStrokeType::beveled
  75667. || (x3 == x4 && y3 == y4)
  75668. || (x1 == x2 && y1 == y2))
  75669. {
  75670. destPath.lineTo (x2, y2);
  75671. destPath.lineTo (x3, y3);
  75672. }
  75673. else
  75674. {
  75675. float jx, jy, distanceBeyondLine1EndSquared;
  75676. // if they intersect, use this point..
  75677. if (lineIntersection (x1, y1, x2, y2,
  75678. x3, y3, x4, y4,
  75679. jx, jy, distanceBeyondLine1EndSquared))
  75680. {
  75681. destPath.lineTo (jx, jy);
  75682. }
  75683. else
  75684. {
  75685. if (style == PathStrokeType::mitered)
  75686. {
  75687. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75688. && distanceBeyondLine1EndSquared > 0.0f)
  75689. {
  75690. destPath.lineTo (jx, jy);
  75691. }
  75692. else
  75693. {
  75694. // the end sticks out too far, so just use a blunt joint
  75695. destPath.lineTo (x2, y2);
  75696. destPath.lineTo (x3, y3);
  75697. }
  75698. }
  75699. else
  75700. {
  75701. // curved joints
  75702. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75703. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75704. const float angleIncrement = 0.1f;
  75705. destPath.lineTo (x2, y2);
  75706. if (std::abs (angle1 - angle2) > angleIncrement)
  75707. {
  75708. if (angle2 > angle1 + float_Pi
  75709. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75710. {
  75711. if (angle2 > angle1)
  75712. angle2 -= float_Pi * 2.0f;
  75713. jassert (angle1 <= angle2 + float_Pi);
  75714. angle1 -= angleIncrement;
  75715. while (angle1 > angle2)
  75716. {
  75717. destPath.lineTo (midX + width * std::sin (angle1),
  75718. midY + width * std::cos (angle1));
  75719. angle1 -= angleIncrement;
  75720. }
  75721. }
  75722. else
  75723. {
  75724. if (angle1 > angle2)
  75725. angle1 -= float_Pi * 2.0f;
  75726. jassert (angle1 >= angle2 - float_Pi);
  75727. angle1 += angleIncrement;
  75728. while (angle1 < angle2)
  75729. {
  75730. destPath.lineTo (midX + width * std::sin (angle1),
  75731. midY + width * std::cos (angle1));
  75732. angle1 += angleIncrement;
  75733. }
  75734. }
  75735. }
  75736. destPath.lineTo (x3, y3);
  75737. }
  75738. }
  75739. }
  75740. }
  75741. static void addLineEnd (Path& destPath,
  75742. const PathStrokeType::EndCapStyle style,
  75743. const float x1, const float y1,
  75744. const float x2, const float y2,
  75745. const float width)
  75746. {
  75747. if (style == PathStrokeType::butt)
  75748. {
  75749. destPath.lineTo (x2, y2);
  75750. }
  75751. else
  75752. {
  75753. float offx1, offy1, offx2, offy2;
  75754. float dx = x2 - x1;
  75755. float dy = y2 - y1;
  75756. const float len = juce_hypotf (dx, dy);
  75757. if (len == 0)
  75758. {
  75759. offx1 = offx2 = x1;
  75760. offy1 = offy2 = y1;
  75761. }
  75762. else
  75763. {
  75764. const float offset = width / len;
  75765. dx *= offset;
  75766. dy *= offset;
  75767. offx1 = x1 + dy;
  75768. offy1 = y1 - dx;
  75769. offx2 = x2 + dy;
  75770. offy2 = y2 - dx;
  75771. }
  75772. if (style == PathStrokeType::square)
  75773. {
  75774. // sqaure ends
  75775. destPath.lineTo (offx1, offy1);
  75776. destPath.lineTo (offx2, offy2);
  75777. destPath.lineTo (x2, y2);
  75778. }
  75779. else
  75780. {
  75781. // rounded ends
  75782. const float midx = (offx1 + offx2) * 0.5f;
  75783. const float midy = (offy1 + offy2) * 0.5f;
  75784. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75785. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75786. midx, midy);
  75787. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75788. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75789. x2, y2);
  75790. }
  75791. }
  75792. }
  75793. struct Arrowhead
  75794. {
  75795. float startWidth, startLength;
  75796. float endWidth, endLength;
  75797. };
  75798. static void addArrowhead (Path& destPath,
  75799. const float x1, const float y1,
  75800. const float x2, const float y2,
  75801. const float tipX, const float tipY,
  75802. const float width,
  75803. const float arrowheadWidth)
  75804. {
  75805. Line<float> line (x1, y1, x2, y2);
  75806. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75807. destPath.lineTo (tipX, tipY);
  75808. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75809. destPath.lineTo (x2, y2);
  75810. }
  75811. struct LineSection
  75812. {
  75813. float x1, y1, x2, y2; // original line
  75814. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75815. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75816. };
  75817. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75818. {
  75819. while (amountAtEnd > 0 && subPath.size() > 0)
  75820. {
  75821. LineSection& l = subPath.getReference (subPath.size() - 1);
  75822. float dx = l.rx2 - l.rx1;
  75823. float dy = l.ry2 - l.ry1;
  75824. const float len = juce_hypotf (dx, dy);
  75825. if (len <= amountAtEnd && subPath.size() > 1)
  75826. {
  75827. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75828. prev.x2 = l.x2;
  75829. prev.y2 = l.y2;
  75830. subPath.removeLast();
  75831. amountAtEnd -= len;
  75832. }
  75833. else
  75834. {
  75835. const float prop = jmin (0.9999f, amountAtEnd / len);
  75836. dx *= prop;
  75837. dy *= prop;
  75838. l.rx1 += dx;
  75839. l.ry1 += dy;
  75840. l.lx2 += dx;
  75841. l.ly2 += dy;
  75842. break;
  75843. }
  75844. }
  75845. while (amountAtStart > 0 && subPath.size() > 0)
  75846. {
  75847. LineSection& l = subPath.getReference (0);
  75848. float dx = l.rx2 - l.rx1;
  75849. float dy = l.ry2 - l.ry1;
  75850. const float len = juce_hypotf (dx, dy);
  75851. if (len <= amountAtStart && subPath.size() > 1)
  75852. {
  75853. LineSection& next = subPath.getReference (1);
  75854. next.x1 = l.x1;
  75855. next.y1 = l.y1;
  75856. subPath.remove (0);
  75857. amountAtStart -= len;
  75858. }
  75859. else
  75860. {
  75861. const float prop = jmin (0.9999f, amountAtStart / len);
  75862. dx *= prop;
  75863. dy *= prop;
  75864. l.rx2 -= dx;
  75865. l.ry2 -= dy;
  75866. l.lx1 -= dx;
  75867. l.ly1 -= dy;
  75868. break;
  75869. }
  75870. }
  75871. }
  75872. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75873. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75874. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75875. const Arrowhead* const arrowhead)
  75876. {
  75877. jassert (subPath.size() > 0);
  75878. if (arrowhead != 0)
  75879. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75880. const LineSection& firstLine = subPath.getReference (0);
  75881. float lastX1 = firstLine.lx1;
  75882. float lastY1 = firstLine.ly1;
  75883. float lastX2 = firstLine.lx2;
  75884. float lastY2 = firstLine.ly2;
  75885. if (isClosed)
  75886. {
  75887. destPath.startNewSubPath (lastX1, lastY1);
  75888. }
  75889. else
  75890. {
  75891. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75892. if (arrowhead != 0)
  75893. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75894. width, arrowhead->startWidth);
  75895. else
  75896. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75897. }
  75898. int i;
  75899. for (i = 1; i < subPath.size(); ++i)
  75900. {
  75901. const LineSection& l = subPath.getReference (i);
  75902. addEdgeAndJoint (destPath, jointStyle,
  75903. maxMiterExtensionSquared, width,
  75904. lastX1, lastY1, lastX2, lastY2,
  75905. l.lx1, l.ly1, l.lx2, l.ly2,
  75906. l.x1, l.y1);
  75907. lastX1 = l.lx1;
  75908. lastY1 = l.ly1;
  75909. lastX2 = l.lx2;
  75910. lastY2 = l.ly2;
  75911. }
  75912. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75913. if (isClosed)
  75914. {
  75915. const LineSection& l = subPath.getReference (0);
  75916. addEdgeAndJoint (destPath, jointStyle,
  75917. maxMiterExtensionSquared, width,
  75918. lastX1, lastY1, lastX2, lastY2,
  75919. l.lx1, l.ly1, l.lx2, l.ly2,
  75920. l.x1, l.y1);
  75921. destPath.closeSubPath();
  75922. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75923. }
  75924. else
  75925. {
  75926. destPath.lineTo (lastX2, lastY2);
  75927. if (arrowhead != 0)
  75928. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75929. width, arrowhead->endWidth);
  75930. else
  75931. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75932. }
  75933. lastX1 = lastLine.rx1;
  75934. lastY1 = lastLine.ry1;
  75935. lastX2 = lastLine.rx2;
  75936. lastY2 = lastLine.ry2;
  75937. for (i = subPath.size() - 1; --i >= 0;)
  75938. {
  75939. const LineSection& l = subPath.getReference (i);
  75940. addEdgeAndJoint (destPath, jointStyle,
  75941. maxMiterExtensionSquared, width,
  75942. lastX1, lastY1, lastX2, lastY2,
  75943. l.rx1, l.ry1, l.rx2, l.ry2,
  75944. l.x2, l.y2);
  75945. lastX1 = l.rx1;
  75946. lastY1 = l.ry1;
  75947. lastX2 = l.rx2;
  75948. lastY2 = l.ry2;
  75949. }
  75950. if (isClosed)
  75951. {
  75952. addEdgeAndJoint (destPath, jointStyle,
  75953. maxMiterExtensionSquared, width,
  75954. lastX1, lastY1, lastX2, lastY2,
  75955. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75956. lastLine.x2, lastLine.y2);
  75957. }
  75958. else
  75959. {
  75960. // do the last line
  75961. destPath.lineTo (lastX2, lastY2);
  75962. }
  75963. destPath.closeSubPath();
  75964. }
  75965. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75966. const PathStrokeType::EndCapStyle endStyle,
  75967. Path& destPath, const Path& source,
  75968. const AffineTransform& transform,
  75969. const float extraAccuracy, const Arrowhead* const arrowhead)
  75970. {
  75971. if (thickness <= 0)
  75972. {
  75973. destPath.clear();
  75974. return;
  75975. }
  75976. const Path* sourcePath = &source;
  75977. Path temp;
  75978. if (sourcePath == &destPath)
  75979. {
  75980. destPath.swapWithPath (temp);
  75981. sourcePath = &temp;
  75982. }
  75983. else
  75984. {
  75985. destPath.clear();
  75986. }
  75987. destPath.setUsingNonZeroWinding (true);
  75988. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75989. const float width = 0.5f * thickness;
  75990. // Iterate the path, creating a list of the
  75991. // left/right-hand lines along either side of it...
  75992. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75993. Array <LineSection> subPath;
  75994. subPath.ensureStorageAllocated (512);
  75995. LineSection l;
  75996. l.x1 = 0;
  75997. l.y1 = 0;
  75998. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75999. while (it.next())
  76000. {
  76001. if (it.subPathIndex == 0)
  76002. {
  76003. if (subPath.size() > 0)
  76004. {
  76005. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76006. subPath.clearQuick();
  76007. }
  76008. l.x1 = it.x1;
  76009. l.y1 = it.y1;
  76010. }
  76011. l.x2 = it.x2;
  76012. l.y2 = it.y2;
  76013. float dx = l.x2 - l.x1;
  76014. float dy = l.y2 - l.y1;
  76015. const float hypotSquared = dx*dx + dy*dy;
  76016. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76017. {
  76018. const float len = std::sqrt (hypotSquared);
  76019. if (len == 0)
  76020. {
  76021. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76022. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76023. }
  76024. else
  76025. {
  76026. const float offset = width / len;
  76027. dx *= offset;
  76028. dy *= offset;
  76029. l.rx2 = l.x1 - dy;
  76030. l.ry2 = l.y1 + dx;
  76031. l.lx1 = l.x1 + dy;
  76032. l.ly1 = l.y1 - dx;
  76033. l.lx2 = l.x2 + dy;
  76034. l.ly2 = l.y2 - dx;
  76035. l.rx1 = l.x2 - dy;
  76036. l.ry1 = l.y2 + dx;
  76037. }
  76038. subPath.add (l);
  76039. if (it.closesSubPath)
  76040. {
  76041. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76042. subPath.clearQuick();
  76043. }
  76044. else
  76045. {
  76046. l.x1 = it.x2;
  76047. l.y1 = it.y2;
  76048. }
  76049. }
  76050. }
  76051. if (subPath.size() > 0)
  76052. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76053. }
  76054. }
  76055. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76056. const AffineTransform& transform, const float extraAccuracy) const
  76057. {
  76058. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76059. transform, extraAccuracy, 0);
  76060. }
  76061. void PathStrokeType::createDashedStroke (Path& destPath,
  76062. const Path& sourcePath,
  76063. const float* dashLengths,
  76064. int numDashLengths,
  76065. const AffineTransform& transform,
  76066. const float extraAccuracy) const
  76067. {
  76068. if (thickness <= 0)
  76069. return;
  76070. // this should really be an even number..
  76071. jassert ((numDashLengths & 1) == 0);
  76072. Path newDestPath;
  76073. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76074. bool first = true;
  76075. int dashNum = 0;
  76076. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76077. float dx = 0.0f, dy = 0.0f;
  76078. for (;;)
  76079. {
  76080. const bool isSolid = ((dashNum & 1) == 0);
  76081. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76082. jassert (dashLen > 0); // must be a positive increment!
  76083. if (dashLen <= 0)
  76084. break;
  76085. pos += dashLen;
  76086. while (pos > lineEndPos)
  76087. {
  76088. if (! it.next())
  76089. {
  76090. if (isSolid && ! first)
  76091. newDestPath.lineTo (it.x2, it.y2);
  76092. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76093. return;
  76094. }
  76095. if (isSolid && ! first)
  76096. newDestPath.lineTo (it.x1, it.y1);
  76097. else
  76098. newDestPath.startNewSubPath (it.x1, it.y1);
  76099. dx = it.x2 - it.x1;
  76100. dy = it.y2 - it.y1;
  76101. lineLen = juce_hypotf (dx, dy);
  76102. lineEndPos += lineLen;
  76103. first = it.closesSubPath;
  76104. }
  76105. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76106. if (isSolid)
  76107. newDestPath.lineTo (it.x1 + dx * alpha,
  76108. it.y1 + dy * alpha);
  76109. else
  76110. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76111. it.y1 + dy * alpha);
  76112. }
  76113. }
  76114. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76115. const Path& sourcePath,
  76116. const float arrowheadStartWidth, const float arrowheadStartLength,
  76117. const float arrowheadEndWidth, const float arrowheadEndLength,
  76118. const AffineTransform& transform,
  76119. const float extraAccuracy) const
  76120. {
  76121. PathStrokeHelpers::Arrowhead head;
  76122. head.startWidth = arrowheadStartWidth;
  76123. head.startLength = arrowheadStartLength;
  76124. head.endWidth = arrowheadEndWidth;
  76125. head.endLength = arrowheadEndLength;
  76126. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76127. destPath, sourcePath, transform, extraAccuracy, &head);
  76128. }
  76129. END_JUCE_NAMESPACE
  76130. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76131. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76132. BEGIN_JUCE_NAMESPACE
  76133. PositionedRectangle::PositionedRectangle() throw()
  76134. : x (0.0),
  76135. y (0.0),
  76136. w (0.0),
  76137. h (0.0),
  76138. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76139. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76140. wMode (absoluteSize),
  76141. hMode (absoluteSize)
  76142. {
  76143. }
  76144. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76145. : x (other.x),
  76146. y (other.y),
  76147. w (other.w),
  76148. h (other.h),
  76149. xMode (other.xMode),
  76150. yMode (other.yMode),
  76151. wMode (other.wMode),
  76152. hMode (other.hMode)
  76153. {
  76154. }
  76155. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76156. {
  76157. x = other.x;
  76158. y = other.y;
  76159. w = other.w;
  76160. h = other.h;
  76161. xMode = other.xMode;
  76162. yMode = other.yMode;
  76163. wMode = other.wMode;
  76164. hMode = other.hMode;
  76165. return *this;
  76166. }
  76167. PositionedRectangle::~PositionedRectangle() throw()
  76168. {
  76169. }
  76170. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76171. {
  76172. return x == other.x
  76173. && y == other.y
  76174. && w == other.w
  76175. && h == other.h
  76176. && xMode == other.xMode
  76177. && yMode == other.yMode
  76178. && wMode == other.wMode
  76179. && hMode == other.hMode;
  76180. }
  76181. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76182. {
  76183. return ! operator== (other);
  76184. }
  76185. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76186. {
  76187. StringArray tokens;
  76188. tokens.addTokens (stringVersion, false);
  76189. decodePosString (tokens [0], xMode, x);
  76190. decodePosString (tokens [1], yMode, y);
  76191. decodeSizeString (tokens [2], wMode, w);
  76192. decodeSizeString (tokens [3], hMode, h);
  76193. }
  76194. const String PositionedRectangle::toString() const throw()
  76195. {
  76196. String s;
  76197. s.preallocateStorage (12);
  76198. addPosDescription (s, xMode, x);
  76199. s << ' ';
  76200. addPosDescription (s, yMode, y);
  76201. s << ' ';
  76202. addSizeDescription (s, wMode, w);
  76203. s << ' ';
  76204. addSizeDescription (s, hMode, h);
  76205. return s;
  76206. }
  76207. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76208. {
  76209. jassert (! target.isEmpty());
  76210. double x_, y_, w_, h_;
  76211. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76212. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76213. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76214. roundToInt (w_), roundToInt (h_));
  76215. }
  76216. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76217. double& x_, double& y_,
  76218. double& w_, double& h_) const throw()
  76219. {
  76220. jassert (! target.isEmpty());
  76221. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76222. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76223. }
  76224. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76225. {
  76226. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76227. }
  76228. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76229. const Rectangle<int>& target) throw()
  76230. {
  76231. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76232. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76233. }
  76234. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76235. const double newW, const double newH,
  76236. const Rectangle<int>& target) throw()
  76237. {
  76238. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76239. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76240. }
  76241. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76242. {
  76243. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76244. updateFrom (comp.getBounds(), Rectangle<int>());
  76245. else
  76246. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76247. }
  76248. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76249. {
  76250. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76251. }
  76252. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76253. {
  76254. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76255. | absoluteFromParentBottomRight
  76256. | absoluteFromParentCentre
  76257. | proportionOfParentSize));
  76258. }
  76259. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76260. {
  76261. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76262. }
  76263. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76264. {
  76265. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76266. | absoluteFromParentBottomRight
  76267. | absoluteFromParentCentre
  76268. | proportionOfParentSize));
  76269. }
  76270. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76271. {
  76272. return (SizeMode) wMode;
  76273. }
  76274. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76275. {
  76276. return (SizeMode) hMode;
  76277. }
  76278. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76279. const PositionMode xMode_,
  76280. const AnchorPoint yAnchor,
  76281. const PositionMode yMode_,
  76282. const SizeMode widthMode,
  76283. const SizeMode heightMode,
  76284. const Rectangle<int>& target) throw()
  76285. {
  76286. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76287. {
  76288. double tx, tw;
  76289. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76290. xMode = (uint8) (xAnchor | xMode_);
  76291. wMode = (uint8) widthMode;
  76292. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76293. }
  76294. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76295. {
  76296. double ty, th;
  76297. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76298. yMode = (uint8) (yAnchor | yMode_);
  76299. hMode = (uint8) heightMode;
  76300. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76301. }
  76302. }
  76303. bool PositionedRectangle::isPositionAbsolute() const throw()
  76304. {
  76305. return xMode == absoluteFromParentTopLeft
  76306. && yMode == absoluteFromParentTopLeft
  76307. && wMode == absoluteSize
  76308. && hMode == absoluteSize;
  76309. }
  76310. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76311. {
  76312. if ((mode & proportionOfParentSize) != 0)
  76313. {
  76314. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76315. }
  76316. else
  76317. {
  76318. s << (roundToInt (value * 100.0) / 100.0);
  76319. if ((mode & absoluteFromParentBottomRight) != 0)
  76320. s << 'R';
  76321. else if ((mode & absoluteFromParentCentre) != 0)
  76322. s << 'C';
  76323. }
  76324. if ((mode & anchorAtRightOrBottom) != 0)
  76325. s << 'r';
  76326. else if ((mode & anchorAtCentre) != 0)
  76327. s << 'c';
  76328. }
  76329. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76330. {
  76331. if (mode == proportionalSize)
  76332. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76333. else if (mode == parentSizeMinusAbsolute)
  76334. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76335. else
  76336. s << (roundToInt (value * 100.0) / 100.0);
  76337. }
  76338. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76339. {
  76340. if (s.containsChar ('r'))
  76341. mode = anchorAtRightOrBottom;
  76342. else if (s.containsChar ('c'))
  76343. mode = anchorAtCentre;
  76344. else
  76345. mode = anchorAtLeftOrTop;
  76346. if (s.containsChar ('%'))
  76347. {
  76348. mode |= proportionOfParentSize;
  76349. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76350. }
  76351. else
  76352. {
  76353. if (s.containsChar ('R'))
  76354. mode |= absoluteFromParentBottomRight;
  76355. else if (s.containsChar ('C'))
  76356. mode |= absoluteFromParentCentre;
  76357. else
  76358. mode |= absoluteFromParentTopLeft;
  76359. value = s.removeCharacters ("rcRC").getDoubleValue();
  76360. }
  76361. }
  76362. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76363. {
  76364. if (s.containsChar ('%'))
  76365. {
  76366. mode = proportionalSize;
  76367. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76368. }
  76369. else if (s.containsChar ('M'))
  76370. {
  76371. mode = parentSizeMinusAbsolute;
  76372. value = s.getDoubleValue();
  76373. }
  76374. else
  76375. {
  76376. mode = absoluteSize;
  76377. value = s.getDoubleValue();
  76378. }
  76379. }
  76380. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76381. const double x_, const double w_,
  76382. const uint8 xMode_, const uint8 wMode_,
  76383. const int parentPos,
  76384. const int parentSize) const throw()
  76385. {
  76386. if (wMode_ == proportionalSize)
  76387. wOut = roundToInt (w_ * parentSize);
  76388. else if (wMode_ == parentSizeMinusAbsolute)
  76389. wOut = jmax (0, parentSize - roundToInt (w_));
  76390. else
  76391. wOut = roundToInt (w_);
  76392. if ((xMode_ & proportionOfParentSize) != 0)
  76393. xOut = parentPos + x_ * parentSize;
  76394. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76395. xOut = (parentPos + parentSize) - x_;
  76396. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76397. xOut = x_ + (parentPos + parentSize / 2);
  76398. else
  76399. xOut = x_ + parentPos;
  76400. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76401. xOut -= wOut;
  76402. else if ((xMode_ & anchorAtCentre) != 0)
  76403. xOut -= wOut / 2;
  76404. }
  76405. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76406. double x_, const double w_,
  76407. const uint8 xMode_, const uint8 wMode_,
  76408. const int parentPos,
  76409. const int parentSize) const throw()
  76410. {
  76411. if (wMode_ == proportionalSize)
  76412. {
  76413. if (parentSize > 0)
  76414. wOut = w_ / parentSize;
  76415. }
  76416. else if (wMode_ == parentSizeMinusAbsolute)
  76417. wOut = parentSize - w_;
  76418. else
  76419. wOut = w_;
  76420. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76421. x_ += w_;
  76422. else if ((xMode_ & anchorAtCentre) != 0)
  76423. x_ += w_ / 2;
  76424. if ((xMode_ & proportionOfParentSize) != 0)
  76425. {
  76426. if (parentSize > 0)
  76427. xOut = (x_ - parentPos) / parentSize;
  76428. }
  76429. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76430. xOut = (parentPos + parentSize) - x_;
  76431. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76432. xOut = x_ - (parentPos + parentSize / 2);
  76433. else
  76434. xOut = x_ - parentPos;
  76435. }
  76436. END_JUCE_NAMESPACE
  76437. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76438. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76439. BEGIN_JUCE_NAMESPACE
  76440. RectangleList::RectangleList() throw()
  76441. {
  76442. }
  76443. RectangleList::RectangleList (const Rectangle<int>& rect)
  76444. {
  76445. if (! rect.isEmpty())
  76446. rects.add (rect);
  76447. }
  76448. RectangleList::RectangleList (const RectangleList& other)
  76449. : rects (other.rects)
  76450. {
  76451. }
  76452. RectangleList& RectangleList::operator= (const RectangleList& other)
  76453. {
  76454. rects = other.rects;
  76455. return *this;
  76456. }
  76457. RectangleList::~RectangleList()
  76458. {
  76459. }
  76460. void RectangleList::clear()
  76461. {
  76462. rects.clearQuick();
  76463. }
  76464. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76465. {
  76466. if (((unsigned int) index) < (unsigned int) rects.size())
  76467. return rects.getReference (index);
  76468. return Rectangle<int>();
  76469. }
  76470. bool RectangleList::isEmpty() const throw()
  76471. {
  76472. return rects.size() == 0;
  76473. }
  76474. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76475. : current (0),
  76476. owner (list),
  76477. index (list.rects.size())
  76478. {
  76479. }
  76480. RectangleList::Iterator::~Iterator()
  76481. {
  76482. }
  76483. bool RectangleList::Iterator::next() throw()
  76484. {
  76485. if (--index >= 0)
  76486. {
  76487. current = & (owner.rects.getReference (index));
  76488. return true;
  76489. }
  76490. return false;
  76491. }
  76492. void RectangleList::add (const Rectangle<int>& rect)
  76493. {
  76494. if (! rect.isEmpty())
  76495. {
  76496. if (rects.size() == 0)
  76497. {
  76498. rects.add (rect);
  76499. }
  76500. else
  76501. {
  76502. bool anyOverlaps = false;
  76503. int i;
  76504. for (i = rects.size(); --i >= 0;)
  76505. {
  76506. Rectangle<int>& ourRect = rects.getReference (i);
  76507. if (rect.intersects (ourRect))
  76508. {
  76509. if (rect.contains (ourRect))
  76510. rects.remove (i);
  76511. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76512. anyOverlaps = true;
  76513. }
  76514. }
  76515. if (anyOverlaps && rects.size() > 0)
  76516. {
  76517. RectangleList r (rect);
  76518. for (i = rects.size(); --i >= 0;)
  76519. {
  76520. const Rectangle<int>& ourRect = rects.getReference (i);
  76521. if (rect.intersects (ourRect))
  76522. {
  76523. r.subtract (ourRect);
  76524. if (r.rects.size() == 0)
  76525. return;
  76526. }
  76527. }
  76528. for (i = r.getNumRectangles(); --i >= 0;)
  76529. rects.add (r.rects.getReference (i));
  76530. }
  76531. else
  76532. {
  76533. rects.add (rect);
  76534. }
  76535. }
  76536. }
  76537. }
  76538. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76539. {
  76540. if (! rect.isEmpty())
  76541. rects.add (rect);
  76542. }
  76543. void RectangleList::add (const int x, const int y, const int w, const int h)
  76544. {
  76545. if (rects.size() == 0)
  76546. {
  76547. if (w > 0 && h > 0)
  76548. rects.add (Rectangle<int> (x, y, w, h));
  76549. }
  76550. else
  76551. {
  76552. add (Rectangle<int> (x, y, w, h));
  76553. }
  76554. }
  76555. void RectangleList::add (const RectangleList& other)
  76556. {
  76557. for (int i = 0; i < other.rects.size(); ++i)
  76558. add (other.rects.getReference (i));
  76559. }
  76560. void RectangleList::subtract (const Rectangle<int>& rect)
  76561. {
  76562. const int originalNumRects = rects.size();
  76563. if (originalNumRects > 0)
  76564. {
  76565. const int x1 = rect.x;
  76566. const int y1 = rect.y;
  76567. const int x2 = x1 + rect.w;
  76568. const int y2 = y1 + rect.h;
  76569. for (int i = getNumRectangles(); --i >= 0;)
  76570. {
  76571. Rectangle<int>& r = rects.getReference (i);
  76572. const int rx1 = r.x;
  76573. const int ry1 = r.y;
  76574. const int rx2 = rx1 + r.w;
  76575. const int ry2 = ry1 + r.h;
  76576. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76577. {
  76578. if (x1 > rx1 && x1 < rx2)
  76579. {
  76580. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76581. {
  76582. r.w = x1 - rx1;
  76583. }
  76584. else
  76585. {
  76586. r.x = x1;
  76587. r.w = rx2 - x1;
  76588. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76589. i += 2;
  76590. }
  76591. }
  76592. else if (x2 > rx1 && x2 < rx2)
  76593. {
  76594. r.x = x2;
  76595. r.w = rx2 - x2;
  76596. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76597. {
  76598. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76599. i += 2;
  76600. }
  76601. }
  76602. else if (y1 > ry1 && y1 < ry2)
  76603. {
  76604. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76605. {
  76606. r.h = y1 - ry1;
  76607. }
  76608. else
  76609. {
  76610. r.y = y1;
  76611. r.h = ry2 - y1;
  76612. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76613. i += 2;
  76614. }
  76615. }
  76616. else if (y2 > ry1 && y2 < ry2)
  76617. {
  76618. r.y = y2;
  76619. r.h = ry2 - y2;
  76620. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76621. {
  76622. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76623. i += 2;
  76624. }
  76625. }
  76626. else
  76627. {
  76628. rects.remove (i);
  76629. }
  76630. }
  76631. }
  76632. }
  76633. }
  76634. bool RectangleList::subtract (const RectangleList& otherList)
  76635. {
  76636. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76637. subtract (otherList.rects.getReference (i));
  76638. return rects.size() > 0;
  76639. }
  76640. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76641. {
  76642. bool notEmpty = false;
  76643. if (rect.isEmpty())
  76644. {
  76645. clear();
  76646. }
  76647. else
  76648. {
  76649. for (int i = rects.size(); --i >= 0;)
  76650. {
  76651. Rectangle<int>& r = rects.getReference (i);
  76652. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76653. rects.remove (i);
  76654. else
  76655. notEmpty = true;
  76656. }
  76657. }
  76658. return notEmpty;
  76659. }
  76660. bool RectangleList::clipTo (const RectangleList& other)
  76661. {
  76662. if (rects.size() == 0)
  76663. return false;
  76664. RectangleList result;
  76665. for (int j = 0; j < rects.size(); ++j)
  76666. {
  76667. const Rectangle<int>& rect = rects.getReference (j);
  76668. for (int i = other.rects.size(); --i >= 0;)
  76669. {
  76670. Rectangle<int> r (other.rects.getReference (i));
  76671. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76672. result.rects.add (r);
  76673. }
  76674. }
  76675. swapWith (result);
  76676. return ! isEmpty();
  76677. }
  76678. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76679. {
  76680. destRegion.clear();
  76681. if (! rect.isEmpty())
  76682. {
  76683. for (int i = rects.size(); --i >= 0;)
  76684. {
  76685. Rectangle<int> r (rects.getReference (i));
  76686. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76687. destRegion.rects.add (r);
  76688. }
  76689. }
  76690. return destRegion.rects.size() > 0;
  76691. }
  76692. void RectangleList::swapWith (RectangleList& otherList) throw()
  76693. {
  76694. rects.swapWithArray (otherList.rects);
  76695. }
  76696. void RectangleList::consolidate()
  76697. {
  76698. int i;
  76699. for (i = 0; i < getNumRectangles() - 1; ++i)
  76700. {
  76701. Rectangle<int>& r = rects.getReference (i);
  76702. const int rx1 = r.x;
  76703. const int ry1 = r.y;
  76704. const int rx2 = rx1 + r.w;
  76705. const int ry2 = ry1 + r.h;
  76706. for (int j = rects.size(); --j > i;)
  76707. {
  76708. Rectangle<int>& r2 = rects.getReference (j);
  76709. const int jrx1 = r2.x;
  76710. const int jry1 = r2.y;
  76711. const int jrx2 = jrx1 + r2.w;
  76712. const int jry2 = jry1 + r2.h;
  76713. // if the vertical edges of any blocks are touching and their horizontals don't
  76714. // line up, split them horizontally..
  76715. if (jrx1 == rx2 || jrx2 == rx1)
  76716. {
  76717. if (jry1 > ry1 && jry1 < ry2)
  76718. {
  76719. r.h = jry1 - ry1;
  76720. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76721. i = -1;
  76722. break;
  76723. }
  76724. if (jry2 > ry1 && jry2 < ry2)
  76725. {
  76726. r.h = jry2 - ry1;
  76727. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76728. i = -1;
  76729. break;
  76730. }
  76731. else if (ry1 > jry1 && ry1 < jry2)
  76732. {
  76733. r2.h = ry1 - jry1;
  76734. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76735. i = -1;
  76736. break;
  76737. }
  76738. else if (ry2 > jry1 && ry2 < jry2)
  76739. {
  76740. r2.h = ry2 - jry1;
  76741. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76742. i = -1;
  76743. break;
  76744. }
  76745. }
  76746. }
  76747. }
  76748. for (i = 0; i < rects.size() - 1; ++i)
  76749. {
  76750. Rectangle<int>& r = rects.getReference (i);
  76751. for (int j = rects.size(); --j > i;)
  76752. {
  76753. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76754. {
  76755. rects.remove (j);
  76756. i = -1;
  76757. break;
  76758. }
  76759. }
  76760. }
  76761. }
  76762. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76763. {
  76764. for (int i = getNumRectangles(); --i >= 0;)
  76765. if (rects.getReference (i).contains (x, y))
  76766. return true;
  76767. return false;
  76768. }
  76769. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76770. {
  76771. if (rects.size() > 1)
  76772. {
  76773. RectangleList r (rectangleToCheck);
  76774. for (int i = rects.size(); --i >= 0;)
  76775. {
  76776. r.subtract (rects.getReference (i));
  76777. if (r.rects.size() == 0)
  76778. return true;
  76779. }
  76780. }
  76781. else if (rects.size() > 0)
  76782. {
  76783. return rects.getReference (0).contains (rectangleToCheck);
  76784. }
  76785. return false;
  76786. }
  76787. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76788. {
  76789. for (int i = rects.size(); --i >= 0;)
  76790. if (rects.getReference (i).intersects (rectangleToCheck))
  76791. return true;
  76792. return false;
  76793. }
  76794. bool RectangleList::intersects (const RectangleList& other) const throw()
  76795. {
  76796. for (int i = rects.size(); --i >= 0;)
  76797. if (other.intersectsRectangle (rects.getReference (i)))
  76798. return true;
  76799. return false;
  76800. }
  76801. const Rectangle<int> RectangleList::getBounds() const throw()
  76802. {
  76803. if (rects.size() <= 1)
  76804. {
  76805. if (rects.size() == 0)
  76806. return Rectangle<int>();
  76807. else
  76808. return rects.getReference (0);
  76809. }
  76810. else
  76811. {
  76812. const Rectangle<int>& r = rects.getReference (0);
  76813. int minX = r.x;
  76814. int minY = r.y;
  76815. int maxX = minX + r.w;
  76816. int maxY = minY + r.h;
  76817. for (int i = rects.size(); --i > 0;)
  76818. {
  76819. const Rectangle<int>& r2 = rects.getReference (i);
  76820. minX = jmin (minX, r2.x);
  76821. minY = jmin (minY, r2.y);
  76822. maxX = jmax (maxX, r2.getRight());
  76823. maxY = jmax (maxY, r2.getBottom());
  76824. }
  76825. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76826. }
  76827. }
  76828. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76829. {
  76830. for (int i = rects.size(); --i >= 0;)
  76831. {
  76832. Rectangle<int>& r = rects.getReference (i);
  76833. r.x += dx;
  76834. r.y += dy;
  76835. }
  76836. }
  76837. const Path RectangleList::toPath() const
  76838. {
  76839. Path p;
  76840. for (int i = rects.size(); --i >= 0;)
  76841. {
  76842. const Rectangle<int>& r = rects.getReference (i);
  76843. p.addRectangle ((float) r.x,
  76844. (float) r.y,
  76845. (float) r.w,
  76846. (float) r.h);
  76847. }
  76848. return p;
  76849. }
  76850. END_JUCE_NAMESPACE
  76851. /*** End of inlined file: juce_RectangleList.cpp ***/
  76852. /*** Start of inlined file: juce_Image.cpp ***/
  76853. BEGIN_JUCE_NAMESPACE
  76854. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76855. : format (format_), width (width_), height (height_)
  76856. {
  76857. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76858. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76859. }
  76860. Image::SharedImage::~SharedImage()
  76861. {
  76862. }
  76863. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76864. {
  76865. return imageData + lineStride * y + pixelStride * x;
  76866. }
  76867. class SoftwareSharedImage : public Image::SharedImage
  76868. {
  76869. public:
  76870. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76871. : Image::SharedImage (format_, width_, height_)
  76872. {
  76873. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76874. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76875. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76876. imageData = imageDataAllocated;
  76877. }
  76878. ~SoftwareSharedImage()
  76879. {
  76880. }
  76881. Image::ImageType getType() const
  76882. {
  76883. return Image::SoftwareImage;
  76884. }
  76885. LowLevelGraphicsContext* createLowLevelContext()
  76886. {
  76887. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76888. }
  76889. SharedImage* clone()
  76890. {
  76891. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76892. memcpy (s->imageData, imageData, lineStride * height);
  76893. return s;
  76894. }
  76895. private:
  76896. HeapBlock<uint8> imageDataAllocated;
  76897. };
  76898. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76899. {
  76900. return new SoftwareSharedImage (format, width, height, clearImage);
  76901. }
  76902. class SubsectionSharedImage : public Image::SharedImage
  76903. {
  76904. public:
  76905. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76906. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76907. image (image_), area (area_)
  76908. {
  76909. pixelStride = image_->getPixelStride();
  76910. lineStride = image_->getLineStride();
  76911. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76912. }
  76913. ~SubsectionSharedImage() {}
  76914. Image::ImageType getType() const
  76915. {
  76916. return Image::SoftwareImage;
  76917. }
  76918. LowLevelGraphicsContext* createLowLevelContext()
  76919. {
  76920. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76921. g->clipToRectangle (area);
  76922. g->setOrigin (area.getX(), area.getY());
  76923. return g;
  76924. }
  76925. SharedImage* clone()
  76926. {
  76927. return new SubsectionSharedImage (image->clone(), area);
  76928. }
  76929. private:
  76930. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76931. const Rectangle<int> area;
  76932. SubsectionSharedImage (const SubsectionSharedImage&);
  76933. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76934. };
  76935. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76936. {
  76937. if (area.contains (getBounds()))
  76938. return *this;
  76939. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76940. if (validArea.isEmpty())
  76941. return Image::null;
  76942. return Image (new SubsectionSharedImage (image, validArea));
  76943. }
  76944. Image::Image()
  76945. {
  76946. }
  76947. Image::Image (SharedImage* const instance)
  76948. : image (instance)
  76949. {
  76950. }
  76951. Image::Image (const PixelFormat format,
  76952. const int width, const int height,
  76953. const bool clearImage, const ImageType type)
  76954. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76955. : new SoftwareSharedImage (format, width, height, clearImage))
  76956. {
  76957. }
  76958. Image::Image (const Image& other)
  76959. : image (other.image)
  76960. {
  76961. }
  76962. Image& Image::operator= (const Image& other)
  76963. {
  76964. image = other.image;
  76965. return *this;
  76966. }
  76967. Image::~Image()
  76968. {
  76969. }
  76970. const Image Image::null;
  76971. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76972. {
  76973. return image == 0 ? 0 : image->createLowLevelContext();
  76974. }
  76975. void Image::duplicateIfShared()
  76976. {
  76977. if (image != 0 && image->getReferenceCount() > 1)
  76978. image = image->clone();
  76979. }
  76980. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76981. {
  76982. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76983. return *this;
  76984. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76985. Graphics g (newImage);
  76986. g.setImageResamplingQuality (quality);
  76987. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76988. return newImage;
  76989. }
  76990. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76991. {
  76992. if (image == 0 || newFormat == image->format)
  76993. return *this;
  76994. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76995. if (newFormat == SingleChannel)
  76996. {
  76997. if (! hasAlphaChannel())
  76998. {
  76999. newImage.clear (getBounds(), Colours::black);
  77000. }
  77001. else
  77002. {
  77003. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77004. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77005. for (int y = 0; y < image->height; ++y)
  77006. {
  77007. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77008. uint8* dst = destData.getLinePointer (y);
  77009. for (int x = image->width; --x >= 0;)
  77010. {
  77011. *dst++ = src->getAlpha();
  77012. ++src;
  77013. }
  77014. }
  77015. }
  77016. }
  77017. else
  77018. {
  77019. if (hasAlphaChannel())
  77020. newImage.clear (getBounds());
  77021. Graphics g (newImage);
  77022. g.drawImageAt (*this, 0, 0);
  77023. }
  77024. return newImage;
  77025. }
  77026. const var Image::getTag() const
  77027. {
  77028. return image == 0 ? var::null : image->userTag;
  77029. }
  77030. void Image::setTag (const var& newTag)
  77031. {
  77032. if (image != 0)
  77033. image->userTag = newTag;
  77034. }
  77035. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77036. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77037. pixelFormat (image.getFormat()),
  77038. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77039. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77040. width (w),
  77041. height (h)
  77042. {
  77043. jassert (data != 0);
  77044. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77045. }
  77046. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77047. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77048. pixelFormat (image.getFormat()),
  77049. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77050. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77051. width (w),
  77052. height (h)
  77053. {
  77054. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77055. }
  77056. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77057. : data (image.image == 0 ? 0 : image.image->imageData),
  77058. pixelFormat (image.getFormat()),
  77059. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77060. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77061. width (image.getWidth()),
  77062. height (image.getHeight())
  77063. {
  77064. }
  77065. Image::BitmapData::~BitmapData()
  77066. {
  77067. }
  77068. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77069. {
  77070. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77071. const uint8* const pixel = getPixelPointer (x, y);
  77072. switch (pixelFormat)
  77073. {
  77074. case Image::ARGB:
  77075. {
  77076. PixelARGB p (*(const PixelARGB*) pixel);
  77077. p.unpremultiply();
  77078. return Colour (p.getARGB());
  77079. }
  77080. case Image::RGB:
  77081. return Colour (((const PixelRGB*) pixel)->getARGB());
  77082. case Image::SingleChannel:
  77083. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77084. default:
  77085. jassertfalse;
  77086. break;
  77087. }
  77088. return Colour();
  77089. }
  77090. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77091. {
  77092. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77093. uint8* const pixel = getPixelPointer (x, y);
  77094. const PixelARGB col (colour.getPixelARGB());
  77095. switch (pixelFormat)
  77096. {
  77097. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77098. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77099. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77100. default: jassertfalse; break;
  77101. }
  77102. }
  77103. void Image::setPixelData (int x, int y, int w, int h,
  77104. const uint8* const sourcePixelData, const int sourceLineStride)
  77105. {
  77106. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77107. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77108. {
  77109. const BitmapData dest (*this, x, y, w, h, true);
  77110. for (int i = 0; i < h; ++i)
  77111. {
  77112. memcpy (dest.getLinePointer(i),
  77113. sourcePixelData + sourceLineStride * i,
  77114. w * dest.pixelStride);
  77115. }
  77116. }
  77117. }
  77118. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77119. {
  77120. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77121. if (! clipped.isEmpty())
  77122. {
  77123. const PixelARGB col (colourToClearTo.getPixelARGB());
  77124. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77125. uint8* dest = destData.data;
  77126. int dh = clipped.getHeight();
  77127. while (--dh >= 0)
  77128. {
  77129. uint8* line = dest;
  77130. dest += destData.lineStride;
  77131. if (isARGB())
  77132. {
  77133. for (int x = clipped.getWidth(); --x >= 0;)
  77134. {
  77135. ((PixelARGB*) line)->set (col);
  77136. line += destData.pixelStride;
  77137. }
  77138. }
  77139. else if (isRGB())
  77140. {
  77141. for (int x = clipped.getWidth(); --x >= 0;)
  77142. {
  77143. ((PixelRGB*) line)->set (col);
  77144. line += destData.pixelStride;
  77145. }
  77146. }
  77147. else
  77148. {
  77149. for (int x = clipped.getWidth(); --x >= 0;)
  77150. {
  77151. *line = col.getAlpha();
  77152. line += destData.pixelStride;
  77153. }
  77154. }
  77155. }
  77156. }
  77157. }
  77158. const Colour Image::getPixelAt (const int x, const int y) const
  77159. {
  77160. if (((unsigned int) x) < (unsigned int) getWidth()
  77161. && ((unsigned int) y) < (unsigned int) getHeight())
  77162. {
  77163. const BitmapData srcData (*this, x, y, 1, 1);
  77164. return srcData.getPixelColour (0, 0);
  77165. }
  77166. return Colour();
  77167. }
  77168. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77169. {
  77170. if (((unsigned int) x) < (unsigned int) getWidth()
  77171. && ((unsigned int) y) < (unsigned int) getHeight())
  77172. {
  77173. const BitmapData destData (*this, x, y, 1, 1, true);
  77174. destData.setPixelColour (0, 0, colour);
  77175. }
  77176. }
  77177. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77178. {
  77179. if (((unsigned int) x) < (unsigned int) getWidth()
  77180. && ((unsigned int) y) < (unsigned int) getHeight()
  77181. && hasAlphaChannel())
  77182. {
  77183. const BitmapData destData (*this, x, y, 1, 1, true);
  77184. if (isARGB())
  77185. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77186. else
  77187. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77188. }
  77189. }
  77190. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77191. {
  77192. if (hasAlphaChannel())
  77193. {
  77194. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77195. if (isARGB())
  77196. {
  77197. for (int y = 0; y < destData.height; ++y)
  77198. {
  77199. uint8* p = destData.getLinePointer (y);
  77200. for (int x = 0; x < destData.width; ++x)
  77201. {
  77202. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77203. p += destData.pixelStride;
  77204. }
  77205. }
  77206. }
  77207. else
  77208. {
  77209. for (int y = 0; y < destData.height; ++y)
  77210. {
  77211. uint8* p = destData.getLinePointer (y);
  77212. for (int x = 0; x < destData.width; ++x)
  77213. {
  77214. *p = (uint8) (*p * amountToMultiplyBy);
  77215. p += destData.pixelStride;
  77216. }
  77217. }
  77218. }
  77219. }
  77220. else
  77221. {
  77222. jassertfalse; // can't do this without an alpha-channel!
  77223. }
  77224. }
  77225. void Image::desaturate()
  77226. {
  77227. if (isARGB() || isRGB())
  77228. {
  77229. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77230. if (isARGB())
  77231. {
  77232. for (int y = 0; y < destData.height; ++y)
  77233. {
  77234. uint8* p = destData.getLinePointer (y);
  77235. for (int x = 0; x < destData.width; ++x)
  77236. {
  77237. ((PixelARGB*) p)->desaturate();
  77238. p += destData.pixelStride;
  77239. }
  77240. }
  77241. }
  77242. else
  77243. {
  77244. for (int y = 0; y < destData.height; ++y)
  77245. {
  77246. uint8* p = destData.getLinePointer (y);
  77247. for (int x = 0; x < destData.width; ++x)
  77248. {
  77249. ((PixelRGB*) p)->desaturate();
  77250. p += destData.pixelStride;
  77251. }
  77252. }
  77253. }
  77254. }
  77255. }
  77256. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77257. {
  77258. if (hasAlphaChannel())
  77259. {
  77260. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77261. SparseSet<int> pixelsOnRow;
  77262. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77263. for (int y = 0; y < srcData.height; ++y)
  77264. {
  77265. pixelsOnRow.clear();
  77266. const uint8* lineData = srcData.getLinePointer (y);
  77267. if (isARGB())
  77268. {
  77269. for (int x = 0; x < srcData.width; ++x)
  77270. {
  77271. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77272. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77273. lineData += srcData.pixelStride;
  77274. }
  77275. }
  77276. else
  77277. {
  77278. for (int x = 0; x < srcData.width; ++x)
  77279. {
  77280. if (*lineData >= threshold)
  77281. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77282. lineData += srcData.pixelStride;
  77283. }
  77284. }
  77285. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77286. {
  77287. const Range<int> range (pixelsOnRow.getRange (i));
  77288. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77289. }
  77290. result.consolidate();
  77291. }
  77292. }
  77293. else
  77294. {
  77295. result.add (0, 0, getWidth(), getHeight());
  77296. }
  77297. }
  77298. void Image::moveImageSection (int dx, int dy,
  77299. int sx, int sy,
  77300. int w, int h)
  77301. {
  77302. if (dx < 0)
  77303. {
  77304. w += dx;
  77305. sx -= dx;
  77306. dx = 0;
  77307. }
  77308. if (dy < 0)
  77309. {
  77310. h += dy;
  77311. sy -= dy;
  77312. dy = 0;
  77313. }
  77314. if (sx < 0)
  77315. {
  77316. w += sx;
  77317. dx -= sx;
  77318. sx = 0;
  77319. }
  77320. if (sy < 0)
  77321. {
  77322. h += sy;
  77323. dy -= sy;
  77324. sy = 0;
  77325. }
  77326. const int minX = jmin (dx, sx);
  77327. const int minY = jmin (dy, sy);
  77328. w = jmin (w, getWidth() - jmax (sx, dx));
  77329. h = jmin (h, getHeight() - jmax (sy, dy));
  77330. if (w > 0 && h > 0)
  77331. {
  77332. const int maxX = jmax (dx, sx) + w;
  77333. const int maxY = jmax (dy, sy) + h;
  77334. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77335. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77336. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77337. const int lineSize = destData.pixelStride * w;
  77338. if (dy > sy)
  77339. {
  77340. while (--h >= 0)
  77341. {
  77342. const int offset = h * destData.lineStride;
  77343. memmove (dst + offset, src + offset, lineSize);
  77344. }
  77345. }
  77346. else if (dst != src)
  77347. {
  77348. while (--h >= 0)
  77349. {
  77350. memmove (dst, src, lineSize);
  77351. dst += destData.lineStride;
  77352. src += destData.lineStride;
  77353. }
  77354. }
  77355. }
  77356. }
  77357. END_JUCE_NAMESPACE
  77358. /*** End of inlined file: juce_Image.cpp ***/
  77359. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77360. BEGIN_JUCE_NAMESPACE
  77361. class ImageCache::Pimpl : public Timer,
  77362. public DeletedAtShutdown
  77363. {
  77364. public:
  77365. Pimpl()
  77366. : cacheTimeout (5000)
  77367. {
  77368. }
  77369. ~Pimpl()
  77370. {
  77371. clearSingletonInstance();
  77372. }
  77373. const Image getFromHashCode (const int64 hashCode)
  77374. {
  77375. const ScopedLock sl (lock);
  77376. for (int i = images.size(); --i >= 0;)
  77377. {
  77378. Item* const item = images.getUnchecked(i);
  77379. if (item->hashCode == hashCode)
  77380. return item->image;
  77381. }
  77382. return Image::null;
  77383. }
  77384. void addImageToCache (const Image& image, const int64 hashCode)
  77385. {
  77386. if (image.isValid())
  77387. {
  77388. if (! isTimerRunning())
  77389. startTimer (2000);
  77390. Item* const item = new Item();
  77391. item->hashCode = hashCode;
  77392. item->image = image;
  77393. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77394. const ScopedLock sl (lock);
  77395. images.add (item);
  77396. }
  77397. }
  77398. void timerCallback()
  77399. {
  77400. const uint32 now = Time::getApproximateMillisecondCounter();
  77401. const ScopedLock sl (lock);
  77402. for (int i = images.size(); --i >= 0;)
  77403. {
  77404. Item* const item = images.getUnchecked(i);
  77405. if (item->image.getReferenceCount() <= 1)
  77406. {
  77407. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77408. images.remove (i);
  77409. }
  77410. else
  77411. {
  77412. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77413. }
  77414. }
  77415. if (images.size() == 0)
  77416. stopTimer();
  77417. }
  77418. struct Item
  77419. {
  77420. Image image;
  77421. int64 hashCode;
  77422. uint32 lastUseTime;
  77423. };
  77424. int cacheTimeout;
  77425. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77426. private:
  77427. OwnedArray<Item> images;
  77428. CriticalSection lock;
  77429. Pimpl (const Pimpl&);
  77430. Pimpl& operator= (const Pimpl&);
  77431. };
  77432. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77433. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77434. {
  77435. if (Pimpl::getInstanceWithoutCreating() != 0)
  77436. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77437. return Image::null;
  77438. }
  77439. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77440. {
  77441. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77442. }
  77443. const Image ImageCache::getFromFile (const File& file)
  77444. {
  77445. const int64 hashCode = file.hashCode64();
  77446. Image image (getFromHashCode (hashCode));
  77447. if (image.isNull())
  77448. {
  77449. image = ImageFileFormat::loadFrom (file);
  77450. addImageToCache (image, hashCode);
  77451. }
  77452. return image;
  77453. }
  77454. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77455. {
  77456. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77457. Image image (getFromHashCode (hashCode));
  77458. if (image.isNull())
  77459. {
  77460. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77461. addImageToCache (image, hashCode);
  77462. }
  77463. return image;
  77464. }
  77465. void ImageCache::setCacheTimeout (const int millisecs)
  77466. {
  77467. Pimpl::getInstance()->cacheTimeout = millisecs;
  77468. }
  77469. END_JUCE_NAMESPACE
  77470. /*** End of inlined file: juce_ImageCache.cpp ***/
  77471. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77472. BEGIN_JUCE_NAMESPACE
  77473. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77474. : values (size_ * size_),
  77475. size (size_)
  77476. {
  77477. clear();
  77478. }
  77479. ImageConvolutionKernel::~ImageConvolutionKernel()
  77480. {
  77481. }
  77482. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77483. {
  77484. if (((unsigned int) x) < (unsigned int) size
  77485. && ((unsigned int) y) < (unsigned int) size)
  77486. {
  77487. return values [x + y * size];
  77488. }
  77489. else
  77490. {
  77491. jassertfalse;
  77492. return 0;
  77493. }
  77494. }
  77495. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77496. {
  77497. if (((unsigned int) x) < (unsigned int) size
  77498. && ((unsigned int) y) < (unsigned int) size)
  77499. {
  77500. values [x + y * size] = value;
  77501. }
  77502. else
  77503. {
  77504. jassertfalse;
  77505. }
  77506. }
  77507. void ImageConvolutionKernel::clear()
  77508. {
  77509. for (int i = size * size; --i >= 0;)
  77510. values[i] = 0;
  77511. }
  77512. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77513. {
  77514. double currentTotal = 0.0;
  77515. for (int i = size * size; --i >= 0;)
  77516. currentTotal += values[i];
  77517. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77518. }
  77519. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77520. {
  77521. for (int i = size * size; --i >= 0;)
  77522. values[i] *= multiplier;
  77523. }
  77524. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77525. {
  77526. const double radiusFactor = -1.0 / (radius * radius * 2);
  77527. const int centre = size >> 1;
  77528. for (int y = size; --y >= 0;)
  77529. {
  77530. for (int x = size; --x >= 0;)
  77531. {
  77532. const int cx = x - centre;
  77533. const int cy = y - centre;
  77534. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77535. }
  77536. }
  77537. setOverallSum (1.0f);
  77538. }
  77539. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77540. const Image& sourceImage,
  77541. const Rectangle<int>& destinationArea) const
  77542. {
  77543. if (sourceImage == destImage)
  77544. {
  77545. destImage.duplicateIfShared();
  77546. }
  77547. else
  77548. {
  77549. if (sourceImage.getWidth() != destImage.getWidth()
  77550. || sourceImage.getHeight() != destImage.getHeight()
  77551. || sourceImage.getFormat() != destImage.getFormat())
  77552. {
  77553. jassertfalse;
  77554. return;
  77555. }
  77556. }
  77557. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77558. if (area.isEmpty())
  77559. return;
  77560. const int right = area.getRight();
  77561. const int bottom = area.getBottom();
  77562. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77563. uint8* line = destData.data;
  77564. const Image::BitmapData srcData (sourceImage, false);
  77565. if (destData.pixelStride == 4)
  77566. {
  77567. for (int y = area.getY(); y < bottom; ++y)
  77568. {
  77569. uint8* dest = line;
  77570. line += destData.lineStride;
  77571. for (int x = area.getX(); x < right; ++x)
  77572. {
  77573. float c1 = 0;
  77574. float c2 = 0;
  77575. float c3 = 0;
  77576. float c4 = 0;
  77577. for (int yy = 0; yy < size; ++yy)
  77578. {
  77579. const int sy = y + yy - (size >> 1);
  77580. if (sy >= srcData.height)
  77581. break;
  77582. if (sy >= 0)
  77583. {
  77584. int sx = x - (size >> 1);
  77585. const uint8* src = srcData.getPixelPointer (sx, sy);
  77586. for (int xx = 0; xx < size; ++xx)
  77587. {
  77588. if (sx >= srcData.width)
  77589. break;
  77590. if (sx >= 0)
  77591. {
  77592. const float kernelMult = values [xx + yy * size];
  77593. c1 += kernelMult * *src++;
  77594. c2 += kernelMult * *src++;
  77595. c3 += kernelMult * *src++;
  77596. c4 += kernelMult * *src++;
  77597. }
  77598. else
  77599. {
  77600. src += 4;
  77601. }
  77602. ++sx;
  77603. }
  77604. }
  77605. }
  77606. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77607. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77608. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77609. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77610. }
  77611. }
  77612. }
  77613. else if (destData.pixelStride == 3)
  77614. {
  77615. for (int y = area.getY(); y < bottom; ++y)
  77616. {
  77617. uint8* dest = line;
  77618. line += destData.lineStride;
  77619. for (int x = area.getX(); x < right; ++x)
  77620. {
  77621. float c1 = 0;
  77622. float c2 = 0;
  77623. float c3 = 0;
  77624. for (int yy = 0; yy < size; ++yy)
  77625. {
  77626. const int sy = y + yy - (size >> 1);
  77627. if (sy >= srcData.height)
  77628. break;
  77629. if (sy >= 0)
  77630. {
  77631. int sx = x - (size >> 1);
  77632. const uint8* src = srcData.getPixelPointer (sx, sy);
  77633. for (int xx = 0; xx < size; ++xx)
  77634. {
  77635. if (sx >= srcData.width)
  77636. break;
  77637. if (sx >= 0)
  77638. {
  77639. const float kernelMult = values [xx + yy * size];
  77640. c1 += kernelMult * *src++;
  77641. c2 += kernelMult * *src++;
  77642. c3 += kernelMult * *src++;
  77643. }
  77644. else
  77645. {
  77646. src += 3;
  77647. }
  77648. ++sx;
  77649. }
  77650. }
  77651. }
  77652. *dest++ = (uint8) roundToInt (c1);
  77653. *dest++ = (uint8) roundToInt (c2);
  77654. *dest++ = (uint8) roundToInt (c3);
  77655. }
  77656. }
  77657. }
  77658. }
  77659. END_JUCE_NAMESPACE
  77660. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77661. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77662. BEGIN_JUCE_NAMESPACE
  77663. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77664. {
  77665. static PNGImageFormat png;
  77666. static JPEGImageFormat jpg;
  77667. static GIFImageFormat gif;
  77668. ImageFileFormat* formats[4];
  77669. int numFormats = 0;
  77670. formats [numFormats++] = &png;
  77671. formats [numFormats++] = &jpg;
  77672. formats [numFormats++] = &gif;
  77673. const int64 streamPos = input.getPosition();
  77674. for (int i = 0; i < numFormats; ++i)
  77675. {
  77676. const bool found = formats[i]->canUnderstand (input);
  77677. input.setPosition (streamPos);
  77678. if (found)
  77679. return formats[i];
  77680. }
  77681. return 0;
  77682. }
  77683. const Image ImageFileFormat::loadFrom (InputStream& input)
  77684. {
  77685. ImageFileFormat* const format = findImageFormatForStream (input);
  77686. if (format != 0)
  77687. return format->decodeImage (input);
  77688. return Image::null;
  77689. }
  77690. const Image ImageFileFormat::loadFrom (const File& file)
  77691. {
  77692. InputStream* const in = file.createInputStream();
  77693. if (in != 0)
  77694. {
  77695. BufferedInputStream b (in, 8192, true);
  77696. return loadFrom (b);
  77697. }
  77698. return Image::null;
  77699. }
  77700. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77701. {
  77702. if (rawData != 0 && numBytes > 4)
  77703. {
  77704. MemoryInputStream stream (rawData, numBytes, false);
  77705. return loadFrom (stream);
  77706. }
  77707. return Image::null;
  77708. }
  77709. END_JUCE_NAMESPACE
  77710. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77711. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77712. BEGIN_JUCE_NAMESPACE
  77713. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77714. const Image juce_loadWithCoreImage (InputStream& input);
  77715. #else
  77716. class GIFLoader
  77717. {
  77718. public:
  77719. GIFLoader (InputStream& in)
  77720. : input (in),
  77721. dataBlockIsZero (false),
  77722. fresh (false),
  77723. finished (false)
  77724. {
  77725. currentBit = lastBit = lastByteIndex = 0;
  77726. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77727. firstcode = oldcode = 0;
  77728. clearCode = end_code = 0;
  77729. int imageWidth, imageHeight;
  77730. int transparent = -1;
  77731. if (! getSizeFromHeader (imageWidth, imageHeight))
  77732. return;
  77733. if ((imageWidth <= 0) || (imageHeight <= 0))
  77734. return;
  77735. unsigned char buf [16];
  77736. if (in.read (buf, 3) != 3)
  77737. return;
  77738. int numColours = 2 << (buf[0] & 7);
  77739. if ((buf[0] & 0x80) != 0)
  77740. readPalette (numColours);
  77741. for (;;)
  77742. {
  77743. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77744. break;
  77745. if (buf[0] == '!')
  77746. {
  77747. if (input.read (buf, 1) != 1)
  77748. break;
  77749. if (processExtension (buf[0], transparent) < 0)
  77750. break;
  77751. continue;
  77752. }
  77753. if (buf[0] != ',')
  77754. continue;
  77755. if (input.read (buf, 9) != 9)
  77756. break;
  77757. imageWidth = makeWord (buf[4], buf[5]);
  77758. imageHeight = makeWord (buf[6], buf[7]);
  77759. numColours = 2 << (buf[8] & 7);
  77760. if ((buf[8] & 0x80) != 0)
  77761. if (! readPalette (numColours))
  77762. break;
  77763. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77764. imageWidth, imageHeight, (transparent >= 0));
  77765. readImage ((buf[8] & 0x40) != 0, transparent);
  77766. break;
  77767. }
  77768. }
  77769. ~GIFLoader() {}
  77770. Image image;
  77771. private:
  77772. InputStream& input;
  77773. uint8 buffer [300];
  77774. uint8 palette [256][4];
  77775. bool dataBlockIsZero, fresh, finished;
  77776. int currentBit, lastBit, lastByteIndex;
  77777. int codeSize, setCodeSize;
  77778. int maxCode, maxCodeSize;
  77779. int firstcode, oldcode;
  77780. int clearCode, end_code;
  77781. enum { maxGifCode = 1 << 12 };
  77782. int table [2] [maxGifCode];
  77783. int stack [2 * maxGifCode];
  77784. int *sp;
  77785. bool getSizeFromHeader (int& w, int& h)
  77786. {
  77787. char b[8];
  77788. if (input.read (b, 6) == 6)
  77789. {
  77790. if ((strncmp ("GIF87a", b, 6) == 0)
  77791. || (strncmp ("GIF89a", b, 6) == 0))
  77792. {
  77793. if (input.read (b, 4) == 4)
  77794. {
  77795. w = makeWord (b[0], b[1]);
  77796. h = makeWord (b[2], b[3]);
  77797. return true;
  77798. }
  77799. }
  77800. }
  77801. return false;
  77802. }
  77803. bool readPalette (const int numCols)
  77804. {
  77805. unsigned char rgb[4];
  77806. for (int i = 0; i < numCols; ++i)
  77807. {
  77808. input.read (rgb, 3);
  77809. palette [i][0] = rgb[0];
  77810. palette [i][1] = rgb[1];
  77811. palette [i][2] = rgb[2];
  77812. palette [i][3] = 0xff;
  77813. }
  77814. return true;
  77815. }
  77816. int readDataBlock (unsigned char* dest)
  77817. {
  77818. unsigned char n;
  77819. if (input.read (&n, 1) == 1)
  77820. {
  77821. dataBlockIsZero = (n == 0);
  77822. if (dataBlockIsZero || (input.read (dest, n) == n))
  77823. return n;
  77824. }
  77825. return -1;
  77826. }
  77827. int processExtension (const int type, int& transparent)
  77828. {
  77829. unsigned char b [300];
  77830. int n = 0;
  77831. if (type == 0xf9)
  77832. {
  77833. n = readDataBlock (b);
  77834. if (n < 0)
  77835. return 1;
  77836. if ((b[0] & 0x1) != 0)
  77837. transparent = b[3];
  77838. }
  77839. do
  77840. {
  77841. n = readDataBlock (b);
  77842. }
  77843. while (n > 0);
  77844. return n;
  77845. }
  77846. int readLZWByte (const bool initialise, const int inputCodeSize)
  77847. {
  77848. int code, incode, i;
  77849. if (initialise)
  77850. {
  77851. setCodeSize = inputCodeSize;
  77852. codeSize = setCodeSize + 1;
  77853. clearCode = 1 << setCodeSize;
  77854. end_code = clearCode + 1;
  77855. maxCodeSize = 2 * clearCode;
  77856. maxCode = clearCode + 2;
  77857. getCode (0, true);
  77858. fresh = true;
  77859. for (i = 0; i < clearCode; ++i)
  77860. {
  77861. table[0][i] = 0;
  77862. table[1][i] = i;
  77863. }
  77864. for (; i < maxGifCode; ++i)
  77865. {
  77866. table[0][i] = 0;
  77867. table[1][i] = 0;
  77868. }
  77869. sp = stack;
  77870. return 0;
  77871. }
  77872. else if (fresh)
  77873. {
  77874. fresh = false;
  77875. do
  77876. {
  77877. firstcode = oldcode
  77878. = getCode (codeSize, false);
  77879. }
  77880. while (firstcode == clearCode);
  77881. return firstcode;
  77882. }
  77883. if (sp > stack)
  77884. return *--sp;
  77885. while ((code = getCode (codeSize, false)) >= 0)
  77886. {
  77887. if (code == clearCode)
  77888. {
  77889. for (i = 0; i < clearCode; ++i)
  77890. {
  77891. table[0][i] = 0;
  77892. table[1][i] = i;
  77893. }
  77894. for (; i < maxGifCode; ++i)
  77895. {
  77896. table[0][i] = 0;
  77897. table[1][i] = 0;
  77898. }
  77899. codeSize = setCodeSize + 1;
  77900. maxCodeSize = 2 * clearCode;
  77901. maxCode = clearCode + 2;
  77902. sp = stack;
  77903. firstcode = oldcode = getCode (codeSize, false);
  77904. return firstcode;
  77905. }
  77906. else if (code == end_code)
  77907. {
  77908. if (dataBlockIsZero)
  77909. return -2;
  77910. unsigned char buf [260];
  77911. int n;
  77912. while ((n = readDataBlock (buf)) > 0)
  77913. {}
  77914. if (n != 0)
  77915. return -2;
  77916. }
  77917. incode = code;
  77918. if (code >= maxCode)
  77919. {
  77920. *sp++ = firstcode;
  77921. code = oldcode;
  77922. }
  77923. while (code >= clearCode)
  77924. {
  77925. *sp++ = table[1][code];
  77926. if (code == table[0][code])
  77927. return -2;
  77928. code = table[0][code];
  77929. }
  77930. *sp++ = firstcode = table[1][code];
  77931. if ((code = maxCode) < maxGifCode)
  77932. {
  77933. table[0][code] = oldcode;
  77934. table[1][code] = firstcode;
  77935. ++maxCode;
  77936. if ((maxCode >= maxCodeSize)
  77937. && (maxCodeSize < maxGifCode))
  77938. {
  77939. maxCodeSize <<= 1;
  77940. ++codeSize;
  77941. }
  77942. }
  77943. oldcode = incode;
  77944. if (sp > stack)
  77945. return *--sp;
  77946. }
  77947. return code;
  77948. }
  77949. int getCode (const int codeSize_, const bool initialise)
  77950. {
  77951. if (initialise)
  77952. {
  77953. currentBit = 0;
  77954. lastBit = 0;
  77955. finished = false;
  77956. return 0;
  77957. }
  77958. if ((currentBit + codeSize_) >= lastBit)
  77959. {
  77960. if (finished)
  77961. return -1;
  77962. buffer[0] = buffer [lastByteIndex - 2];
  77963. buffer[1] = buffer [lastByteIndex - 1];
  77964. const int n = readDataBlock (&buffer[2]);
  77965. if (n == 0)
  77966. finished = true;
  77967. lastByteIndex = 2 + n;
  77968. currentBit = (currentBit - lastBit) + 16;
  77969. lastBit = (2 + n) * 8 ;
  77970. }
  77971. int result = 0;
  77972. int i = currentBit;
  77973. for (int j = 0; j < codeSize_; ++j)
  77974. {
  77975. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77976. ++i;
  77977. }
  77978. currentBit += codeSize_;
  77979. return result;
  77980. }
  77981. bool readImage (const int interlace, const int transparent)
  77982. {
  77983. unsigned char c;
  77984. if (input.read (&c, 1) != 1
  77985. || readLZWByte (true, c) < 0)
  77986. return false;
  77987. if (transparent >= 0)
  77988. {
  77989. palette [transparent][0] = 0;
  77990. palette [transparent][1] = 0;
  77991. palette [transparent][2] = 0;
  77992. palette [transparent][3] = 0;
  77993. }
  77994. int index;
  77995. int xpos = 0, ypos = 0, pass = 0;
  77996. const Image::BitmapData destData (image, true);
  77997. uint8* p = destData.data;
  77998. const bool hasAlpha = image.hasAlphaChannel();
  77999. while ((index = readLZWByte (false, c)) >= 0)
  78000. {
  78001. const uint8* const paletteEntry = palette [index];
  78002. if (hasAlpha)
  78003. {
  78004. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78005. paletteEntry[0],
  78006. paletteEntry[1],
  78007. paletteEntry[2]);
  78008. ((PixelARGB*) p)->premultiply();
  78009. }
  78010. else
  78011. {
  78012. ((PixelRGB*) p)->setARGB (0,
  78013. paletteEntry[0],
  78014. paletteEntry[1],
  78015. paletteEntry[2]);
  78016. }
  78017. p += destData.pixelStride;
  78018. ++xpos;
  78019. if (xpos == destData.width)
  78020. {
  78021. xpos = 0;
  78022. if (interlace)
  78023. {
  78024. switch (pass)
  78025. {
  78026. case 0:
  78027. case 1: ypos += 8; break;
  78028. case 2: ypos += 4; break;
  78029. case 3: ypos += 2; break;
  78030. }
  78031. while (ypos >= destData.height)
  78032. {
  78033. ++pass;
  78034. switch (pass)
  78035. {
  78036. case 1: ypos = 4; break;
  78037. case 2: ypos = 2; break;
  78038. case 3: ypos = 1; break;
  78039. default: return true;
  78040. }
  78041. }
  78042. }
  78043. else
  78044. {
  78045. ++ypos;
  78046. }
  78047. p = destData.getPixelPointer (xpos, ypos);
  78048. }
  78049. if (ypos >= destData.height)
  78050. break;
  78051. }
  78052. return true;
  78053. }
  78054. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78055. GIFLoader (const GIFLoader&);
  78056. GIFLoader& operator= (const GIFLoader&);
  78057. };
  78058. #endif
  78059. GIFImageFormat::GIFImageFormat() {}
  78060. GIFImageFormat::~GIFImageFormat() {}
  78061. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78062. bool GIFImageFormat::canUnderstand (InputStream& in)
  78063. {
  78064. char header [4];
  78065. return (in.read (header, sizeof (header)) == sizeof (header))
  78066. && header[0] == 'G'
  78067. && header[1] == 'I'
  78068. && header[2] == 'F';
  78069. }
  78070. const Image GIFImageFormat::decodeImage (InputStream& in)
  78071. {
  78072. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78073. return juce_loadWithCoreImage (in);
  78074. #else
  78075. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78076. return loader->image;
  78077. #endif
  78078. }
  78079. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78080. {
  78081. jassertfalse; // writing isn't implemented for GIFs!
  78082. return false;
  78083. }
  78084. END_JUCE_NAMESPACE
  78085. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78086. #endif
  78087. //==============================================================================
  78088. // some files include lots of library code, so leave them to the end to avoid cluttering
  78089. // up the build for the clean files.
  78090. #if JUCE_BUILD_CORE
  78091. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78092. namespace zlibNamespace
  78093. {
  78094. #if JUCE_INCLUDE_ZLIB_CODE
  78095. #undef OS_CODE
  78096. #undef fdopen
  78097. /*** Start of inlined file: zlib.h ***/
  78098. #ifndef ZLIB_H
  78099. #define ZLIB_H
  78100. /*** Start of inlined file: zconf.h ***/
  78101. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78102. #ifndef ZCONF_H
  78103. #define ZCONF_H
  78104. // *** Just a few hacks here to make it compile nicely with Juce..
  78105. #define Z_PREFIX 1
  78106. #undef __MACTYPES__
  78107. #ifdef _MSC_VER
  78108. #pragma warning (disable : 4131 4127 4244 4267)
  78109. #endif
  78110. /*
  78111. * If you *really* need a unique prefix for all types and library functions,
  78112. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78113. */
  78114. #ifdef Z_PREFIX
  78115. # define deflateInit_ z_deflateInit_
  78116. # define deflate z_deflate
  78117. # define deflateEnd z_deflateEnd
  78118. # define inflateInit_ z_inflateInit_
  78119. # define inflate z_inflate
  78120. # define inflateEnd z_inflateEnd
  78121. # define inflatePrime z_inflatePrime
  78122. # define inflateGetHeader z_inflateGetHeader
  78123. # define adler32_combine z_adler32_combine
  78124. # define crc32_combine z_crc32_combine
  78125. # define deflateInit2_ z_deflateInit2_
  78126. # define deflateSetDictionary z_deflateSetDictionary
  78127. # define deflateCopy z_deflateCopy
  78128. # define deflateReset z_deflateReset
  78129. # define deflateParams z_deflateParams
  78130. # define deflateBound z_deflateBound
  78131. # define deflatePrime z_deflatePrime
  78132. # define inflateInit2_ z_inflateInit2_
  78133. # define inflateSetDictionary z_inflateSetDictionary
  78134. # define inflateSync z_inflateSync
  78135. # define inflateSyncPoint z_inflateSyncPoint
  78136. # define inflateCopy z_inflateCopy
  78137. # define inflateReset z_inflateReset
  78138. # define inflateBack z_inflateBack
  78139. # define inflateBackEnd z_inflateBackEnd
  78140. # define compress z_compress
  78141. # define compress2 z_compress2
  78142. # define compressBound z_compressBound
  78143. # define uncompress z_uncompress
  78144. # define adler32 z_adler32
  78145. # define crc32 z_crc32
  78146. # define get_crc_table z_get_crc_table
  78147. # define zError z_zError
  78148. # define alloc_func z_alloc_func
  78149. # define free_func z_free_func
  78150. # define in_func z_in_func
  78151. # define out_func z_out_func
  78152. # define Byte z_Byte
  78153. # define uInt z_uInt
  78154. # define uLong z_uLong
  78155. # define Bytef z_Bytef
  78156. # define charf z_charf
  78157. # define intf z_intf
  78158. # define uIntf z_uIntf
  78159. # define uLongf z_uLongf
  78160. # define voidpf z_voidpf
  78161. # define voidp z_voidp
  78162. #endif
  78163. #if defined(__MSDOS__) && !defined(MSDOS)
  78164. # define MSDOS
  78165. #endif
  78166. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78167. # define OS2
  78168. #endif
  78169. #if defined(_WINDOWS) && !defined(WINDOWS)
  78170. # define WINDOWS
  78171. #endif
  78172. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78173. # ifndef WIN32
  78174. # define WIN32
  78175. # endif
  78176. #endif
  78177. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78178. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78179. # ifndef SYS16BIT
  78180. # define SYS16BIT
  78181. # endif
  78182. # endif
  78183. #endif
  78184. /*
  78185. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78186. * than 64k bytes at a time (needed on systems with 16-bit int).
  78187. */
  78188. #ifdef SYS16BIT
  78189. # define MAXSEG_64K
  78190. #endif
  78191. #ifdef MSDOS
  78192. # define UNALIGNED_OK
  78193. #endif
  78194. #ifdef __STDC_VERSION__
  78195. # ifndef STDC
  78196. # define STDC
  78197. # endif
  78198. # if __STDC_VERSION__ >= 199901L
  78199. # ifndef STDC99
  78200. # define STDC99
  78201. # endif
  78202. # endif
  78203. #endif
  78204. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78205. # define STDC
  78206. #endif
  78207. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78208. # define STDC
  78209. #endif
  78210. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78211. # define STDC
  78212. #endif
  78213. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78214. # define STDC
  78215. #endif
  78216. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78217. # define STDC
  78218. #endif
  78219. #ifndef STDC
  78220. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78221. # define const /* note: need a more gentle solution here */
  78222. # endif
  78223. #endif
  78224. /* Some Mac compilers merge all .h files incorrectly: */
  78225. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78226. # define NO_DUMMY_DECL
  78227. #endif
  78228. /* Maximum value for memLevel in deflateInit2 */
  78229. #ifndef MAX_MEM_LEVEL
  78230. # ifdef MAXSEG_64K
  78231. # define MAX_MEM_LEVEL 8
  78232. # else
  78233. # define MAX_MEM_LEVEL 9
  78234. # endif
  78235. #endif
  78236. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78237. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78238. * created by gzip. (Files created by minigzip can still be extracted by
  78239. * gzip.)
  78240. */
  78241. #ifndef MAX_WBITS
  78242. # define MAX_WBITS 15 /* 32K LZ77 window */
  78243. #endif
  78244. /* The memory requirements for deflate are (in bytes):
  78245. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78246. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78247. plus a few kilobytes for small objects. For example, if you want to reduce
  78248. the default memory requirements from 256K to 128K, compile with
  78249. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78250. Of course this will generally degrade compression (there's no free lunch).
  78251. The memory requirements for inflate are (in bytes) 1 << windowBits
  78252. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78253. for small objects.
  78254. */
  78255. /* Type declarations */
  78256. #ifndef OF /* function prototypes */
  78257. # ifdef STDC
  78258. # define OF(args) args
  78259. # else
  78260. # define OF(args) ()
  78261. # endif
  78262. #endif
  78263. /* The following definitions for FAR are needed only for MSDOS mixed
  78264. * model programming (small or medium model with some far allocations).
  78265. * This was tested only with MSC; for other MSDOS compilers you may have
  78266. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78267. * just define FAR to be empty.
  78268. */
  78269. #ifdef SYS16BIT
  78270. # if defined(M_I86SM) || defined(M_I86MM)
  78271. /* MSC small or medium model */
  78272. # define SMALL_MEDIUM
  78273. # ifdef _MSC_VER
  78274. # define FAR _far
  78275. # else
  78276. # define FAR far
  78277. # endif
  78278. # endif
  78279. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78280. /* Turbo C small or medium model */
  78281. # define SMALL_MEDIUM
  78282. # ifdef __BORLANDC__
  78283. # define FAR _far
  78284. # else
  78285. # define FAR far
  78286. # endif
  78287. # endif
  78288. #endif
  78289. #if defined(WINDOWS) || defined(WIN32)
  78290. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78291. * This is not mandatory, but it offers a little performance increase.
  78292. */
  78293. # ifdef ZLIB_DLL
  78294. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78295. # ifdef ZLIB_INTERNAL
  78296. # define ZEXTERN extern __declspec(dllexport)
  78297. # else
  78298. # define ZEXTERN extern __declspec(dllimport)
  78299. # endif
  78300. # endif
  78301. # endif /* ZLIB_DLL */
  78302. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78303. * define ZLIB_WINAPI.
  78304. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78305. */
  78306. # ifdef ZLIB_WINAPI
  78307. # ifdef FAR
  78308. # undef FAR
  78309. # endif
  78310. # include <windows.h>
  78311. /* No need for _export, use ZLIB.DEF instead. */
  78312. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78313. # define ZEXPORT WINAPI
  78314. # ifdef WIN32
  78315. # define ZEXPORTVA WINAPIV
  78316. # else
  78317. # define ZEXPORTVA FAR CDECL
  78318. # endif
  78319. # endif
  78320. #endif
  78321. #if defined (__BEOS__)
  78322. # ifdef ZLIB_DLL
  78323. # ifdef ZLIB_INTERNAL
  78324. # define ZEXPORT __declspec(dllexport)
  78325. # define ZEXPORTVA __declspec(dllexport)
  78326. # else
  78327. # define ZEXPORT __declspec(dllimport)
  78328. # define ZEXPORTVA __declspec(dllimport)
  78329. # endif
  78330. # endif
  78331. #endif
  78332. #ifndef ZEXTERN
  78333. # define ZEXTERN extern
  78334. #endif
  78335. #ifndef ZEXPORT
  78336. # define ZEXPORT
  78337. #endif
  78338. #ifndef ZEXPORTVA
  78339. # define ZEXPORTVA
  78340. #endif
  78341. #ifndef FAR
  78342. # define FAR
  78343. #endif
  78344. #if !defined(__MACTYPES__)
  78345. typedef unsigned char Byte; /* 8 bits */
  78346. #endif
  78347. typedef unsigned int uInt; /* 16 bits or more */
  78348. typedef unsigned long uLong; /* 32 bits or more */
  78349. #ifdef SMALL_MEDIUM
  78350. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78351. # define Bytef Byte FAR
  78352. #else
  78353. typedef Byte FAR Bytef;
  78354. #endif
  78355. typedef char FAR charf;
  78356. typedef int FAR intf;
  78357. typedef uInt FAR uIntf;
  78358. typedef uLong FAR uLongf;
  78359. #ifdef STDC
  78360. typedef void const *voidpc;
  78361. typedef void FAR *voidpf;
  78362. typedef void *voidp;
  78363. #else
  78364. typedef Byte const *voidpc;
  78365. typedef Byte FAR *voidpf;
  78366. typedef Byte *voidp;
  78367. #endif
  78368. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78369. # include <sys/types.h> /* for off_t */
  78370. # include <unistd.h> /* for SEEK_* and off_t */
  78371. # ifdef VMS
  78372. # include <unixio.h> /* for off_t */
  78373. # endif
  78374. # define z_off_t off_t
  78375. #endif
  78376. #ifndef SEEK_SET
  78377. # define SEEK_SET 0 /* Seek from beginning of file. */
  78378. # define SEEK_CUR 1 /* Seek from current position. */
  78379. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78380. #endif
  78381. #ifndef z_off_t
  78382. # define z_off_t long
  78383. #endif
  78384. #if defined(__OS400__)
  78385. # define NO_vsnprintf
  78386. #endif
  78387. #if defined(__MVS__)
  78388. # define NO_vsnprintf
  78389. # ifdef FAR
  78390. # undef FAR
  78391. # endif
  78392. #endif
  78393. /* MVS linker does not support external names larger than 8 bytes */
  78394. #if defined(__MVS__)
  78395. # pragma map(deflateInit_,"DEIN")
  78396. # pragma map(deflateInit2_,"DEIN2")
  78397. # pragma map(deflateEnd,"DEEND")
  78398. # pragma map(deflateBound,"DEBND")
  78399. # pragma map(inflateInit_,"ININ")
  78400. # pragma map(inflateInit2_,"ININ2")
  78401. # pragma map(inflateEnd,"INEND")
  78402. # pragma map(inflateSync,"INSY")
  78403. # pragma map(inflateSetDictionary,"INSEDI")
  78404. # pragma map(compressBound,"CMBND")
  78405. # pragma map(inflate_table,"INTABL")
  78406. # pragma map(inflate_fast,"INFA")
  78407. # pragma map(inflate_copyright,"INCOPY")
  78408. #endif
  78409. #endif /* ZCONF_H */
  78410. /*** End of inlined file: zconf.h ***/
  78411. #ifdef __cplusplus
  78412. //extern "C" {
  78413. #endif
  78414. #define ZLIB_VERSION "1.2.3"
  78415. #define ZLIB_VERNUM 0x1230
  78416. /*
  78417. The 'zlib' compression library provides in-memory compression and
  78418. decompression functions, including integrity checks of the uncompressed
  78419. data. This version of the library supports only one compression method
  78420. (deflation) but other algorithms will be added later and will have the same
  78421. stream interface.
  78422. Compression can be done in a single step if the buffers are large
  78423. enough (for example if an input file is mmap'ed), or can be done by
  78424. repeated calls of the compression function. In the latter case, the
  78425. application must provide more input and/or consume the output
  78426. (providing more output space) before each call.
  78427. The compressed data format used by default by the in-memory functions is
  78428. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78429. around a deflate stream, which is itself documented in RFC 1951.
  78430. The library also supports reading and writing files in gzip (.gz) format
  78431. with an interface similar to that of stdio using the functions that start
  78432. with "gz". The gzip format is different from the zlib format. gzip is a
  78433. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78434. This library can optionally read and write gzip streams in memory as well.
  78435. The zlib format was designed to be compact and fast for use in memory
  78436. and on communications channels. The gzip format was designed for single-
  78437. file compression on file systems, has a larger header than zlib to maintain
  78438. directory information, and uses a different, slower check method than zlib.
  78439. The library does not install any signal handler. The decoder checks
  78440. the consistency of the compressed data, so the library should never
  78441. crash even in case of corrupted input.
  78442. */
  78443. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78444. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78445. struct internal_state;
  78446. typedef struct z_stream_s {
  78447. Bytef *next_in; /* next input byte */
  78448. uInt avail_in; /* number of bytes available at next_in */
  78449. uLong total_in; /* total nb of input bytes read so far */
  78450. Bytef *next_out; /* next output byte should be put there */
  78451. uInt avail_out; /* remaining free space at next_out */
  78452. uLong total_out; /* total nb of bytes output so far */
  78453. char *msg; /* last error message, NULL if no error */
  78454. struct internal_state FAR *state; /* not visible by applications */
  78455. alloc_func zalloc; /* used to allocate the internal state */
  78456. free_func zfree; /* used to free the internal state */
  78457. voidpf opaque; /* private data object passed to zalloc and zfree */
  78458. int data_type; /* best guess about the data type: binary or text */
  78459. uLong adler; /* adler32 value of the uncompressed data */
  78460. uLong reserved; /* reserved for future use */
  78461. } z_stream;
  78462. typedef z_stream FAR *z_streamp;
  78463. /*
  78464. gzip header information passed to and from zlib routines. See RFC 1952
  78465. for more details on the meanings of these fields.
  78466. */
  78467. typedef struct gz_header_s {
  78468. int text; /* true if compressed data believed to be text */
  78469. uLong time; /* modification time */
  78470. int xflags; /* extra flags (not used when writing a gzip file) */
  78471. int os; /* operating system */
  78472. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78473. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78474. uInt extra_max; /* space at extra (only when reading header) */
  78475. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78476. uInt name_max; /* space at name (only when reading header) */
  78477. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78478. uInt comm_max; /* space at comment (only when reading header) */
  78479. int hcrc; /* true if there was or will be a header crc */
  78480. int done; /* true when done reading gzip header (not used
  78481. when writing a gzip file) */
  78482. } gz_header;
  78483. typedef gz_header FAR *gz_headerp;
  78484. /*
  78485. The application must update next_in and avail_in when avail_in has
  78486. dropped to zero. It must update next_out and avail_out when avail_out
  78487. has dropped to zero. The application must initialize zalloc, zfree and
  78488. opaque before calling the init function. All other fields are set by the
  78489. compression library and must not be updated by the application.
  78490. The opaque value provided by the application will be passed as the first
  78491. parameter for calls of zalloc and zfree. This can be useful for custom
  78492. memory management. The compression library attaches no meaning to the
  78493. opaque value.
  78494. zalloc must return Z_NULL if there is not enough memory for the object.
  78495. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78496. thread safe.
  78497. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78498. exactly 65536 bytes, but will not be required to allocate more than this
  78499. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78500. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78501. have their offset normalized to zero. The default allocation function
  78502. provided by this library ensures this (see zutil.c). To reduce memory
  78503. requirements and avoid any allocation of 64K objects, at the expense of
  78504. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78505. The fields total_in and total_out can be used for statistics or
  78506. progress reports. After compression, total_in holds the total size of
  78507. the uncompressed data and may be saved for use in the decompressor
  78508. (particularly if the decompressor wants to decompress everything in
  78509. a single step).
  78510. */
  78511. /* constants */
  78512. #define Z_NO_FLUSH 0
  78513. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78514. #define Z_SYNC_FLUSH 2
  78515. #define Z_FULL_FLUSH 3
  78516. #define Z_FINISH 4
  78517. #define Z_BLOCK 5
  78518. /* Allowed flush values; see deflate() and inflate() below for details */
  78519. #define Z_OK 0
  78520. #define Z_STREAM_END 1
  78521. #define Z_NEED_DICT 2
  78522. #define Z_ERRNO (-1)
  78523. #define Z_STREAM_ERROR (-2)
  78524. #define Z_DATA_ERROR (-3)
  78525. #define Z_MEM_ERROR (-4)
  78526. #define Z_BUF_ERROR (-5)
  78527. #define Z_VERSION_ERROR (-6)
  78528. /* Return codes for the compression/decompression functions. Negative
  78529. * values are errors, positive values are used for special but normal events.
  78530. */
  78531. #define Z_NO_COMPRESSION 0
  78532. #define Z_BEST_SPEED 1
  78533. #define Z_BEST_COMPRESSION 9
  78534. #define Z_DEFAULT_COMPRESSION (-1)
  78535. /* compression levels */
  78536. #define Z_FILTERED 1
  78537. #define Z_HUFFMAN_ONLY 2
  78538. #define Z_RLE 3
  78539. #define Z_FIXED 4
  78540. #define Z_DEFAULT_STRATEGY 0
  78541. /* compression strategy; see deflateInit2() below for details */
  78542. #define Z_BINARY 0
  78543. #define Z_TEXT 1
  78544. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78545. #define Z_UNKNOWN 2
  78546. /* Possible values of the data_type field (though see inflate()) */
  78547. #define Z_DEFLATED 8
  78548. /* The deflate compression method (the only one supported in this version) */
  78549. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78550. #define zlib_version zlibVersion()
  78551. /* for compatibility with versions < 1.0.2 */
  78552. /* basic functions */
  78553. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78554. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78555. If the first character differs, the library code actually used is
  78556. not compatible with the zlib.h header file used by the application.
  78557. This check is automatically made by deflateInit and inflateInit.
  78558. */
  78559. /*
  78560. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78561. Initializes the internal stream state for compression. The fields
  78562. zalloc, zfree and opaque must be initialized before by the caller.
  78563. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78564. use default allocation functions.
  78565. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78566. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78567. all (the input data is simply copied a block at a time).
  78568. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78569. compression (currently equivalent to level 6).
  78570. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78571. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78572. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78573. with the version assumed by the caller (ZLIB_VERSION).
  78574. msg is set to null if there is no error message. deflateInit does not
  78575. perform any compression: this will be done by deflate().
  78576. */
  78577. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78578. /*
  78579. deflate compresses as much data as possible, and stops when the input
  78580. buffer becomes empty or the output buffer becomes full. It may introduce some
  78581. output latency (reading input without producing any output) except when
  78582. forced to flush.
  78583. The detailed semantics are as follows. deflate performs one or both of the
  78584. following actions:
  78585. - Compress more input starting at next_in and update next_in and avail_in
  78586. accordingly. If not all input can be processed (because there is not
  78587. enough room in the output buffer), next_in and avail_in are updated and
  78588. processing will resume at this point for the next call of deflate().
  78589. - Provide more output starting at next_out and update next_out and avail_out
  78590. accordingly. This action is forced if the parameter flush is non zero.
  78591. Forcing flush frequently degrades the compression ratio, so this parameter
  78592. should be set only when necessary (in interactive applications).
  78593. Some output may be provided even if flush is not set.
  78594. Before the call of deflate(), the application should ensure that at least
  78595. one of the actions is possible, by providing more input and/or consuming
  78596. more output, and updating avail_in or avail_out accordingly; avail_out
  78597. should never be zero before the call. The application can consume the
  78598. compressed output when it wants, for example when the output buffer is full
  78599. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78600. and with zero avail_out, it must be called again after making room in the
  78601. output buffer because there might be more output pending.
  78602. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78603. decide how much data to accumualte before producing output, in order to
  78604. maximize compression.
  78605. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78606. flushed to the output buffer and the output is aligned on a byte boundary, so
  78607. that the decompressor can get all input data available so far. (In particular
  78608. avail_in is zero after the call if enough output space has been provided
  78609. before the call.) Flushing may degrade compression for some compression
  78610. algorithms and so it should be used only when necessary.
  78611. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78612. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78613. restart from this point if previous compressed data has been damaged or if
  78614. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78615. compression.
  78616. If deflate returns with avail_out == 0, this function must be called again
  78617. with the same value of the flush parameter and more output space (updated
  78618. avail_out), until the flush is complete (deflate returns with non-zero
  78619. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78620. avail_out is greater than six to avoid repeated flush markers due to
  78621. avail_out == 0 on return.
  78622. If the parameter flush is set to Z_FINISH, pending input is processed,
  78623. pending output is flushed and deflate returns with Z_STREAM_END if there
  78624. was enough output space; if deflate returns with Z_OK, this function must be
  78625. called again with Z_FINISH and more output space (updated avail_out) but no
  78626. more input data, until it returns with Z_STREAM_END or an error. After
  78627. deflate has returned Z_STREAM_END, the only possible operations on the
  78628. stream are deflateReset or deflateEnd.
  78629. Z_FINISH can be used immediately after deflateInit if all the compression
  78630. is to be done in a single step. In this case, avail_out must be at least
  78631. the value returned by deflateBound (see below). If deflate does not return
  78632. Z_STREAM_END, then it must be called again as described above.
  78633. deflate() sets strm->adler to the adler32 checksum of all input read
  78634. so far (that is, total_in bytes).
  78635. deflate() may update strm->data_type if it can make a good guess about
  78636. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78637. binary. This field is only for information purposes and does not affect
  78638. the compression algorithm in any manner.
  78639. deflate() returns Z_OK if some progress has been made (more input
  78640. processed or more output produced), Z_STREAM_END if all input has been
  78641. consumed and all output has been produced (only when flush is set to
  78642. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78643. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78644. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78645. fatal, and deflate() can be called again with more input and more output
  78646. space to continue compressing.
  78647. */
  78648. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78649. /*
  78650. All dynamically allocated data structures for this stream are freed.
  78651. This function discards any unprocessed input and does not flush any
  78652. pending output.
  78653. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78654. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78655. prematurely (some input or output was discarded). In the error case,
  78656. msg may be set but then points to a static string (which must not be
  78657. deallocated).
  78658. */
  78659. /*
  78660. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78661. Initializes the internal stream state for decompression. The fields
  78662. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78663. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78664. value depends on the compression method), inflateInit determines the
  78665. compression method from the zlib header and allocates all data structures
  78666. accordingly; otherwise the allocation will be deferred to the first call of
  78667. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78668. use default allocation functions.
  78669. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78670. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78671. version assumed by the caller. msg is set to null if there is no error
  78672. message. inflateInit does not perform any decompression apart from reading
  78673. the zlib header if present: this will be done by inflate(). (So next_in and
  78674. avail_in may be modified, but next_out and avail_out are unchanged.)
  78675. */
  78676. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78677. /*
  78678. inflate decompresses as much data as possible, and stops when the input
  78679. buffer becomes empty or the output buffer becomes full. It may introduce
  78680. some output latency (reading input without producing any output) except when
  78681. forced to flush.
  78682. The detailed semantics are as follows. inflate performs one or both of the
  78683. following actions:
  78684. - Decompress more input starting at next_in and update next_in and avail_in
  78685. accordingly. If not all input can be processed (because there is not
  78686. enough room in the output buffer), next_in is updated and processing
  78687. will resume at this point for the next call of inflate().
  78688. - Provide more output starting at next_out and update next_out and avail_out
  78689. accordingly. inflate() provides as much output as possible, until there
  78690. is no more input data or no more space in the output buffer (see below
  78691. about the flush parameter).
  78692. Before the call of inflate(), the application should ensure that at least
  78693. one of the actions is possible, by providing more input and/or consuming
  78694. more output, and updating the next_* and avail_* values accordingly.
  78695. The application can consume the uncompressed output when it wants, for
  78696. example when the output buffer is full (avail_out == 0), or after each
  78697. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78698. must be called again after making room in the output buffer because there
  78699. might be more output pending.
  78700. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78701. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78702. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78703. if and when it gets to the next deflate block boundary. When decoding the
  78704. zlib or gzip format, this will cause inflate() to return immediately after
  78705. the header and before the first block. When doing a raw inflate, inflate()
  78706. will go ahead and process the first block, and will return when it gets to
  78707. the end of that block, or when it runs out of data.
  78708. The Z_BLOCK option assists in appending to or combining deflate streams.
  78709. Also to assist in this, on return inflate() will set strm->data_type to the
  78710. number of unused bits in the last byte taken from strm->next_in, plus 64
  78711. if inflate() is currently decoding the last block in the deflate stream,
  78712. plus 128 if inflate() returned immediately after decoding an end-of-block
  78713. code or decoding the complete header up to just before the first byte of the
  78714. deflate stream. The end-of-block will not be indicated until all of the
  78715. uncompressed data from that block has been written to strm->next_out. The
  78716. number of unused bits may in general be greater than seven, except when
  78717. bit 7 of data_type is set, in which case the number of unused bits will be
  78718. less than eight.
  78719. inflate() should normally be called until it returns Z_STREAM_END or an
  78720. error. However if all decompression is to be performed in a single step
  78721. (a single call of inflate), the parameter flush should be set to
  78722. Z_FINISH. In this case all pending input is processed and all pending
  78723. output is flushed; avail_out must be large enough to hold all the
  78724. uncompressed data. (The size of the uncompressed data may have been saved
  78725. by the compressor for this purpose.) The next operation on this stream must
  78726. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78727. is never required, but can be used to inform inflate that a faster approach
  78728. may be used for the single inflate() call.
  78729. In this implementation, inflate() always flushes as much output as
  78730. possible to the output buffer, and always uses the faster approach on the
  78731. first call. So the only effect of the flush parameter in this implementation
  78732. is on the return value of inflate(), as noted below, or when it returns early
  78733. because Z_BLOCK is used.
  78734. If a preset dictionary is needed after this call (see inflateSetDictionary
  78735. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78736. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78737. strm->adler to the adler32 checksum of all output produced so far (that is,
  78738. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78739. below. At the end of the stream, inflate() checks that its computed adler32
  78740. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78741. only if the checksum is correct.
  78742. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78743. deflate data. The header type is detected automatically. Any information
  78744. contained in the gzip header is not retained, so applications that need that
  78745. information should instead use raw inflate, see inflateInit2() below, or
  78746. inflateBack() and perform their own processing of the gzip header and
  78747. trailer.
  78748. inflate() returns Z_OK if some progress has been made (more input processed
  78749. or more output produced), Z_STREAM_END if the end of the compressed data has
  78750. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78751. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78752. corrupted (input stream not conforming to the zlib format or incorrect check
  78753. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78754. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78755. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78756. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78757. inflate() can be called again with more input and more output space to
  78758. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78759. call inflateSync() to look for a good compression block if a partial recovery
  78760. of the data is desired.
  78761. */
  78762. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78763. /*
  78764. All dynamically allocated data structures for this stream are freed.
  78765. This function discards any unprocessed input and does not flush any
  78766. pending output.
  78767. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78768. was inconsistent. In the error case, msg may be set but then points to a
  78769. static string (which must not be deallocated).
  78770. */
  78771. /* Advanced functions */
  78772. /*
  78773. The following functions are needed only in some special applications.
  78774. */
  78775. /*
  78776. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78777. int level,
  78778. int method,
  78779. int windowBits,
  78780. int memLevel,
  78781. int strategy));
  78782. This is another version of deflateInit with more compression options. The
  78783. fields next_in, zalloc, zfree and opaque must be initialized before by
  78784. the caller.
  78785. The method parameter is the compression method. It must be Z_DEFLATED in
  78786. this version of the library.
  78787. The windowBits parameter is the base two logarithm of the window size
  78788. (the size of the history buffer). It should be in the range 8..15 for this
  78789. version of the library. Larger values of this parameter result in better
  78790. compression at the expense of memory usage. The default value is 15 if
  78791. deflateInit is used instead.
  78792. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78793. determines the window size. deflate() will then generate raw deflate data
  78794. with no zlib header or trailer, and will not compute an adler32 check value.
  78795. windowBits can also be greater than 15 for optional gzip encoding. Add
  78796. 16 to windowBits to write a simple gzip header and trailer around the
  78797. compressed data instead of a zlib wrapper. The gzip header will have no
  78798. file name, no extra data, no comment, no modification time (set to zero),
  78799. no header crc, and the operating system will be set to 255 (unknown). If a
  78800. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78801. The memLevel parameter specifies how much memory should be allocated
  78802. for the internal compression state. memLevel=1 uses minimum memory but
  78803. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78804. for optimal speed. The default value is 8. See zconf.h for total memory
  78805. usage as a function of windowBits and memLevel.
  78806. The strategy parameter is used to tune the compression algorithm. Use the
  78807. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78808. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78809. string match), or Z_RLE to limit match distances to one (run-length
  78810. encoding). Filtered data consists mostly of small values with a somewhat
  78811. random distribution. In this case, the compression algorithm is tuned to
  78812. compress them better. The effect of Z_FILTERED is to force more Huffman
  78813. coding and less string matching; it is somewhat intermediate between
  78814. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78815. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78816. parameter only affects the compression ratio but not the correctness of the
  78817. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78818. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78819. applications.
  78820. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78821. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78822. method). msg is set to null if there is no error message. deflateInit2 does
  78823. not perform any compression: this will be done by deflate().
  78824. */
  78825. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78826. const Bytef *dictionary,
  78827. uInt dictLength));
  78828. /*
  78829. Initializes the compression dictionary from the given byte sequence
  78830. without producing any compressed output. This function must be called
  78831. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78832. call of deflate. The compressor and decompressor must use exactly the same
  78833. dictionary (see inflateSetDictionary).
  78834. The dictionary should consist of strings (byte sequences) that are likely
  78835. to be encountered later in the data to be compressed, with the most commonly
  78836. used strings preferably put towards the end of the dictionary. Using a
  78837. dictionary is most useful when the data to be compressed is short and can be
  78838. predicted with good accuracy; the data can then be compressed better than
  78839. with the default empty dictionary.
  78840. Depending on the size of the compression data structures selected by
  78841. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78842. discarded, for example if the dictionary is larger than the window size in
  78843. deflate or deflate2. Thus the strings most likely to be useful should be
  78844. put at the end of the dictionary, not at the front. In addition, the
  78845. current implementation of deflate will use at most the window size minus
  78846. 262 bytes of the provided dictionary.
  78847. Upon return of this function, strm->adler is set to the adler32 value
  78848. of the dictionary; the decompressor may later use this value to determine
  78849. which dictionary has been used by the compressor. (The adler32 value
  78850. applies to the whole dictionary even if only a subset of the dictionary is
  78851. actually used by the compressor.) If a raw deflate was requested, then the
  78852. adler32 value is not computed and strm->adler is not set.
  78853. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78854. parameter is invalid (such as NULL dictionary) or the stream state is
  78855. inconsistent (for example if deflate has already been called for this stream
  78856. or if the compression method is bsort). deflateSetDictionary does not
  78857. perform any compression: this will be done by deflate().
  78858. */
  78859. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78860. z_streamp source));
  78861. /*
  78862. Sets the destination stream as a complete copy of the source stream.
  78863. This function can be useful when several compression strategies will be
  78864. tried, for example when there are several ways of pre-processing the input
  78865. data with a filter. The streams that will be discarded should then be freed
  78866. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78867. compression state which can be quite large, so this strategy is slow and
  78868. can consume lots of memory.
  78869. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78870. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78871. (such as zalloc being NULL). msg is left unchanged in both source and
  78872. destination.
  78873. */
  78874. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78875. /*
  78876. This function is equivalent to deflateEnd followed by deflateInit,
  78877. but does not free and reallocate all the internal compression state.
  78878. The stream will keep the same compression level and any other attributes
  78879. that may have been set by deflateInit2.
  78880. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78881. stream state was inconsistent (such as zalloc or state being NULL).
  78882. */
  78883. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78884. int level,
  78885. int strategy));
  78886. /*
  78887. Dynamically update the compression level and compression strategy. The
  78888. interpretation of level and strategy is as in deflateInit2. This can be
  78889. used to switch between compression and straight copy of the input data, or
  78890. to switch to a different kind of input data requiring a different
  78891. strategy. If the compression level is changed, the input available so far
  78892. is compressed with the old level (and may be flushed); the new level will
  78893. take effect only at the next call of deflate().
  78894. Before the call of deflateParams, the stream state must be set as for
  78895. a call of deflate(), since the currently available input may have to
  78896. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78897. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78898. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78899. if strm->avail_out was zero.
  78900. */
  78901. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78902. int good_length,
  78903. int max_lazy,
  78904. int nice_length,
  78905. int max_chain));
  78906. /*
  78907. Fine tune deflate's internal compression parameters. This should only be
  78908. used by someone who understands the algorithm used by zlib's deflate for
  78909. searching for the best matching string, and even then only by the most
  78910. fanatic optimizer trying to squeeze out the last compressed bit for their
  78911. specific input data. Read the deflate.c source code for the meaning of the
  78912. max_lazy, good_length, nice_length, and max_chain parameters.
  78913. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78914. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78915. */
  78916. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78917. uLong sourceLen));
  78918. /*
  78919. deflateBound() returns an upper bound on the compressed size after
  78920. deflation of sourceLen bytes. It must be called after deflateInit()
  78921. or deflateInit2(). This would be used to allocate an output buffer
  78922. for deflation in a single pass, and so would be called before deflate().
  78923. */
  78924. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78925. int bits,
  78926. int value));
  78927. /*
  78928. deflatePrime() inserts bits in the deflate output stream. The intent
  78929. is that this function is used to start off the deflate output with the
  78930. bits leftover from a previous deflate stream when appending to it. As such,
  78931. this function can only be used for raw deflate, and must be used before the
  78932. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78933. less than or equal to 16, and that many of the least significant bits of
  78934. value will be inserted in the output.
  78935. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78936. stream state was inconsistent.
  78937. */
  78938. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78939. gz_headerp head));
  78940. /*
  78941. deflateSetHeader() provides gzip header information for when a gzip
  78942. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78943. after deflateInit2() or deflateReset() and before the first call of
  78944. deflate(). The text, time, os, extra field, name, and comment information
  78945. in the provided gz_header structure are written to the gzip header (xflag is
  78946. ignored -- the extra flags are set according to the compression level). The
  78947. caller must assure that, if not Z_NULL, name and comment are terminated with
  78948. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78949. available there. If hcrc is true, a gzip header crc is included. Note that
  78950. the current versions of the command-line version of gzip (up through version
  78951. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78952. gzip file" and give up.
  78953. If deflateSetHeader is not used, the default gzip header has text false,
  78954. the time set to zero, and os set to 255, with no extra, name, or comment
  78955. fields. The gzip header is returned to the default state by deflateReset().
  78956. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78957. stream state was inconsistent.
  78958. */
  78959. /*
  78960. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78961. int windowBits));
  78962. This is another version of inflateInit with an extra parameter. The
  78963. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78964. before by the caller.
  78965. The windowBits parameter is the base two logarithm of the maximum window
  78966. size (the size of the history buffer). It should be in the range 8..15 for
  78967. this version of the library. The default value is 15 if inflateInit is used
  78968. instead. windowBits must be greater than or equal to the windowBits value
  78969. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78970. deflateInit2() was not used. If a compressed stream with a larger window
  78971. size is given as input, inflate() will return with the error code
  78972. Z_DATA_ERROR instead of trying to allocate a larger window.
  78973. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78974. determines the window size. inflate() will then process raw deflate data,
  78975. not looking for a zlib or gzip header, not generating a check value, and not
  78976. looking for any check values for comparison at the end of the stream. This
  78977. is for use with other formats that use the deflate compressed data format
  78978. such as zip. Those formats provide their own check values. If a custom
  78979. format is developed using the raw deflate format for compressed data, it is
  78980. recommended that a check value such as an adler32 or a crc32 be applied to
  78981. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78982. most applications, the zlib format should be used as is. Note that comments
  78983. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78984. windowBits can also be greater than 15 for optional gzip decoding. Add
  78985. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78986. detection, or add 16 to decode only the gzip format (the zlib format will
  78987. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78988. a crc32 instead of an adler32.
  78989. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78990. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78991. is set to null if there is no error message. inflateInit2 does not perform
  78992. any decompression apart from reading the zlib header if present: this will
  78993. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78994. and avail_out are unchanged.)
  78995. */
  78996. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78997. const Bytef *dictionary,
  78998. uInt dictLength));
  78999. /*
  79000. Initializes the decompression dictionary from the given uncompressed byte
  79001. sequence. This function must be called immediately after a call of inflate,
  79002. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79003. can be determined from the adler32 value returned by that call of inflate.
  79004. The compressor and decompressor must use exactly the same dictionary (see
  79005. deflateSetDictionary). For raw inflate, this function can be called
  79006. immediately after inflateInit2() or inflateReset() and before any call of
  79007. inflate() to set the dictionary. The application must insure that the
  79008. dictionary that was used for compression is provided.
  79009. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79010. parameter is invalid (such as NULL dictionary) or the stream state is
  79011. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79012. expected one (incorrect adler32 value). inflateSetDictionary does not
  79013. perform any decompression: this will be done by subsequent calls of
  79014. inflate().
  79015. */
  79016. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79017. /*
  79018. Skips invalid compressed data until a full flush point (see above the
  79019. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79020. available input is skipped. No output is provided.
  79021. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79022. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79023. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79024. case, the application may save the current current value of total_in which
  79025. indicates where valid compressed data was found. In the error case, the
  79026. application may repeatedly call inflateSync, providing more input each time,
  79027. until success or end of the input data.
  79028. */
  79029. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79030. z_streamp source));
  79031. /*
  79032. Sets the destination stream as a complete copy of the source stream.
  79033. This function can be useful when randomly accessing a large stream. The
  79034. first pass through the stream can periodically record the inflate state,
  79035. allowing restarting inflate at those points when randomly accessing the
  79036. stream.
  79037. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79038. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79039. (such as zalloc being NULL). msg is left unchanged in both source and
  79040. destination.
  79041. */
  79042. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79043. /*
  79044. This function is equivalent to inflateEnd followed by inflateInit,
  79045. but does not free and reallocate all the internal decompression state.
  79046. The stream will keep attributes that may have been set by inflateInit2.
  79047. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79048. stream state was inconsistent (such as zalloc or state being NULL).
  79049. */
  79050. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79051. int bits,
  79052. int value));
  79053. /*
  79054. This function inserts bits in the inflate input stream. The intent is
  79055. that this function is used to start inflating at a bit position in the
  79056. middle of a byte. The provided bits will be used before any bytes are used
  79057. from next_in. This function should only be used with raw inflate, and
  79058. should be used before the first inflate() call after inflateInit2() or
  79059. inflateReset(). bits must be less than or equal to 16, and that many of the
  79060. least significant bits of value will be inserted in the input.
  79061. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79062. stream state was inconsistent.
  79063. */
  79064. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79065. gz_headerp head));
  79066. /*
  79067. inflateGetHeader() requests that gzip header information be stored in the
  79068. provided gz_header structure. inflateGetHeader() may be called after
  79069. inflateInit2() or inflateReset(), and before the first call of inflate().
  79070. As inflate() processes the gzip stream, head->done is zero until the header
  79071. is completed, at which time head->done is set to one. If a zlib stream is
  79072. being decoded, then head->done is set to -1 to indicate that there will be
  79073. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79074. force inflate() to return immediately after header processing is complete
  79075. and before any actual data is decompressed.
  79076. The text, time, xflags, and os fields are filled in with the gzip header
  79077. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79078. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79079. contains the maximum number of bytes to write to extra. Once done is true,
  79080. extra_len contains the actual extra field length, and extra contains the
  79081. extra field, or that field truncated if extra_max is less than extra_len.
  79082. If name is not Z_NULL, then up to name_max characters are written there,
  79083. terminated with a zero unless the length is greater than name_max. If
  79084. comment is not Z_NULL, then up to comm_max characters are written there,
  79085. terminated with a zero unless the length is greater than comm_max. When
  79086. any of extra, name, or comment are not Z_NULL and the respective field is
  79087. not present in the header, then that field is set to Z_NULL to signal its
  79088. absence. This allows the use of deflateSetHeader() with the returned
  79089. structure to duplicate the header. However if those fields are set to
  79090. allocated memory, then the application will need to save those pointers
  79091. elsewhere so that they can be eventually freed.
  79092. If inflateGetHeader is not used, then the header information is simply
  79093. discarded. The header is always checked for validity, including the header
  79094. CRC if present. inflateReset() will reset the process to discard the header
  79095. information. The application would need to call inflateGetHeader() again to
  79096. retrieve the header from the next gzip stream.
  79097. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79098. stream state was inconsistent.
  79099. */
  79100. /*
  79101. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79102. unsigned char FAR *window));
  79103. Initialize the internal stream state for decompression using inflateBack()
  79104. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79105. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79106. derived memory allocation routines are used. windowBits is the base two
  79107. logarithm of the window size, in the range 8..15. window is a caller
  79108. supplied buffer of that size. Except for special applications where it is
  79109. assured that deflate was used with small window sizes, windowBits must be 15
  79110. and a 32K byte window must be supplied to be able to decompress general
  79111. deflate streams.
  79112. See inflateBack() for the usage of these routines.
  79113. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79114. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79115. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79116. match the version of the header file.
  79117. */
  79118. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79119. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79120. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79121. in_func in, void FAR *in_desc,
  79122. out_func out, void FAR *out_desc));
  79123. /*
  79124. inflateBack() does a raw inflate with a single call using a call-back
  79125. interface for input and output. This is more efficient than inflate() for
  79126. file i/o applications in that it avoids copying between the output and the
  79127. sliding window by simply making the window itself the output buffer. This
  79128. function trusts the application to not change the output buffer passed by
  79129. the output function, at least until inflateBack() returns.
  79130. inflateBackInit() must be called first to allocate the internal state
  79131. and to initialize the state with the user-provided window buffer.
  79132. inflateBack() may then be used multiple times to inflate a complete, raw
  79133. deflate stream with each call. inflateBackEnd() is then called to free
  79134. the allocated state.
  79135. A raw deflate stream is one with no zlib or gzip header or trailer.
  79136. This routine would normally be used in a utility that reads zip or gzip
  79137. files and writes out uncompressed files. The utility would decode the
  79138. header and process the trailer on its own, hence this routine expects
  79139. only the raw deflate stream to decompress. This is different from the
  79140. normal behavior of inflate(), which expects either a zlib or gzip header and
  79141. trailer around the deflate stream.
  79142. inflateBack() uses two subroutines supplied by the caller that are then
  79143. called by inflateBack() for input and output. inflateBack() calls those
  79144. routines until it reads a complete deflate stream and writes out all of the
  79145. uncompressed data, or until it encounters an error. The function's
  79146. parameters and return types are defined above in the in_func and out_func
  79147. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79148. number of bytes of provided input, and a pointer to that input in buf. If
  79149. there is no input available, in() must return zero--buf is ignored in that
  79150. case--and inflateBack() will return a buffer error. inflateBack() will call
  79151. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79152. should return zero on success, or non-zero on failure. If out() returns
  79153. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79154. are permitted to change the contents of the window provided to
  79155. inflateBackInit(), which is also the buffer that out() uses to write from.
  79156. The length written by out() will be at most the window size. Any non-zero
  79157. amount of input may be provided by in().
  79158. For convenience, inflateBack() can be provided input on the first call by
  79159. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79160. in() will be called. Therefore strm->next_in must be initialized before
  79161. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79162. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79163. must also be initialized, and then if strm->avail_in is not zero, input will
  79164. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79165. The in_desc and out_desc parameters of inflateBack() is passed as the
  79166. first parameter of in() and out() respectively when they are called. These
  79167. descriptors can be optionally used to pass any information that the caller-
  79168. supplied in() and out() functions need to do their job.
  79169. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79170. pass back any unused input that was provided by the last in() call. The
  79171. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79172. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79173. error in the deflate stream (in which case strm->msg is set to indicate the
  79174. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79175. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79176. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79177. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79178. out() returning non-zero. (in() will always be called before out(), so
  79179. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79180. that inflateBack() cannot return Z_OK.
  79181. */
  79182. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79183. /*
  79184. All memory allocated by inflateBackInit() is freed.
  79185. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79186. state was inconsistent.
  79187. */
  79188. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79189. /* Return flags indicating compile-time options.
  79190. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79191. 1.0: size of uInt
  79192. 3.2: size of uLong
  79193. 5.4: size of voidpf (pointer)
  79194. 7.6: size of z_off_t
  79195. Compiler, assembler, and debug options:
  79196. 8: DEBUG
  79197. 9: ASMV or ASMINF -- use ASM code
  79198. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79199. 11: 0 (reserved)
  79200. One-time table building (smaller code, but not thread-safe if true):
  79201. 12: BUILDFIXED -- build static block decoding tables when needed
  79202. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79203. 14,15: 0 (reserved)
  79204. Library content (indicates missing functionality):
  79205. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79206. deflate code when not needed)
  79207. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79208. and decode gzip streams (to avoid linking crc code)
  79209. 18-19: 0 (reserved)
  79210. Operation variations (changes in library functionality):
  79211. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79212. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79213. 22,23: 0 (reserved)
  79214. The sprintf variant used by gzprintf (zero is best):
  79215. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79216. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79217. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79218. Remainder:
  79219. 27-31: 0 (reserved)
  79220. */
  79221. /* utility functions */
  79222. /*
  79223. The following utility functions are implemented on top of the
  79224. basic stream-oriented functions. To simplify the interface, some
  79225. default options are assumed (compression level and memory usage,
  79226. standard memory allocation functions). The source code of these
  79227. utility functions can easily be modified if you need special options.
  79228. */
  79229. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79230. const Bytef *source, uLong sourceLen));
  79231. /*
  79232. Compresses the source buffer into the destination buffer. sourceLen is
  79233. the byte length of the source buffer. Upon entry, destLen is the total
  79234. size of the destination buffer, which must be at least the value returned
  79235. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79236. compressed buffer.
  79237. This function can be used to compress a whole file at once if the
  79238. input file is mmap'ed.
  79239. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79240. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79241. buffer.
  79242. */
  79243. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79244. const Bytef *source, uLong sourceLen,
  79245. int level));
  79246. /*
  79247. Compresses the source buffer into the destination buffer. The level
  79248. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79249. length of the source buffer. Upon entry, destLen is the total size of the
  79250. destination buffer, which must be at least the value returned by
  79251. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79252. compressed buffer.
  79253. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79254. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79255. Z_STREAM_ERROR if the level parameter is invalid.
  79256. */
  79257. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79258. /*
  79259. compressBound() returns an upper bound on the compressed size after
  79260. compress() or compress2() on sourceLen bytes. It would be used before
  79261. a compress() or compress2() call to allocate the destination buffer.
  79262. */
  79263. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79264. const Bytef *source, uLong sourceLen));
  79265. /*
  79266. Decompresses the source buffer into the destination buffer. sourceLen is
  79267. the byte length of the source buffer. Upon entry, destLen is the total
  79268. size of the destination buffer, which must be large enough to hold the
  79269. entire uncompressed data. (The size of the uncompressed data must have
  79270. been saved previously by the compressor and transmitted to the decompressor
  79271. by some mechanism outside the scope of this compression library.)
  79272. Upon exit, destLen is the actual size of the compressed buffer.
  79273. This function can be used to decompress a whole file at once if the
  79274. input file is mmap'ed.
  79275. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79276. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79277. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79278. */
  79279. typedef voidp gzFile;
  79280. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79281. /*
  79282. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79283. is as in fopen ("rb" or "wb") but can also include a compression level
  79284. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79285. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79286. as in "wb1R". (See the description of deflateInit2 for more information
  79287. about the strategy parameter.)
  79288. gzopen can be used to read a file which is not in gzip format; in this
  79289. case gzread will directly read from the file without decompression.
  79290. gzopen returns NULL if the file could not be opened or if there was
  79291. insufficient memory to allocate the (de)compression state; errno
  79292. can be checked to distinguish the two cases (if errno is zero, the
  79293. zlib error is Z_MEM_ERROR). */
  79294. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79295. /*
  79296. gzdopen() associates a gzFile with the file descriptor fd. File
  79297. descriptors are obtained from calls like open, dup, creat, pipe or
  79298. fileno (in the file has been previously opened with fopen).
  79299. The mode parameter is as in gzopen.
  79300. The next call of gzclose on the returned gzFile will also close the
  79301. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79302. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79303. gzdopen returns NULL if there was insufficient memory to allocate
  79304. the (de)compression state.
  79305. */
  79306. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79307. /*
  79308. Dynamically update the compression level or strategy. See the description
  79309. of deflateInit2 for the meaning of these parameters.
  79310. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79311. opened for writing.
  79312. */
  79313. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79314. /*
  79315. Reads the given number of uncompressed bytes from the compressed file.
  79316. If the input file was not in gzip format, gzread copies the given number
  79317. of bytes into the buffer.
  79318. gzread returns the number of uncompressed bytes actually read (0 for
  79319. end of file, -1 for error). */
  79320. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79321. voidpc buf, unsigned len));
  79322. /*
  79323. Writes the given number of uncompressed bytes into the compressed file.
  79324. gzwrite returns the number of uncompressed bytes actually written
  79325. (0 in case of error).
  79326. */
  79327. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79328. /*
  79329. Converts, formats, and writes the args to the compressed file under
  79330. control of the format string, as in fprintf. gzprintf returns the number of
  79331. uncompressed bytes actually written (0 in case of error). The number of
  79332. uncompressed bytes written is limited to 4095. The caller should assure that
  79333. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79334. return an error (0) with nothing written. In this case, there may also be a
  79335. buffer overflow with unpredictable consequences, which is possible only if
  79336. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79337. because the secure snprintf() or vsnprintf() functions were not available.
  79338. */
  79339. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79340. /*
  79341. Writes the given null-terminated string to the compressed file, excluding
  79342. the terminating null character.
  79343. gzputs returns the number of characters written, or -1 in case of error.
  79344. */
  79345. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79346. /*
  79347. Reads bytes from the compressed file until len-1 characters are read, or
  79348. a newline character is read and transferred to buf, or an end-of-file
  79349. condition is encountered. The string is then terminated with a null
  79350. character.
  79351. gzgets returns buf, or Z_NULL in case of error.
  79352. */
  79353. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79354. /*
  79355. Writes c, converted to an unsigned char, into the compressed file.
  79356. gzputc returns the value that was written, or -1 in case of error.
  79357. */
  79358. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79359. /*
  79360. Reads one byte from the compressed file. gzgetc returns this byte
  79361. or -1 in case of end of file or error.
  79362. */
  79363. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79364. /*
  79365. Push one character back onto the stream to be read again later.
  79366. Only one character of push-back is allowed. gzungetc() returns the
  79367. character pushed, or -1 on failure. gzungetc() will fail if a
  79368. character has been pushed but not read yet, or if c is -1. The pushed
  79369. character will be discarded if the stream is repositioned with gzseek()
  79370. or gzrewind().
  79371. */
  79372. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79373. /*
  79374. Flushes all pending output into the compressed file. The parameter
  79375. flush is as in the deflate() function. The return value is the zlib
  79376. error number (see function gzerror below). gzflush returns Z_OK if
  79377. the flush parameter is Z_FINISH and all output could be flushed.
  79378. gzflush should be called only when strictly necessary because it can
  79379. degrade compression.
  79380. */
  79381. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79382. z_off_t offset, int whence));
  79383. /*
  79384. Sets the starting position for the next gzread or gzwrite on the
  79385. given compressed file. The offset represents a number of bytes in the
  79386. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79387. the value SEEK_END is not supported.
  79388. If the file is opened for reading, this function is emulated but can be
  79389. extremely slow. If the file is opened for writing, only forward seeks are
  79390. supported; gzseek then compresses a sequence of zeroes up to the new
  79391. starting position.
  79392. gzseek returns the resulting offset location as measured in bytes from
  79393. the beginning of the uncompressed stream, or -1 in case of error, in
  79394. particular if the file is opened for writing and the new starting position
  79395. would be before the current position.
  79396. */
  79397. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79398. /*
  79399. Rewinds the given file. This function is supported only for reading.
  79400. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79401. */
  79402. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79403. /*
  79404. Returns the starting position for the next gzread or gzwrite on the
  79405. given compressed file. This position represents a number of bytes in the
  79406. uncompressed data stream.
  79407. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79408. */
  79409. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79410. /*
  79411. Returns 1 when EOF has previously been detected reading the given
  79412. input stream, otherwise zero.
  79413. */
  79414. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79415. /*
  79416. Returns 1 if file is being read directly without decompression, otherwise
  79417. zero.
  79418. */
  79419. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79420. /*
  79421. Flushes all pending output if necessary, closes the compressed file
  79422. and deallocates all the (de)compression state. The return value is the zlib
  79423. error number (see function gzerror below).
  79424. */
  79425. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79426. /*
  79427. Returns the error message for the last error which occurred on the
  79428. given compressed file. errnum is set to zlib error number. If an
  79429. error occurred in the file system and not in the compression library,
  79430. errnum is set to Z_ERRNO and the application may consult errno
  79431. to get the exact error code.
  79432. */
  79433. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79434. /*
  79435. Clears the error and end-of-file flags for file. This is analogous to the
  79436. clearerr() function in stdio. This is useful for continuing to read a gzip
  79437. file that is being written concurrently.
  79438. */
  79439. /* checksum functions */
  79440. /*
  79441. These functions are not related to compression but are exported
  79442. anyway because they might be useful in applications using the
  79443. compression library.
  79444. */
  79445. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79446. /*
  79447. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79448. return the updated checksum. If buf is NULL, this function returns
  79449. the required initial value for the checksum.
  79450. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79451. much faster. Usage example:
  79452. uLong adler = adler32(0L, Z_NULL, 0);
  79453. while (read_buffer(buffer, length) != EOF) {
  79454. adler = adler32(adler, buffer, length);
  79455. }
  79456. if (adler != original_adler) error();
  79457. */
  79458. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79459. z_off_t len2));
  79460. /*
  79461. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79462. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79463. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79464. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79465. */
  79466. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79467. /*
  79468. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79469. updated CRC-32. If buf is NULL, this function returns the required initial
  79470. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79471. performed within this function so it shouldn't be done by the application.
  79472. Usage example:
  79473. uLong crc = crc32(0L, Z_NULL, 0);
  79474. while (read_buffer(buffer, length) != EOF) {
  79475. crc = crc32(crc, buffer, length);
  79476. }
  79477. if (crc != original_crc) error();
  79478. */
  79479. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79480. /*
  79481. Combine two CRC-32 check values into one. For two sequences of bytes,
  79482. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79483. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79484. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79485. len2.
  79486. */
  79487. /* various hacks, don't look :) */
  79488. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79489. * and the compiler's view of z_stream:
  79490. */
  79491. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79492. const char *version, int stream_size));
  79493. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79494. const char *version, int stream_size));
  79495. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79496. int windowBits, int memLevel,
  79497. int strategy, const char *version,
  79498. int stream_size));
  79499. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79500. const char *version, int stream_size));
  79501. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79502. unsigned char FAR *window,
  79503. const char *version,
  79504. int stream_size));
  79505. #define deflateInit(strm, level) \
  79506. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79507. #define inflateInit(strm) \
  79508. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79509. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79510. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79511. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79512. #define inflateInit2(strm, windowBits) \
  79513. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79514. #define inflateBackInit(strm, windowBits, window) \
  79515. inflateBackInit_((strm), (windowBits), (window), \
  79516. ZLIB_VERSION, sizeof(z_stream))
  79517. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79518. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79519. #endif
  79520. ZEXTERN const char * ZEXPORT zError OF((int));
  79521. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79522. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79523. #ifdef __cplusplus
  79524. //}
  79525. #endif
  79526. #endif /* ZLIB_H */
  79527. /*** End of inlined file: zlib.h ***/
  79528. #undef OS_CODE
  79529. #else
  79530. #include <zlib.h>
  79531. #endif
  79532. }
  79533. BEGIN_JUCE_NAMESPACE
  79534. // internal helper object that holds the zlib structures so they don't have to be
  79535. // included publicly.
  79536. class GZIPCompressorHelper
  79537. {
  79538. public:
  79539. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79540. : data (0),
  79541. dataSize (0),
  79542. compLevel (compressionLevel),
  79543. strategy (0),
  79544. setParams (true),
  79545. streamIsValid (false),
  79546. finished (false),
  79547. shouldFinish (false)
  79548. {
  79549. using namespace zlibNamespace;
  79550. zerostruct (stream);
  79551. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79552. nowrap ? -MAX_WBITS : MAX_WBITS,
  79553. 8, strategy) == Z_OK);
  79554. }
  79555. ~GZIPCompressorHelper()
  79556. {
  79557. using namespace zlibNamespace;
  79558. if (streamIsValid)
  79559. deflateEnd (&stream);
  79560. }
  79561. bool needsInput() const throw()
  79562. {
  79563. return dataSize <= 0;
  79564. }
  79565. void setInput (const uint8* const newData, const int size) throw()
  79566. {
  79567. data = newData;
  79568. dataSize = size;
  79569. }
  79570. int doNextBlock (uint8* const dest, const int destSize) throw()
  79571. {
  79572. using namespace zlibNamespace;
  79573. if (streamIsValid)
  79574. {
  79575. stream.next_in = const_cast <uint8*> (data);
  79576. stream.next_out = dest;
  79577. stream.avail_in = dataSize;
  79578. stream.avail_out = destSize;
  79579. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79580. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79581. setParams = false;
  79582. switch (result)
  79583. {
  79584. case Z_STREAM_END:
  79585. finished = true;
  79586. // Deliberate fall-through..
  79587. case Z_OK:
  79588. data += dataSize - stream.avail_in;
  79589. dataSize = stream.avail_in;
  79590. return destSize - stream.avail_out;
  79591. default:
  79592. break;
  79593. }
  79594. }
  79595. return 0;
  79596. }
  79597. private:
  79598. zlibNamespace::z_stream stream;
  79599. const uint8* data;
  79600. int dataSize, compLevel, strategy;
  79601. bool setParams, streamIsValid;
  79602. public:
  79603. bool finished, shouldFinish;
  79604. };
  79605. const int gzipCompBufferSize = 32768;
  79606. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79607. int compressionLevel,
  79608. const bool deleteDestStream,
  79609. const bool noWrap)
  79610. : destStream (destStream_),
  79611. streamToDelete (deleteDestStream ? destStream_ : 0),
  79612. buffer (gzipCompBufferSize)
  79613. {
  79614. if (compressionLevel < 1 || compressionLevel > 9)
  79615. compressionLevel = -1;
  79616. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79617. }
  79618. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79619. {
  79620. flush();
  79621. }
  79622. void GZIPCompressorOutputStream::flush()
  79623. {
  79624. if (! helper->finished)
  79625. {
  79626. helper->shouldFinish = true;
  79627. while (! helper->finished)
  79628. doNextBlock();
  79629. }
  79630. destStream->flush();
  79631. }
  79632. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79633. {
  79634. if (! helper->finished)
  79635. {
  79636. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79637. while (! helper->needsInput())
  79638. {
  79639. if (! doNextBlock())
  79640. return false;
  79641. }
  79642. }
  79643. return true;
  79644. }
  79645. bool GZIPCompressorOutputStream::doNextBlock()
  79646. {
  79647. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79648. if (len > 0)
  79649. return destStream->write (buffer, len);
  79650. else
  79651. return true;
  79652. }
  79653. int64 GZIPCompressorOutputStream::getPosition()
  79654. {
  79655. return destStream->getPosition();
  79656. }
  79657. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79658. {
  79659. jassertfalse; // can't do it!
  79660. return false;
  79661. }
  79662. END_JUCE_NAMESPACE
  79663. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79664. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79665. #if JUCE_MSVC
  79666. #pragma warning (push)
  79667. #pragma warning (disable: 4309 4305)
  79668. #endif
  79669. namespace zlibNamespace
  79670. {
  79671. #if JUCE_INCLUDE_ZLIB_CODE
  79672. #undef OS_CODE
  79673. #undef fdopen
  79674. #define ZLIB_INTERNAL
  79675. #define NO_DUMMY_DECL
  79676. /*** Start of inlined file: adler32.c ***/
  79677. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79678. #define ZLIB_INTERNAL
  79679. #define BASE 65521UL /* largest prime smaller than 65536 */
  79680. #define NMAX 5552
  79681. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79682. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79683. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79684. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79685. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79686. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79687. /* use NO_DIVIDE if your processor does not do division in hardware */
  79688. #ifdef NO_DIVIDE
  79689. # define MOD(a) \
  79690. do { \
  79691. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79692. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79693. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79694. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79695. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79696. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79697. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79698. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79699. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79700. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79701. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79702. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79703. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79704. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79705. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79706. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79707. if (a >= BASE) a -= BASE; \
  79708. } while (0)
  79709. # define MOD4(a) \
  79710. do { \
  79711. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79712. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79713. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79714. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79715. if (a >= BASE) a -= BASE; \
  79716. } while (0)
  79717. #else
  79718. # define MOD(a) a %= BASE
  79719. # define MOD4(a) a %= BASE
  79720. #endif
  79721. /* ========================================================================= */
  79722. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79723. {
  79724. unsigned long sum2;
  79725. unsigned n;
  79726. /* split Adler-32 into component sums */
  79727. sum2 = (adler >> 16) & 0xffff;
  79728. adler &= 0xffff;
  79729. /* in case user likes doing a byte at a time, keep it fast */
  79730. if (len == 1) {
  79731. adler += buf[0];
  79732. if (adler >= BASE)
  79733. adler -= BASE;
  79734. sum2 += adler;
  79735. if (sum2 >= BASE)
  79736. sum2 -= BASE;
  79737. return adler | (sum2 << 16);
  79738. }
  79739. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79740. if (buf == Z_NULL)
  79741. return 1L;
  79742. /* in case short lengths are provided, keep it somewhat fast */
  79743. if (len < 16) {
  79744. while (len--) {
  79745. adler += *buf++;
  79746. sum2 += adler;
  79747. }
  79748. if (adler >= BASE)
  79749. adler -= BASE;
  79750. MOD4(sum2); /* only added so many BASE's */
  79751. return adler | (sum2 << 16);
  79752. }
  79753. /* do length NMAX blocks -- requires just one modulo operation */
  79754. while (len >= NMAX) {
  79755. len -= NMAX;
  79756. n = NMAX / 16; /* NMAX is divisible by 16 */
  79757. do {
  79758. DO16(buf); /* 16 sums unrolled */
  79759. buf += 16;
  79760. } while (--n);
  79761. MOD(adler);
  79762. MOD(sum2);
  79763. }
  79764. /* do remaining bytes (less than NMAX, still just one modulo) */
  79765. if (len) { /* avoid modulos if none remaining */
  79766. while (len >= 16) {
  79767. len -= 16;
  79768. DO16(buf);
  79769. buf += 16;
  79770. }
  79771. while (len--) {
  79772. adler += *buf++;
  79773. sum2 += adler;
  79774. }
  79775. MOD(adler);
  79776. MOD(sum2);
  79777. }
  79778. /* return recombined sums */
  79779. return adler | (sum2 << 16);
  79780. }
  79781. /* ========================================================================= */
  79782. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79783. {
  79784. unsigned long sum1;
  79785. unsigned long sum2;
  79786. unsigned rem;
  79787. /* the derivation of this formula is left as an exercise for the reader */
  79788. rem = (unsigned)(len2 % BASE);
  79789. sum1 = adler1 & 0xffff;
  79790. sum2 = rem * sum1;
  79791. MOD(sum2);
  79792. sum1 += (adler2 & 0xffff) + BASE - 1;
  79793. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79794. if (sum1 > BASE) sum1 -= BASE;
  79795. if (sum1 > BASE) sum1 -= BASE;
  79796. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79797. if (sum2 > BASE) sum2 -= BASE;
  79798. return sum1 | (sum2 << 16);
  79799. }
  79800. /*** End of inlined file: adler32.c ***/
  79801. /*** Start of inlined file: compress.c ***/
  79802. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79803. #define ZLIB_INTERNAL
  79804. /* ===========================================================================
  79805. Compresses the source buffer into the destination buffer. The level
  79806. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79807. length of the source buffer. Upon entry, destLen is the total size of the
  79808. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79809. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79810. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79811. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79812. Z_STREAM_ERROR if the level parameter is invalid.
  79813. */
  79814. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79815. uLong sourceLen, int level)
  79816. {
  79817. z_stream stream;
  79818. int err;
  79819. stream.next_in = (Bytef*)source;
  79820. stream.avail_in = (uInt)sourceLen;
  79821. #ifdef MAXSEG_64K
  79822. /* Check for source > 64K on 16-bit machine: */
  79823. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79824. #endif
  79825. stream.next_out = dest;
  79826. stream.avail_out = (uInt)*destLen;
  79827. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79828. stream.zalloc = (alloc_func)0;
  79829. stream.zfree = (free_func)0;
  79830. stream.opaque = (voidpf)0;
  79831. err = deflateInit(&stream, level);
  79832. if (err != Z_OK) return err;
  79833. err = deflate(&stream, Z_FINISH);
  79834. if (err != Z_STREAM_END) {
  79835. deflateEnd(&stream);
  79836. return err == Z_OK ? Z_BUF_ERROR : err;
  79837. }
  79838. *destLen = stream.total_out;
  79839. err = deflateEnd(&stream);
  79840. return err;
  79841. }
  79842. /* ===========================================================================
  79843. */
  79844. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79845. {
  79846. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79847. }
  79848. /* ===========================================================================
  79849. If the default memLevel or windowBits for deflateInit() is changed, then
  79850. this function needs to be updated.
  79851. */
  79852. uLong ZEXPORT compressBound (uLong sourceLen)
  79853. {
  79854. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79855. }
  79856. /*** End of inlined file: compress.c ***/
  79857. #undef DO1
  79858. #undef DO8
  79859. /*** Start of inlined file: crc32.c ***/
  79860. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79861. /*
  79862. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79863. protection on the static variables used to control the first-use generation
  79864. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79865. first call get_crc_table() to initialize the tables before allowing more than
  79866. one thread to use crc32().
  79867. */
  79868. #ifdef MAKECRCH
  79869. # include <stdio.h>
  79870. # ifndef DYNAMIC_CRC_TABLE
  79871. # define DYNAMIC_CRC_TABLE
  79872. # endif /* !DYNAMIC_CRC_TABLE */
  79873. #endif /* MAKECRCH */
  79874. /*** Start of inlined file: zutil.h ***/
  79875. /* WARNING: this file should *not* be used by applications. It is
  79876. part of the implementation of the compression library and is
  79877. subject to change. Applications should only use zlib.h.
  79878. */
  79879. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79880. #ifndef ZUTIL_H
  79881. #define ZUTIL_H
  79882. #define ZLIB_INTERNAL
  79883. #ifdef STDC
  79884. # ifndef _WIN32_WCE
  79885. # include <stddef.h>
  79886. # endif
  79887. # include <string.h>
  79888. # include <stdlib.h>
  79889. #endif
  79890. #ifdef NO_ERRNO_H
  79891. # ifdef _WIN32_WCE
  79892. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79893. * errno. We define it as a global variable to simplify porting.
  79894. * Its value is always 0 and should not be used. We rename it to
  79895. * avoid conflict with other libraries that use the same workaround.
  79896. */
  79897. # define errno z_errno
  79898. # endif
  79899. extern int errno;
  79900. #else
  79901. # ifndef _WIN32_WCE
  79902. # include <errno.h>
  79903. # endif
  79904. #endif
  79905. #ifndef local
  79906. # define local static
  79907. #endif
  79908. /* compile with -Dlocal if your debugger can't find static symbols */
  79909. typedef unsigned char uch;
  79910. typedef uch FAR uchf;
  79911. typedef unsigned short ush;
  79912. typedef ush FAR ushf;
  79913. typedef unsigned long ulg;
  79914. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79915. /* (size given to avoid silly warnings with Visual C++) */
  79916. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79917. #define ERR_RETURN(strm,err) \
  79918. return (strm->msg = (char*)ERR_MSG(err), (err))
  79919. /* To be used only when the state is known to be valid */
  79920. /* common constants */
  79921. #ifndef DEF_WBITS
  79922. # define DEF_WBITS MAX_WBITS
  79923. #endif
  79924. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79925. #if MAX_MEM_LEVEL >= 8
  79926. # define DEF_MEM_LEVEL 8
  79927. #else
  79928. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79929. #endif
  79930. /* default memLevel */
  79931. #define STORED_BLOCK 0
  79932. #define STATIC_TREES 1
  79933. #define DYN_TREES 2
  79934. /* The three kinds of block type */
  79935. #define MIN_MATCH 3
  79936. #define MAX_MATCH 258
  79937. /* The minimum and maximum match lengths */
  79938. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79939. /* target dependencies */
  79940. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79941. # define OS_CODE 0x00
  79942. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79943. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79944. /* Allow compilation with ANSI keywords only enabled */
  79945. void _Cdecl farfree( void *block );
  79946. void *_Cdecl farmalloc( unsigned long nbytes );
  79947. # else
  79948. # include <alloc.h>
  79949. # endif
  79950. # else /* MSC or DJGPP */
  79951. # include <malloc.h>
  79952. # endif
  79953. #endif
  79954. #ifdef AMIGA
  79955. # define OS_CODE 0x01
  79956. #endif
  79957. #if defined(VAXC) || defined(VMS)
  79958. # define OS_CODE 0x02
  79959. # define F_OPEN(name, mode) \
  79960. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79961. #endif
  79962. #if defined(ATARI) || defined(atarist)
  79963. # define OS_CODE 0x05
  79964. #endif
  79965. #ifdef OS2
  79966. # define OS_CODE 0x06
  79967. # ifdef M_I86
  79968. #include <malloc.h>
  79969. # endif
  79970. #endif
  79971. #if defined(MACOS) || TARGET_OS_MAC
  79972. # define OS_CODE 0x07
  79973. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79974. # include <unix.h> /* for fdopen */
  79975. # else
  79976. # ifndef fdopen
  79977. # define fdopen(fd,mode) NULL /* No fdopen() */
  79978. # endif
  79979. # endif
  79980. #endif
  79981. #ifdef TOPS20
  79982. # define OS_CODE 0x0a
  79983. #endif
  79984. #ifdef WIN32
  79985. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79986. # define OS_CODE 0x0b
  79987. # endif
  79988. #endif
  79989. #ifdef __50SERIES /* Prime/PRIMOS */
  79990. # define OS_CODE 0x0f
  79991. #endif
  79992. #if defined(_BEOS_) || defined(RISCOS)
  79993. # define fdopen(fd,mode) NULL /* No fdopen() */
  79994. #endif
  79995. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79996. # if defined(_WIN32_WCE)
  79997. # define fdopen(fd,mode) NULL /* No fdopen() */
  79998. # ifndef _PTRDIFF_T_DEFINED
  79999. typedef int ptrdiff_t;
  80000. # define _PTRDIFF_T_DEFINED
  80001. # endif
  80002. # else
  80003. # define fdopen(fd,type) _fdopen(fd,type)
  80004. # endif
  80005. #endif
  80006. /* common defaults */
  80007. #ifndef OS_CODE
  80008. # define OS_CODE 0x03 /* assume Unix */
  80009. #endif
  80010. #ifndef F_OPEN
  80011. # define F_OPEN(name, mode) fopen((name), (mode))
  80012. #endif
  80013. /* functions */
  80014. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80015. # ifndef HAVE_VSNPRINTF
  80016. # define HAVE_VSNPRINTF
  80017. # endif
  80018. #endif
  80019. #if defined(__CYGWIN__)
  80020. # ifndef HAVE_VSNPRINTF
  80021. # define HAVE_VSNPRINTF
  80022. # endif
  80023. #endif
  80024. #ifndef HAVE_VSNPRINTF
  80025. # ifdef MSDOS
  80026. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80027. but for now we just assume it doesn't. */
  80028. # define NO_vsnprintf
  80029. # endif
  80030. # ifdef __TURBOC__
  80031. # define NO_vsnprintf
  80032. # endif
  80033. # ifdef WIN32
  80034. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80035. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80036. # define vsnprintf _vsnprintf
  80037. # endif
  80038. # endif
  80039. # ifdef __SASC
  80040. # define NO_vsnprintf
  80041. # endif
  80042. #endif
  80043. #ifdef VMS
  80044. # define NO_vsnprintf
  80045. #endif
  80046. #if defined(pyr)
  80047. # define NO_MEMCPY
  80048. #endif
  80049. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80050. /* Use our own functions for small and medium model with MSC <= 5.0.
  80051. * You may have to use the same strategy for Borland C (untested).
  80052. * The __SC__ check is for Symantec.
  80053. */
  80054. # define NO_MEMCPY
  80055. #endif
  80056. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80057. # define HAVE_MEMCPY
  80058. #endif
  80059. #ifdef HAVE_MEMCPY
  80060. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80061. # define zmemcpy _fmemcpy
  80062. # define zmemcmp _fmemcmp
  80063. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80064. # else
  80065. # define zmemcpy memcpy
  80066. # define zmemcmp memcmp
  80067. # define zmemzero(dest, len) memset(dest, 0, len)
  80068. # endif
  80069. #else
  80070. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80071. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80072. extern void zmemzero OF((Bytef* dest, uInt len));
  80073. #endif
  80074. /* Diagnostic functions */
  80075. #ifdef DEBUG
  80076. # include <stdio.h>
  80077. extern int z_verbose;
  80078. extern void z_error OF((const char *m));
  80079. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80080. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80081. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80082. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80083. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80084. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80085. #else
  80086. # define Assert(cond,msg)
  80087. # define Trace(x)
  80088. # define Tracev(x)
  80089. # define Tracevv(x)
  80090. # define Tracec(c,x)
  80091. # define Tracecv(c,x)
  80092. #endif
  80093. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80094. void zcfree OF((voidpf opaque, voidpf ptr));
  80095. #define ZALLOC(strm, items, size) \
  80096. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80097. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80098. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80099. #endif /* ZUTIL_H */
  80100. /*** End of inlined file: zutil.h ***/
  80101. /* for STDC and FAR definitions */
  80102. #define local static
  80103. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80104. #ifndef NOBYFOUR
  80105. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80106. # include <limits.h>
  80107. # define BYFOUR
  80108. # if (UINT_MAX == 0xffffffffUL)
  80109. typedef unsigned int u4;
  80110. # else
  80111. # if (ULONG_MAX == 0xffffffffUL)
  80112. typedef unsigned long u4;
  80113. # else
  80114. # if (USHRT_MAX == 0xffffffffUL)
  80115. typedef unsigned short u4;
  80116. # else
  80117. # undef BYFOUR /* can't find a four-byte integer type! */
  80118. # endif
  80119. # endif
  80120. # endif
  80121. # endif /* STDC */
  80122. #endif /* !NOBYFOUR */
  80123. /* Definitions for doing the crc four data bytes at a time. */
  80124. #ifdef BYFOUR
  80125. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80126. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80127. local unsigned long crc32_little OF((unsigned long,
  80128. const unsigned char FAR *, unsigned));
  80129. local unsigned long crc32_big OF((unsigned long,
  80130. const unsigned char FAR *, unsigned));
  80131. # define TBLS 8
  80132. #else
  80133. # define TBLS 1
  80134. #endif /* BYFOUR */
  80135. /* Local functions for crc concatenation */
  80136. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80137. unsigned long vec));
  80138. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80139. #ifdef DYNAMIC_CRC_TABLE
  80140. local volatile int crc_table_empty = 1;
  80141. local unsigned long FAR crc_table[TBLS][256];
  80142. local void make_crc_table OF((void));
  80143. #ifdef MAKECRCH
  80144. local void write_table OF((FILE *, const unsigned long FAR *));
  80145. #endif /* MAKECRCH */
  80146. /*
  80147. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80148. 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.
  80149. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80150. with the lowest powers in the most significant bit. Then adding polynomials
  80151. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80152. one. If we call the above polynomial p, and represent a byte as the
  80153. polynomial q, also with the lowest power in the most significant bit (so the
  80154. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80155. where a mod b means the remainder after dividing a by b.
  80156. This calculation is done using the shift-register method of multiplying and
  80157. taking the remainder. The register is initialized to zero, and for each
  80158. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80159. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80160. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80161. out is a one). We start with the highest power (least significant bit) of
  80162. q and repeat for all eight bits of q.
  80163. The first table is simply the CRC of all possible eight bit values. This is
  80164. all the information needed to generate CRCs on data a byte at a time for all
  80165. combinations of CRC register values and incoming bytes. The remaining tables
  80166. allow for word-at-a-time CRC calculation for both big-endian and little-
  80167. endian machines, where a word is four bytes.
  80168. */
  80169. local void make_crc_table()
  80170. {
  80171. unsigned long c;
  80172. int n, k;
  80173. unsigned long poly; /* polynomial exclusive-or pattern */
  80174. /* terms of polynomial defining this crc (except x^32): */
  80175. static volatile int first = 1; /* flag to limit concurrent making */
  80176. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80177. /* See if another task is already doing this (not thread-safe, but better
  80178. than nothing -- significantly reduces duration of vulnerability in
  80179. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80180. if (first) {
  80181. first = 0;
  80182. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80183. poly = 0UL;
  80184. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80185. poly |= 1UL << (31 - p[n]);
  80186. /* generate a crc for every 8-bit value */
  80187. for (n = 0; n < 256; n++) {
  80188. c = (unsigned long)n;
  80189. for (k = 0; k < 8; k++)
  80190. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80191. crc_table[0][n] = c;
  80192. }
  80193. #ifdef BYFOUR
  80194. /* generate crc for each value followed by one, two, and three zeros,
  80195. and then the byte reversal of those as well as the first table */
  80196. for (n = 0; n < 256; n++) {
  80197. c = crc_table[0][n];
  80198. crc_table[4][n] = REV(c);
  80199. for (k = 1; k < 4; k++) {
  80200. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80201. crc_table[k][n] = c;
  80202. crc_table[k + 4][n] = REV(c);
  80203. }
  80204. }
  80205. #endif /* BYFOUR */
  80206. crc_table_empty = 0;
  80207. }
  80208. else { /* not first */
  80209. /* wait for the other guy to finish (not efficient, but rare) */
  80210. while (crc_table_empty)
  80211. ;
  80212. }
  80213. #ifdef MAKECRCH
  80214. /* write out CRC tables to crc32.h */
  80215. {
  80216. FILE *out;
  80217. out = fopen("crc32.h", "w");
  80218. if (out == NULL) return;
  80219. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80220. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80221. fprintf(out, "local const unsigned long FAR ");
  80222. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80223. write_table(out, crc_table[0]);
  80224. # ifdef BYFOUR
  80225. fprintf(out, "#ifdef BYFOUR\n");
  80226. for (k = 1; k < 8; k++) {
  80227. fprintf(out, " },\n {\n");
  80228. write_table(out, crc_table[k]);
  80229. }
  80230. fprintf(out, "#endif\n");
  80231. # endif /* BYFOUR */
  80232. fprintf(out, " }\n};\n");
  80233. fclose(out);
  80234. }
  80235. #endif /* MAKECRCH */
  80236. }
  80237. #ifdef MAKECRCH
  80238. local void write_table(out, table)
  80239. FILE *out;
  80240. const unsigned long FAR *table;
  80241. {
  80242. int n;
  80243. for (n = 0; n < 256; n++)
  80244. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80245. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80246. }
  80247. #endif /* MAKECRCH */
  80248. #else /* !DYNAMIC_CRC_TABLE */
  80249. /* ========================================================================
  80250. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80251. */
  80252. /*** Start of inlined file: crc32.h ***/
  80253. local const unsigned long FAR crc_table[TBLS][256] =
  80254. {
  80255. {
  80256. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80257. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80258. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80259. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80260. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80261. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80262. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80263. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80264. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80265. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80266. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80267. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80268. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80269. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80270. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80271. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80272. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80273. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80274. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80275. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80276. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80277. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80278. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80279. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80280. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80281. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80282. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80283. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80284. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80285. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80286. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80287. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80288. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80289. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80290. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80291. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80292. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80293. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80294. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80295. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80296. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80297. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80298. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80299. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80300. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80301. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80302. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80303. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80304. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80305. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80306. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80307. 0x2d02ef8dUL
  80308. #ifdef BYFOUR
  80309. },
  80310. {
  80311. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80312. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80313. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80314. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80315. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80316. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80317. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80318. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80319. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80320. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80321. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80322. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80323. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80324. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80325. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80326. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80327. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80328. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80329. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80330. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80331. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80332. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80333. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80334. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80335. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80336. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80337. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80338. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80339. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80340. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80341. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80342. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80343. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80344. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80345. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80346. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80347. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80348. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80349. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80350. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80351. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80352. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80353. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80354. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80355. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80356. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80357. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80358. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80359. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80360. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80361. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80362. 0x9324fd72UL
  80363. },
  80364. {
  80365. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80366. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80367. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80368. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80369. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80370. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80371. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80372. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80373. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80374. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80375. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80376. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80377. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80378. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80379. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80380. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80381. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80382. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80383. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80384. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80385. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80386. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80387. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80388. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80389. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80390. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80391. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80392. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80393. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80394. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80395. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80396. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80397. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80398. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80399. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80400. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80401. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80402. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80403. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80404. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80405. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80406. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80407. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80408. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80409. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80410. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80411. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80412. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80413. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80414. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80415. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80416. 0xbe9834edUL
  80417. },
  80418. {
  80419. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80420. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80421. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80422. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80423. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80424. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80425. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80426. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80427. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80428. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80429. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80430. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80431. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80432. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80433. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80434. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80435. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80436. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80437. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80438. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80439. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80440. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80441. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80442. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80443. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80444. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80445. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80446. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80447. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80448. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80449. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80450. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80451. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80452. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80453. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80454. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80455. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80456. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80457. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80458. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80459. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80460. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80461. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80462. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80463. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80464. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80465. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80466. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80467. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80468. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80469. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80470. 0xde0506f1UL
  80471. },
  80472. {
  80473. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80474. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80475. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80476. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80477. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80478. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80479. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80480. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80481. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80482. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80483. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80484. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80485. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80486. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80487. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80488. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80489. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80490. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80491. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80492. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80493. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80494. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80495. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80496. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80497. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80498. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80499. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80500. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80501. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80502. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80503. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80504. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80505. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80506. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80507. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80508. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80509. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80510. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80511. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80512. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80513. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80514. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80515. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80516. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80517. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80518. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80519. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80520. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80521. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80522. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80523. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80524. 0x8def022dUL
  80525. },
  80526. {
  80527. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80528. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80529. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80530. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80531. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80532. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80533. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80534. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80535. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80536. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80537. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80538. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80539. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80540. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80541. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80542. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80543. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80544. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80545. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80546. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80547. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80548. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80549. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80550. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80551. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80552. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80553. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80554. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80555. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80556. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80557. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80558. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80559. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80560. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80561. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80562. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80563. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80564. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80565. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80566. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80567. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80568. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80569. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80570. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80571. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80572. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80573. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80574. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80575. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80576. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80577. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80578. 0x72fd2493UL
  80579. },
  80580. {
  80581. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80582. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80583. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80584. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80585. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80586. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80587. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80588. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80589. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80590. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80591. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80592. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80593. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80594. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80595. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80596. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80597. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80598. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80599. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80600. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80601. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80602. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80603. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80604. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80605. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80606. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80607. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80608. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80609. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80610. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80611. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80612. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80613. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80614. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80615. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80616. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80617. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80618. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80619. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80620. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80621. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80622. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80623. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80624. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80625. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80626. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80627. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80628. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80629. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80630. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80631. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80632. 0xed3498beUL
  80633. },
  80634. {
  80635. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80636. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80637. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80638. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80639. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80640. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80641. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80642. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80643. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80644. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80645. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80646. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80647. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80648. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80649. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80650. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80651. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80652. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80653. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80654. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80655. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80656. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80657. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80658. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80659. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80660. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80661. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80662. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80663. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80664. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80665. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80666. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80667. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80668. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80669. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80670. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80671. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80672. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80673. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80674. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80675. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80676. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80677. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80678. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80679. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80680. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80681. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80682. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80683. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80684. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80685. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80686. 0xf10605deUL
  80687. #endif
  80688. }
  80689. };
  80690. /*** End of inlined file: crc32.h ***/
  80691. #endif /* DYNAMIC_CRC_TABLE */
  80692. /* =========================================================================
  80693. * This function can be used by asm versions of crc32()
  80694. */
  80695. const unsigned long FAR * ZEXPORT get_crc_table()
  80696. {
  80697. #ifdef DYNAMIC_CRC_TABLE
  80698. if (crc_table_empty)
  80699. make_crc_table();
  80700. #endif /* DYNAMIC_CRC_TABLE */
  80701. return (const unsigned long FAR *)crc_table;
  80702. }
  80703. /* ========================================================================= */
  80704. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80705. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80706. /* ========================================================================= */
  80707. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80708. {
  80709. if (buf == Z_NULL) return 0UL;
  80710. #ifdef DYNAMIC_CRC_TABLE
  80711. if (crc_table_empty)
  80712. make_crc_table();
  80713. #endif /* DYNAMIC_CRC_TABLE */
  80714. #ifdef BYFOUR
  80715. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80716. u4 endian;
  80717. endian = 1;
  80718. if (*((unsigned char *)(&endian)))
  80719. return crc32_little(crc, buf, len);
  80720. else
  80721. return crc32_big(crc, buf, len);
  80722. }
  80723. #endif /* BYFOUR */
  80724. crc = crc ^ 0xffffffffUL;
  80725. while (len >= 8) {
  80726. DO8;
  80727. len -= 8;
  80728. }
  80729. if (len) do {
  80730. DO1;
  80731. } while (--len);
  80732. return crc ^ 0xffffffffUL;
  80733. }
  80734. #ifdef BYFOUR
  80735. /* ========================================================================= */
  80736. #define DOLIT4 c ^= *buf4++; \
  80737. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80738. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80739. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80740. /* ========================================================================= */
  80741. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80742. {
  80743. register u4 c;
  80744. register const u4 FAR *buf4;
  80745. c = (u4)crc;
  80746. c = ~c;
  80747. while (len && ((ptrdiff_t)buf & 3)) {
  80748. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80749. len--;
  80750. }
  80751. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80752. while (len >= 32) {
  80753. DOLIT32;
  80754. len -= 32;
  80755. }
  80756. while (len >= 4) {
  80757. DOLIT4;
  80758. len -= 4;
  80759. }
  80760. buf = (const unsigned char FAR *)buf4;
  80761. if (len) do {
  80762. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80763. } while (--len);
  80764. c = ~c;
  80765. return (unsigned long)c;
  80766. }
  80767. /* ========================================================================= */
  80768. #define DOBIG4 c ^= *++buf4; \
  80769. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80770. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80771. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80772. /* ========================================================================= */
  80773. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80774. {
  80775. register u4 c;
  80776. register const u4 FAR *buf4;
  80777. c = REV((u4)crc);
  80778. c = ~c;
  80779. while (len && ((ptrdiff_t)buf & 3)) {
  80780. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80781. len--;
  80782. }
  80783. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80784. buf4--;
  80785. while (len >= 32) {
  80786. DOBIG32;
  80787. len -= 32;
  80788. }
  80789. while (len >= 4) {
  80790. DOBIG4;
  80791. len -= 4;
  80792. }
  80793. buf4++;
  80794. buf = (const unsigned char FAR *)buf4;
  80795. if (len) do {
  80796. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80797. } while (--len);
  80798. c = ~c;
  80799. return (unsigned long)(REV(c));
  80800. }
  80801. #endif /* BYFOUR */
  80802. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80803. /* ========================================================================= */
  80804. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80805. {
  80806. unsigned long sum;
  80807. sum = 0;
  80808. while (vec) {
  80809. if (vec & 1)
  80810. sum ^= *mat;
  80811. vec >>= 1;
  80812. mat++;
  80813. }
  80814. return sum;
  80815. }
  80816. /* ========================================================================= */
  80817. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80818. {
  80819. int n;
  80820. for (n = 0; n < GF2_DIM; n++)
  80821. square[n] = gf2_matrix_times(mat, mat[n]);
  80822. }
  80823. /* ========================================================================= */
  80824. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80825. {
  80826. int n;
  80827. unsigned long row;
  80828. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80829. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80830. /* degenerate case */
  80831. if (len2 == 0)
  80832. return crc1;
  80833. /* put operator for one zero bit in odd */
  80834. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80835. row = 1;
  80836. for (n = 1; n < GF2_DIM; n++) {
  80837. odd[n] = row;
  80838. row <<= 1;
  80839. }
  80840. /* put operator for two zero bits in even */
  80841. gf2_matrix_square(even, odd);
  80842. /* put operator for four zero bits in odd */
  80843. gf2_matrix_square(odd, even);
  80844. /* apply len2 zeros to crc1 (first square will put the operator for one
  80845. zero byte, eight zero bits, in even) */
  80846. do {
  80847. /* apply zeros operator for this bit of len2 */
  80848. gf2_matrix_square(even, odd);
  80849. if (len2 & 1)
  80850. crc1 = gf2_matrix_times(even, crc1);
  80851. len2 >>= 1;
  80852. /* if no more bits set, then done */
  80853. if (len2 == 0)
  80854. break;
  80855. /* another iteration of the loop with odd and even swapped */
  80856. gf2_matrix_square(odd, even);
  80857. if (len2 & 1)
  80858. crc1 = gf2_matrix_times(odd, crc1);
  80859. len2 >>= 1;
  80860. /* if no more bits set, then done */
  80861. } while (len2 != 0);
  80862. /* return combined crc */
  80863. crc1 ^= crc2;
  80864. return crc1;
  80865. }
  80866. /*** End of inlined file: crc32.c ***/
  80867. /*** Start of inlined file: deflate.c ***/
  80868. /*
  80869. * ALGORITHM
  80870. *
  80871. * The "deflation" process depends on being able to identify portions
  80872. * of the input text which are identical to earlier input (within a
  80873. * sliding window trailing behind the input currently being processed).
  80874. *
  80875. * The most straightforward technique turns out to be the fastest for
  80876. * most input files: try all possible matches and select the longest.
  80877. * The key feature of this algorithm is that insertions into the string
  80878. * dictionary are very simple and thus fast, and deletions are avoided
  80879. * completely. Insertions are performed at each input character, whereas
  80880. * string matches are performed only when the previous match ends. So it
  80881. * is preferable to spend more time in matches to allow very fast string
  80882. * insertions and avoid deletions. The matching algorithm for small
  80883. * strings is inspired from that of Rabin & Karp. A brute force approach
  80884. * is used to find longer strings when a small match has been found.
  80885. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80886. * (by Leonid Broukhis).
  80887. * A previous version of this file used a more sophisticated algorithm
  80888. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80889. * time, but has a larger average cost, uses more memory and is patented.
  80890. * However the F&G algorithm may be faster for some highly redundant
  80891. * files if the parameter max_chain_length (described below) is too large.
  80892. *
  80893. * ACKNOWLEDGEMENTS
  80894. *
  80895. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80896. * I found it in 'freeze' written by Leonid Broukhis.
  80897. * Thanks to many people for bug reports and testing.
  80898. *
  80899. * REFERENCES
  80900. *
  80901. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80902. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80903. *
  80904. * A description of the Rabin and Karp algorithm is given in the book
  80905. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80906. *
  80907. * Fiala,E.R., and Greene,D.H.
  80908. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80909. *
  80910. */
  80911. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80912. /*** Start of inlined file: deflate.h ***/
  80913. /* WARNING: this file should *not* be used by applications. It is
  80914. part of the implementation of the compression library and is
  80915. subject to change. Applications should only use zlib.h.
  80916. */
  80917. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80918. #ifndef DEFLATE_H
  80919. #define DEFLATE_H
  80920. /* define NO_GZIP when compiling if you want to disable gzip header and
  80921. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80922. the crc code when it is not needed. For shared libraries, gzip encoding
  80923. should be left enabled. */
  80924. #ifndef NO_GZIP
  80925. # define GZIP
  80926. #endif
  80927. #define NO_DUMMY_DECL
  80928. /* ===========================================================================
  80929. * Internal compression state.
  80930. */
  80931. #define LENGTH_CODES 29
  80932. /* number of length codes, not counting the special END_BLOCK code */
  80933. #define LITERALS 256
  80934. /* number of literal bytes 0..255 */
  80935. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80936. /* number of Literal or Length codes, including the END_BLOCK code */
  80937. #define D_CODES 30
  80938. /* number of distance codes */
  80939. #define BL_CODES 19
  80940. /* number of codes used to transfer the bit lengths */
  80941. #define HEAP_SIZE (2*L_CODES+1)
  80942. /* maximum heap size */
  80943. #define MAX_BITS 15
  80944. /* All codes must not exceed MAX_BITS bits */
  80945. #define INIT_STATE 42
  80946. #define EXTRA_STATE 69
  80947. #define NAME_STATE 73
  80948. #define COMMENT_STATE 91
  80949. #define HCRC_STATE 103
  80950. #define BUSY_STATE 113
  80951. #define FINISH_STATE 666
  80952. /* Stream status */
  80953. /* Data structure describing a single value and its code string. */
  80954. typedef struct ct_data_s {
  80955. union {
  80956. ush freq; /* frequency count */
  80957. ush code; /* bit string */
  80958. } fc;
  80959. union {
  80960. ush dad; /* father node in Huffman tree */
  80961. ush len; /* length of bit string */
  80962. } dl;
  80963. } FAR ct_data;
  80964. #define Freq fc.freq
  80965. #define Code fc.code
  80966. #define Dad dl.dad
  80967. #define Len dl.len
  80968. typedef struct static_tree_desc_s static_tree_desc;
  80969. typedef struct tree_desc_s {
  80970. ct_data *dyn_tree; /* the dynamic tree */
  80971. int max_code; /* largest code with non zero frequency */
  80972. static_tree_desc *stat_desc; /* the corresponding static tree */
  80973. } FAR tree_desc;
  80974. typedef ush Pos;
  80975. typedef Pos FAR Posf;
  80976. typedef unsigned IPos;
  80977. /* A Pos is an index in the character window. We use short instead of int to
  80978. * save space in the various tables. IPos is used only for parameter passing.
  80979. */
  80980. typedef struct internal_state {
  80981. z_streamp strm; /* pointer back to this zlib stream */
  80982. int status; /* as the name implies */
  80983. Bytef *pending_buf; /* output still pending */
  80984. ulg pending_buf_size; /* size of pending_buf */
  80985. Bytef *pending_out; /* next pending byte to output to the stream */
  80986. uInt pending; /* nb of bytes in the pending buffer */
  80987. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80988. gz_headerp gzhead; /* gzip header information to write */
  80989. uInt gzindex; /* where in extra, name, or comment */
  80990. Byte method; /* STORED (for zip only) or DEFLATED */
  80991. int last_flush; /* value of flush param for previous deflate call */
  80992. /* used by deflate.c: */
  80993. uInt w_size; /* LZ77 window size (32K by default) */
  80994. uInt w_bits; /* log2(w_size) (8..16) */
  80995. uInt w_mask; /* w_size - 1 */
  80996. Bytef *window;
  80997. /* Sliding window. Input bytes are read into the second half of the window,
  80998. * and move to the first half later to keep a dictionary of at least wSize
  80999. * bytes. With this organization, matches are limited to a distance of
  81000. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81001. * performed with a length multiple of the block size. Also, it limits
  81002. * the window size to 64K, which is quite useful on MSDOS.
  81003. * To do: use the user input buffer as sliding window.
  81004. */
  81005. ulg window_size;
  81006. /* Actual size of window: 2*wSize, except when the user input buffer
  81007. * is directly used as sliding window.
  81008. */
  81009. Posf *prev;
  81010. /* Link to older string with same hash index. To limit the size of this
  81011. * array to 64K, this link is maintained only for the last 32K strings.
  81012. * An index in this array is thus a window index modulo 32K.
  81013. */
  81014. Posf *head; /* Heads of the hash chains or NIL. */
  81015. uInt ins_h; /* hash index of string to be inserted */
  81016. uInt hash_size; /* number of elements in hash table */
  81017. uInt hash_bits; /* log2(hash_size) */
  81018. uInt hash_mask; /* hash_size-1 */
  81019. uInt hash_shift;
  81020. /* Number of bits by which ins_h must be shifted at each input
  81021. * step. It must be such that after MIN_MATCH steps, the oldest
  81022. * byte no longer takes part in the hash key, that is:
  81023. * hash_shift * MIN_MATCH >= hash_bits
  81024. */
  81025. long block_start;
  81026. /* Window position at the beginning of the current output block. Gets
  81027. * negative when the window is moved backwards.
  81028. */
  81029. uInt match_length; /* length of best match */
  81030. IPos prev_match; /* previous match */
  81031. int match_available; /* set if previous match exists */
  81032. uInt strstart; /* start of string to insert */
  81033. uInt match_start; /* start of matching string */
  81034. uInt lookahead; /* number of valid bytes ahead in window */
  81035. uInt prev_length;
  81036. /* Length of the best match at previous step. Matches not greater than this
  81037. * are discarded. This is used in the lazy match evaluation.
  81038. */
  81039. uInt max_chain_length;
  81040. /* To speed up deflation, hash chains are never searched beyond this
  81041. * length. A higher limit improves compression ratio but degrades the
  81042. * speed.
  81043. */
  81044. uInt max_lazy_match;
  81045. /* Attempt to find a better match only when the current match is strictly
  81046. * smaller than this value. This mechanism is used only for compression
  81047. * levels >= 4.
  81048. */
  81049. # define max_insert_length max_lazy_match
  81050. /* Insert new strings in the hash table only if the match length is not
  81051. * greater than this length. This saves time but degrades compression.
  81052. * max_insert_length is used only for compression levels <= 3.
  81053. */
  81054. int level; /* compression level (1..9) */
  81055. int strategy; /* favor or force Huffman coding*/
  81056. uInt good_match;
  81057. /* Use a faster search when the previous match is longer than this */
  81058. int nice_match; /* Stop searching when current match exceeds this */
  81059. /* used by trees.c: */
  81060. /* Didn't use ct_data typedef below to supress compiler warning */
  81061. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81062. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81063. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81064. struct tree_desc_s l_desc; /* desc. for literal tree */
  81065. struct tree_desc_s d_desc; /* desc. for distance tree */
  81066. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81067. ush bl_count[MAX_BITS+1];
  81068. /* number of codes at each bit length for an optimal tree */
  81069. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81070. int heap_len; /* number of elements in the heap */
  81071. int heap_max; /* element of largest frequency */
  81072. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81073. * The same heap array is used to build all trees.
  81074. */
  81075. uch depth[2*L_CODES+1];
  81076. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81077. */
  81078. uchf *l_buf; /* buffer for literals or lengths */
  81079. uInt lit_bufsize;
  81080. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81081. * limiting lit_bufsize to 64K:
  81082. * - frequencies can be kept in 16 bit counters
  81083. * - if compression is not successful for the first block, all input
  81084. * data is still in the window so we can still emit a stored block even
  81085. * when input comes from standard input. (This can also be done for
  81086. * all blocks if lit_bufsize is not greater than 32K.)
  81087. * - if compression is not successful for a file smaller than 64K, we can
  81088. * even emit a stored file instead of a stored block (saving 5 bytes).
  81089. * This is applicable only for zip (not gzip or zlib).
  81090. * - creating new Huffman trees less frequently may not provide fast
  81091. * adaptation to changes in the input data statistics. (Take for
  81092. * example a binary file with poorly compressible code followed by
  81093. * a highly compressible string table.) Smaller buffer sizes give
  81094. * fast adaptation but have of course the overhead of transmitting
  81095. * trees more frequently.
  81096. * - I can't count above 4
  81097. */
  81098. uInt last_lit; /* running index in l_buf */
  81099. ushf *d_buf;
  81100. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81101. * the same number of elements. To use different lengths, an extra flag
  81102. * array would be necessary.
  81103. */
  81104. ulg opt_len; /* bit length of current block with optimal trees */
  81105. ulg static_len; /* bit length of current block with static trees */
  81106. uInt matches; /* number of string matches in current block */
  81107. int last_eob_len; /* bit length of EOB code for last block */
  81108. #ifdef DEBUG
  81109. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81110. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81111. #endif
  81112. ush bi_buf;
  81113. /* Output buffer. bits are inserted starting at the bottom (least
  81114. * significant bits).
  81115. */
  81116. int bi_valid;
  81117. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81118. * are always zero.
  81119. */
  81120. } FAR deflate_state;
  81121. /* Output a byte on the stream.
  81122. * IN assertion: there is enough room in pending_buf.
  81123. */
  81124. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81125. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81126. /* Minimum amount of lookahead, except at the end of the input file.
  81127. * See deflate.c for comments about the MIN_MATCH+1.
  81128. */
  81129. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81130. /* In order to simplify the code, particularly on 16 bit machines, match
  81131. * distances are limited to MAX_DIST instead of WSIZE.
  81132. */
  81133. /* in trees.c */
  81134. void _tr_init OF((deflate_state *s));
  81135. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81136. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81137. int eof));
  81138. void _tr_align OF((deflate_state *s));
  81139. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81140. int eof));
  81141. #define d_code(dist) \
  81142. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81143. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81144. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81145. * used.
  81146. */
  81147. #ifndef DEBUG
  81148. /* Inline versions of _tr_tally for speed: */
  81149. #if defined(GEN_TREES_H) || !defined(STDC)
  81150. extern uch _length_code[];
  81151. extern uch _dist_code[];
  81152. #else
  81153. extern const uch _length_code[];
  81154. extern const uch _dist_code[];
  81155. #endif
  81156. # define _tr_tally_lit(s, c, flush) \
  81157. { uch cc = (c); \
  81158. s->d_buf[s->last_lit] = 0; \
  81159. s->l_buf[s->last_lit++] = cc; \
  81160. s->dyn_ltree[cc].Freq++; \
  81161. flush = (s->last_lit == s->lit_bufsize-1); \
  81162. }
  81163. # define _tr_tally_dist(s, distance, length, flush) \
  81164. { uch len = (length); \
  81165. ush dist = (distance); \
  81166. s->d_buf[s->last_lit] = dist; \
  81167. s->l_buf[s->last_lit++] = len; \
  81168. dist--; \
  81169. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81170. s->dyn_dtree[d_code(dist)].Freq++; \
  81171. flush = (s->last_lit == s->lit_bufsize-1); \
  81172. }
  81173. #else
  81174. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81175. # define _tr_tally_dist(s, distance, length, flush) \
  81176. flush = _tr_tally(s, distance, length)
  81177. #endif
  81178. #endif /* DEFLATE_H */
  81179. /*** End of inlined file: deflate.h ***/
  81180. const char deflate_copyright[] =
  81181. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81182. /*
  81183. If you use the zlib library in a product, an acknowledgment is welcome
  81184. in the documentation of your product. If for some reason you cannot
  81185. include such an acknowledgment, I would appreciate that you keep this
  81186. copyright string in the executable of your product.
  81187. */
  81188. /* ===========================================================================
  81189. * Function prototypes.
  81190. */
  81191. typedef enum {
  81192. need_more, /* block not completed, need more input or more output */
  81193. block_done, /* block flush performed */
  81194. finish_started, /* finish started, need only more output at next deflate */
  81195. finish_done /* finish done, accept no more input or output */
  81196. } block_state;
  81197. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81198. /* Compression function. Returns the block state after the call. */
  81199. local void fill_window OF((deflate_state *s));
  81200. local block_state deflate_stored OF((deflate_state *s, int flush));
  81201. local block_state deflate_fast OF((deflate_state *s, int flush));
  81202. #ifndef FASTEST
  81203. local block_state deflate_slow OF((deflate_state *s, int flush));
  81204. #endif
  81205. local void lm_init OF((deflate_state *s));
  81206. local void putShortMSB OF((deflate_state *s, uInt b));
  81207. local void flush_pending OF((z_streamp strm));
  81208. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81209. #ifndef FASTEST
  81210. #ifdef ASMV
  81211. void match_init OF((void)); /* asm code initialization */
  81212. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81213. #else
  81214. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81215. #endif
  81216. #endif
  81217. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81218. #ifdef DEBUG
  81219. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81220. int length));
  81221. #endif
  81222. /* ===========================================================================
  81223. * Local data
  81224. */
  81225. #define NIL 0
  81226. /* Tail of hash chains */
  81227. #ifndef TOO_FAR
  81228. # define TOO_FAR 4096
  81229. #endif
  81230. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81231. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81232. /* Minimum amount of lookahead, except at the end of the input file.
  81233. * See deflate.c for comments about the MIN_MATCH+1.
  81234. */
  81235. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81236. * the desired pack level (0..9). The values given below have been tuned to
  81237. * exclude worst case performance for pathological files. Better values may be
  81238. * found for specific files.
  81239. */
  81240. typedef struct config_s {
  81241. ush good_length; /* reduce lazy search above this match length */
  81242. ush max_lazy; /* do not perform lazy search above this match length */
  81243. ush nice_length; /* quit search above this match length */
  81244. ush max_chain;
  81245. compress_func func;
  81246. } config;
  81247. #ifdef FASTEST
  81248. local const config configuration_table[2] = {
  81249. /* good lazy nice chain */
  81250. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81251. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81252. #else
  81253. local const config configuration_table[10] = {
  81254. /* good lazy nice chain */
  81255. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81256. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81257. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81258. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81259. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81260. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81261. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81262. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81263. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81264. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81265. #endif
  81266. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81267. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81268. * meaning.
  81269. */
  81270. #define EQUAL 0
  81271. /* result of memcmp for equal strings */
  81272. #ifndef NO_DUMMY_DECL
  81273. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81274. #endif
  81275. /* ===========================================================================
  81276. * Update a hash value with the given input byte
  81277. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81278. * input characters, so that a running hash key can be computed from the
  81279. * previous key instead of complete recalculation each time.
  81280. */
  81281. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81282. /* ===========================================================================
  81283. * Insert string str in the dictionary and set match_head to the previous head
  81284. * of the hash chain (the most recent string with same hash key). Return
  81285. * the previous length of the hash chain.
  81286. * If this file is compiled with -DFASTEST, the compression level is forced
  81287. * to 1, and no hash chains are maintained.
  81288. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81289. * input characters and the first MIN_MATCH bytes of str are valid
  81290. * (except for the last MIN_MATCH-1 bytes of the input file).
  81291. */
  81292. #ifdef FASTEST
  81293. #define INSERT_STRING(s, str, match_head) \
  81294. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81295. match_head = s->head[s->ins_h], \
  81296. s->head[s->ins_h] = (Pos)(str))
  81297. #else
  81298. #define INSERT_STRING(s, str, match_head) \
  81299. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81300. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81301. s->head[s->ins_h] = (Pos)(str))
  81302. #endif
  81303. /* ===========================================================================
  81304. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81305. * prev[] will be initialized on the fly.
  81306. */
  81307. #define CLEAR_HASH(s) \
  81308. s->head[s->hash_size-1] = NIL; \
  81309. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81310. /* ========================================================================= */
  81311. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81312. {
  81313. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81314. Z_DEFAULT_STRATEGY, version, stream_size);
  81315. /* To do: ignore strm->next_in if we use it as window */
  81316. }
  81317. /* ========================================================================= */
  81318. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81319. {
  81320. deflate_state *s;
  81321. int wrap = 1;
  81322. static const char my_version[] = ZLIB_VERSION;
  81323. ushf *overlay;
  81324. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81325. * output size for (length,distance) codes is <= 24 bits.
  81326. */
  81327. if (version == Z_NULL || version[0] != my_version[0] ||
  81328. stream_size != sizeof(z_stream)) {
  81329. return Z_VERSION_ERROR;
  81330. }
  81331. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81332. strm->msg = Z_NULL;
  81333. if (strm->zalloc == (alloc_func)0) {
  81334. strm->zalloc = zcalloc;
  81335. strm->opaque = (voidpf)0;
  81336. }
  81337. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81338. #ifdef FASTEST
  81339. if (level != 0) level = 1;
  81340. #else
  81341. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81342. #endif
  81343. if (windowBits < 0) { /* suppress zlib wrapper */
  81344. wrap = 0;
  81345. windowBits = -windowBits;
  81346. }
  81347. #ifdef GZIP
  81348. else if (windowBits > 15) {
  81349. wrap = 2; /* write gzip wrapper instead */
  81350. windowBits -= 16;
  81351. }
  81352. #endif
  81353. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81354. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81355. strategy < 0 || strategy > Z_FIXED) {
  81356. return Z_STREAM_ERROR;
  81357. }
  81358. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81359. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81360. if (s == Z_NULL) return Z_MEM_ERROR;
  81361. strm->state = (struct internal_state FAR *)s;
  81362. s->strm = strm;
  81363. s->wrap = wrap;
  81364. s->gzhead = Z_NULL;
  81365. s->w_bits = windowBits;
  81366. s->w_size = 1 << s->w_bits;
  81367. s->w_mask = s->w_size - 1;
  81368. s->hash_bits = memLevel + 7;
  81369. s->hash_size = 1 << s->hash_bits;
  81370. s->hash_mask = s->hash_size - 1;
  81371. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81372. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81373. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81374. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81375. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81376. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81377. s->pending_buf = (uchf *) overlay;
  81378. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81379. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81380. s->pending_buf == Z_NULL) {
  81381. s->status = FINISH_STATE;
  81382. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81383. deflateEnd (strm);
  81384. return Z_MEM_ERROR;
  81385. }
  81386. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81387. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81388. s->level = level;
  81389. s->strategy = strategy;
  81390. s->method = (Byte)method;
  81391. return deflateReset(strm);
  81392. }
  81393. /* ========================================================================= */
  81394. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81395. {
  81396. deflate_state *s;
  81397. uInt length = dictLength;
  81398. uInt n;
  81399. IPos hash_head = 0;
  81400. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81401. strm->state->wrap == 2 ||
  81402. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81403. return Z_STREAM_ERROR;
  81404. s = strm->state;
  81405. if (s->wrap)
  81406. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81407. if (length < MIN_MATCH) return Z_OK;
  81408. if (length > MAX_DIST(s)) {
  81409. length = MAX_DIST(s);
  81410. dictionary += dictLength - length; /* use the tail of the dictionary */
  81411. }
  81412. zmemcpy(s->window, dictionary, length);
  81413. s->strstart = length;
  81414. s->block_start = (long)length;
  81415. /* Insert all strings in the hash table (except for the last two bytes).
  81416. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81417. * call of fill_window.
  81418. */
  81419. s->ins_h = s->window[0];
  81420. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81421. for (n = 0; n <= length - MIN_MATCH; n++) {
  81422. INSERT_STRING(s, n, hash_head);
  81423. }
  81424. if (hash_head) hash_head = 0; /* to make compiler happy */
  81425. return Z_OK;
  81426. }
  81427. /* ========================================================================= */
  81428. int ZEXPORT deflateReset (z_streamp strm)
  81429. {
  81430. deflate_state *s;
  81431. if (strm == Z_NULL || strm->state == Z_NULL ||
  81432. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81433. return Z_STREAM_ERROR;
  81434. }
  81435. strm->total_in = strm->total_out = 0;
  81436. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81437. strm->data_type = Z_UNKNOWN;
  81438. s = (deflate_state *)strm->state;
  81439. s->pending = 0;
  81440. s->pending_out = s->pending_buf;
  81441. if (s->wrap < 0) {
  81442. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81443. }
  81444. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81445. strm->adler =
  81446. #ifdef GZIP
  81447. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81448. #endif
  81449. adler32(0L, Z_NULL, 0);
  81450. s->last_flush = Z_NO_FLUSH;
  81451. _tr_init(s);
  81452. lm_init(s);
  81453. return Z_OK;
  81454. }
  81455. /* ========================================================================= */
  81456. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81457. {
  81458. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81459. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81460. strm->state->gzhead = head;
  81461. return Z_OK;
  81462. }
  81463. /* ========================================================================= */
  81464. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81465. {
  81466. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81467. strm->state->bi_valid = bits;
  81468. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81469. return Z_OK;
  81470. }
  81471. /* ========================================================================= */
  81472. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81473. {
  81474. deflate_state *s;
  81475. compress_func func;
  81476. int err = Z_OK;
  81477. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81478. s = strm->state;
  81479. #ifdef FASTEST
  81480. if (level != 0) level = 1;
  81481. #else
  81482. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81483. #endif
  81484. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81485. return Z_STREAM_ERROR;
  81486. }
  81487. func = configuration_table[s->level].func;
  81488. if (func != configuration_table[level].func && strm->total_in != 0) {
  81489. /* Flush the last buffer: */
  81490. err = deflate(strm, Z_PARTIAL_FLUSH);
  81491. }
  81492. if (s->level != level) {
  81493. s->level = level;
  81494. s->max_lazy_match = configuration_table[level].max_lazy;
  81495. s->good_match = configuration_table[level].good_length;
  81496. s->nice_match = configuration_table[level].nice_length;
  81497. s->max_chain_length = configuration_table[level].max_chain;
  81498. }
  81499. s->strategy = strategy;
  81500. return err;
  81501. }
  81502. /* ========================================================================= */
  81503. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81504. {
  81505. deflate_state *s;
  81506. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81507. s = strm->state;
  81508. s->good_match = good_length;
  81509. s->max_lazy_match = max_lazy;
  81510. s->nice_match = nice_length;
  81511. s->max_chain_length = max_chain;
  81512. return Z_OK;
  81513. }
  81514. /* =========================================================================
  81515. * For the default windowBits of 15 and memLevel of 8, this function returns
  81516. * a close to exact, as well as small, upper bound on the compressed size.
  81517. * They are coded as constants here for a reason--if the #define's are
  81518. * changed, then this function needs to be changed as well. The return
  81519. * value for 15 and 8 only works for those exact settings.
  81520. *
  81521. * For any setting other than those defaults for windowBits and memLevel,
  81522. * the value returned is a conservative worst case for the maximum expansion
  81523. * resulting from using fixed blocks instead of stored blocks, which deflate
  81524. * can emit on compressed data for some combinations of the parameters.
  81525. *
  81526. * This function could be more sophisticated to provide closer upper bounds
  81527. * for every combination of windowBits and memLevel, as well as wrap.
  81528. * But even the conservative upper bound of about 14% expansion does not
  81529. * seem onerous for output buffer allocation.
  81530. */
  81531. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81532. {
  81533. deflate_state *s;
  81534. uLong destLen;
  81535. /* conservative upper bound */
  81536. destLen = sourceLen +
  81537. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81538. /* if can't get parameters, return conservative bound */
  81539. if (strm == Z_NULL || strm->state == Z_NULL)
  81540. return destLen;
  81541. /* if not default parameters, return conservative bound */
  81542. s = strm->state;
  81543. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81544. return destLen;
  81545. /* default settings: return tight bound for that case */
  81546. return compressBound(sourceLen);
  81547. }
  81548. /* =========================================================================
  81549. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81550. * IN assertion: the stream state is correct and there is enough room in
  81551. * pending_buf.
  81552. */
  81553. local void putShortMSB (deflate_state *s, uInt b)
  81554. {
  81555. put_byte(s, (Byte)(b >> 8));
  81556. put_byte(s, (Byte)(b & 0xff));
  81557. }
  81558. /* =========================================================================
  81559. * Flush as much pending output as possible. All deflate() output goes
  81560. * through this function so some applications may wish to modify it
  81561. * to avoid allocating a large strm->next_out buffer and copying into it.
  81562. * (See also read_buf()).
  81563. */
  81564. local void flush_pending (z_streamp strm)
  81565. {
  81566. unsigned len = strm->state->pending;
  81567. if (len > strm->avail_out) len = strm->avail_out;
  81568. if (len == 0) return;
  81569. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81570. strm->next_out += len;
  81571. strm->state->pending_out += len;
  81572. strm->total_out += len;
  81573. strm->avail_out -= len;
  81574. strm->state->pending -= len;
  81575. if (strm->state->pending == 0) {
  81576. strm->state->pending_out = strm->state->pending_buf;
  81577. }
  81578. }
  81579. /* ========================================================================= */
  81580. int ZEXPORT deflate (z_streamp strm, int flush)
  81581. {
  81582. int old_flush; /* value of flush param for previous deflate call */
  81583. deflate_state *s;
  81584. if (strm == Z_NULL || strm->state == Z_NULL ||
  81585. flush > Z_FINISH || flush < 0) {
  81586. return Z_STREAM_ERROR;
  81587. }
  81588. s = strm->state;
  81589. if (strm->next_out == Z_NULL ||
  81590. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81591. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81592. ERR_RETURN(strm, Z_STREAM_ERROR);
  81593. }
  81594. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81595. s->strm = strm; /* just in case */
  81596. old_flush = s->last_flush;
  81597. s->last_flush = flush;
  81598. /* Write the header */
  81599. if (s->status == INIT_STATE) {
  81600. #ifdef GZIP
  81601. if (s->wrap == 2) {
  81602. strm->adler = crc32(0L, Z_NULL, 0);
  81603. put_byte(s, 31);
  81604. put_byte(s, 139);
  81605. put_byte(s, 8);
  81606. if (s->gzhead == NULL) {
  81607. put_byte(s, 0);
  81608. put_byte(s, 0);
  81609. put_byte(s, 0);
  81610. put_byte(s, 0);
  81611. put_byte(s, 0);
  81612. put_byte(s, s->level == 9 ? 2 :
  81613. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81614. 4 : 0));
  81615. put_byte(s, OS_CODE);
  81616. s->status = BUSY_STATE;
  81617. }
  81618. else {
  81619. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81620. (s->gzhead->hcrc ? 2 : 0) +
  81621. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81622. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81623. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81624. );
  81625. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81626. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81627. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81628. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81629. put_byte(s, s->level == 9 ? 2 :
  81630. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81631. 4 : 0));
  81632. put_byte(s, s->gzhead->os & 0xff);
  81633. if (s->gzhead->extra != NULL) {
  81634. put_byte(s, s->gzhead->extra_len & 0xff);
  81635. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81636. }
  81637. if (s->gzhead->hcrc)
  81638. strm->adler = crc32(strm->adler, s->pending_buf,
  81639. s->pending);
  81640. s->gzindex = 0;
  81641. s->status = EXTRA_STATE;
  81642. }
  81643. }
  81644. else
  81645. #endif
  81646. {
  81647. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81648. uInt level_flags;
  81649. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81650. level_flags = 0;
  81651. else if (s->level < 6)
  81652. level_flags = 1;
  81653. else if (s->level == 6)
  81654. level_flags = 2;
  81655. else
  81656. level_flags = 3;
  81657. header |= (level_flags << 6);
  81658. if (s->strstart != 0) header |= PRESET_DICT;
  81659. header += 31 - (header % 31);
  81660. s->status = BUSY_STATE;
  81661. putShortMSB(s, header);
  81662. /* Save the adler32 of the preset dictionary: */
  81663. if (s->strstart != 0) {
  81664. putShortMSB(s, (uInt)(strm->adler >> 16));
  81665. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81666. }
  81667. strm->adler = adler32(0L, Z_NULL, 0);
  81668. }
  81669. }
  81670. #ifdef GZIP
  81671. if (s->status == EXTRA_STATE) {
  81672. if (s->gzhead->extra != NULL) {
  81673. uInt beg = s->pending; /* start of bytes to update crc */
  81674. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81675. if (s->pending == s->pending_buf_size) {
  81676. if (s->gzhead->hcrc && s->pending > beg)
  81677. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81678. s->pending - beg);
  81679. flush_pending(strm);
  81680. beg = s->pending;
  81681. if (s->pending == s->pending_buf_size)
  81682. break;
  81683. }
  81684. put_byte(s, s->gzhead->extra[s->gzindex]);
  81685. s->gzindex++;
  81686. }
  81687. if (s->gzhead->hcrc && s->pending > beg)
  81688. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81689. s->pending - beg);
  81690. if (s->gzindex == s->gzhead->extra_len) {
  81691. s->gzindex = 0;
  81692. s->status = NAME_STATE;
  81693. }
  81694. }
  81695. else
  81696. s->status = NAME_STATE;
  81697. }
  81698. if (s->status == NAME_STATE) {
  81699. if (s->gzhead->name != NULL) {
  81700. uInt beg = s->pending; /* start of bytes to update crc */
  81701. int val;
  81702. do {
  81703. if (s->pending == s->pending_buf_size) {
  81704. if (s->gzhead->hcrc && s->pending > beg)
  81705. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81706. s->pending - beg);
  81707. flush_pending(strm);
  81708. beg = s->pending;
  81709. if (s->pending == s->pending_buf_size) {
  81710. val = 1;
  81711. break;
  81712. }
  81713. }
  81714. val = s->gzhead->name[s->gzindex++];
  81715. put_byte(s, val);
  81716. } while (val != 0);
  81717. if (s->gzhead->hcrc && s->pending > beg)
  81718. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81719. s->pending - beg);
  81720. if (val == 0) {
  81721. s->gzindex = 0;
  81722. s->status = COMMENT_STATE;
  81723. }
  81724. }
  81725. else
  81726. s->status = COMMENT_STATE;
  81727. }
  81728. if (s->status == COMMENT_STATE) {
  81729. if (s->gzhead->comment != NULL) {
  81730. uInt beg = s->pending; /* start of bytes to update crc */
  81731. int val;
  81732. do {
  81733. if (s->pending == s->pending_buf_size) {
  81734. if (s->gzhead->hcrc && s->pending > beg)
  81735. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81736. s->pending - beg);
  81737. flush_pending(strm);
  81738. beg = s->pending;
  81739. if (s->pending == s->pending_buf_size) {
  81740. val = 1;
  81741. break;
  81742. }
  81743. }
  81744. val = s->gzhead->comment[s->gzindex++];
  81745. put_byte(s, val);
  81746. } while (val != 0);
  81747. if (s->gzhead->hcrc && s->pending > beg)
  81748. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81749. s->pending - beg);
  81750. if (val == 0)
  81751. s->status = HCRC_STATE;
  81752. }
  81753. else
  81754. s->status = HCRC_STATE;
  81755. }
  81756. if (s->status == HCRC_STATE) {
  81757. if (s->gzhead->hcrc) {
  81758. if (s->pending + 2 > s->pending_buf_size)
  81759. flush_pending(strm);
  81760. if (s->pending + 2 <= s->pending_buf_size) {
  81761. put_byte(s, (Byte)(strm->adler & 0xff));
  81762. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81763. strm->adler = crc32(0L, Z_NULL, 0);
  81764. s->status = BUSY_STATE;
  81765. }
  81766. }
  81767. else
  81768. s->status = BUSY_STATE;
  81769. }
  81770. #endif
  81771. /* Flush as much pending output as possible */
  81772. if (s->pending != 0) {
  81773. flush_pending(strm);
  81774. if (strm->avail_out == 0) {
  81775. /* Since avail_out is 0, deflate will be called again with
  81776. * more output space, but possibly with both pending and
  81777. * avail_in equal to zero. There won't be anything to do,
  81778. * but this is not an error situation so make sure we
  81779. * return OK instead of BUF_ERROR at next call of deflate:
  81780. */
  81781. s->last_flush = -1;
  81782. return Z_OK;
  81783. }
  81784. /* Make sure there is something to do and avoid duplicate consecutive
  81785. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81786. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81787. */
  81788. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81789. flush != Z_FINISH) {
  81790. ERR_RETURN(strm, Z_BUF_ERROR);
  81791. }
  81792. /* User must not provide more input after the first FINISH: */
  81793. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81794. ERR_RETURN(strm, Z_BUF_ERROR);
  81795. }
  81796. /* Start a new block or continue the current one.
  81797. */
  81798. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81799. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81800. block_state bstate;
  81801. bstate = (*(configuration_table[s->level].func))(s, flush);
  81802. if (bstate == finish_started || bstate == finish_done) {
  81803. s->status = FINISH_STATE;
  81804. }
  81805. if (bstate == need_more || bstate == finish_started) {
  81806. if (strm->avail_out == 0) {
  81807. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81808. }
  81809. return Z_OK;
  81810. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81811. * of deflate should use the same flush parameter to make sure
  81812. * that the flush is complete. So we don't have to output an
  81813. * empty block here, this will be done at next call. This also
  81814. * ensures that for a very small output buffer, we emit at most
  81815. * one empty block.
  81816. */
  81817. }
  81818. if (bstate == block_done) {
  81819. if (flush == Z_PARTIAL_FLUSH) {
  81820. _tr_align(s);
  81821. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81822. _tr_stored_block(s, (char*)0, 0L, 0);
  81823. /* For a full flush, this empty block will be recognized
  81824. * as a special marker by inflate_sync().
  81825. */
  81826. if (flush == Z_FULL_FLUSH) {
  81827. CLEAR_HASH(s); /* forget history */
  81828. }
  81829. }
  81830. flush_pending(strm);
  81831. if (strm->avail_out == 0) {
  81832. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81833. return Z_OK;
  81834. }
  81835. }
  81836. }
  81837. Assert(strm->avail_out > 0, "bug2");
  81838. if (flush != Z_FINISH) return Z_OK;
  81839. if (s->wrap <= 0) return Z_STREAM_END;
  81840. /* Write the trailer */
  81841. #ifdef GZIP
  81842. if (s->wrap == 2) {
  81843. put_byte(s, (Byte)(strm->adler & 0xff));
  81844. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81845. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81846. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81847. put_byte(s, (Byte)(strm->total_in & 0xff));
  81848. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81849. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81850. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81851. }
  81852. else
  81853. #endif
  81854. {
  81855. putShortMSB(s, (uInt)(strm->adler >> 16));
  81856. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81857. }
  81858. flush_pending(strm);
  81859. /* If avail_out is zero, the application will call deflate again
  81860. * to flush the rest.
  81861. */
  81862. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81863. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81864. }
  81865. /* ========================================================================= */
  81866. int ZEXPORT deflateEnd (z_streamp strm)
  81867. {
  81868. int status;
  81869. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81870. status = strm->state->status;
  81871. if (status != INIT_STATE &&
  81872. status != EXTRA_STATE &&
  81873. status != NAME_STATE &&
  81874. status != COMMENT_STATE &&
  81875. status != HCRC_STATE &&
  81876. status != BUSY_STATE &&
  81877. status != FINISH_STATE) {
  81878. return Z_STREAM_ERROR;
  81879. }
  81880. /* Deallocate in reverse order of allocations: */
  81881. TRY_FREE(strm, strm->state->pending_buf);
  81882. TRY_FREE(strm, strm->state->head);
  81883. TRY_FREE(strm, strm->state->prev);
  81884. TRY_FREE(strm, strm->state->window);
  81885. ZFREE(strm, strm->state);
  81886. strm->state = Z_NULL;
  81887. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81888. }
  81889. /* =========================================================================
  81890. * Copy the source state to the destination state.
  81891. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81892. * doesn't have enough memory anyway to duplicate compression states).
  81893. */
  81894. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81895. {
  81896. #ifdef MAXSEG_64K
  81897. return Z_STREAM_ERROR;
  81898. #else
  81899. deflate_state *ds;
  81900. deflate_state *ss;
  81901. ushf *overlay;
  81902. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81903. return Z_STREAM_ERROR;
  81904. }
  81905. ss = source->state;
  81906. zmemcpy(dest, source, sizeof(z_stream));
  81907. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81908. if (ds == Z_NULL) return Z_MEM_ERROR;
  81909. dest->state = (struct internal_state FAR *) ds;
  81910. zmemcpy(ds, ss, sizeof(deflate_state));
  81911. ds->strm = dest;
  81912. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81913. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81914. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81915. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81916. ds->pending_buf = (uchf *) overlay;
  81917. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81918. ds->pending_buf == Z_NULL) {
  81919. deflateEnd (dest);
  81920. return Z_MEM_ERROR;
  81921. }
  81922. /* following zmemcpy do not work for 16-bit MSDOS */
  81923. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81924. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81925. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81926. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81927. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81928. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81929. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81930. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81931. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81932. ds->bl_desc.dyn_tree = ds->bl_tree;
  81933. return Z_OK;
  81934. #endif /* MAXSEG_64K */
  81935. }
  81936. /* ===========================================================================
  81937. * Read a new buffer from the current input stream, update the adler32
  81938. * and total number of bytes read. All deflate() input goes through
  81939. * this function so some applications may wish to modify it to avoid
  81940. * allocating a large strm->next_in buffer and copying from it.
  81941. * (See also flush_pending()).
  81942. */
  81943. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81944. {
  81945. unsigned len = strm->avail_in;
  81946. if (len > size) len = size;
  81947. if (len == 0) return 0;
  81948. strm->avail_in -= len;
  81949. if (strm->state->wrap == 1) {
  81950. strm->adler = adler32(strm->adler, strm->next_in, len);
  81951. }
  81952. #ifdef GZIP
  81953. else if (strm->state->wrap == 2) {
  81954. strm->adler = crc32(strm->adler, strm->next_in, len);
  81955. }
  81956. #endif
  81957. zmemcpy(buf, strm->next_in, len);
  81958. strm->next_in += len;
  81959. strm->total_in += len;
  81960. return (int)len;
  81961. }
  81962. /* ===========================================================================
  81963. * Initialize the "longest match" routines for a new zlib stream
  81964. */
  81965. local void lm_init (deflate_state *s)
  81966. {
  81967. s->window_size = (ulg)2L*s->w_size;
  81968. CLEAR_HASH(s);
  81969. /* Set the default configuration parameters:
  81970. */
  81971. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81972. s->good_match = configuration_table[s->level].good_length;
  81973. s->nice_match = configuration_table[s->level].nice_length;
  81974. s->max_chain_length = configuration_table[s->level].max_chain;
  81975. s->strstart = 0;
  81976. s->block_start = 0L;
  81977. s->lookahead = 0;
  81978. s->match_length = s->prev_length = MIN_MATCH-1;
  81979. s->match_available = 0;
  81980. s->ins_h = 0;
  81981. #ifndef FASTEST
  81982. #ifdef ASMV
  81983. match_init(); /* initialize the asm code */
  81984. #endif
  81985. #endif
  81986. }
  81987. #ifndef FASTEST
  81988. /* ===========================================================================
  81989. * Set match_start to the longest match starting at the given string and
  81990. * return its length. Matches shorter or equal to prev_length are discarded,
  81991. * in which case the result is equal to prev_length and match_start is
  81992. * garbage.
  81993. * IN assertions: cur_match is the head of the hash chain for the current
  81994. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81995. * OUT assertion: the match length is not greater than s->lookahead.
  81996. */
  81997. #ifndef ASMV
  81998. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81999. * match.S. The code will be functionally equivalent.
  82000. */
  82001. local uInt longest_match(deflate_state *s, IPos cur_match)
  82002. {
  82003. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82004. register Bytef *scan = s->window + s->strstart; /* current string */
  82005. register Bytef *match; /* matched string */
  82006. register int len; /* length of current match */
  82007. int best_len = s->prev_length; /* best match length so far */
  82008. int nice_match = s->nice_match; /* stop if match long enough */
  82009. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82010. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82011. /* Stop when cur_match becomes <= limit. To simplify the code,
  82012. * we prevent matches with the string of window index 0.
  82013. */
  82014. Posf *prev = s->prev;
  82015. uInt wmask = s->w_mask;
  82016. #ifdef UNALIGNED_OK
  82017. /* Compare two bytes at a time. Note: this is not always beneficial.
  82018. * Try with and without -DUNALIGNED_OK to check.
  82019. */
  82020. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82021. register ush scan_start = *(ushf*)scan;
  82022. register ush scan_end = *(ushf*)(scan+best_len-1);
  82023. #else
  82024. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82025. register Byte scan_end1 = scan[best_len-1];
  82026. register Byte scan_end = scan[best_len];
  82027. #endif
  82028. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82029. * It is easy to get rid of this optimization if necessary.
  82030. */
  82031. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82032. /* Do not waste too much time if we already have a good match: */
  82033. if (s->prev_length >= s->good_match) {
  82034. chain_length >>= 2;
  82035. }
  82036. /* Do not look for matches beyond the end of the input. This is necessary
  82037. * to make deflate deterministic.
  82038. */
  82039. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82040. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82041. do {
  82042. Assert(cur_match < s->strstart, "no future");
  82043. match = s->window + cur_match;
  82044. /* Skip to next match if the match length cannot increase
  82045. * or if the match length is less than 2. Note that the checks below
  82046. * for insufficient lookahead only occur occasionally for performance
  82047. * reasons. Therefore uninitialized memory will be accessed, and
  82048. * conditional jumps will be made that depend on those values.
  82049. * However the length of the match is limited to the lookahead, so
  82050. * the output of deflate is not affected by the uninitialized values.
  82051. */
  82052. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82053. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82054. * UNALIGNED_OK if your compiler uses a different size.
  82055. */
  82056. if (*(ushf*)(match+best_len-1) != scan_end ||
  82057. *(ushf*)match != scan_start) continue;
  82058. /* It is not necessary to compare scan[2] and match[2] since they are
  82059. * always equal when the other bytes match, given that the hash keys
  82060. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82061. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82062. * lookahead only every 4th comparison; the 128th check will be made
  82063. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82064. * necessary to put more guard bytes at the end of the window, or
  82065. * to check more often for insufficient lookahead.
  82066. */
  82067. Assert(scan[2] == match[2], "scan[2]?");
  82068. scan++, match++;
  82069. do {
  82070. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82071. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82072. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82073. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82074. scan < strend);
  82075. /* The funny "do {}" generates better code on most compilers */
  82076. /* Here, scan <= window+strstart+257 */
  82077. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82078. if (*scan == *match) scan++;
  82079. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82080. scan = strend - (MAX_MATCH-1);
  82081. #else /* UNALIGNED_OK */
  82082. if (match[best_len] != scan_end ||
  82083. match[best_len-1] != scan_end1 ||
  82084. *match != *scan ||
  82085. *++match != scan[1]) continue;
  82086. /* The check at best_len-1 can be removed because it will be made
  82087. * again later. (This heuristic is not always a win.)
  82088. * It is not necessary to compare scan[2] and match[2] since they
  82089. * are always equal when the other bytes match, given that
  82090. * the hash keys are equal and that HASH_BITS >= 8.
  82091. */
  82092. scan += 2, match++;
  82093. Assert(*scan == *match, "match[2]?");
  82094. /* We check for insufficient lookahead only every 8th comparison;
  82095. * the 256th check will be made at strstart+258.
  82096. */
  82097. do {
  82098. } while (*++scan == *++match && *++scan == *++match &&
  82099. *++scan == *++match && *++scan == *++match &&
  82100. *++scan == *++match && *++scan == *++match &&
  82101. *++scan == *++match && *++scan == *++match &&
  82102. scan < strend);
  82103. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82104. len = MAX_MATCH - (int)(strend - scan);
  82105. scan = strend - MAX_MATCH;
  82106. #endif /* UNALIGNED_OK */
  82107. if (len > best_len) {
  82108. s->match_start = cur_match;
  82109. best_len = len;
  82110. if (len >= nice_match) break;
  82111. #ifdef UNALIGNED_OK
  82112. scan_end = *(ushf*)(scan+best_len-1);
  82113. #else
  82114. scan_end1 = scan[best_len-1];
  82115. scan_end = scan[best_len];
  82116. #endif
  82117. }
  82118. } while ((cur_match = prev[cur_match & wmask]) > limit
  82119. && --chain_length != 0);
  82120. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82121. return s->lookahead;
  82122. }
  82123. #endif /* ASMV */
  82124. #endif /* FASTEST */
  82125. /* ---------------------------------------------------------------------------
  82126. * Optimized version for level == 1 or strategy == Z_RLE only
  82127. */
  82128. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82129. {
  82130. register Bytef *scan = s->window + s->strstart; /* current string */
  82131. register Bytef *match; /* matched string */
  82132. register int len; /* length of current match */
  82133. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82134. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82135. * It is easy to get rid of this optimization if necessary.
  82136. */
  82137. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82138. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82139. Assert(cur_match < s->strstart, "no future");
  82140. match = s->window + cur_match;
  82141. /* Return failure if the match length is less than 2:
  82142. */
  82143. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82144. /* The check at best_len-1 can be removed because it will be made
  82145. * again later. (This heuristic is not always a win.)
  82146. * It is not necessary to compare scan[2] and match[2] since they
  82147. * are always equal when the other bytes match, given that
  82148. * the hash keys are equal and that HASH_BITS >= 8.
  82149. */
  82150. scan += 2, match += 2;
  82151. Assert(*scan == *match, "match[2]?");
  82152. /* We check for insufficient lookahead only every 8th comparison;
  82153. * the 256th check will be made at strstart+258.
  82154. */
  82155. do {
  82156. } while (*++scan == *++match && *++scan == *++match &&
  82157. *++scan == *++match && *++scan == *++match &&
  82158. *++scan == *++match && *++scan == *++match &&
  82159. *++scan == *++match && *++scan == *++match &&
  82160. scan < strend);
  82161. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82162. len = MAX_MATCH - (int)(strend - scan);
  82163. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82164. s->match_start = cur_match;
  82165. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82166. }
  82167. #ifdef DEBUG
  82168. /* ===========================================================================
  82169. * Check that the match at match_start is indeed a match.
  82170. */
  82171. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82172. {
  82173. /* check that the match is indeed a match */
  82174. if (zmemcmp(s->window + match,
  82175. s->window + start, length) != EQUAL) {
  82176. fprintf(stderr, " start %u, match %u, length %d\n",
  82177. start, match, length);
  82178. do {
  82179. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82180. } while (--length != 0);
  82181. z_error("invalid match");
  82182. }
  82183. if (z_verbose > 1) {
  82184. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82185. do { putc(s->window[start++], stderr); } while (--length != 0);
  82186. }
  82187. }
  82188. #else
  82189. # define check_match(s, start, match, length)
  82190. #endif /* DEBUG */
  82191. /* ===========================================================================
  82192. * Fill the window when the lookahead becomes insufficient.
  82193. * Updates strstart and lookahead.
  82194. *
  82195. * IN assertion: lookahead < MIN_LOOKAHEAD
  82196. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82197. * At least one byte has been read, or avail_in == 0; reads are
  82198. * performed for at least two bytes (required for the zip translate_eol
  82199. * option -- not supported here).
  82200. */
  82201. local void fill_window (deflate_state *s)
  82202. {
  82203. register unsigned n, m;
  82204. register Posf *p;
  82205. unsigned more; /* Amount of free space at the end of the window. */
  82206. uInt wsize = s->w_size;
  82207. do {
  82208. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82209. /* Deal with !@#$% 64K limit: */
  82210. if (sizeof(int) <= 2) {
  82211. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82212. more = wsize;
  82213. } else if (more == (unsigned)(-1)) {
  82214. /* Very unlikely, but possible on 16 bit machine if
  82215. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82216. */
  82217. more--;
  82218. }
  82219. }
  82220. /* If the window is almost full and there is insufficient lookahead,
  82221. * move the upper half to the lower one to make room in the upper half.
  82222. */
  82223. if (s->strstart >= wsize+MAX_DIST(s)) {
  82224. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82225. s->match_start -= wsize;
  82226. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82227. s->block_start -= (long) wsize;
  82228. /* Slide the hash table (could be avoided with 32 bit values
  82229. at the expense of memory usage). We slide even when level == 0
  82230. to keep the hash table consistent if we switch back to level > 0
  82231. later. (Using level 0 permanently is not an optimal usage of
  82232. zlib, so we don't care about this pathological case.)
  82233. */
  82234. /* %%% avoid this when Z_RLE */
  82235. n = s->hash_size;
  82236. p = &s->head[n];
  82237. do {
  82238. m = *--p;
  82239. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82240. } while (--n);
  82241. n = wsize;
  82242. #ifndef FASTEST
  82243. p = &s->prev[n];
  82244. do {
  82245. m = *--p;
  82246. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82247. /* If n is not on any hash chain, prev[n] is garbage but
  82248. * its value will never be used.
  82249. */
  82250. } while (--n);
  82251. #endif
  82252. more += wsize;
  82253. }
  82254. if (s->strm->avail_in == 0) return;
  82255. /* If there was no sliding:
  82256. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82257. * more == window_size - lookahead - strstart
  82258. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82259. * => more >= window_size - 2*WSIZE + 2
  82260. * In the BIG_MEM or MMAP case (not yet supported),
  82261. * window_size == input_size + MIN_LOOKAHEAD &&
  82262. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82263. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82264. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82265. */
  82266. Assert(more >= 2, "more < 2");
  82267. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82268. s->lookahead += n;
  82269. /* Initialize the hash value now that we have some input: */
  82270. if (s->lookahead >= MIN_MATCH) {
  82271. s->ins_h = s->window[s->strstart];
  82272. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82273. #if MIN_MATCH != 3
  82274. Call UPDATE_HASH() MIN_MATCH-3 more times
  82275. #endif
  82276. }
  82277. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82278. * but this is not important since only literal bytes will be emitted.
  82279. */
  82280. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82281. }
  82282. /* ===========================================================================
  82283. * Flush the current block, with given end-of-file flag.
  82284. * IN assertion: strstart is set to the end of the current match.
  82285. */
  82286. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82287. _tr_flush_block(s, (s->block_start >= 0L ? \
  82288. (charf *)&s->window[(unsigned)s->block_start] : \
  82289. (charf *)Z_NULL), \
  82290. (ulg)((long)s->strstart - s->block_start), \
  82291. (eof)); \
  82292. s->block_start = s->strstart; \
  82293. flush_pending(s->strm); \
  82294. Tracev((stderr,"[FLUSH]")); \
  82295. }
  82296. /* Same but force premature exit if necessary. */
  82297. #define FLUSH_BLOCK(s, eof) { \
  82298. FLUSH_BLOCK_ONLY(s, eof); \
  82299. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82300. }
  82301. /* ===========================================================================
  82302. * Copy without compression as much as possible from the input stream, return
  82303. * the current block state.
  82304. * This function does not insert new strings in the dictionary since
  82305. * uncompressible data is probably not useful. This function is used
  82306. * only for the level=0 compression option.
  82307. * NOTE: this function should be optimized to avoid extra copying from
  82308. * window to pending_buf.
  82309. */
  82310. local block_state deflate_stored(deflate_state *s, int flush)
  82311. {
  82312. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82313. * to pending_buf_size, and each stored block has a 5 byte header:
  82314. */
  82315. ulg max_block_size = 0xffff;
  82316. ulg max_start;
  82317. if (max_block_size > s->pending_buf_size - 5) {
  82318. max_block_size = s->pending_buf_size - 5;
  82319. }
  82320. /* Copy as much as possible from input to output: */
  82321. for (;;) {
  82322. /* Fill the window as much as possible: */
  82323. if (s->lookahead <= 1) {
  82324. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82325. s->block_start >= (long)s->w_size, "slide too late");
  82326. fill_window(s);
  82327. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82328. if (s->lookahead == 0) break; /* flush the current block */
  82329. }
  82330. Assert(s->block_start >= 0L, "block gone");
  82331. s->strstart += s->lookahead;
  82332. s->lookahead = 0;
  82333. /* Emit a stored block if pending_buf will be full: */
  82334. max_start = s->block_start + max_block_size;
  82335. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82336. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82337. s->lookahead = (uInt)(s->strstart - max_start);
  82338. s->strstart = (uInt)max_start;
  82339. FLUSH_BLOCK(s, 0);
  82340. }
  82341. /* Flush if we may have to slide, otherwise block_start may become
  82342. * negative and the data will be gone:
  82343. */
  82344. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82345. FLUSH_BLOCK(s, 0);
  82346. }
  82347. }
  82348. FLUSH_BLOCK(s, flush == Z_FINISH);
  82349. return flush == Z_FINISH ? finish_done : block_done;
  82350. }
  82351. /* ===========================================================================
  82352. * Compress as much as possible from the input stream, return the current
  82353. * block state.
  82354. * This function does not perform lazy evaluation of matches and inserts
  82355. * new strings in the dictionary only for unmatched strings or for short
  82356. * matches. It is used only for the fast compression options.
  82357. */
  82358. local block_state deflate_fast(deflate_state *s, int flush)
  82359. {
  82360. IPos hash_head = NIL; /* head of the hash chain */
  82361. int bflush; /* set if current block must be flushed */
  82362. for (;;) {
  82363. /* Make sure that we always have enough lookahead, except
  82364. * at the end of the input file. We need MAX_MATCH bytes
  82365. * for the next match, plus MIN_MATCH bytes to insert the
  82366. * string following the next match.
  82367. */
  82368. if (s->lookahead < MIN_LOOKAHEAD) {
  82369. fill_window(s);
  82370. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82371. return need_more;
  82372. }
  82373. if (s->lookahead == 0) break; /* flush the current block */
  82374. }
  82375. /* Insert the string window[strstart .. strstart+2] in the
  82376. * dictionary, and set hash_head to the head of the hash chain:
  82377. */
  82378. if (s->lookahead >= MIN_MATCH) {
  82379. INSERT_STRING(s, s->strstart, hash_head);
  82380. }
  82381. /* Find the longest match, discarding those <= prev_length.
  82382. * At this point we have always match_length < MIN_MATCH
  82383. */
  82384. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82385. /* To simplify the code, we prevent matches with the string
  82386. * of window index 0 (in particular we have to avoid a match
  82387. * of the string with itself at the start of the input file).
  82388. */
  82389. #ifdef FASTEST
  82390. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82391. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82392. s->match_length = longest_match_fast (s, hash_head);
  82393. }
  82394. #else
  82395. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82396. s->match_length = longest_match (s, hash_head);
  82397. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82398. s->match_length = longest_match_fast (s, hash_head);
  82399. }
  82400. #endif
  82401. /* longest_match() or longest_match_fast() sets match_start */
  82402. }
  82403. if (s->match_length >= MIN_MATCH) {
  82404. check_match(s, s->strstart, s->match_start, s->match_length);
  82405. _tr_tally_dist(s, s->strstart - s->match_start,
  82406. s->match_length - MIN_MATCH, bflush);
  82407. s->lookahead -= s->match_length;
  82408. /* Insert new strings in the hash table only if the match length
  82409. * is not too large. This saves time but degrades compression.
  82410. */
  82411. #ifndef FASTEST
  82412. if (s->match_length <= s->max_insert_length &&
  82413. s->lookahead >= MIN_MATCH) {
  82414. s->match_length--; /* string at strstart already in table */
  82415. do {
  82416. s->strstart++;
  82417. INSERT_STRING(s, s->strstart, hash_head);
  82418. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82419. * always MIN_MATCH bytes ahead.
  82420. */
  82421. } while (--s->match_length != 0);
  82422. s->strstart++;
  82423. } else
  82424. #endif
  82425. {
  82426. s->strstart += s->match_length;
  82427. s->match_length = 0;
  82428. s->ins_h = s->window[s->strstart];
  82429. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82430. #if MIN_MATCH != 3
  82431. Call UPDATE_HASH() MIN_MATCH-3 more times
  82432. #endif
  82433. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82434. * matter since it will be recomputed at next deflate call.
  82435. */
  82436. }
  82437. } else {
  82438. /* No match, output a literal byte */
  82439. Tracevv((stderr,"%c", s->window[s->strstart]));
  82440. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82441. s->lookahead--;
  82442. s->strstart++;
  82443. }
  82444. if (bflush) FLUSH_BLOCK(s, 0);
  82445. }
  82446. FLUSH_BLOCK(s, flush == Z_FINISH);
  82447. return flush == Z_FINISH ? finish_done : block_done;
  82448. }
  82449. #ifndef FASTEST
  82450. /* ===========================================================================
  82451. * Same as above, but achieves better compression. We use a lazy
  82452. * evaluation for matches: a match is finally adopted only if there is
  82453. * no better match at the next window position.
  82454. */
  82455. local block_state deflate_slow(deflate_state *s, int flush)
  82456. {
  82457. IPos hash_head = NIL; /* head of hash chain */
  82458. int bflush; /* set if current block must be flushed */
  82459. /* Process the input block. */
  82460. for (;;) {
  82461. /* Make sure that we always have enough lookahead, except
  82462. * at the end of the input file. We need MAX_MATCH bytes
  82463. * for the next match, plus MIN_MATCH bytes to insert the
  82464. * string following the next match.
  82465. */
  82466. if (s->lookahead < MIN_LOOKAHEAD) {
  82467. fill_window(s);
  82468. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82469. return need_more;
  82470. }
  82471. if (s->lookahead == 0) break; /* flush the current block */
  82472. }
  82473. /* Insert the string window[strstart .. strstart+2] in the
  82474. * dictionary, and set hash_head to the head of the hash chain:
  82475. */
  82476. if (s->lookahead >= MIN_MATCH) {
  82477. INSERT_STRING(s, s->strstart, hash_head);
  82478. }
  82479. /* Find the longest match, discarding those <= prev_length.
  82480. */
  82481. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82482. s->match_length = MIN_MATCH-1;
  82483. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82484. s->strstart - hash_head <= MAX_DIST(s)) {
  82485. /* To simplify the code, we prevent matches with the string
  82486. * of window index 0 (in particular we have to avoid a match
  82487. * of the string with itself at the start of the input file).
  82488. */
  82489. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82490. s->match_length = longest_match (s, hash_head);
  82491. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82492. s->match_length = longest_match_fast (s, hash_head);
  82493. }
  82494. /* longest_match() or longest_match_fast() sets match_start */
  82495. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82496. #if TOO_FAR <= 32767
  82497. || (s->match_length == MIN_MATCH &&
  82498. s->strstart - s->match_start > TOO_FAR)
  82499. #endif
  82500. )) {
  82501. /* If prev_match is also MIN_MATCH, match_start is garbage
  82502. * but we will ignore the current match anyway.
  82503. */
  82504. s->match_length = MIN_MATCH-1;
  82505. }
  82506. }
  82507. /* If there was a match at the previous step and the current
  82508. * match is not better, output the previous match:
  82509. */
  82510. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82511. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82512. /* Do not insert strings in hash table beyond this. */
  82513. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82514. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82515. s->prev_length - MIN_MATCH, bflush);
  82516. /* Insert in hash table all strings up to the end of the match.
  82517. * strstart-1 and strstart are already inserted. If there is not
  82518. * enough lookahead, the last two strings are not inserted in
  82519. * the hash table.
  82520. */
  82521. s->lookahead -= s->prev_length-1;
  82522. s->prev_length -= 2;
  82523. do {
  82524. if (++s->strstart <= max_insert) {
  82525. INSERT_STRING(s, s->strstart, hash_head);
  82526. }
  82527. } while (--s->prev_length != 0);
  82528. s->match_available = 0;
  82529. s->match_length = MIN_MATCH-1;
  82530. s->strstart++;
  82531. if (bflush) FLUSH_BLOCK(s, 0);
  82532. } else if (s->match_available) {
  82533. /* If there was no match at the previous position, output a
  82534. * single literal. If there was a match but the current match
  82535. * is longer, truncate the previous match to a single literal.
  82536. */
  82537. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82538. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82539. if (bflush) {
  82540. FLUSH_BLOCK_ONLY(s, 0);
  82541. }
  82542. s->strstart++;
  82543. s->lookahead--;
  82544. if (s->strm->avail_out == 0) return need_more;
  82545. } else {
  82546. /* There is no previous match to compare with, wait for
  82547. * the next step to decide.
  82548. */
  82549. s->match_available = 1;
  82550. s->strstart++;
  82551. s->lookahead--;
  82552. }
  82553. }
  82554. Assert (flush != Z_NO_FLUSH, "no flush?");
  82555. if (s->match_available) {
  82556. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82557. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82558. s->match_available = 0;
  82559. }
  82560. FLUSH_BLOCK(s, flush == Z_FINISH);
  82561. return flush == Z_FINISH ? finish_done : block_done;
  82562. }
  82563. #endif /* FASTEST */
  82564. #if 0
  82565. /* ===========================================================================
  82566. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82567. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82568. * deflate switches away from Z_RLE.)
  82569. */
  82570. local block_state deflate_rle(s, flush)
  82571. deflate_state *s;
  82572. int flush;
  82573. {
  82574. int bflush; /* set if current block must be flushed */
  82575. uInt run; /* length of run */
  82576. uInt max; /* maximum length of run */
  82577. uInt prev; /* byte at distance one to match */
  82578. Bytef *scan; /* scan for end of run */
  82579. for (;;) {
  82580. /* Make sure that we always have enough lookahead, except
  82581. * at the end of the input file. We need MAX_MATCH bytes
  82582. * for the longest encodable run.
  82583. */
  82584. if (s->lookahead < MAX_MATCH) {
  82585. fill_window(s);
  82586. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82587. return need_more;
  82588. }
  82589. if (s->lookahead == 0) break; /* flush the current block */
  82590. }
  82591. /* See how many times the previous byte repeats */
  82592. run = 0;
  82593. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82594. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82595. scan = s->window + s->strstart - 1;
  82596. prev = *scan++;
  82597. do {
  82598. if (*scan++ != prev)
  82599. break;
  82600. } while (++run < max);
  82601. }
  82602. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82603. if (run >= MIN_MATCH) {
  82604. check_match(s, s->strstart, s->strstart - 1, run);
  82605. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82606. s->lookahead -= run;
  82607. s->strstart += run;
  82608. } else {
  82609. /* No match, output a literal byte */
  82610. Tracevv((stderr,"%c", s->window[s->strstart]));
  82611. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82612. s->lookahead--;
  82613. s->strstart++;
  82614. }
  82615. if (bflush) FLUSH_BLOCK(s, 0);
  82616. }
  82617. FLUSH_BLOCK(s, flush == Z_FINISH);
  82618. return flush == Z_FINISH ? finish_done : block_done;
  82619. }
  82620. #endif
  82621. /*** End of inlined file: deflate.c ***/
  82622. /*** Start of inlined file: inffast.c ***/
  82623. /*** Start of inlined file: inftrees.h ***/
  82624. /* WARNING: this file should *not* be used by applications. It is
  82625. part of the implementation of the compression library and is
  82626. subject to change. Applications should only use zlib.h.
  82627. */
  82628. #ifndef _INFTREES_H_
  82629. #define _INFTREES_H_
  82630. /* Structure for decoding tables. Each entry provides either the
  82631. information needed to do the operation requested by the code that
  82632. indexed that table entry, or it provides a pointer to another
  82633. table that indexes more bits of the code. op indicates whether
  82634. the entry is a pointer to another table, a literal, a length or
  82635. distance, an end-of-block, or an invalid code. For a table
  82636. pointer, the low four bits of op is the number of index bits of
  82637. that table. For a length or distance, the low four bits of op
  82638. is the number of extra bits to get after the code. bits is
  82639. the number of bits in this code or part of the code to drop off
  82640. of the bit buffer. val is the actual byte to output in the case
  82641. of a literal, the base length or distance, or the offset from
  82642. the current table to the next table. Each entry is four bytes. */
  82643. typedef struct {
  82644. unsigned char op; /* operation, extra bits, table bits */
  82645. unsigned char bits; /* bits in this part of the code */
  82646. unsigned short val; /* offset in table or code value */
  82647. } code;
  82648. /* op values as set by inflate_table():
  82649. 00000000 - literal
  82650. 0000tttt - table link, tttt != 0 is the number of table index bits
  82651. 0001eeee - length or distance, eeee is the number of extra bits
  82652. 01100000 - end of block
  82653. 01000000 - invalid code
  82654. */
  82655. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82656. exhaustive search was 1444 code structures (852 for length/literals
  82657. and 592 for distances, the latter actually the result of an
  82658. exhaustive search). The true maximum is not known, but the value
  82659. below is more than safe. */
  82660. #define ENOUGH 2048
  82661. #define MAXD 592
  82662. /* Type of code to build for inftable() */
  82663. typedef enum {
  82664. CODES,
  82665. LENS,
  82666. DISTS
  82667. } codetype;
  82668. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82669. unsigned codes, code FAR * FAR *table,
  82670. unsigned FAR *bits, unsigned short FAR *work));
  82671. #endif
  82672. /*** End of inlined file: inftrees.h ***/
  82673. /*** Start of inlined file: inflate.h ***/
  82674. /* WARNING: this file should *not* be used by applications. It is
  82675. part of the implementation of the compression library and is
  82676. subject to change. Applications should only use zlib.h.
  82677. */
  82678. #ifndef _INFLATE_H_
  82679. #define _INFLATE_H_
  82680. /* define NO_GZIP when compiling if you want to disable gzip header and
  82681. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82682. the crc code when it is not needed. For shared libraries, gzip decoding
  82683. should be left enabled. */
  82684. #ifndef NO_GZIP
  82685. # define GUNZIP
  82686. #endif
  82687. /* Possible inflate modes between inflate() calls */
  82688. typedef enum {
  82689. HEAD, /* i: waiting for magic header */
  82690. FLAGS, /* i: waiting for method and flags (gzip) */
  82691. TIME, /* i: waiting for modification time (gzip) */
  82692. OS, /* i: waiting for extra flags and operating system (gzip) */
  82693. EXLEN, /* i: waiting for extra length (gzip) */
  82694. EXTRA, /* i: waiting for extra bytes (gzip) */
  82695. NAME, /* i: waiting for end of file name (gzip) */
  82696. COMMENT, /* i: waiting for end of comment (gzip) */
  82697. HCRC, /* i: waiting for header crc (gzip) */
  82698. DICTID, /* i: waiting for dictionary check value */
  82699. DICT, /* waiting for inflateSetDictionary() call */
  82700. TYPE, /* i: waiting for type bits, including last-flag bit */
  82701. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82702. STORED, /* i: waiting for stored size (length and complement) */
  82703. COPY, /* i/o: waiting for input or output to copy stored block */
  82704. TABLE, /* i: waiting for dynamic block table lengths */
  82705. LENLENS, /* i: waiting for code length code lengths */
  82706. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82707. LEN, /* i: waiting for length/lit code */
  82708. LENEXT, /* i: waiting for length extra bits */
  82709. DIST, /* i: waiting for distance code */
  82710. DISTEXT, /* i: waiting for distance extra bits */
  82711. MATCH, /* o: waiting for output space to copy string */
  82712. LIT, /* o: waiting for output space to write literal */
  82713. CHECK, /* i: waiting for 32-bit check value */
  82714. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82715. DONE, /* finished check, done -- remain here until reset */
  82716. BAD, /* got a data error -- remain here until reset */
  82717. MEM, /* got an inflate() memory error -- remain here until reset */
  82718. SYNC /* looking for synchronization bytes to restart inflate() */
  82719. } inflate_mode;
  82720. /*
  82721. State transitions between above modes -
  82722. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82723. Process header:
  82724. HEAD -> (gzip) or (zlib)
  82725. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82726. NAME -> COMMENT -> HCRC -> TYPE
  82727. (zlib) -> DICTID or TYPE
  82728. DICTID -> DICT -> TYPE
  82729. Read deflate blocks:
  82730. TYPE -> STORED or TABLE or LEN or CHECK
  82731. STORED -> COPY -> TYPE
  82732. TABLE -> LENLENS -> CODELENS -> LEN
  82733. Read deflate codes:
  82734. LEN -> LENEXT or LIT or TYPE
  82735. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82736. LIT -> LEN
  82737. Process trailer:
  82738. CHECK -> LENGTH -> DONE
  82739. */
  82740. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82741. struct inflate_state {
  82742. inflate_mode mode; /* current inflate mode */
  82743. int last; /* true if processing last block */
  82744. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82745. int havedict; /* true if dictionary provided */
  82746. int flags; /* gzip header method and flags (0 if zlib) */
  82747. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82748. unsigned long check; /* protected copy of check value */
  82749. unsigned long total; /* protected copy of output count */
  82750. gz_headerp head; /* where to save gzip header information */
  82751. /* sliding window */
  82752. unsigned wbits; /* log base 2 of requested window size */
  82753. unsigned wsize; /* window size or zero if not using window */
  82754. unsigned whave; /* valid bytes in the window */
  82755. unsigned write; /* window write index */
  82756. unsigned char FAR *window; /* allocated sliding window, if needed */
  82757. /* bit accumulator */
  82758. unsigned long hold; /* input bit accumulator */
  82759. unsigned bits; /* number of bits in "in" */
  82760. /* for string and stored block copying */
  82761. unsigned length; /* literal or length of data to copy */
  82762. unsigned offset; /* distance back to copy string from */
  82763. /* for table and code decoding */
  82764. unsigned extra; /* extra bits needed */
  82765. /* fixed and dynamic code tables */
  82766. code const FAR *lencode; /* starting table for length/literal codes */
  82767. code const FAR *distcode; /* starting table for distance codes */
  82768. unsigned lenbits; /* index bits for lencode */
  82769. unsigned distbits; /* index bits for distcode */
  82770. /* dynamic table building */
  82771. unsigned ncode; /* number of code length code lengths */
  82772. unsigned nlen; /* number of length code lengths */
  82773. unsigned ndist; /* number of distance code lengths */
  82774. unsigned have; /* number of code lengths in lens[] */
  82775. code FAR *next; /* next available space in codes[] */
  82776. unsigned short lens[320]; /* temporary storage for code lengths */
  82777. unsigned short work[288]; /* work area for code table building */
  82778. code codes[ENOUGH]; /* space for code tables */
  82779. };
  82780. #endif
  82781. /*** End of inlined file: inflate.h ***/
  82782. /*** Start of inlined file: inffast.h ***/
  82783. /* WARNING: this file should *not* be used by applications. It is
  82784. part of the implementation of the compression library and is
  82785. subject to change. Applications should only use zlib.h.
  82786. */
  82787. void inflate_fast OF((z_streamp strm, unsigned start));
  82788. /*** End of inlined file: inffast.h ***/
  82789. #ifndef ASMINF
  82790. /* Allow machine dependent optimization for post-increment or pre-increment.
  82791. Based on testing to date,
  82792. Pre-increment preferred for:
  82793. - PowerPC G3 (Adler)
  82794. - MIPS R5000 (Randers-Pehrson)
  82795. Post-increment preferred for:
  82796. - none
  82797. No measurable difference:
  82798. - Pentium III (Anderson)
  82799. - M68060 (Nikl)
  82800. */
  82801. #ifdef POSTINC
  82802. # define OFF 0
  82803. # define PUP(a) *(a)++
  82804. #else
  82805. # define OFF 1
  82806. # define PUP(a) *++(a)
  82807. #endif
  82808. /*
  82809. Decode literal, length, and distance codes and write out the resulting
  82810. literal and match bytes until either not enough input or output is
  82811. available, an end-of-block is encountered, or a data error is encountered.
  82812. When large enough input and output buffers are supplied to inflate(), for
  82813. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82814. inflate execution time is spent in this routine.
  82815. Entry assumptions:
  82816. state->mode == LEN
  82817. strm->avail_in >= 6
  82818. strm->avail_out >= 258
  82819. start >= strm->avail_out
  82820. state->bits < 8
  82821. On return, state->mode is one of:
  82822. LEN -- ran out of enough output space or enough available input
  82823. TYPE -- reached end of block code, inflate() to interpret next block
  82824. BAD -- error in block data
  82825. Notes:
  82826. - The maximum input bits used by a length/distance pair is 15 bits for the
  82827. length code, 5 bits for the length extra, 15 bits for the distance code,
  82828. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82829. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82830. checking for available input while decoding.
  82831. - The maximum bytes that a single length/distance pair can output is 258
  82832. bytes, which is the maximum length that can be coded. inflate_fast()
  82833. requires strm->avail_out >= 258 for each loop to avoid checking for
  82834. output space.
  82835. */
  82836. void inflate_fast (z_streamp strm, unsigned start)
  82837. {
  82838. struct inflate_state FAR *state;
  82839. unsigned char FAR *in; /* local strm->next_in */
  82840. unsigned char FAR *last; /* while in < last, enough input available */
  82841. unsigned char FAR *out; /* local strm->next_out */
  82842. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82843. unsigned char FAR *end; /* while out < end, enough space available */
  82844. #ifdef INFLATE_STRICT
  82845. unsigned dmax; /* maximum distance from zlib header */
  82846. #endif
  82847. unsigned wsize; /* window size or zero if not using window */
  82848. unsigned whave; /* valid bytes in the window */
  82849. unsigned write; /* window write index */
  82850. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82851. unsigned long hold; /* local strm->hold */
  82852. unsigned bits; /* local strm->bits */
  82853. code const FAR *lcode; /* local strm->lencode */
  82854. code const FAR *dcode; /* local strm->distcode */
  82855. unsigned lmask; /* mask for first level of length codes */
  82856. unsigned dmask; /* mask for first level of distance codes */
  82857. code thisx; /* retrieved table entry */
  82858. unsigned op; /* code bits, operation, extra bits, or */
  82859. /* window position, window bytes to copy */
  82860. unsigned len; /* match length, unused bytes */
  82861. unsigned dist; /* match distance */
  82862. unsigned char FAR *from; /* where to copy match from */
  82863. /* copy state to local variables */
  82864. state = (struct inflate_state FAR *)strm->state;
  82865. in = strm->next_in - OFF;
  82866. last = in + (strm->avail_in - 5);
  82867. out = strm->next_out - OFF;
  82868. beg = out - (start - strm->avail_out);
  82869. end = out + (strm->avail_out - 257);
  82870. #ifdef INFLATE_STRICT
  82871. dmax = state->dmax;
  82872. #endif
  82873. wsize = state->wsize;
  82874. whave = state->whave;
  82875. write = state->write;
  82876. window = state->window;
  82877. hold = state->hold;
  82878. bits = state->bits;
  82879. lcode = state->lencode;
  82880. dcode = state->distcode;
  82881. lmask = (1U << state->lenbits) - 1;
  82882. dmask = (1U << state->distbits) - 1;
  82883. /* decode literals and length/distances until end-of-block or not enough
  82884. input data or output space */
  82885. do {
  82886. if (bits < 15) {
  82887. hold += (unsigned long)(PUP(in)) << bits;
  82888. bits += 8;
  82889. hold += (unsigned long)(PUP(in)) << bits;
  82890. bits += 8;
  82891. }
  82892. thisx = lcode[hold & lmask];
  82893. dolen:
  82894. op = (unsigned)(thisx.bits);
  82895. hold >>= op;
  82896. bits -= op;
  82897. op = (unsigned)(thisx.op);
  82898. if (op == 0) { /* literal */
  82899. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82900. "inflate: literal '%c'\n" :
  82901. "inflate: literal 0x%02x\n", thisx.val));
  82902. PUP(out) = (unsigned char)(thisx.val);
  82903. }
  82904. else if (op & 16) { /* length base */
  82905. len = (unsigned)(thisx.val);
  82906. op &= 15; /* number of extra bits */
  82907. if (op) {
  82908. if (bits < op) {
  82909. hold += (unsigned long)(PUP(in)) << bits;
  82910. bits += 8;
  82911. }
  82912. len += (unsigned)hold & ((1U << op) - 1);
  82913. hold >>= op;
  82914. bits -= op;
  82915. }
  82916. Tracevv((stderr, "inflate: length %u\n", len));
  82917. if (bits < 15) {
  82918. hold += (unsigned long)(PUP(in)) << bits;
  82919. bits += 8;
  82920. hold += (unsigned long)(PUP(in)) << bits;
  82921. bits += 8;
  82922. }
  82923. thisx = dcode[hold & dmask];
  82924. dodist:
  82925. op = (unsigned)(thisx.bits);
  82926. hold >>= op;
  82927. bits -= op;
  82928. op = (unsigned)(thisx.op);
  82929. if (op & 16) { /* distance base */
  82930. dist = (unsigned)(thisx.val);
  82931. op &= 15; /* number of extra bits */
  82932. if (bits < op) {
  82933. hold += (unsigned long)(PUP(in)) << bits;
  82934. bits += 8;
  82935. if (bits < op) {
  82936. hold += (unsigned long)(PUP(in)) << bits;
  82937. bits += 8;
  82938. }
  82939. }
  82940. dist += (unsigned)hold & ((1U << op) - 1);
  82941. #ifdef INFLATE_STRICT
  82942. if (dist > dmax) {
  82943. strm->msg = (char *)"invalid distance too far back";
  82944. state->mode = BAD;
  82945. break;
  82946. }
  82947. #endif
  82948. hold >>= op;
  82949. bits -= op;
  82950. Tracevv((stderr, "inflate: distance %u\n", dist));
  82951. op = (unsigned)(out - beg); /* max distance in output */
  82952. if (dist > op) { /* see if copy from window */
  82953. op = dist - op; /* distance back in window */
  82954. if (op > whave) {
  82955. strm->msg = (char *)"invalid distance too far back";
  82956. state->mode = BAD;
  82957. break;
  82958. }
  82959. from = window - OFF;
  82960. if (write == 0) { /* very common case */
  82961. from += wsize - op;
  82962. if (op < len) { /* some from window */
  82963. len -= op;
  82964. do {
  82965. PUP(out) = PUP(from);
  82966. } while (--op);
  82967. from = out - dist; /* rest from output */
  82968. }
  82969. }
  82970. else if (write < op) { /* wrap around window */
  82971. from += wsize + write - op;
  82972. op -= write;
  82973. if (op < len) { /* some from end of window */
  82974. len -= op;
  82975. do {
  82976. PUP(out) = PUP(from);
  82977. } while (--op);
  82978. from = window - OFF;
  82979. if (write < len) { /* some from start of window */
  82980. op = write;
  82981. len -= op;
  82982. do {
  82983. PUP(out) = PUP(from);
  82984. } while (--op);
  82985. from = out - dist; /* rest from output */
  82986. }
  82987. }
  82988. }
  82989. else { /* contiguous in window */
  82990. from += write - op;
  82991. if (op < len) { /* some from window */
  82992. len -= op;
  82993. do {
  82994. PUP(out) = PUP(from);
  82995. } while (--op);
  82996. from = out - dist; /* rest from output */
  82997. }
  82998. }
  82999. while (len > 2) {
  83000. PUP(out) = PUP(from);
  83001. PUP(out) = PUP(from);
  83002. PUP(out) = PUP(from);
  83003. len -= 3;
  83004. }
  83005. if (len) {
  83006. PUP(out) = PUP(from);
  83007. if (len > 1)
  83008. PUP(out) = PUP(from);
  83009. }
  83010. }
  83011. else {
  83012. from = out - dist; /* copy direct from output */
  83013. do { /* minimum length is three */
  83014. PUP(out) = PUP(from);
  83015. PUP(out) = PUP(from);
  83016. PUP(out) = PUP(from);
  83017. len -= 3;
  83018. } while (len > 2);
  83019. if (len) {
  83020. PUP(out) = PUP(from);
  83021. if (len > 1)
  83022. PUP(out) = PUP(from);
  83023. }
  83024. }
  83025. }
  83026. else if ((op & 64) == 0) { /* 2nd level distance code */
  83027. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83028. goto dodist;
  83029. }
  83030. else {
  83031. strm->msg = (char *)"invalid distance code";
  83032. state->mode = BAD;
  83033. break;
  83034. }
  83035. }
  83036. else if ((op & 64) == 0) { /* 2nd level length code */
  83037. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83038. goto dolen;
  83039. }
  83040. else if (op & 32) { /* end-of-block */
  83041. Tracevv((stderr, "inflate: end of block\n"));
  83042. state->mode = TYPE;
  83043. break;
  83044. }
  83045. else {
  83046. strm->msg = (char *)"invalid literal/length code";
  83047. state->mode = BAD;
  83048. break;
  83049. }
  83050. } while (in < last && out < end);
  83051. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83052. len = bits >> 3;
  83053. in -= len;
  83054. bits -= len << 3;
  83055. hold &= (1U << bits) - 1;
  83056. /* update state and return */
  83057. strm->next_in = in + OFF;
  83058. strm->next_out = out + OFF;
  83059. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83060. strm->avail_out = (unsigned)(out < end ?
  83061. 257 + (end - out) : 257 - (out - end));
  83062. state->hold = hold;
  83063. state->bits = bits;
  83064. return;
  83065. }
  83066. /*
  83067. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83068. - Using bit fields for code structure
  83069. - Different op definition to avoid & for extra bits (do & for table bits)
  83070. - Three separate decoding do-loops for direct, window, and write == 0
  83071. - Special case for distance > 1 copies to do overlapped load and store copy
  83072. - Explicit branch predictions (based on measured branch probabilities)
  83073. - Deferring match copy and interspersed it with decoding subsequent codes
  83074. - Swapping literal/length else
  83075. - Swapping window/direct else
  83076. - Larger unrolled copy loops (three is about right)
  83077. - Moving len -= 3 statement into middle of loop
  83078. */
  83079. #endif /* !ASMINF */
  83080. /*** End of inlined file: inffast.c ***/
  83081. #undef PULLBYTE
  83082. #undef LOAD
  83083. #undef RESTORE
  83084. #undef INITBITS
  83085. #undef NEEDBITS
  83086. #undef DROPBITS
  83087. #undef BYTEBITS
  83088. /*** Start of inlined file: inflate.c ***/
  83089. /*
  83090. * Change history:
  83091. *
  83092. * 1.2.beta0 24 Nov 2002
  83093. * - First version -- complete rewrite of inflate to simplify code, avoid
  83094. * creation of window when not needed, minimize use of window when it is
  83095. * needed, make inffast.c even faster, implement gzip decoding, and to
  83096. * improve code readability and style over the previous zlib inflate code
  83097. *
  83098. * 1.2.beta1 25 Nov 2002
  83099. * - Use pointers for available input and output checking in inffast.c
  83100. * - Remove input and output counters in inffast.c
  83101. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83102. * - Remove unnecessary second byte pull from length extra in inffast.c
  83103. * - Unroll direct copy to three copies per loop in inffast.c
  83104. *
  83105. * 1.2.beta2 4 Dec 2002
  83106. * - Change external routine names to reduce potential conflicts
  83107. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83108. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83109. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83110. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83111. *
  83112. * 1.2.beta3 22 Dec 2002
  83113. * - Add comments on state->bits assertion in inffast.c
  83114. * - Add comments on op field in inftrees.h
  83115. * - Fix bug in reuse of allocated window after inflateReset()
  83116. * - Remove bit fields--back to byte structure for speed
  83117. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83118. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83119. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83120. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83121. * - Use local copies of stream next and avail values, as well as local bit
  83122. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83123. *
  83124. * 1.2.beta4 1 Jan 2003
  83125. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83126. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83127. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83128. * - Rearrange window copies in inflate_fast() for speed and simplification
  83129. * - Unroll last copy for window match in inflate_fast()
  83130. * - Use local copies of window variables in inflate_fast() for speed
  83131. * - Pull out common write == 0 case for speed in inflate_fast()
  83132. * - Make op and len in inflate_fast() unsigned for consistency
  83133. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83134. * - Simplified bad distance check in inflate_fast()
  83135. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83136. * source file infback.c to provide a call-back interface to inflate for
  83137. * programs like gzip and unzip -- uses window as output buffer to avoid
  83138. * window copying
  83139. *
  83140. * 1.2.beta5 1 Jan 2003
  83141. * - Improved inflateBack() interface to allow the caller to provide initial
  83142. * input in strm.
  83143. * - Fixed stored blocks bug in inflateBack()
  83144. *
  83145. * 1.2.beta6 4 Jan 2003
  83146. * - Added comments in inffast.c on effectiveness of POSTINC
  83147. * - Typecasting all around to reduce compiler warnings
  83148. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83149. * make compilers happy
  83150. * - Changed type of window in inflateBackInit() to unsigned char *
  83151. *
  83152. * 1.2.beta7 27 Jan 2003
  83153. * - Changed many types to unsigned or unsigned short to avoid warnings
  83154. * - Added inflateCopy() function
  83155. *
  83156. * 1.2.0 9 Mar 2003
  83157. * - Changed inflateBack() interface to provide separate opaque descriptors
  83158. * for the in() and out() functions
  83159. * - Changed inflateBack() argument and in_func typedef to swap the length
  83160. * and buffer address return values for the input function
  83161. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83162. *
  83163. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83164. */
  83165. /*** Start of inlined file: inffast.h ***/
  83166. /* WARNING: this file should *not* be used by applications. It is
  83167. part of the implementation of the compression library and is
  83168. subject to change. Applications should only use zlib.h.
  83169. */
  83170. void inflate_fast OF((z_streamp strm, unsigned start));
  83171. /*** End of inlined file: inffast.h ***/
  83172. #ifdef MAKEFIXED
  83173. # ifndef BUILDFIXED
  83174. # define BUILDFIXED
  83175. # endif
  83176. #endif
  83177. /* function prototypes */
  83178. local void fixedtables OF((struct inflate_state FAR *state));
  83179. local int updatewindow OF((z_streamp strm, unsigned out));
  83180. #ifdef BUILDFIXED
  83181. void makefixed OF((void));
  83182. #endif
  83183. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83184. unsigned len));
  83185. int ZEXPORT inflateReset (z_streamp strm)
  83186. {
  83187. struct inflate_state FAR *state;
  83188. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83189. state = (struct inflate_state FAR *)strm->state;
  83190. strm->total_in = strm->total_out = state->total = 0;
  83191. strm->msg = Z_NULL;
  83192. strm->adler = 1; /* to support ill-conceived Java test suite */
  83193. state->mode = HEAD;
  83194. state->last = 0;
  83195. state->havedict = 0;
  83196. state->dmax = 32768U;
  83197. state->head = Z_NULL;
  83198. state->wsize = 0;
  83199. state->whave = 0;
  83200. state->write = 0;
  83201. state->hold = 0;
  83202. state->bits = 0;
  83203. state->lencode = state->distcode = state->next = state->codes;
  83204. Tracev((stderr, "inflate: reset\n"));
  83205. return Z_OK;
  83206. }
  83207. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83208. {
  83209. struct inflate_state FAR *state;
  83210. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83211. state = (struct inflate_state FAR *)strm->state;
  83212. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83213. value &= (1L << bits) - 1;
  83214. state->hold += value << state->bits;
  83215. state->bits += bits;
  83216. return Z_OK;
  83217. }
  83218. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83219. {
  83220. struct inflate_state FAR *state;
  83221. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83222. stream_size != (int)(sizeof(z_stream)))
  83223. return Z_VERSION_ERROR;
  83224. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83225. strm->msg = Z_NULL; /* in case we return an error */
  83226. if (strm->zalloc == (alloc_func)0) {
  83227. strm->zalloc = zcalloc;
  83228. strm->opaque = (voidpf)0;
  83229. }
  83230. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83231. state = (struct inflate_state FAR *)
  83232. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83233. if (state == Z_NULL) return Z_MEM_ERROR;
  83234. Tracev((stderr, "inflate: allocated\n"));
  83235. strm->state = (struct internal_state FAR *)state;
  83236. if (windowBits < 0) {
  83237. state->wrap = 0;
  83238. windowBits = -windowBits;
  83239. }
  83240. else {
  83241. state->wrap = (windowBits >> 4) + 1;
  83242. #ifdef GUNZIP
  83243. if (windowBits < 48) windowBits &= 15;
  83244. #endif
  83245. }
  83246. if (windowBits < 8 || windowBits > 15) {
  83247. ZFREE(strm, state);
  83248. strm->state = Z_NULL;
  83249. return Z_STREAM_ERROR;
  83250. }
  83251. state->wbits = (unsigned)windowBits;
  83252. state->window = Z_NULL;
  83253. return inflateReset(strm);
  83254. }
  83255. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83256. {
  83257. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83258. }
  83259. /*
  83260. Return state with length and distance decoding tables and index sizes set to
  83261. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83262. If BUILDFIXED is defined, then instead this routine builds the tables the
  83263. first time it's called, and returns those tables the first time and
  83264. thereafter. This reduces the size of the code by about 2K bytes, in
  83265. exchange for a little execution time. However, BUILDFIXED should not be
  83266. used for threaded applications, since the rewriting of the tables and virgin
  83267. may not be thread-safe.
  83268. */
  83269. local void fixedtables (struct inflate_state FAR *state)
  83270. {
  83271. #ifdef BUILDFIXED
  83272. static int virgin = 1;
  83273. static code *lenfix, *distfix;
  83274. static code fixed[544];
  83275. /* build fixed huffman tables if first call (may not be thread safe) */
  83276. if (virgin) {
  83277. unsigned sym, bits;
  83278. static code *next;
  83279. /* literal/length table */
  83280. sym = 0;
  83281. while (sym < 144) state->lens[sym++] = 8;
  83282. while (sym < 256) state->lens[sym++] = 9;
  83283. while (sym < 280) state->lens[sym++] = 7;
  83284. while (sym < 288) state->lens[sym++] = 8;
  83285. next = fixed;
  83286. lenfix = next;
  83287. bits = 9;
  83288. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83289. /* distance table */
  83290. sym = 0;
  83291. while (sym < 32) state->lens[sym++] = 5;
  83292. distfix = next;
  83293. bits = 5;
  83294. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83295. /* do this just once */
  83296. virgin = 0;
  83297. }
  83298. #else /* !BUILDFIXED */
  83299. /*** Start of inlined file: inffixed.h ***/
  83300. /* WARNING: this file should *not* be used by applications. It
  83301. is part of the implementation of the compression library and
  83302. is subject to change. Applications should only use zlib.h.
  83303. */
  83304. static const code lenfix[512] = {
  83305. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83306. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83307. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83308. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83309. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83310. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83311. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83312. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83313. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83314. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83315. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83316. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83317. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83318. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83319. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83320. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83321. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83322. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83323. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83324. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83325. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83326. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83327. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83328. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83329. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83330. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83331. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83332. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83333. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83334. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83335. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83336. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83337. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83338. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83339. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83340. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83341. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83342. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83343. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83344. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83345. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83346. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83347. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83348. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83349. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83350. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83351. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83352. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83353. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83354. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83355. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83356. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83357. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83358. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83359. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83360. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83361. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83362. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83363. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83364. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83365. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83366. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83367. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83368. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83369. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83370. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83371. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83372. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83373. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83374. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83375. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83376. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83377. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83378. {0,9,255}
  83379. };
  83380. static const code distfix[32] = {
  83381. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83382. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83383. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83384. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83385. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83386. {22,5,193},{64,5,0}
  83387. };
  83388. /*** End of inlined file: inffixed.h ***/
  83389. #endif /* BUILDFIXED */
  83390. state->lencode = lenfix;
  83391. state->lenbits = 9;
  83392. state->distcode = distfix;
  83393. state->distbits = 5;
  83394. }
  83395. #ifdef MAKEFIXED
  83396. #include <stdio.h>
  83397. /*
  83398. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83399. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83400. those tables to stdout, which would be piped to inffixed.h. A small program
  83401. can simply call makefixed to do this:
  83402. void makefixed(void);
  83403. int main(void)
  83404. {
  83405. makefixed();
  83406. return 0;
  83407. }
  83408. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83409. a.out > inffixed.h
  83410. */
  83411. void makefixed()
  83412. {
  83413. unsigned low, size;
  83414. struct inflate_state state;
  83415. fixedtables(&state);
  83416. puts(" /* inffixed.h -- table for decoding fixed codes");
  83417. puts(" * Generated automatically by makefixed().");
  83418. puts(" */");
  83419. puts("");
  83420. puts(" /* WARNING: this file should *not* be used by applications.");
  83421. puts(" It is part of the implementation of this library and is");
  83422. puts(" subject to change. Applications should only use zlib.h.");
  83423. puts(" */");
  83424. puts("");
  83425. size = 1U << 9;
  83426. printf(" static const code lenfix[%u] = {", size);
  83427. low = 0;
  83428. for (;;) {
  83429. if ((low % 7) == 0) printf("\n ");
  83430. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83431. state.lencode[low].val);
  83432. if (++low == size) break;
  83433. putchar(',');
  83434. }
  83435. puts("\n };");
  83436. size = 1U << 5;
  83437. printf("\n static const code distfix[%u] = {", size);
  83438. low = 0;
  83439. for (;;) {
  83440. if ((low % 6) == 0) printf("\n ");
  83441. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83442. state.distcode[low].val);
  83443. if (++low == size) break;
  83444. putchar(',');
  83445. }
  83446. puts("\n };");
  83447. }
  83448. #endif /* MAKEFIXED */
  83449. /*
  83450. Update the window with the last wsize (normally 32K) bytes written before
  83451. returning. If window does not exist yet, create it. This is only called
  83452. when a window is already in use, or when output has been written during this
  83453. inflate call, but the end of the deflate stream has not been reached yet.
  83454. It is also called to create a window for dictionary data when a dictionary
  83455. is loaded.
  83456. Providing output buffers larger than 32K to inflate() should provide a speed
  83457. advantage, since only the last 32K of output is copied to the sliding window
  83458. upon return from inflate(), and since all distances after the first 32K of
  83459. output will fall in the output data, making match copies simpler and faster.
  83460. The advantage may be dependent on the size of the processor's data caches.
  83461. */
  83462. local int updatewindow (z_streamp strm, unsigned out)
  83463. {
  83464. struct inflate_state FAR *state;
  83465. unsigned copy, dist;
  83466. state = (struct inflate_state FAR *)strm->state;
  83467. /* if it hasn't been done already, allocate space for the window */
  83468. if (state->window == Z_NULL) {
  83469. state->window = (unsigned char FAR *)
  83470. ZALLOC(strm, 1U << state->wbits,
  83471. sizeof(unsigned char));
  83472. if (state->window == Z_NULL) return 1;
  83473. }
  83474. /* if window not in use yet, initialize */
  83475. if (state->wsize == 0) {
  83476. state->wsize = 1U << state->wbits;
  83477. state->write = 0;
  83478. state->whave = 0;
  83479. }
  83480. /* copy state->wsize or less output bytes into the circular window */
  83481. copy = out - strm->avail_out;
  83482. if (copy >= state->wsize) {
  83483. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83484. state->write = 0;
  83485. state->whave = state->wsize;
  83486. }
  83487. else {
  83488. dist = state->wsize - state->write;
  83489. if (dist > copy) dist = copy;
  83490. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83491. copy -= dist;
  83492. if (copy) {
  83493. zmemcpy(state->window, strm->next_out - copy, copy);
  83494. state->write = copy;
  83495. state->whave = state->wsize;
  83496. }
  83497. else {
  83498. state->write += dist;
  83499. if (state->write == state->wsize) state->write = 0;
  83500. if (state->whave < state->wsize) state->whave += dist;
  83501. }
  83502. }
  83503. return 0;
  83504. }
  83505. /* Macros for inflate(): */
  83506. /* check function to use adler32() for zlib or crc32() for gzip */
  83507. #ifdef GUNZIP
  83508. # define UPDATE(check, buf, len) \
  83509. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83510. #else
  83511. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83512. #endif
  83513. /* check macros for header crc */
  83514. #ifdef GUNZIP
  83515. # define CRC2(check, word) \
  83516. do { \
  83517. hbuf[0] = (unsigned char)(word); \
  83518. hbuf[1] = (unsigned char)((word) >> 8); \
  83519. check = crc32(check, hbuf, 2); \
  83520. } while (0)
  83521. # define CRC4(check, word) \
  83522. do { \
  83523. hbuf[0] = (unsigned char)(word); \
  83524. hbuf[1] = (unsigned char)((word) >> 8); \
  83525. hbuf[2] = (unsigned char)((word) >> 16); \
  83526. hbuf[3] = (unsigned char)((word) >> 24); \
  83527. check = crc32(check, hbuf, 4); \
  83528. } while (0)
  83529. #endif
  83530. /* Load registers with state in inflate() for speed */
  83531. #define LOAD() \
  83532. do { \
  83533. put = strm->next_out; \
  83534. left = strm->avail_out; \
  83535. next = strm->next_in; \
  83536. have = strm->avail_in; \
  83537. hold = state->hold; \
  83538. bits = state->bits; \
  83539. } while (0)
  83540. /* Restore state from registers in inflate() */
  83541. #define RESTORE() \
  83542. do { \
  83543. strm->next_out = put; \
  83544. strm->avail_out = left; \
  83545. strm->next_in = next; \
  83546. strm->avail_in = have; \
  83547. state->hold = hold; \
  83548. state->bits = bits; \
  83549. } while (0)
  83550. /* Clear the input bit accumulator */
  83551. #define INITBITS() \
  83552. do { \
  83553. hold = 0; \
  83554. bits = 0; \
  83555. } while (0)
  83556. /* Get a byte of input into the bit accumulator, or return from inflate()
  83557. if there is no input available. */
  83558. #define PULLBYTE() \
  83559. do { \
  83560. if (have == 0) goto inf_leave; \
  83561. have--; \
  83562. hold += (unsigned long)(*next++) << bits; \
  83563. bits += 8; \
  83564. } while (0)
  83565. /* Assure that there are at least n bits in the bit accumulator. If there is
  83566. not enough available input to do that, then return from inflate(). */
  83567. #define NEEDBITS(n) \
  83568. do { \
  83569. while (bits < (unsigned)(n)) \
  83570. PULLBYTE(); \
  83571. } while (0)
  83572. /* Return the low n bits of the bit accumulator (n < 16) */
  83573. #define BITS(n) \
  83574. ((unsigned)hold & ((1U << (n)) - 1))
  83575. /* Remove n bits from the bit accumulator */
  83576. #define DROPBITS(n) \
  83577. do { \
  83578. hold >>= (n); \
  83579. bits -= (unsigned)(n); \
  83580. } while (0)
  83581. /* Remove zero to seven bits as needed to go to a byte boundary */
  83582. #define BYTEBITS() \
  83583. do { \
  83584. hold >>= bits & 7; \
  83585. bits -= bits & 7; \
  83586. } while (0)
  83587. /* Reverse the bytes in a 32-bit value */
  83588. #define REVERSE(q) \
  83589. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83590. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83591. /*
  83592. inflate() uses a state machine to process as much input data and generate as
  83593. much output data as possible before returning. The state machine is
  83594. structured roughly as follows:
  83595. for (;;) switch (state) {
  83596. ...
  83597. case STATEn:
  83598. if (not enough input data or output space to make progress)
  83599. return;
  83600. ... make progress ...
  83601. state = STATEm;
  83602. break;
  83603. ...
  83604. }
  83605. so when inflate() is called again, the same case is attempted again, and
  83606. if the appropriate resources are provided, the machine proceeds to the
  83607. next state. The NEEDBITS() macro is usually the way the state evaluates
  83608. whether it can proceed or should return. NEEDBITS() does the return if
  83609. the requested bits are not available. The typical use of the BITS macros
  83610. is:
  83611. NEEDBITS(n);
  83612. ... do something with BITS(n) ...
  83613. DROPBITS(n);
  83614. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83615. input left to load n bits into the accumulator, or it continues. BITS(n)
  83616. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83617. the low n bits off the accumulator. INITBITS() clears the accumulator
  83618. and sets the number of available bits to zero. BYTEBITS() discards just
  83619. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83620. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83621. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83622. if there is no input available. The decoding of variable length codes uses
  83623. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83624. code, and no more.
  83625. Some states loop until they get enough input, making sure that enough
  83626. state information is maintained to continue the loop where it left off
  83627. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83628. would all have to actually be part of the saved state in case NEEDBITS()
  83629. returns:
  83630. case STATEw:
  83631. while (want < need) {
  83632. NEEDBITS(n);
  83633. keep[want++] = BITS(n);
  83634. DROPBITS(n);
  83635. }
  83636. state = STATEx;
  83637. case STATEx:
  83638. As shown above, if the next state is also the next case, then the break
  83639. is omitted.
  83640. A state may also return if there is not enough output space available to
  83641. complete that state. Those states are copying stored data, writing a
  83642. literal byte, and copying a matching string.
  83643. When returning, a "goto inf_leave" is used to update the total counters,
  83644. update the check value, and determine whether any progress has been made
  83645. during that inflate() call in order to return the proper return code.
  83646. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83647. When there is a window, goto inf_leave will update the window with the last
  83648. output written. If a goto inf_leave occurs in the middle of decompression
  83649. and there is no window currently, goto inf_leave will create one and copy
  83650. output to the window for the next call of inflate().
  83651. In this implementation, the flush parameter of inflate() only affects the
  83652. return code (per zlib.h). inflate() always writes as much as possible to
  83653. strm->next_out, given the space available and the provided input--the effect
  83654. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83655. the allocation of and copying into a sliding window until necessary, which
  83656. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83657. stream available. So the only thing the flush parameter actually does is:
  83658. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83659. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83660. */
  83661. int ZEXPORT inflate (z_streamp strm, int flush)
  83662. {
  83663. struct inflate_state FAR *state;
  83664. unsigned char FAR *next; /* next input */
  83665. unsigned char FAR *put; /* next output */
  83666. unsigned have, left; /* available input and output */
  83667. unsigned long hold; /* bit buffer */
  83668. unsigned bits; /* bits in bit buffer */
  83669. unsigned in, out; /* save starting available input and output */
  83670. unsigned copy; /* number of stored or match bytes to copy */
  83671. unsigned char FAR *from; /* where to copy match bytes from */
  83672. code thisx; /* current decoding table entry */
  83673. code last; /* parent table entry */
  83674. unsigned len; /* length to copy for repeats, bits to drop */
  83675. int ret; /* return code */
  83676. #ifdef GUNZIP
  83677. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83678. #endif
  83679. static const unsigned short order[19] = /* permutation of code lengths */
  83680. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83681. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83682. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83683. return Z_STREAM_ERROR;
  83684. state = (struct inflate_state FAR *)strm->state;
  83685. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83686. LOAD();
  83687. in = have;
  83688. out = left;
  83689. ret = Z_OK;
  83690. for (;;)
  83691. switch (state->mode) {
  83692. case HEAD:
  83693. if (state->wrap == 0) {
  83694. state->mode = TYPEDO;
  83695. break;
  83696. }
  83697. NEEDBITS(16);
  83698. #ifdef GUNZIP
  83699. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83700. state->check = crc32(0L, Z_NULL, 0);
  83701. CRC2(state->check, hold);
  83702. INITBITS();
  83703. state->mode = FLAGS;
  83704. break;
  83705. }
  83706. state->flags = 0; /* expect zlib header */
  83707. if (state->head != Z_NULL)
  83708. state->head->done = -1;
  83709. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83710. #else
  83711. if (
  83712. #endif
  83713. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83714. strm->msg = (char *)"incorrect header check";
  83715. state->mode = BAD;
  83716. break;
  83717. }
  83718. if (BITS(4) != Z_DEFLATED) {
  83719. strm->msg = (char *)"unknown compression method";
  83720. state->mode = BAD;
  83721. break;
  83722. }
  83723. DROPBITS(4);
  83724. len = BITS(4) + 8;
  83725. if (len > state->wbits) {
  83726. strm->msg = (char *)"invalid window size";
  83727. state->mode = BAD;
  83728. break;
  83729. }
  83730. state->dmax = 1U << len;
  83731. Tracev((stderr, "inflate: zlib header ok\n"));
  83732. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83733. state->mode = hold & 0x200 ? DICTID : TYPE;
  83734. INITBITS();
  83735. break;
  83736. #ifdef GUNZIP
  83737. case FLAGS:
  83738. NEEDBITS(16);
  83739. state->flags = (int)(hold);
  83740. if ((state->flags & 0xff) != Z_DEFLATED) {
  83741. strm->msg = (char *)"unknown compression method";
  83742. state->mode = BAD;
  83743. break;
  83744. }
  83745. if (state->flags & 0xe000) {
  83746. strm->msg = (char *)"unknown header flags set";
  83747. state->mode = BAD;
  83748. break;
  83749. }
  83750. if (state->head != Z_NULL)
  83751. state->head->text = (int)((hold >> 8) & 1);
  83752. if (state->flags & 0x0200) CRC2(state->check, hold);
  83753. INITBITS();
  83754. state->mode = TIME;
  83755. case TIME:
  83756. NEEDBITS(32);
  83757. if (state->head != Z_NULL)
  83758. state->head->time = hold;
  83759. if (state->flags & 0x0200) CRC4(state->check, hold);
  83760. INITBITS();
  83761. state->mode = OS;
  83762. case OS:
  83763. NEEDBITS(16);
  83764. if (state->head != Z_NULL) {
  83765. state->head->xflags = (int)(hold & 0xff);
  83766. state->head->os = (int)(hold >> 8);
  83767. }
  83768. if (state->flags & 0x0200) CRC2(state->check, hold);
  83769. INITBITS();
  83770. state->mode = EXLEN;
  83771. case EXLEN:
  83772. if (state->flags & 0x0400) {
  83773. NEEDBITS(16);
  83774. state->length = (unsigned)(hold);
  83775. if (state->head != Z_NULL)
  83776. state->head->extra_len = (unsigned)hold;
  83777. if (state->flags & 0x0200) CRC2(state->check, hold);
  83778. INITBITS();
  83779. }
  83780. else if (state->head != Z_NULL)
  83781. state->head->extra = Z_NULL;
  83782. state->mode = EXTRA;
  83783. case EXTRA:
  83784. if (state->flags & 0x0400) {
  83785. copy = state->length;
  83786. if (copy > have) copy = have;
  83787. if (copy) {
  83788. if (state->head != Z_NULL &&
  83789. state->head->extra != Z_NULL) {
  83790. len = state->head->extra_len - state->length;
  83791. zmemcpy(state->head->extra + len, next,
  83792. len + copy > state->head->extra_max ?
  83793. state->head->extra_max - len : copy);
  83794. }
  83795. if (state->flags & 0x0200)
  83796. state->check = crc32(state->check, next, copy);
  83797. have -= copy;
  83798. next += copy;
  83799. state->length -= copy;
  83800. }
  83801. if (state->length) goto inf_leave;
  83802. }
  83803. state->length = 0;
  83804. state->mode = NAME;
  83805. case NAME:
  83806. if (state->flags & 0x0800) {
  83807. if (have == 0) goto inf_leave;
  83808. copy = 0;
  83809. do {
  83810. len = (unsigned)(next[copy++]);
  83811. if (state->head != Z_NULL &&
  83812. state->head->name != Z_NULL &&
  83813. state->length < state->head->name_max)
  83814. state->head->name[state->length++] = len;
  83815. } while (len && copy < have);
  83816. if (state->flags & 0x0200)
  83817. state->check = crc32(state->check, next, copy);
  83818. have -= copy;
  83819. next += copy;
  83820. if (len) goto inf_leave;
  83821. }
  83822. else if (state->head != Z_NULL)
  83823. state->head->name = Z_NULL;
  83824. state->length = 0;
  83825. state->mode = COMMENT;
  83826. case COMMENT:
  83827. if (state->flags & 0x1000) {
  83828. if (have == 0) goto inf_leave;
  83829. copy = 0;
  83830. do {
  83831. len = (unsigned)(next[copy++]);
  83832. if (state->head != Z_NULL &&
  83833. state->head->comment != Z_NULL &&
  83834. state->length < state->head->comm_max)
  83835. state->head->comment[state->length++] = len;
  83836. } while (len && copy < have);
  83837. if (state->flags & 0x0200)
  83838. state->check = crc32(state->check, next, copy);
  83839. have -= copy;
  83840. next += copy;
  83841. if (len) goto inf_leave;
  83842. }
  83843. else if (state->head != Z_NULL)
  83844. state->head->comment = Z_NULL;
  83845. state->mode = HCRC;
  83846. case HCRC:
  83847. if (state->flags & 0x0200) {
  83848. NEEDBITS(16);
  83849. if (hold != (state->check & 0xffff)) {
  83850. strm->msg = (char *)"header crc mismatch";
  83851. state->mode = BAD;
  83852. break;
  83853. }
  83854. INITBITS();
  83855. }
  83856. if (state->head != Z_NULL) {
  83857. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83858. state->head->done = 1;
  83859. }
  83860. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83861. state->mode = TYPE;
  83862. break;
  83863. #endif
  83864. case DICTID:
  83865. NEEDBITS(32);
  83866. strm->adler = state->check = REVERSE(hold);
  83867. INITBITS();
  83868. state->mode = DICT;
  83869. case DICT:
  83870. if (state->havedict == 0) {
  83871. RESTORE();
  83872. return Z_NEED_DICT;
  83873. }
  83874. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83875. state->mode = TYPE;
  83876. case TYPE:
  83877. if (flush == Z_BLOCK) goto inf_leave;
  83878. case TYPEDO:
  83879. if (state->last) {
  83880. BYTEBITS();
  83881. state->mode = CHECK;
  83882. break;
  83883. }
  83884. NEEDBITS(3);
  83885. state->last = BITS(1);
  83886. DROPBITS(1);
  83887. switch (BITS(2)) {
  83888. case 0: /* stored block */
  83889. Tracev((stderr, "inflate: stored block%s\n",
  83890. state->last ? " (last)" : ""));
  83891. state->mode = STORED;
  83892. break;
  83893. case 1: /* fixed block */
  83894. fixedtables(state);
  83895. Tracev((stderr, "inflate: fixed codes block%s\n",
  83896. state->last ? " (last)" : ""));
  83897. state->mode = LEN; /* decode codes */
  83898. break;
  83899. case 2: /* dynamic block */
  83900. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83901. state->last ? " (last)" : ""));
  83902. state->mode = TABLE;
  83903. break;
  83904. case 3:
  83905. strm->msg = (char *)"invalid block type";
  83906. state->mode = BAD;
  83907. }
  83908. DROPBITS(2);
  83909. break;
  83910. case STORED:
  83911. BYTEBITS(); /* go to byte boundary */
  83912. NEEDBITS(32);
  83913. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83914. strm->msg = (char *)"invalid stored block lengths";
  83915. state->mode = BAD;
  83916. break;
  83917. }
  83918. state->length = (unsigned)hold & 0xffff;
  83919. Tracev((stderr, "inflate: stored length %u\n",
  83920. state->length));
  83921. INITBITS();
  83922. state->mode = COPY;
  83923. case COPY:
  83924. copy = state->length;
  83925. if (copy) {
  83926. if (copy > have) copy = have;
  83927. if (copy > left) copy = left;
  83928. if (copy == 0) goto inf_leave;
  83929. zmemcpy(put, next, copy);
  83930. have -= copy;
  83931. next += copy;
  83932. left -= copy;
  83933. put += copy;
  83934. state->length -= copy;
  83935. break;
  83936. }
  83937. Tracev((stderr, "inflate: stored end\n"));
  83938. state->mode = TYPE;
  83939. break;
  83940. case TABLE:
  83941. NEEDBITS(14);
  83942. state->nlen = BITS(5) + 257;
  83943. DROPBITS(5);
  83944. state->ndist = BITS(5) + 1;
  83945. DROPBITS(5);
  83946. state->ncode = BITS(4) + 4;
  83947. DROPBITS(4);
  83948. #ifndef PKZIP_BUG_WORKAROUND
  83949. if (state->nlen > 286 || state->ndist > 30) {
  83950. strm->msg = (char *)"too many length or distance symbols";
  83951. state->mode = BAD;
  83952. break;
  83953. }
  83954. #endif
  83955. Tracev((stderr, "inflate: table sizes ok\n"));
  83956. state->have = 0;
  83957. state->mode = LENLENS;
  83958. case LENLENS:
  83959. while (state->have < state->ncode) {
  83960. NEEDBITS(3);
  83961. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83962. DROPBITS(3);
  83963. }
  83964. while (state->have < 19)
  83965. state->lens[order[state->have++]] = 0;
  83966. state->next = state->codes;
  83967. state->lencode = (code const FAR *)(state->next);
  83968. state->lenbits = 7;
  83969. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83970. &(state->lenbits), state->work);
  83971. if (ret) {
  83972. strm->msg = (char *)"invalid code lengths set";
  83973. state->mode = BAD;
  83974. break;
  83975. }
  83976. Tracev((stderr, "inflate: code lengths ok\n"));
  83977. state->have = 0;
  83978. state->mode = CODELENS;
  83979. case CODELENS:
  83980. while (state->have < state->nlen + state->ndist) {
  83981. for (;;) {
  83982. thisx = state->lencode[BITS(state->lenbits)];
  83983. if ((unsigned)(thisx.bits) <= bits) break;
  83984. PULLBYTE();
  83985. }
  83986. if (thisx.val < 16) {
  83987. NEEDBITS(thisx.bits);
  83988. DROPBITS(thisx.bits);
  83989. state->lens[state->have++] = thisx.val;
  83990. }
  83991. else {
  83992. if (thisx.val == 16) {
  83993. NEEDBITS(thisx.bits + 2);
  83994. DROPBITS(thisx.bits);
  83995. if (state->have == 0) {
  83996. strm->msg = (char *)"invalid bit length repeat";
  83997. state->mode = BAD;
  83998. break;
  83999. }
  84000. len = state->lens[state->have - 1];
  84001. copy = 3 + BITS(2);
  84002. DROPBITS(2);
  84003. }
  84004. else if (thisx.val == 17) {
  84005. NEEDBITS(thisx.bits + 3);
  84006. DROPBITS(thisx.bits);
  84007. len = 0;
  84008. copy = 3 + BITS(3);
  84009. DROPBITS(3);
  84010. }
  84011. else {
  84012. NEEDBITS(thisx.bits + 7);
  84013. DROPBITS(thisx.bits);
  84014. len = 0;
  84015. copy = 11 + BITS(7);
  84016. DROPBITS(7);
  84017. }
  84018. if (state->have + copy > state->nlen + state->ndist) {
  84019. strm->msg = (char *)"invalid bit length repeat";
  84020. state->mode = BAD;
  84021. break;
  84022. }
  84023. while (copy--)
  84024. state->lens[state->have++] = (unsigned short)len;
  84025. }
  84026. }
  84027. /* handle error breaks in while */
  84028. if (state->mode == BAD) break;
  84029. /* build code tables */
  84030. state->next = state->codes;
  84031. state->lencode = (code const FAR *)(state->next);
  84032. state->lenbits = 9;
  84033. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84034. &(state->lenbits), state->work);
  84035. if (ret) {
  84036. strm->msg = (char *)"invalid literal/lengths set";
  84037. state->mode = BAD;
  84038. break;
  84039. }
  84040. state->distcode = (code const FAR *)(state->next);
  84041. state->distbits = 6;
  84042. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84043. &(state->next), &(state->distbits), state->work);
  84044. if (ret) {
  84045. strm->msg = (char *)"invalid distances set";
  84046. state->mode = BAD;
  84047. break;
  84048. }
  84049. Tracev((stderr, "inflate: codes ok\n"));
  84050. state->mode = LEN;
  84051. case LEN:
  84052. if (have >= 6 && left >= 258) {
  84053. RESTORE();
  84054. inflate_fast(strm, out);
  84055. LOAD();
  84056. break;
  84057. }
  84058. for (;;) {
  84059. thisx = state->lencode[BITS(state->lenbits)];
  84060. if ((unsigned)(thisx.bits) <= bits) break;
  84061. PULLBYTE();
  84062. }
  84063. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84064. last = thisx;
  84065. for (;;) {
  84066. thisx = state->lencode[last.val +
  84067. (BITS(last.bits + last.op) >> last.bits)];
  84068. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84069. PULLBYTE();
  84070. }
  84071. DROPBITS(last.bits);
  84072. }
  84073. DROPBITS(thisx.bits);
  84074. state->length = (unsigned)thisx.val;
  84075. if ((int)(thisx.op) == 0) {
  84076. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84077. "inflate: literal '%c'\n" :
  84078. "inflate: literal 0x%02x\n", thisx.val));
  84079. state->mode = LIT;
  84080. break;
  84081. }
  84082. if (thisx.op & 32) {
  84083. Tracevv((stderr, "inflate: end of block\n"));
  84084. state->mode = TYPE;
  84085. break;
  84086. }
  84087. if (thisx.op & 64) {
  84088. strm->msg = (char *)"invalid literal/length code";
  84089. state->mode = BAD;
  84090. break;
  84091. }
  84092. state->extra = (unsigned)(thisx.op) & 15;
  84093. state->mode = LENEXT;
  84094. case LENEXT:
  84095. if (state->extra) {
  84096. NEEDBITS(state->extra);
  84097. state->length += BITS(state->extra);
  84098. DROPBITS(state->extra);
  84099. }
  84100. Tracevv((stderr, "inflate: length %u\n", state->length));
  84101. state->mode = DIST;
  84102. case DIST:
  84103. for (;;) {
  84104. thisx = state->distcode[BITS(state->distbits)];
  84105. if ((unsigned)(thisx.bits) <= bits) break;
  84106. PULLBYTE();
  84107. }
  84108. if ((thisx.op & 0xf0) == 0) {
  84109. last = thisx;
  84110. for (;;) {
  84111. thisx = state->distcode[last.val +
  84112. (BITS(last.bits + last.op) >> last.bits)];
  84113. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84114. PULLBYTE();
  84115. }
  84116. DROPBITS(last.bits);
  84117. }
  84118. DROPBITS(thisx.bits);
  84119. if (thisx.op & 64) {
  84120. strm->msg = (char *)"invalid distance code";
  84121. state->mode = BAD;
  84122. break;
  84123. }
  84124. state->offset = (unsigned)thisx.val;
  84125. state->extra = (unsigned)(thisx.op) & 15;
  84126. state->mode = DISTEXT;
  84127. case DISTEXT:
  84128. if (state->extra) {
  84129. NEEDBITS(state->extra);
  84130. state->offset += BITS(state->extra);
  84131. DROPBITS(state->extra);
  84132. }
  84133. #ifdef INFLATE_STRICT
  84134. if (state->offset > state->dmax) {
  84135. strm->msg = (char *)"invalid distance too far back";
  84136. state->mode = BAD;
  84137. break;
  84138. }
  84139. #endif
  84140. if (state->offset > state->whave + out - left) {
  84141. strm->msg = (char *)"invalid distance too far back";
  84142. state->mode = BAD;
  84143. break;
  84144. }
  84145. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84146. state->mode = MATCH;
  84147. case MATCH:
  84148. if (left == 0) goto inf_leave;
  84149. copy = out - left;
  84150. if (state->offset > copy) { /* copy from window */
  84151. copy = state->offset - copy;
  84152. if (copy > state->write) {
  84153. copy -= state->write;
  84154. from = state->window + (state->wsize - copy);
  84155. }
  84156. else
  84157. from = state->window + (state->write - copy);
  84158. if (copy > state->length) copy = state->length;
  84159. }
  84160. else { /* copy from output */
  84161. from = put - state->offset;
  84162. copy = state->length;
  84163. }
  84164. if (copy > left) copy = left;
  84165. left -= copy;
  84166. state->length -= copy;
  84167. do {
  84168. *put++ = *from++;
  84169. } while (--copy);
  84170. if (state->length == 0) state->mode = LEN;
  84171. break;
  84172. case LIT:
  84173. if (left == 0) goto inf_leave;
  84174. *put++ = (unsigned char)(state->length);
  84175. left--;
  84176. state->mode = LEN;
  84177. break;
  84178. case CHECK:
  84179. if (state->wrap) {
  84180. NEEDBITS(32);
  84181. out -= left;
  84182. strm->total_out += out;
  84183. state->total += out;
  84184. if (out)
  84185. strm->adler = state->check =
  84186. UPDATE(state->check, put - out, out);
  84187. out = left;
  84188. if ((
  84189. #ifdef GUNZIP
  84190. state->flags ? hold :
  84191. #endif
  84192. REVERSE(hold)) != state->check) {
  84193. strm->msg = (char *)"incorrect data check";
  84194. state->mode = BAD;
  84195. break;
  84196. }
  84197. INITBITS();
  84198. Tracev((stderr, "inflate: check matches trailer\n"));
  84199. }
  84200. #ifdef GUNZIP
  84201. state->mode = LENGTH;
  84202. case LENGTH:
  84203. if (state->wrap && state->flags) {
  84204. NEEDBITS(32);
  84205. if (hold != (state->total & 0xffffffffUL)) {
  84206. strm->msg = (char *)"incorrect length check";
  84207. state->mode = BAD;
  84208. break;
  84209. }
  84210. INITBITS();
  84211. Tracev((stderr, "inflate: length matches trailer\n"));
  84212. }
  84213. #endif
  84214. state->mode = DONE;
  84215. case DONE:
  84216. ret = Z_STREAM_END;
  84217. goto inf_leave;
  84218. case BAD:
  84219. ret = Z_DATA_ERROR;
  84220. goto inf_leave;
  84221. case MEM:
  84222. return Z_MEM_ERROR;
  84223. case SYNC:
  84224. default:
  84225. return Z_STREAM_ERROR;
  84226. }
  84227. /*
  84228. Return from inflate(), updating the total counts and the check value.
  84229. If there was no progress during the inflate() call, return a buffer
  84230. error. Call updatewindow() to create and/or update the window state.
  84231. Note: a memory error from inflate() is non-recoverable.
  84232. */
  84233. inf_leave:
  84234. RESTORE();
  84235. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84236. if (updatewindow(strm, out)) {
  84237. state->mode = MEM;
  84238. return Z_MEM_ERROR;
  84239. }
  84240. in -= strm->avail_in;
  84241. out -= strm->avail_out;
  84242. strm->total_in += in;
  84243. strm->total_out += out;
  84244. state->total += out;
  84245. if (state->wrap && out)
  84246. strm->adler = state->check =
  84247. UPDATE(state->check, strm->next_out - out, out);
  84248. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84249. (state->mode == TYPE ? 128 : 0);
  84250. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84251. ret = Z_BUF_ERROR;
  84252. return ret;
  84253. }
  84254. int ZEXPORT inflateEnd (z_streamp strm)
  84255. {
  84256. struct inflate_state FAR *state;
  84257. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84258. return Z_STREAM_ERROR;
  84259. state = (struct inflate_state FAR *)strm->state;
  84260. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84261. ZFREE(strm, strm->state);
  84262. strm->state = Z_NULL;
  84263. Tracev((stderr, "inflate: end\n"));
  84264. return Z_OK;
  84265. }
  84266. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84267. {
  84268. struct inflate_state FAR *state;
  84269. unsigned long id_;
  84270. /* check state */
  84271. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84272. state = (struct inflate_state FAR *)strm->state;
  84273. if (state->wrap != 0 && state->mode != DICT)
  84274. return Z_STREAM_ERROR;
  84275. /* check for correct dictionary id */
  84276. if (state->mode == DICT) {
  84277. id_ = adler32(0L, Z_NULL, 0);
  84278. id_ = adler32(id_, dictionary, dictLength);
  84279. if (id_ != state->check)
  84280. return Z_DATA_ERROR;
  84281. }
  84282. /* copy dictionary to window */
  84283. if (updatewindow(strm, strm->avail_out)) {
  84284. state->mode = MEM;
  84285. return Z_MEM_ERROR;
  84286. }
  84287. if (dictLength > state->wsize) {
  84288. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84289. state->wsize);
  84290. state->whave = state->wsize;
  84291. }
  84292. else {
  84293. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84294. dictLength);
  84295. state->whave = dictLength;
  84296. }
  84297. state->havedict = 1;
  84298. Tracev((stderr, "inflate: dictionary set\n"));
  84299. return Z_OK;
  84300. }
  84301. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84302. {
  84303. struct inflate_state FAR *state;
  84304. /* check state */
  84305. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84306. state = (struct inflate_state FAR *)strm->state;
  84307. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84308. /* save header structure */
  84309. state->head = head;
  84310. head->done = 0;
  84311. return Z_OK;
  84312. }
  84313. /*
  84314. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84315. or when out of input. When called, *have is the number of pattern bytes
  84316. found in order so far, in 0..3. On return *have is updated to the new
  84317. state. If on return *have equals four, then the pattern was found and the
  84318. return value is how many bytes were read including the last byte of the
  84319. pattern. If *have is less than four, then the pattern has not been found
  84320. yet and the return value is len. In the latter case, syncsearch() can be
  84321. called again with more data and the *have state. *have is initialized to
  84322. zero for the first call.
  84323. */
  84324. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84325. {
  84326. unsigned got;
  84327. unsigned next;
  84328. got = *have;
  84329. next = 0;
  84330. while (next < len && got < 4) {
  84331. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84332. got++;
  84333. else if (buf[next])
  84334. got = 0;
  84335. else
  84336. got = 4 - got;
  84337. next++;
  84338. }
  84339. *have = got;
  84340. return next;
  84341. }
  84342. int ZEXPORT inflateSync (z_streamp strm)
  84343. {
  84344. unsigned len; /* number of bytes to look at or looked at */
  84345. unsigned long in, out; /* temporary to save total_in and total_out */
  84346. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84347. struct inflate_state FAR *state;
  84348. /* check parameters */
  84349. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84350. state = (struct inflate_state FAR *)strm->state;
  84351. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84352. /* if first time, start search in bit buffer */
  84353. if (state->mode != SYNC) {
  84354. state->mode = SYNC;
  84355. state->hold <<= state->bits & 7;
  84356. state->bits -= state->bits & 7;
  84357. len = 0;
  84358. while (state->bits >= 8) {
  84359. buf[len++] = (unsigned char)(state->hold);
  84360. state->hold >>= 8;
  84361. state->bits -= 8;
  84362. }
  84363. state->have = 0;
  84364. syncsearch(&(state->have), buf, len);
  84365. }
  84366. /* search available input */
  84367. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84368. strm->avail_in -= len;
  84369. strm->next_in += len;
  84370. strm->total_in += len;
  84371. /* return no joy or set up to restart inflate() on a new block */
  84372. if (state->have != 4) return Z_DATA_ERROR;
  84373. in = strm->total_in; out = strm->total_out;
  84374. inflateReset(strm);
  84375. strm->total_in = in; strm->total_out = out;
  84376. state->mode = TYPE;
  84377. return Z_OK;
  84378. }
  84379. /*
  84380. Returns true if inflate is currently at the end of a block generated by
  84381. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84382. implementation to provide an additional safety check. PPP uses
  84383. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84384. block. When decompressing, PPP checks that at the end of input packet,
  84385. inflate is waiting for these length bytes.
  84386. */
  84387. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84388. {
  84389. struct inflate_state FAR *state;
  84390. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84391. state = (struct inflate_state FAR *)strm->state;
  84392. return state->mode == STORED && state->bits == 0;
  84393. }
  84394. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84395. {
  84396. struct inflate_state FAR *state;
  84397. struct inflate_state FAR *copy;
  84398. unsigned char FAR *window;
  84399. unsigned wsize;
  84400. /* check input */
  84401. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84402. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84403. return Z_STREAM_ERROR;
  84404. state = (struct inflate_state FAR *)source->state;
  84405. /* allocate space */
  84406. copy = (struct inflate_state FAR *)
  84407. ZALLOC(source, 1, sizeof(struct inflate_state));
  84408. if (copy == Z_NULL) return Z_MEM_ERROR;
  84409. window = Z_NULL;
  84410. if (state->window != Z_NULL) {
  84411. window = (unsigned char FAR *)
  84412. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84413. if (window == Z_NULL) {
  84414. ZFREE(source, copy);
  84415. return Z_MEM_ERROR;
  84416. }
  84417. }
  84418. /* copy state */
  84419. zmemcpy(dest, source, sizeof(z_stream));
  84420. zmemcpy(copy, state, sizeof(struct inflate_state));
  84421. if (state->lencode >= state->codes &&
  84422. state->lencode <= state->codes + ENOUGH - 1) {
  84423. copy->lencode = copy->codes + (state->lencode - state->codes);
  84424. copy->distcode = copy->codes + (state->distcode - state->codes);
  84425. }
  84426. copy->next = copy->codes + (state->next - state->codes);
  84427. if (window != Z_NULL) {
  84428. wsize = 1U << state->wbits;
  84429. zmemcpy(window, state->window, wsize);
  84430. }
  84431. copy->window = window;
  84432. dest->state = (struct internal_state FAR *)copy;
  84433. return Z_OK;
  84434. }
  84435. /*** End of inlined file: inflate.c ***/
  84436. /*** Start of inlined file: inftrees.c ***/
  84437. #define MAXBITS 15
  84438. const char inflate_copyright[] =
  84439. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84440. /*
  84441. If you use the zlib library in a product, an acknowledgment is welcome
  84442. in the documentation of your product. If for some reason you cannot
  84443. include such an acknowledgment, I would appreciate that you keep this
  84444. copyright string in the executable of your product.
  84445. */
  84446. /*
  84447. Build a set of tables to decode the provided canonical Huffman code.
  84448. The code lengths are lens[0..codes-1]. The result starts at *table,
  84449. whose indices are 0..2^bits-1. work is a writable array of at least
  84450. lens shorts, which is used as a work area. type is the type of code
  84451. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84452. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84453. on return points to the next available entry's address. bits is the
  84454. requested root table index bits, and on return it is the actual root
  84455. table index bits. It will differ if the request is greater than the
  84456. longest code or if it is less than the shortest code.
  84457. */
  84458. int inflate_table (codetype type,
  84459. unsigned short FAR *lens,
  84460. unsigned codes,
  84461. code FAR * FAR *table,
  84462. unsigned FAR *bits,
  84463. unsigned short FAR *work)
  84464. {
  84465. unsigned len; /* a code's length in bits */
  84466. unsigned sym; /* index of code symbols */
  84467. unsigned min, max; /* minimum and maximum code lengths */
  84468. unsigned root; /* number of index bits for root table */
  84469. unsigned curr; /* number of index bits for current table */
  84470. unsigned drop; /* code bits to drop for sub-table */
  84471. int left; /* number of prefix codes available */
  84472. unsigned used; /* code entries in table used */
  84473. unsigned huff; /* Huffman code */
  84474. unsigned incr; /* for incrementing code, index */
  84475. unsigned fill; /* index for replicating entries */
  84476. unsigned low; /* low bits for current root entry */
  84477. unsigned mask; /* mask for low root bits */
  84478. code thisx; /* table entry for duplication */
  84479. code FAR *next; /* next available space in table */
  84480. const unsigned short FAR *base; /* base value table to use */
  84481. const unsigned short FAR *extra; /* extra bits table to use */
  84482. int end; /* use base and extra for symbol > end */
  84483. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84484. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84485. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84486. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84487. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84488. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84489. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84490. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84491. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84492. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84493. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84494. 8193, 12289, 16385, 24577, 0, 0};
  84495. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84496. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84497. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84498. 28, 28, 29, 29, 64, 64};
  84499. /*
  84500. Process a set of code lengths to create a canonical Huffman code. The
  84501. code lengths are lens[0..codes-1]. Each length corresponds to the
  84502. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84503. symbols by length from short to long, and retaining the symbol order
  84504. for codes with equal lengths. Then the code starts with all zero bits
  84505. for the first code of the shortest length, and the codes are integer
  84506. increments for the same length, and zeros are appended as the length
  84507. increases. For the deflate format, these bits are stored backwards
  84508. from their more natural integer increment ordering, and so when the
  84509. decoding tables are built in the large loop below, the integer codes
  84510. are incremented backwards.
  84511. This routine assumes, but does not check, that all of the entries in
  84512. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84513. 1..MAXBITS is interpreted as that code length. zero means that that
  84514. symbol does not occur in this code.
  84515. The codes are sorted by computing a count of codes for each length,
  84516. creating from that a table of starting indices for each length in the
  84517. sorted table, and then entering the symbols in order in the sorted
  84518. table. The sorted table is work[], with that space being provided by
  84519. the caller.
  84520. The length counts are used for other purposes as well, i.e. finding
  84521. the minimum and maximum length codes, determining if there are any
  84522. codes at all, checking for a valid set of lengths, and looking ahead
  84523. at length counts to determine sub-table sizes when building the
  84524. decoding tables.
  84525. */
  84526. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84527. for (len = 0; len <= MAXBITS; len++)
  84528. count[len] = 0;
  84529. for (sym = 0; sym < codes; sym++)
  84530. count[lens[sym]]++;
  84531. /* bound code lengths, force root to be within code lengths */
  84532. root = *bits;
  84533. for (max = MAXBITS; max >= 1; max--)
  84534. if (count[max] != 0) break;
  84535. if (root > max) root = max;
  84536. if (max == 0) { /* no symbols to code at all */
  84537. thisx.op = (unsigned char)64; /* invalid code marker */
  84538. thisx.bits = (unsigned char)1;
  84539. thisx.val = (unsigned short)0;
  84540. *(*table)++ = thisx; /* make a table to force an error */
  84541. *(*table)++ = thisx;
  84542. *bits = 1;
  84543. return 0; /* no symbols, but wait for decoding to report error */
  84544. }
  84545. for (min = 1; min <= MAXBITS; min++)
  84546. if (count[min] != 0) break;
  84547. if (root < min) root = min;
  84548. /* check for an over-subscribed or incomplete set of lengths */
  84549. left = 1;
  84550. for (len = 1; len <= MAXBITS; len++) {
  84551. left <<= 1;
  84552. left -= count[len];
  84553. if (left < 0) return -1; /* over-subscribed */
  84554. }
  84555. if (left > 0 && (type == CODES || max != 1))
  84556. return -1; /* incomplete set */
  84557. /* generate offsets into symbol table for each length for sorting */
  84558. offs[1] = 0;
  84559. for (len = 1; len < MAXBITS; len++)
  84560. offs[len + 1] = offs[len] + count[len];
  84561. /* sort symbols by length, by symbol order within each length */
  84562. for (sym = 0; sym < codes; sym++)
  84563. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84564. /*
  84565. Create and fill in decoding tables. In this loop, the table being
  84566. filled is at next and has curr index bits. The code being used is huff
  84567. with length len. That code is converted to an index by dropping drop
  84568. bits off of the bottom. For codes where len is less than drop + curr,
  84569. those top drop + curr - len bits are incremented through all values to
  84570. fill the table with replicated entries.
  84571. root is the number of index bits for the root table. When len exceeds
  84572. root, sub-tables are created pointed to by the root entry with an index
  84573. of the low root bits of huff. This is saved in low to check for when a
  84574. new sub-table should be started. drop is zero when the root table is
  84575. being filled, and drop is root when sub-tables are being filled.
  84576. When a new sub-table is needed, it is necessary to look ahead in the
  84577. code lengths to determine what size sub-table is needed. The length
  84578. counts are used for this, and so count[] is decremented as codes are
  84579. entered in the tables.
  84580. used keeps track of how many table entries have been allocated from the
  84581. provided *table space. It is checked when a LENS table is being made
  84582. against the space in *table, ENOUGH, minus the maximum space needed by
  84583. the worst case distance code, MAXD. This should never happen, but the
  84584. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84585. This assumes that when type == LENS, bits == 9.
  84586. sym increments through all symbols, and the loop terminates when
  84587. all codes of length max, i.e. all codes, have been processed. This
  84588. routine permits incomplete codes, so another loop after this one fills
  84589. in the rest of the decoding tables with invalid code markers.
  84590. */
  84591. /* set up for code type */
  84592. switch (type) {
  84593. case CODES:
  84594. base = extra = work; /* dummy value--not used */
  84595. end = 19;
  84596. break;
  84597. case LENS:
  84598. base = lbase;
  84599. base -= 257;
  84600. extra = lext;
  84601. extra -= 257;
  84602. end = 256;
  84603. break;
  84604. default: /* DISTS */
  84605. base = dbase;
  84606. extra = dext;
  84607. end = -1;
  84608. }
  84609. /* initialize state for loop */
  84610. huff = 0; /* starting code */
  84611. sym = 0; /* starting code symbol */
  84612. len = min; /* starting code length */
  84613. next = *table; /* current table to fill in */
  84614. curr = root; /* current table index bits */
  84615. drop = 0; /* current bits to drop from code for index */
  84616. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84617. used = 1U << root; /* use root table entries */
  84618. mask = used - 1; /* mask for comparing low */
  84619. /* check available table space */
  84620. if (type == LENS && used >= ENOUGH - MAXD)
  84621. return 1;
  84622. /* process all codes and make table entries */
  84623. for (;;) {
  84624. /* create table entry */
  84625. thisx.bits = (unsigned char)(len - drop);
  84626. if ((int)(work[sym]) < end) {
  84627. thisx.op = (unsigned char)0;
  84628. thisx.val = work[sym];
  84629. }
  84630. else if ((int)(work[sym]) > end) {
  84631. thisx.op = (unsigned char)(extra[work[sym]]);
  84632. thisx.val = base[work[sym]];
  84633. }
  84634. else {
  84635. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84636. thisx.val = 0;
  84637. }
  84638. /* replicate for those indices with low len bits equal to huff */
  84639. incr = 1U << (len - drop);
  84640. fill = 1U << curr;
  84641. min = fill; /* save offset to next table */
  84642. do {
  84643. fill -= incr;
  84644. next[(huff >> drop) + fill] = thisx;
  84645. } while (fill != 0);
  84646. /* backwards increment the len-bit code huff */
  84647. incr = 1U << (len - 1);
  84648. while (huff & incr)
  84649. incr >>= 1;
  84650. if (incr != 0) {
  84651. huff &= incr - 1;
  84652. huff += incr;
  84653. }
  84654. else
  84655. huff = 0;
  84656. /* go to next symbol, update count, len */
  84657. sym++;
  84658. if (--(count[len]) == 0) {
  84659. if (len == max) break;
  84660. len = lens[work[sym]];
  84661. }
  84662. /* create new sub-table if needed */
  84663. if (len > root && (huff & mask) != low) {
  84664. /* if first time, transition to sub-tables */
  84665. if (drop == 0)
  84666. drop = root;
  84667. /* increment past last table */
  84668. next += min; /* here min is 1 << curr */
  84669. /* determine length of next table */
  84670. curr = len - drop;
  84671. left = (int)(1 << curr);
  84672. while (curr + drop < max) {
  84673. left -= count[curr + drop];
  84674. if (left <= 0) break;
  84675. curr++;
  84676. left <<= 1;
  84677. }
  84678. /* check for enough space */
  84679. used += 1U << curr;
  84680. if (type == LENS && used >= ENOUGH - MAXD)
  84681. return 1;
  84682. /* point entry in root table to sub-table */
  84683. low = huff & mask;
  84684. (*table)[low].op = (unsigned char)curr;
  84685. (*table)[low].bits = (unsigned char)root;
  84686. (*table)[low].val = (unsigned short)(next - *table);
  84687. }
  84688. }
  84689. /*
  84690. Fill in rest of table for incomplete codes. This loop is similar to the
  84691. loop above in incrementing huff for table indices. It is assumed that
  84692. len is equal to curr + drop, so there is no loop needed to increment
  84693. through high index bits. When the current sub-table is filled, the loop
  84694. drops back to the root table to fill in any remaining entries there.
  84695. */
  84696. thisx.op = (unsigned char)64; /* invalid code marker */
  84697. thisx.bits = (unsigned char)(len - drop);
  84698. thisx.val = (unsigned short)0;
  84699. while (huff != 0) {
  84700. /* when done with sub-table, drop back to root table */
  84701. if (drop != 0 && (huff & mask) != low) {
  84702. drop = 0;
  84703. len = root;
  84704. next = *table;
  84705. thisx.bits = (unsigned char)len;
  84706. }
  84707. /* put invalid code marker in table */
  84708. next[huff >> drop] = thisx;
  84709. /* backwards increment the len-bit code huff */
  84710. incr = 1U << (len - 1);
  84711. while (huff & incr)
  84712. incr >>= 1;
  84713. if (incr != 0) {
  84714. huff &= incr - 1;
  84715. huff += incr;
  84716. }
  84717. else
  84718. huff = 0;
  84719. }
  84720. /* set return parameters */
  84721. *table += used;
  84722. *bits = root;
  84723. return 0;
  84724. }
  84725. /*** End of inlined file: inftrees.c ***/
  84726. /*** Start of inlined file: trees.c ***/
  84727. /*
  84728. * ALGORITHM
  84729. *
  84730. * The "deflation" process uses several Huffman trees. The more
  84731. * common source values are represented by shorter bit sequences.
  84732. *
  84733. * Each code tree is stored in a compressed form which is itself
  84734. * a Huffman encoding of the lengths of all the code strings (in
  84735. * ascending order by source values). The actual code strings are
  84736. * reconstructed from the lengths in the inflate process, as described
  84737. * in the deflate specification.
  84738. *
  84739. * REFERENCES
  84740. *
  84741. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84742. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84743. *
  84744. * Storer, James A.
  84745. * Data Compression: Methods and Theory, pp. 49-50.
  84746. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84747. *
  84748. * Sedgewick, R.
  84749. * Algorithms, p290.
  84750. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84751. */
  84752. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84753. /* #define GEN_TREES_H */
  84754. #ifdef DEBUG
  84755. # include <ctype.h>
  84756. #endif
  84757. /* ===========================================================================
  84758. * Constants
  84759. */
  84760. #define MAX_BL_BITS 7
  84761. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84762. #define END_BLOCK 256
  84763. /* end of block literal code */
  84764. #define REP_3_6 16
  84765. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84766. #define REPZ_3_10 17
  84767. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84768. #define REPZ_11_138 18
  84769. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84770. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84771. = {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};
  84772. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84773. = {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};
  84774. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84775. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84776. local const uch bl_order[BL_CODES]
  84777. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84778. /* The lengths of the bit length codes are sent in order of decreasing
  84779. * probability, to avoid transmitting the lengths for unused bit length codes.
  84780. */
  84781. #define Buf_size (8 * 2*sizeof(char))
  84782. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84783. * more than 16 bits on some systems.)
  84784. */
  84785. /* ===========================================================================
  84786. * Local data. These are initialized only once.
  84787. */
  84788. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84789. #if defined(GEN_TREES_H) || !defined(STDC)
  84790. /* non ANSI compilers may not accept trees.h */
  84791. local ct_data static_ltree[L_CODES+2];
  84792. /* The static literal tree. Since the bit lengths are imposed, there is no
  84793. * need for the L_CODES extra codes used during heap construction. However
  84794. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84795. * below).
  84796. */
  84797. local ct_data static_dtree[D_CODES];
  84798. /* The static distance tree. (Actually a trivial tree since all codes use
  84799. * 5 bits.)
  84800. */
  84801. uch _dist_code[DIST_CODE_LEN];
  84802. /* Distance codes. The first 256 values correspond to the distances
  84803. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84804. * the 15 bit distances.
  84805. */
  84806. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84807. /* length code for each normalized match length (0 == MIN_MATCH) */
  84808. local int base_length[LENGTH_CODES];
  84809. /* First normalized length for each code (0 = MIN_MATCH) */
  84810. local int base_dist[D_CODES];
  84811. /* First normalized distance for each code (0 = distance of 1) */
  84812. #else
  84813. /*** Start of inlined file: trees.h ***/
  84814. local const ct_data static_ltree[L_CODES+2] = {
  84815. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84816. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84817. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84818. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84819. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84820. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84821. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84822. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84823. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84824. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84825. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84826. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84827. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84828. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84829. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84830. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84831. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84832. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84833. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84834. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84835. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84836. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84837. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84838. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84839. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84840. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84841. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84842. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84843. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84844. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84845. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84846. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84847. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84848. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84849. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84850. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84851. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84852. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84853. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84854. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84855. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84856. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84857. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84858. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84859. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84860. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84861. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84862. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84863. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84864. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84865. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84866. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84867. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84868. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84869. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84870. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84871. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84872. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84873. };
  84874. local const ct_data static_dtree[D_CODES] = {
  84875. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84876. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84877. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84878. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84879. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84880. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84881. };
  84882. const uch _dist_code[DIST_CODE_LEN] = {
  84883. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84884. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84885. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84886. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84887. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84888. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84889. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84890. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84891. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84892. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84893. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84894. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84895. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84896. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84897. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84898. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84899. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84900. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84901. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84902. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84903. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84904. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84905. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84906. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84907. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84908. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84909. };
  84910. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84911. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84912. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84913. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84914. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84915. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84916. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84917. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84918. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84919. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84920. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84921. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84922. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84923. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84924. };
  84925. local const int base_length[LENGTH_CODES] = {
  84926. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84927. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84928. };
  84929. local const int base_dist[D_CODES] = {
  84930. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84931. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84932. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84933. };
  84934. /*** End of inlined file: trees.h ***/
  84935. #endif /* GEN_TREES_H */
  84936. struct static_tree_desc_s {
  84937. const ct_data *static_tree; /* static tree or NULL */
  84938. const intf *extra_bits; /* extra bits for each code or NULL */
  84939. int extra_base; /* base index for extra_bits */
  84940. int elems; /* max number of elements in the tree */
  84941. int max_length; /* max bit length for the codes */
  84942. };
  84943. local static_tree_desc static_l_desc =
  84944. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84945. local static_tree_desc static_d_desc =
  84946. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84947. local static_tree_desc static_bl_desc =
  84948. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84949. /* ===========================================================================
  84950. * Local (static) routines in this file.
  84951. */
  84952. local void tr_static_init OF((void));
  84953. local void init_block OF((deflate_state *s));
  84954. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84955. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84956. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84957. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84958. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84959. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84960. local int build_bl_tree OF((deflate_state *s));
  84961. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84962. int blcodes));
  84963. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84964. ct_data *dtree));
  84965. local void set_data_type OF((deflate_state *s));
  84966. local unsigned bi_reverse OF((unsigned value, int length));
  84967. local void bi_windup OF((deflate_state *s));
  84968. local void bi_flush OF((deflate_state *s));
  84969. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84970. int header));
  84971. #ifdef GEN_TREES_H
  84972. local void gen_trees_header OF((void));
  84973. #endif
  84974. #ifndef DEBUG
  84975. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84976. /* Send a code of the given tree. c and tree must not have side effects */
  84977. #else /* DEBUG */
  84978. # define send_code(s, c, tree) \
  84979. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84980. send_bits(s, tree[c].Code, tree[c].Len); }
  84981. #endif
  84982. /* ===========================================================================
  84983. * Output a short LSB first on the stream.
  84984. * IN assertion: there is enough room in pendingBuf.
  84985. */
  84986. #define put_short(s, w) { \
  84987. put_byte(s, (uch)((w) & 0xff)); \
  84988. put_byte(s, (uch)((ush)(w) >> 8)); \
  84989. }
  84990. /* ===========================================================================
  84991. * Send a value on a given number of bits.
  84992. * IN assertion: length <= 16 and value fits in length bits.
  84993. */
  84994. #ifdef DEBUG
  84995. local void send_bits OF((deflate_state *s, int value, int length));
  84996. local void send_bits (deflate_state *s, int value, int length)
  84997. {
  84998. Tracevv((stderr," l %2d v %4x ", length, value));
  84999. Assert(length > 0 && length <= 15, "invalid length");
  85000. s->bits_sent += (ulg)length;
  85001. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85002. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85003. * unused bits in value.
  85004. */
  85005. if (s->bi_valid > (int)Buf_size - length) {
  85006. s->bi_buf |= (value << s->bi_valid);
  85007. put_short(s, s->bi_buf);
  85008. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85009. s->bi_valid += length - Buf_size;
  85010. } else {
  85011. s->bi_buf |= value << s->bi_valid;
  85012. s->bi_valid += length;
  85013. }
  85014. }
  85015. #else /* !DEBUG */
  85016. #define send_bits(s, value, length) \
  85017. { int len = length;\
  85018. if (s->bi_valid > (int)Buf_size - len) {\
  85019. int val = value;\
  85020. s->bi_buf |= (val << s->bi_valid);\
  85021. put_short(s, s->bi_buf);\
  85022. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85023. s->bi_valid += len - Buf_size;\
  85024. } else {\
  85025. s->bi_buf |= (value) << s->bi_valid;\
  85026. s->bi_valid += len;\
  85027. }\
  85028. }
  85029. #endif /* DEBUG */
  85030. /* the arguments must not have side effects */
  85031. /* ===========================================================================
  85032. * Initialize the various 'constant' tables.
  85033. */
  85034. local void tr_static_init()
  85035. {
  85036. #if defined(GEN_TREES_H) || !defined(STDC)
  85037. static int static_init_done = 0;
  85038. int n; /* iterates over tree elements */
  85039. int bits; /* bit counter */
  85040. int length; /* length value */
  85041. int code; /* code value */
  85042. int dist; /* distance index */
  85043. ush bl_count[MAX_BITS+1];
  85044. /* number of codes at each bit length for an optimal tree */
  85045. if (static_init_done) return;
  85046. /* For some embedded targets, global variables are not initialized: */
  85047. static_l_desc.static_tree = static_ltree;
  85048. static_l_desc.extra_bits = extra_lbits;
  85049. static_d_desc.static_tree = static_dtree;
  85050. static_d_desc.extra_bits = extra_dbits;
  85051. static_bl_desc.extra_bits = extra_blbits;
  85052. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85053. length = 0;
  85054. for (code = 0; code < LENGTH_CODES-1; code++) {
  85055. base_length[code] = length;
  85056. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85057. _length_code[length++] = (uch)code;
  85058. }
  85059. }
  85060. Assert (length == 256, "tr_static_init: length != 256");
  85061. /* Note that the length 255 (match length 258) can be represented
  85062. * in two different ways: code 284 + 5 bits or code 285, so we
  85063. * overwrite length_code[255] to use the best encoding:
  85064. */
  85065. _length_code[length-1] = (uch)code;
  85066. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85067. dist = 0;
  85068. for (code = 0 ; code < 16; code++) {
  85069. base_dist[code] = dist;
  85070. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85071. _dist_code[dist++] = (uch)code;
  85072. }
  85073. }
  85074. Assert (dist == 256, "tr_static_init: dist != 256");
  85075. dist >>= 7; /* from now on, all distances are divided by 128 */
  85076. for ( ; code < D_CODES; code++) {
  85077. base_dist[code] = dist << 7;
  85078. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85079. _dist_code[256 + dist++] = (uch)code;
  85080. }
  85081. }
  85082. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85083. /* Construct the codes of the static literal tree */
  85084. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85085. n = 0;
  85086. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85087. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85088. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85089. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85090. /* Codes 286 and 287 do not exist, but we must include them in the
  85091. * tree construction to get a canonical Huffman tree (longest code
  85092. * all ones)
  85093. */
  85094. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85095. /* The static distance tree is trivial: */
  85096. for (n = 0; n < D_CODES; n++) {
  85097. static_dtree[n].Len = 5;
  85098. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85099. }
  85100. static_init_done = 1;
  85101. # ifdef GEN_TREES_H
  85102. gen_trees_header();
  85103. # endif
  85104. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85105. }
  85106. /* ===========================================================================
  85107. * Genererate the file trees.h describing the static trees.
  85108. */
  85109. #ifdef GEN_TREES_H
  85110. # ifndef DEBUG
  85111. # include <stdio.h>
  85112. # endif
  85113. # define SEPARATOR(i, last, width) \
  85114. ((i) == (last)? "\n};\n\n" : \
  85115. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85116. void gen_trees_header()
  85117. {
  85118. FILE *header = fopen("trees.h", "w");
  85119. int i;
  85120. Assert (header != NULL, "Can't open trees.h");
  85121. fprintf(header,
  85122. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85123. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85124. for (i = 0; i < L_CODES+2; i++) {
  85125. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85126. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85127. }
  85128. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85129. for (i = 0; i < D_CODES; i++) {
  85130. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85131. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85132. }
  85133. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85134. for (i = 0; i < DIST_CODE_LEN; i++) {
  85135. fprintf(header, "%2u%s", _dist_code[i],
  85136. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85137. }
  85138. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85139. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85140. fprintf(header, "%2u%s", _length_code[i],
  85141. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85142. }
  85143. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85144. for (i = 0; i < LENGTH_CODES; i++) {
  85145. fprintf(header, "%1u%s", base_length[i],
  85146. SEPARATOR(i, LENGTH_CODES-1, 20));
  85147. }
  85148. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85149. for (i = 0; i < D_CODES; i++) {
  85150. fprintf(header, "%5u%s", base_dist[i],
  85151. SEPARATOR(i, D_CODES-1, 10));
  85152. }
  85153. fclose(header);
  85154. }
  85155. #endif /* GEN_TREES_H */
  85156. /* ===========================================================================
  85157. * Initialize the tree data structures for a new zlib stream.
  85158. */
  85159. void _tr_init(deflate_state *s)
  85160. {
  85161. tr_static_init();
  85162. s->l_desc.dyn_tree = s->dyn_ltree;
  85163. s->l_desc.stat_desc = &static_l_desc;
  85164. s->d_desc.dyn_tree = s->dyn_dtree;
  85165. s->d_desc.stat_desc = &static_d_desc;
  85166. s->bl_desc.dyn_tree = s->bl_tree;
  85167. s->bl_desc.stat_desc = &static_bl_desc;
  85168. s->bi_buf = 0;
  85169. s->bi_valid = 0;
  85170. s->last_eob_len = 8; /* enough lookahead for inflate */
  85171. #ifdef DEBUG
  85172. s->compressed_len = 0L;
  85173. s->bits_sent = 0L;
  85174. #endif
  85175. /* Initialize the first block of the first file: */
  85176. init_block(s);
  85177. }
  85178. /* ===========================================================================
  85179. * Initialize a new block.
  85180. */
  85181. local void init_block (deflate_state *s)
  85182. {
  85183. int n; /* iterates over tree elements */
  85184. /* Initialize the trees. */
  85185. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85186. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85187. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85188. s->dyn_ltree[END_BLOCK].Freq = 1;
  85189. s->opt_len = s->static_len = 0L;
  85190. s->last_lit = s->matches = 0;
  85191. }
  85192. #define SMALLEST 1
  85193. /* Index within the heap array of least frequent node in the Huffman tree */
  85194. /* ===========================================================================
  85195. * Remove the smallest element from the heap and recreate the heap with
  85196. * one less element. Updates heap and heap_len.
  85197. */
  85198. #define pqremove(s, tree, top) \
  85199. {\
  85200. top = s->heap[SMALLEST]; \
  85201. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85202. pqdownheap(s, tree, SMALLEST); \
  85203. }
  85204. /* ===========================================================================
  85205. * Compares to subtrees, using the tree depth as tie breaker when
  85206. * the subtrees have equal frequency. This minimizes the worst case length.
  85207. */
  85208. #define smaller(tree, n, m, depth) \
  85209. (tree[n].Freq < tree[m].Freq || \
  85210. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85211. /* ===========================================================================
  85212. * Restore the heap property by moving down the tree starting at node k,
  85213. * exchanging a node with the smallest of its two sons if necessary, stopping
  85214. * when the heap property is re-established (each father smaller than its
  85215. * two sons).
  85216. */
  85217. local void pqdownheap (deflate_state *s,
  85218. ct_data *tree, /* the tree to restore */
  85219. int k) /* node to move down */
  85220. {
  85221. int v = s->heap[k];
  85222. int j = k << 1; /* left son of k */
  85223. while (j <= s->heap_len) {
  85224. /* Set j to the smallest of the two sons: */
  85225. if (j < s->heap_len &&
  85226. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85227. j++;
  85228. }
  85229. /* Exit if v is smaller than both sons */
  85230. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85231. /* Exchange v with the smallest son */
  85232. s->heap[k] = s->heap[j]; k = j;
  85233. /* And continue down the tree, setting j to the left son of k */
  85234. j <<= 1;
  85235. }
  85236. s->heap[k] = v;
  85237. }
  85238. /* ===========================================================================
  85239. * Compute the optimal bit lengths for a tree and update the total bit length
  85240. * for the current block.
  85241. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85242. * above are the tree nodes sorted by increasing frequency.
  85243. * OUT assertions: the field len is set to the optimal bit length, the
  85244. * array bl_count contains the frequencies for each bit length.
  85245. * The length opt_len is updated; static_len is also updated if stree is
  85246. * not null.
  85247. */
  85248. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85249. {
  85250. ct_data *tree = desc->dyn_tree;
  85251. int max_code = desc->max_code;
  85252. const ct_data *stree = desc->stat_desc->static_tree;
  85253. const intf *extra = desc->stat_desc->extra_bits;
  85254. int base = desc->stat_desc->extra_base;
  85255. int max_length = desc->stat_desc->max_length;
  85256. int h; /* heap index */
  85257. int n, m; /* iterate over the tree elements */
  85258. int bits; /* bit length */
  85259. int xbits; /* extra bits */
  85260. ush f; /* frequency */
  85261. int overflow = 0; /* number of elements with bit length too large */
  85262. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85263. /* In a first pass, compute the optimal bit lengths (which may
  85264. * overflow in the case of the bit length tree).
  85265. */
  85266. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85267. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85268. n = s->heap[h];
  85269. bits = tree[tree[n].Dad].Len + 1;
  85270. if (bits > max_length) bits = max_length, overflow++;
  85271. tree[n].Len = (ush)bits;
  85272. /* We overwrite tree[n].Dad which is no longer needed */
  85273. if (n > max_code) continue; /* not a leaf node */
  85274. s->bl_count[bits]++;
  85275. xbits = 0;
  85276. if (n >= base) xbits = extra[n-base];
  85277. f = tree[n].Freq;
  85278. s->opt_len += (ulg)f * (bits + xbits);
  85279. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85280. }
  85281. if (overflow == 0) return;
  85282. Trace((stderr,"\nbit length overflow\n"));
  85283. /* This happens for example on obj2 and pic of the Calgary corpus */
  85284. /* Find the first bit length which could increase: */
  85285. do {
  85286. bits = max_length-1;
  85287. while (s->bl_count[bits] == 0) bits--;
  85288. s->bl_count[bits]--; /* move one leaf down the tree */
  85289. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85290. s->bl_count[max_length]--;
  85291. /* The brother of the overflow item also moves one step up,
  85292. * but this does not affect bl_count[max_length]
  85293. */
  85294. overflow -= 2;
  85295. } while (overflow > 0);
  85296. /* Now recompute all bit lengths, scanning in increasing frequency.
  85297. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85298. * lengths instead of fixing only the wrong ones. This idea is taken
  85299. * from 'ar' written by Haruhiko Okumura.)
  85300. */
  85301. for (bits = max_length; bits != 0; bits--) {
  85302. n = s->bl_count[bits];
  85303. while (n != 0) {
  85304. m = s->heap[--h];
  85305. if (m > max_code) continue;
  85306. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85307. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85308. s->opt_len += ((long)bits - (long)tree[m].Len)
  85309. *(long)tree[m].Freq;
  85310. tree[m].Len = (ush)bits;
  85311. }
  85312. n--;
  85313. }
  85314. }
  85315. }
  85316. /* ===========================================================================
  85317. * Generate the codes for a given tree and bit counts (which need not be
  85318. * optimal).
  85319. * IN assertion: the array bl_count contains the bit length statistics for
  85320. * the given tree and the field len is set for all tree elements.
  85321. * OUT assertion: the field code is set for all tree elements of non
  85322. * zero code length.
  85323. */
  85324. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85325. int max_code, /* largest code with non zero frequency */
  85326. ushf *bl_count) /* number of codes at each bit length */
  85327. {
  85328. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85329. ush code = 0; /* running code value */
  85330. int bits; /* bit index */
  85331. int n; /* code index */
  85332. /* The distribution counts are first used to generate the code values
  85333. * without bit reversal.
  85334. */
  85335. for (bits = 1; bits <= MAX_BITS; bits++) {
  85336. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85337. }
  85338. /* Check that the bit counts in bl_count are consistent. The last code
  85339. * must be all ones.
  85340. */
  85341. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85342. "inconsistent bit counts");
  85343. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85344. for (n = 0; n <= max_code; n++) {
  85345. int len = tree[n].Len;
  85346. if (len == 0) continue;
  85347. /* Now reverse the bits */
  85348. tree[n].Code = bi_reverse(next_code[len]++, len);
  85349. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85350. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85351. }
  85352. }
  85353. /* ===========================================================================
  85354. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85355. * Update the total bit length for the current block.
  85356. * IN assertion: the field freq is set for all tree elements.
  85357. * OUT assertions: the fields len and code are set to the optimal bit length
  85358. * and corresponding code. The length opt_len is updated; static_len is
  85359. * also updated if stree is not null. The field max_code is set.
  85360. */
  85361. local void build_tree (deflate_state *s,
  85362. tree_desc *desc) /* the tree descriptor */
  85363. {
  85364. ct_data *tree = desc->dyn_tree;
  85365. const ct_data *stree = desc->stat_desc->static_tree;
  85366. int elems = desc->stat_desc->elems;
  85367. int n, m; /* iterate over heap elements */
  85368. int max_code = -1; /* largest code with non zero frequency */
  85369. int node; /* new node being created */
  85370. /* Construct the initial heap, with least frequent element in
  85371. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85372. * heap[0] is not used.
  85373. */
  85374. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85375. for (n = 0; n < elems; n++) {
  85376. if (tree[n].Freq != 0) {
  85377. s->heap[++(s->heap_len)] = max_code = n;
  85378. s->depth[n] = 0;
  85379. } else {
  85380. tree[n].Len = 0;
  85381. }
  85382. }
  85383. /* The pkzip format requires that at least one distance code exists,
  85384. * and that at least one bit should be sent even if there is only one
  85385. * possible code. So to avoid special checks later on we force at least
  85386. * two codes of non zero frequency.
  85387. */
  85388. while (s->heap_len < 2) {
  85389. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85390. tree[node].Freq = 1;
  85391. s->depth[node] = 0;
  85392. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85393. /* node is 0 or 1 so it does not have extra bits */
  85394. }
  85395. desc->max_code = max_code;
  85396. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85397. * establish sub-heaps of increasing lengths:
  85398. */
  85399. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85400. /* Construct the Huffman tree by repeatedly combining the least two
  85401. * frequent nodes.
  85402. */
  85403. node = elems; /* next internal node of the tree */
  85404. do {
  85405. pqremove(s, tree, n); /* n = node of least frequency */
  85406. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85407. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85408. s->heap[--(s->heap_max)] = m;
  85409. /* Create a new node father of n and m */
  85410. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85411. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85412. s->depth[n] : s->depth[m]) + 1);
  85413. tree[n].Dad = tree[m].Dad = (ush)node;
  85414. #ifdef DUMP_BL_TREE
  85415. if (tree == s->bl_tree) {
  85416. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85417. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85418. }
  85419. #endif
  85420. /* and insert the new node in the heap */
  85421. s->heap[SMALLEST] = node++;
  85422. pqdownheap(s, tree, SMALLEST);
  85423. } while (s->heap_len >= 2);
  85424. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85425. /* At this point, the fields freq and dad are set. We can now
  85426. * generate the bit lengths.
  85427. */
  85428. gen_bitlen(s, (tree_desc *)desc);
  85429. /* The field len is now set, we can generate the bit codes */
  85430. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85431. }
  85432. /* ===========================================================================
  85433. * Scan a literal or distance tree to determine the frequencies of the codes
  85434. * in the bit length tree.
  85435. */
  85436. local void scan_tree (deflate_state *s,
  85437. ct_data *tree, /* the tree to be scanned */
  85438. int max_code) /* and its largest code of non zero frequency */
  85439. {
  85440. int n; /* iterates over all tree elements */
  85441. int prevlen = -1; /* last emitted length */
  85442. int curlen; /* length of current code */
  85443. int nextlen = tree[0].Len; /* length of next code */
  85444. int count = 0; /* repeat count of the current code */
  85445. int max_count = 7; /* max repeat count */
  85446. int min_count = 4; /* min repeat count */
  85447. if (nextlen == 0) max_count = 138, min_count = 3;
  85448. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85449. for (n = 0; n <= max_code; n++) {
  85450. curlen = nextlen; nextlen = tree[n+1].Len;
  85451. if (++count < max_count && curlen == nextlen) {
  85452. continue;
  85453. } else if (count < min_count) {
  85454. s->bl_tree[curlen].Freq += count;
  85455. } else if (curlen != 0) {
  85456. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85457. s->bl_tree[REP_3_6].Freq++;
  85458. } else if (count <= 10) {
  85459. s->bl_tree[REPZ_3_10].Freq++;
  85460. } else {
  85461. s->bl_tree[REPZ_11_138].Freq++;
  85462. }
  85463. count = 0; prevlen = curlen;
  85464. if (nextlen == 0) {
  85465. max_count = 138, min_count = 3;
  85466. } else if (curlen == nextlen) {
  85467. max_count = 6, min_count = 3;
  85468. } else {
  85469. max_count = 7, min_count = 4;
  85470. }
  85471. }
  85472. }
  85473. /* ===========================================================================
  85474. * Send a literal or distance tree in compressed form, using the codes in
  85475. * bl_tree.
  85476. */
  85477. local void send_tree (deflate_state *s,
  85478. ct_data *tree, /* the tree to be scanned */
  85479. int max_code) /* and its largest code of non zero frequency */
  85480. {
  85481. int n; /* iterates over all tree elements */
  85482. int prevlen = -1; /* last emitted length */
  85483. int curlen; /* length of current code */
  85484. int nextlen = tree[0].Len; /* length of next code */
  85485. int count = 0; /* repeat count of the current code */
  85486. int max_count = 7; /* max repeat count */
  85487. int min_count = 4; /* min repeat count */
  85488. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85489. if (nextlen == 0) max_count = 138, min_count = 3;
  85490. for (n = 0; n <= max_code; n++) {
  85491. curlen = nextlen; nextlen = tree[n+1].Len;
  85492. if (++count < max_count && curlen == nextlen) {
  85493. continue;
  85494. } else if (count < min_count) {
  85495. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85496. } else if (curlen != 0) {
  85497. if (curlen != prevlen) {
  85498. send_code(s, curlen, s->bl_tree); count--;
  85499. }
  85500. Assert(count >= 3 && count <= 6, " 3_6?");
  85501. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85502. } else if (count <= 10) {
  85503. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85504. } else {
  85505. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85506. }
  85507. count = 0; prevlen = curlen;
  85508. if (nextlen == 0) {
  85509. max_count = 138, min_count = 3;
  85510. } else if (curlen == nextlen) {
  85511. max_count = 6, min_count = 3;
  85512. } else {
  85513. max_count = 7, min_count = 4;
  85514. }
  85515. }
  85516. }
  85517. /* ===========================================================================
  85518. * Construct the Huffman tree for the bit lengths and return the index in
  85519. * bl_order of the last bit length code to send.
  85520. */
  85521. local int build_bl_tree (deflate_state *s)
  85522. {
  85523. int max_blindex; /* index of last bit length code of non zero freq */
  85524. /* Determine the bit length frequencies for literal and distance trees */
  85525. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85526. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85527. /* Build the bit length tree: */
  85528. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85529. /* opt_len now includes the length of the tree representations, except
  85530. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85531. */
  85532. /* Determine the number of bit length codes to send. The pkzip format
  85533. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85534. * 3 but the actual value used is 4.)
  85535. */
  85536. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85537. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85538. }
  85539. /* Update opt_len to include the bit length tree and counts */
  85540. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85541. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85542. s->opt_len, s->static_len));
  85543. return max_blindex;
  85544. }
  85545. /* ===========================================================================
  85546. * Send the header for a block using dynamic Huffman trees: the counts, the
  85547. * lengths of the bit length codes, the literal tree and the distance tree.
  85548. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85549. */
  85550. local void send_all_trees (deflate_state *s,
  85551. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85552. {
  85553. int rank; /* index in bl_order */
  85554. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85555. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85556. "too many codes");
  85557. Tracev((stderr, "\nbl counts: "));
  85558. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85559. send_bits(s, dcodes-1, 5);
  85560. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85561. for (rank = 0; rank < blcodes; rank++) {
  85562. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85563. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85564. }
  85565. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85566. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85567. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85568. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85569. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85570. }
  85571. /* ===========================================================================
  85572. * Send a stored block
  85573. */
  85574. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85575. {
  85576. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85577. #ifdef DEBUG
  85578. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85579. s->compressed_len += (stored_len + 4) << 3;
  85580. #endif
  85581. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85582. }
  85583. /* ===========================================================================
  85584. * Send one empty static block to give enough lookahead for inflate.
  85585. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85586. * The current inflate code requires 9 bits of lookahead. If the
  85587. * last two codes for the previous block (real code plus EOB) were coded
  85588. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85589. * the last real code. In this case we send two empty static blocks instead
  85590. * of one. (There are no problems if the previous block is stored or fixed.)
  85591. * To simplify the code, we assume the worst case of last real code encoded
  85592. * on one bit only.
  85593. */
  85594. void _tr_align (deflate_state *s)
  85595. {
  85596. send_bits(s, STATIC_TREES<<1, 3);
  85597. send_code(s, END_BLOCK, static_ltree);
  85598. #ifdef DEBUG
  85599. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85600. #endif
  85601. bi_flush(s);
  85602. /* Of the 10 bits for the empty block, we have already sent
  85603. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85604. * the EOB of the previous block) was thus at least one plus the length
  85605. * of the EOB plus what we have just sent of the empty static block.
  85606. */
  85607. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85608. send_bits(s, STATIC_TREES<<1, 3);
  85609. send_code(s, END_BLOCK, static_ltree);
  85610. #ifdef DEBUG
  85611. s->compressed_len += 10L;
  85612. #endif
  85613. bi_flush(s);
  85614. }
  85615. s->last_eob_len = 7;
  85616. }
  85617. /* ===========================================================================
  85618. * Determine the best encoding for the current block: dynamic trees, static
  85619. * trees or store, and output the encoded block to the zip file.
  85620. */
  85621. void _tr_flush_block (deflate_state *s,
  85622. charf *buf, /* input block, or NULL if too old */
  85623. ulg stored_len, /* length of input block */
  85624. int eof) /* true if this is the last block for a file */
  85625. {
  85626. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85627. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85628. /* Build the Huffman trees unless a stored block is forced */
  85629. if (s->level > 0) {
  85630. /* Check if the file is binary or text */
  85631. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85632. set_data_type(s);
  85633. /* Construct the literal and distance trees */
  85634. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85635. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85636. s->static_len));
  85637. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85638. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85639. s->static_len));
  85640. /* At this point, opt_len and static_len are the total bit lengths of
  85641. * the compressed block data, excluding the tree representations.
  85642. */
  85643. /* Build the bit length tree for the above two trees, and get the index
  85644. * in bl_order of the last bit length code to send.
  85645. */
  85646. max_blindex = build_bl_tree(s);
  85647. /* Determine the best encoding. Compute the block lengths in bytes. */
  85648. opt_lenb = (s->opt_len+3+7)>>3;
  85649. static_lenb = (s->static_len+3+7)>>3;
  85650. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85651. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85652. s->last_lit));
  85653. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85654. } else {
  85655. Assert(buf != (char*)0, "lost buf");
  85656. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85657. }
  85658. #ifdef FORCE_STORED
  85659. if (buf != (char*)0) { /* force stored block */
  85660. #else
  85661. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85662. /* 4: two words for the lengths */
  85663. #endif
  85664. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85665. * Otherwise we can't have processed more than WSIZE input bytes since
  85666. * the last block flush, because compression would have been
  85667. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85668. * transform a block into a stored block.
  85669. */
  85670. _tr_stored_block(s, buf, stored_len, eof);
  85671. #ifdef FORCE_STATIC
  85672. } else if (static_lenb >= 0) { /* force static trees */
  85673. #else
  85674. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85675. #endif
  85676. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85677. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85678. #ifdef DEBUG
  85679. s->compressed_len += 3 + s->static_len;
  85680. #endif
  85681. } else {
  85682. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85683. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85684. max_blindex+1);
  85685. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85686. #ifdef DEBUG
  85687. s->compressed_len += 3 + s->opt_len;
  85688. #endif
  85689. }
  85690. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85691. /* The above check is made mod 2^32, for files larger than 512 MB
  85692. * and uLong implemented on 32 bits.
  85693. */
  85694. init_block(s);
  85695. if (eof) {
  85696. bi_windup(s);
  85697. #ifdef DEBUG
  85698. s->compressed_len += 7; /* align on byte boundary */
  85699. #endif
  85700. }
  85701. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85702. s->compressed_len-7*eof));
  85703. }
  85704. /* ===========================================================================
  85705. * Save the match info and tally the frequency counts. Return true if
  85706. * the current block must be flushed.
  85707. */
  85708. int _tr_tally (deflate_state *s,
  85709. unsigned dist, /* distance of matched string */
  85710. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85711. {
  85712. s->d_buf[s->last_lit] = (ush)dist;
  85713. s->l_buf[s->last_lit++] = (uch)lc;
  85714. if (dist == 0) {
  85715. /* lc is the unmatched char */
  85716. s->dyn_ltree[lc].Freq++;
  85717. } else {
  85718. s->matches++;
  85719. /* Here, lc is the match length - MIN_MATCH */
  85720. dist--; /* dist = match distance - 1 */
  85721. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85722. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85723. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85724. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85725. s->dyn_dtree[d_code(dist)].Freq++;
  85726. }
  85727. #ifdef TRUNCATE_BLOCK
  85728. /* Try to guess if it is profitable to stop the current block here */
  85729. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85730. /* Compute an upper bound for the compressed length */
  85731. ulg out_length = (ulg)s->last_lit*8L;
  85732. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85733. int dcode;
  85734. for (dcode = 0; dcode < D_CODES; dcode++) {
  85735. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85736. (5L+extra_dbits[dcode]);
  85737. }
  85738. out_length >>= 3;
  85739. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85740. s->last_lit, in_length, out_length,
  85741. 100L - out_length*100L/in_length));
  85742. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85743. }
  85744. #endif
  85745. return (s->last_lit == s->lit_bufsize-1);
  85746. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85747. * on 16 bit machines and because stored blocks are restricted to
  85748. * 64K-1 bytes.
  85749. */
  85750. }
  85751. /* ===========================================================================
  85752. * Send the block data compressed using the given Huffman trees
  85753. */
  85754. local void compress_block (deflate_state *s,
  85755. ct_data *ltree, /* literal tree */
  85756. ct_data *dtree) /* distance tree */
  85757. {
  85758. unsigned dist; /* distance of matched string */
  85759. int lc; /* match length or unmatched char (if dist == 0) */
  85760. unsigned lx = 0; /* running index in l_buf */
  85761. unsigned code; /* the code to send */
  85762. int extra; /* number of extra bits to send */
  85763. if (s->last_lit != 0) do {
  85764. dist = s->d_buf[lx];
  85765. lc = s->l_buf[lx++];
  85766. if (dist == 0) {
  85767. send_code(s, lc, ltree); /* send a literal byte */
  85768. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85769. } else {
  85770. /* Here, lc is the match length - MIN_MATCH */
  85771. code = _length_code[lc];
  85772. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85773. extra = extra_lbits[code];
  85774. if (extra != 0) {
  85775. lc -= base_length[code];
  85776. send_bits(s, lc, extra); /* send the extra length bits */
  85777. }
  85778. dist--; /* dist is now the match distance - 1 */
  85779. code = d_code(dist);
  85780. Assert (code < D_CODES, "bad d_code");
  85781. send_code(s, code, dtree); /* send the distance code */
  85782. extra = extra_dbits[code];
  85783. if (extra != 0) {
  85784. dist -= base_dist[code];
  85785. send_bits(s, dist, extra); /* send the extra distance bits */
  85786. }
  85787. } /* literal or match pair ? */
  85788. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85789. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85790. "pendingBuf overflow");
  85791. } while (lx < s->last_lit);
  85792. send_code(s, END_BLOCK, ltree);
  85793. s->last_eob_len = ltree[END_BLOCK].Len;
  85794. }
  85795. /* ===========================================================================
  85796. * Set the data type to BINARY or TEXT, using a crude approximation:
  85797. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85798. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85799. * IN assertion: the fields Freq of dyn_ltree are set.
  85800. */
  85801. local void set_data_type (deflate_state *s)
  85802. {
  85803. int n;
  85804. for (n = 0; n < 9; n++)
  85805. if (s->dyn_ltree[n].Freq != 0)
  85806. break;
  85807. if (n == 9)
  85808. for (n = 14; n < 32; n++)
  85809. if (s->dyn_ltree[n].Freq != 0)
  85810. break;
  85811. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85812. }
  85813. /* ===========================================================================
  85814. * Reverse the first len bits of a code, using straightforward code (a faster
  85815. * method would use a table)
  85816. * IN assertion: 1 <= len <= 15
  85817. */
  85818. local unsigned bi_reverse (unsigned code, int len)
  85819. {
  85820. register unsigned res = 0;
  85821. do {
  85822. res |= code & 1;
  85823. code >>= 1, res <<= 1;
  85824. } while (--len > 0);
  85825. return res >> 1;
  85826. }
  85827. /* ===========================================================================
  85828. * Flush the bit buffer, keeping at most 7 bits in it.
  85829. */
  85830. local void bi_flush (deflate_state *s)
  85831. {
  85832. if (s->bi_valid == 16) {
  85833. put_short(s, s->bi_buf);
  85834. s->bi_buf = 0;
  85835. s->bi_valid = 0;
  85836. } else if (s->bi_valid >= 8) {
  85837. put_byte(s, (Byte)s->bi_buf);
  85838. s->bi_buf >>= 8;
  85839. s->bi_valid -= 8;
  85840. }
  85841. }
  85842. /* ===========================================================================
  85843. * Flush the bit buffer and align the output on a byte boundary
  85844. */
  85845. local void bi_windup (deflate_state *s)
  85846. {
  85847. if (s->bi_valid > 8) {
  85848. put_short(s, s->bi_buf);
  85849. } else if (s->bi_valid > 0) {
  85850. put_byte(s, (Byte)s->bi_buf);
  85851. }
  85852. s->bi_buf = 0;
  85853. s->bi_valid = 0;
  85854. #ifdef DEBUG
  85855. s->bits_sent = (s->bits_sent+7) & ~7;
  85856. #endif
  85857. }
  85858. /* ===========================================================================
  85859. * Copy a stored block, storing first the length and its
  85860. * one's complement if requested.
  85861. */
  85862. local void copy_block(deflate_state *s,
  85863. charf *buf, /* the input data */
  85864. unsigned len, /* its length */
  85865. int header) /* true if block header must be written */
  85866. {
  85867. bi_windup(s); /* align on byte boundary */
  85868. s->last_eob_len = 8; /* enough lookahead for inflate */
  85869. if (header) {
  85870. put_short(s, (ush)len);
  85871. put_short(s, (ush)~len);
  85872. #ifdef DEBUG
  85873. s->bits_sent += 2*16;
  85874. #endif
  85875. }
  85876. #ifdef DEBUG
  85877. s->bits_sent += (ulg)len<<3;
  85878. #endif
  85879. while (len--) {
  85880. put_byte(s, *buf++);
  85881. }
  85882. }
  85883. /*** End of inlined file: trees.c ***/
  85884. /*** Start of inlined file: zutil.c ***/
  85885. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85886. #ifndef NO_DUMMY_DECL
  85887. struct internal_state {int dummy;}; /* for buggy compilers */
  85888. #endif
  85889. const char * const z_errmsg[10] = {
  85890. "need dictionary", /* Z_NEED_DICT 2 */
  85891. "stream end", /* Z_STREAM_END 1 */
  85892. "", /* Z_OK 0 */
  85893. "file error", /* Z_ERRNO (-1) */
  85894. "stream error", /* Z_STREAM_ERROR (-2) */
  85895. "data error", /* Z_DATA_ERROR (-3) */
  85896. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85897. "buffer error", /* Z_BUF_ERROR (-5) */
  85898. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85899. ""};
  85900. /*const char * ZEXPORT zlibVersion()
  85901. {
  85902. return ZLIB_VERSION;
  85903. }
  85904. uLong ZEXPORT zlibCompileFlags()
  85905. {
  85906. uLong flags;
  85907. flags = 0;
  85908. switch (sizeof(uInt)) {
  85909. case 2: break;
  85910. case 4: flags += 1; break;
  85911. case 8: flags += 2; break;
  85912. default: flags += 3;
  85913. }
  85914. switch (sizeof(uLong)) {
  85915. case 2: break;
  85916. case 4: flags += 1 << 2; break;
  85917. case 8: flags += 2 << 2; break;
  85918. default: flags += 3 << 2;
  85919. }
  85920. switch (sizeof(voidpf)) {
  85921. case 2: break;
  85922. case 4: flags += 1 << 4; break;
  85923. case 8: flags += 2 << 4; break;
  85924. default: flags += 3 << 4;
  85925. }
  85926. switch (sizeof(z_off_t)) {
  85927. case 2: break;
  85928. case 4: flags += 1 << 6; break;
  85929. case 8: flags += 2 << 6; break;
  85930. default: flags += 3 << 6;
  85931. }
  85932. #ifdef DEBUG
  85933. flags += 1 << 8;
  85934. #endif
  85935. #if defined(ASMV) || defined(ASMINF)
  85936. flags += 1 << 9;
  85937. #endif
  85938. #ifdef ZLIB_WINAPI
  85939. flags += 1 << 10;
  85940. #endif
  85941. #ifdef BUILDFIXED
  85942. flags += 1 << 12;
  85943. #endif
  85944. #ifdef DYNAMIC_CRC_TABLE
  85945. flags += 1 << 13;
  85946. #endif
  85947. #ifdef NO_GZCOMPRESS
  85948. flags += 1L << 16;
  85949. #endif
  85950. #ifdef NO_GZIP
  85951. flags += 1L << 17;
  85952. #endif
  85953. #ifdef PKZIP_BUG_WORKAROUND
  85954. flags += 1L << 20;
  85955. #endif
  85956. #ifdef FASTEST
  85957. flags += 1L << 21;
  85958. #endif
  85959. #ifdef STDC
  85960. # ifdef NO_vsnprintf
  85961. flags += 1L << 25;
  85962. # ifdef HAS_vsprintf_void
  85963. flags += 1L << 26;
  85964. # endif
  85965. # else
  85966. # ifdef HAS_vsnprintf_void
  85967. flags += 1L << 26;
  85968. # endif
  85969. # endif
  85970. #else
  85971. flags += 1L << 24;
  85972. # ifdef NO_snprintf
  85973. flags += 1L << 25;
  85974. # ifdef HAS_sprintf_void
  85975. flags += 1L << 26;
  85976. # endif
  85977. # else
  85978. # ifdef HAS_snprintf_void
  85979. flags += 1L << 26;
  85980. # endif
  85981. # endif
  85982. #endif
  85983. return flags;
  85984. }*/
  85985. #ifdef DEBUG
  85986. # ifndef verbose
  85987. # define verbose 0
  85988. # endif
  85989. int z_verbose = verbose;
  85990. void z_error (const char *m)
  85991. {
  85992. fprintf(stderr, "%s\n", m);
  85993. exit(1);
  85994. }
  85995. #endif
  85996. /* exported to allow conversion of error code to string for compress() and
  85997. * uncompress()
  85998. */
  85999. const char * ZEXPORT zError(int err)
  86000. {
  86001. return ERR_MSG(err);
  86002. }
  86003. #if defined(_WIN32_WCE)
  86004. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86005. * errno. We define it as a global variable to simplify porting.
  86006. * Its value is always 0 and should not be used.
  86007. */
  86008. int errno = 0;
  86009. #endif
  86010. #ifndef HAVE_MEMCPY
  86011. void zmemcpy(dest, source, len)
  86012. Bytef* dest;
  86013. const Bytef* source;
  86014. uInt len;
  86015. {
  86016. if (len == 0) return;
  86017. do {
  86018. *dest++ = *source++; /* ??? to be unrolled */
  86019. } while (--len != 0);
  86020. }
  86021. int zmemcmp(s1, s2, len)
  86022. const Bytef* s1;
  86023. const Bytef* s2;
  86024. uInt len;
  86025. {
  86026. uInt j;
  86027. for (j = 0; j < len; j++) {
  86028. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86029. }
  86030. return 0;
  86031. }
  86032. void zmemzero(dest, len)
  86033. Bytef* dest;
  86034. uInt len;
  86035. {
  86036. if (len == 0) return;
  86037. do {
  86038. *dest++ = 0; /* ??? to be unrolled */
  86039. } while (--len != 0);
  86040. }
  86041. #endif
  86042. #ifdef SYS16BIT
  86043. #ifdef __TURBOC__
  86044. /* Turbo C in 16-bit mode */
  86045. # define MY_ZCALLOC
  86046. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86047. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86048. * must fix the pointer. Warning: the pointer must be put back to its
  86049. * original form in order to free it, use zcfree().
  86050. */
  86051. #define MAX_PTR 10
  86052. /* 10*64K = 640K */
  86053. local int next_ptr = 0;
  86054. typedef struct ptr_table_s {
  86055. voidpf org_ptr;
  86056. voidpf new_ptr;
  86057. } ptr_table;
  86058. local ptr_table table[MAX_PTR];
  86059. /* This table is used to remember the original form of pointers
  86060. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86061. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86062. * protected from concurrent access. This hack doesn't work anyway on
  86063. * a protected system like OS/2. Use Microsoft C instead.
  86064. */
  86065. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86066. {
  86067. voidpf buf = opaque; /* just to make some compilers happy */
  86068. ulg bsize = (ulg)items*size;
  86069. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86070. * will return a usable pointer which doesn't have to be normalized.
  86071. */
  86072. if (bsize < 65520L) {
  86073. buf = farmalloc(bsize);
  86074. if (*(ush*)&buf != 0) return buf;
  86075. } else {
  86076. buf = farmalloc(bsize + 16L);
  86077. }
  86078. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86079. table[next_ptr].org_ptr = buf;
  86080. /* Normalize the pointer to seg:0 */
  86081. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86082. *(ush*)&buf = 0;
  86083. table[next_ptr++].new_ptr = buf;
  86084. return buf;
  86085. }
  86086. void zcfree (voidpf opaque, voidpf ptr)
  86087. {
  86088. int n;
  86089. if (*(ush*)&ptr != 0) { /* object < 64K */
  86090. farfree(ptr);
  86091. return;
  86092. }
  86093. /* Find the original pointer */
  86094. for (n = 0; n < next_ptr; n++) {
  86095. if (ptr != table[n].new_ptr) continue;
  86096. farfree(table[n].org_ptr);
  86097. while (++n < next_ptr) {
  86098. table[n-1] = table[n];
  86099. }
  86100. next_ptr--;
  86101. return;
  86102. }
  86103. ptr = opaque; /* just to make some compilers happy */
  86104. Assert(0, "zcfree: ptr not found");
  86105. }
  86106. #endif /* __TURBOC__ */
  86107. #ifdef M_I86
  86108. /* Microsoft C in 16-bit mode */
  86109. # define MY_ZCALLOC
  86110. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86111. # define _halloc halloc
  86112. # define _hfree hfree
  86113. #endif
  86114. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86115. {
  86116. if (opaque) opaque = 0; /* to make compiler happy */
  86117. return _halloc((long)items, size);
  86118. }
  86119. void zcfree (voidpf opaque, voidpf ptr)
  86120. {
  86121. if (opaque) opaque = 0; /* to make compiler happy */
  86122. _hfree(ptr);
  86123. }
  86124. #endif /* M_I86 */
  86125. #endif /* SYS16BIT */
  86126. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86127. #ifndef STDC
  86128. extern voidp malloc OF((uInt size));
  86129. extern voidp calloc OF((uInt items, uInt size));
  86130. extern void free OF((voidpf ptr));
  86131. #endif
  86132. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86133. {
  86134. if (opaque) items += size - size; /* make compiler happy */
  86135. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86136. (voidpf)calloc(items, size);
  86137. }
  86138. void zcfree (voidpf opaque, voidpf ptr)
  86139. {
  86140. free(ptr);
  86141. if (opaque) return; /* make compiler happy */
  86142. }
  86143. #endif /* MY_ZCALLOC */
  86144. /*** End of inlined file: zutil.c ***/
  86145. #undef Byte
  86146. #else
  86147. #include <zlib.h>
  86148. #endif
  86149. }
  86150. #if JUCE_MSVC
  86151. #pragma warning (pop)
  86152. #endif
  86153. BEGIN_JUCE_NAMESPACE
  86154. // internal helper object that holds the zlib structures so they don't have to be
  86155. // included publicly.
  86156. class GZIPDecompressHelper
  86157. {
  86158. public:
  86159. GZIPDecompressHelper (const bool noWrap)
  86160. : finished (true),
  86161. needsDictionary (false),
  86162. error (true),
  86163. streamIsValid (false),
  86164. data (0),
  86165. dataSize (0)
  86166. {
  86167. using namespace zlibNamespace;
  86168. zerostruct (stream);
  86169. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86170. finished = error = ! streamIsValid;
  86171. }
  86172. ~GZIPDecompressHelper()
  86173. {
  86174. using namespace zlibNamespace;
  86175. if (streamIsValid)
  86176. inflateEnd (&stream);
  86177. }
  86178. bool needsInput() const throw() { return dataSize <= 0; }
  86179. void setInput (uint8* const data_, const int size) throw()
  86180. {
  86181. data = data_;
  86182. dataSize = size;
  86183. }
  86184. int doNextBlock (uint8* const dest, const int destSize)
  86185. {
  86186. using namespace zlibNamespace;
  86187. if (streamIsValid && data != 0 && ! finished)
  86188. {
  86189. stream.next_in = data;
  86190. stream.next_out = dest;
  86191. stream.avail_in = dataSize;
  86192. stream.avail_out = destSize;
  86193. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86194. {
  86195. case Z_STREAM_END:
  86196. finished = true;
  86197. // deliberate fall-through
  86198. case Z_OK:
  86199. data += dataSize - stream.avail_in;
  86200. dataSize = stream.avail_in;
  86201. return destSize - stream.avail_out;
  86202. case Z_NEED_DICT:
  86203. needsDictionary = true;
  86204. data += dataSize - stream.avail_in;
  86205. dataSize = stream.avail_in;
  86206. break;
  86207. case Z_DATA_ERROR:
  86208. case Z_MEM_ERROR:
  86209. error = true;
  86210. default:
  86211. break;
  86212. }
  86213. }
  86214. return 0;
  86215. }
  86216. bool finished, needsDictionary, error, streamIsValid;
  86217. private:
  86218. zlibNamespace::z_stream stream;
  86219. uint8* data;
  86220. int dataSize;
  86221. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86222. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86223. };
  86224. const int gzipDecompBufferSize = 32768;
  86225. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86226. const bool deleteSourceWhenDestroyed,
  86227. const bool noWrap_,
  86228. const int64 uncompressedStreamLength_)
  86229. : sourceStream (sourceStream_),
  86230. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86231. uncompressedStreamLength (uncompressedStreamLength_),
  86232. noWrap (noWrap_),
  86233. isEof (false),
  86234. activeBufferSize (0),
  86235. originalSourcePos (sourceStream_->getPosition()),
  86236. currentPos (0),
  86237. buffer (gzipDecompBufferSize),
  86238. helper (new GZIPDecompressHelper (noWrap_))
  86239. {
  86240. }
  86241. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86242. {
  86243. }
  86244. int64 GZIPDecompressorInputStream::getTotalLength()
  86245. {
  86246. return uncompressedStreamLength;
  86247. }
  86248. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86249. {
  86250. if ((howMany > 0) && ! isEof)
  86251. {
  86252. jassert (destBuffer != 0);
  86253. if (destBuffer != 0)
  86254. {
  86255. int numRead = 0;
  86256. uint8* d = static_cast <uint8*> (destBuffer);
  86257. while (! helper->error)
  86258. {
  86259. const int n = helper->doNextBlock (d, howMany);
  86260. currentPos += n;
  86261. if (n == 0)
  86262. {
  86263. if (helper->finished || helper->needsDictionary)
  86264. {
  86265. isEof = true;
  86266. return numRead;
  86267. }
  86268. if (helper->needsInput())
  86269. {
  86270. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86271. if (activeBufferSize > 0)
  86272. {
  86273. helper->setInput (buffer, activeBufferSize);
  86274. }
  86275. else
  86276. {
  86277. isEof = true;
  86278. return numRead;
  86279. }
  86280. }
  86281. }
  86282. else
  86283. {
  86284. numRead += n;
  86285. howMany -= n;
  86286. d += n;
  86287. if (howMany <= 0)
  86288. return numRead;
  86289. }
  86290. }
  86291. }
  86292. }
  86293. return 0;
  86294. }
  86295. bool GZIPDecompressorInputStream::isExhausted()
  86296. {
  86297. return helper->error || isEof;
  86298. }
  86299. int64 GZIPDecompressorInputStream::getPosition()
  86300. {
  86301. return currentPos;
  86302. }
  86303. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86304. {
  86305. if (newPos < currentPos)
  86306. {
  86307. // to go backwards, reset the stream and start again..
  86308. isEof = false;
  86309. activeBufferSize = 0;
  86310. currentPos = 0;
  86311. helper = new GZIPDecompressHelper (noWrap);
  86312. sourceStream->setPosition (originalSourcePos);
  86313. }
  86314. skipNextBytes (newPos - currentPos);
  86315. return true;
  86316. }
  86317. END_JUCE_NAMESPACE
  86318. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86319. #endif
  86320. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86321. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86322. #if JUCE_USE_FLAC
  86323. #if JUCE_WINDOWS
  86324. #include <windows.h>
  86325. #endif
  86326. namespace FlacNamespace
  86327. {
  86328. #if JUCE_INCLUDE_FLAC_CODE
  86329. #if JUCE_MSVC
  86330. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86331. #endif
  86332. #define FLAC__NO_DLL 1
  86333. #if ! defined (SIZE_MAX)
  86334. #define SIZE_MAX 0xffffffff
  86335. #endif
  86336. #define __STDC_LIMIT_MACROS 1
  86337. /*** Start of inlined file: all.h ***/
  86338. #ifndef FLAC__ALL_H
  86339. #define FLAC__ALL_H
  86340. /*** Start of inlined file: export.h ***/
  86341. #ifndef FLAC__EXPORT_H
  86342. #define FLAC__EXPORT_H
  86343. /** \file include/FLAC/export.h
  86344. *
  86345. * \brief
  86346. * This module contains #defines and symbols for exporting function
  86347. * calls, and providing version information and compiled-in features.
  86348. *
  86349. * See the \link flac_export export \endlink module.
  86350. */
  86351. /** \defgroup flac_export FLAC/export.h: export symbols
  86352. * \ingroup flac
  86353. *
  86354. * \brief
  86355. * This module contains #defines and symbols for exporting function
  86356. * calls, and providing version information and compiled-in features.
  86357. *
  86358. * If you are compiling with MSVC and will link to the static library
  86359. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86360. * make sure the symbols are exported properly.
  86361. *
  86362. * \{
  86363. */
  86364. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86365. #define FLAC_API
  86366. #else
  86367. #ifdef FLAC_API_EXPORTS
  86368. #define FLAC_API _declspec(dllexport)
  86369. #else
  86370. #define FLAC_API _declspec(dllimport)
  86371. #endif
  86372. #endif
  86373. /** These #defines will mirror the libtool-based library version number, see
  86374. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86375. */
  86376. #define FLAC_API_VERSION_CURRENT 10
  86377. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86378. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86379. #ifdef __cplusplus
  86380. extern "C" {
  86381. #endif
  86382. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86383. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86384. #ifdef __cplusplus
  86385. }
  86386. #endif
  86387. /* \} */
  86388. #endif
  86389. /*** End of inlined file: export.h ***/
  86390. /*** Start of inlined file: assert.h ***/
  86391. #ifndef FLAC__ASSERT_H
  86392. #define FLAC__ASSERT_H
  86393. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86394. #ifdef DEBUG
  86395. #include <assert.h>
  86396. #define FLAC__ASSERT(x) assert(x)
  86397. #define FLAC__ASSERT_DECLARATION(x) x
  86398. #else
  86399. #define FLAC__ASSERT(x)
  86400. #define FLAC__ASSERT_DECLARATION(x)
  86401. #endif
  86402. #endif
  86403. /*** End of inlined file: assert.h ***/
  86404. /*** Start of inlined file: callback.h ***/
  86405. #ifndef FLAC__CALLBACK_H
  86406. #define FLAC__CALLBACK_H
  86407. /*** Start of inlined file: ordinals.h ***/
  86408. #ifndef FLAC__ORDINALS_H
  86409. #define FLAC__ORDINALS_H
  86410. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86411. #include <inttypes.h>
  86412. #endif
  86413. typedef signed char FLAC__int8;
  86414. typedef unsigned char FLAC__uint8;
  86415. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86416. typedef __int16 FLAC__int16;
  86417. typedef __int32 FLAC__int32;
  86418. typedef __int64 FLAC__int64;
  86419. typedef unsigned __int16 FLAC__uint16;
  86420. typedef unsigned __int32 FLAC__uint32;
  86421. typedef unsigned __int64 FLAC__uint64;
  86422. #elif defined(__EMX__)
  86423. typedef short FLAC__int16;
  86424. typedef long FLAC__int32;
  86425. typedef long long FLAC__int64;
  86426. typedef unsigned short FLAC__uint16;
  86427. typedef unsigned long FLAC__uint32;
  86428. typedef unsigned long long FLAC__uint64;
  86429. #else
  86430. typedef int16_t FLAC__int16;
  86431. typedef int32_t FLAC__int32;
  86432. typedef int64_t FLAC__int64;
  86433. typedef uint16_t FLAC__uint16;
  86434. typedef uint32_t FLAC__uint32;
  86435. typedef uint64_t FLAC__uint64;
  86436. #endif
  86437. typedef int FLAC__bool;
  86438. typedef FLAC__uint8 FLAC__byte;
  86439. #ifdef true
  86440. #undef true
  86441. #endif
  86442. #ifdef false
  86443. #undef false
  86444. #endif
  86445. #ifndef __cplusplus
  86446. #define true 1
  86447. #define false 0
  86448. #endif
  86449. #endif
  86450. /*** End of inlined file: ordinals.h ***/
  86451. #include <stdlib.h> /* for size_t */
  86452. /** \file include/FLAC/callback.h
  86453. *
  86454. * \brief
  86455. * This module defines the structures for describing I/O callbacks
  86456. * to the other FLAC interfaces.
  86457. *
  86458. * See the detailed documentation for callbacks in the
  86459. * \link flac_callbacks callbacks \endlink module.
  86460. */
  86461. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86462. * \ingroup flac
  86463. *
  86464. * \brief
  86465. * This module defines the structures for describing I/O callbacks
  86466. * to the other FLAC interfaces.
  86467. *
  86468. * The purpose of the I/O callback functions is to create a common way
  86469. * for the metadata interfaces to handle I/O.
  86470. *
  86471. * Originally the metadata interfaces required filenames as the way of
  86472. * specifying FLAC files to operate on. This is problematic in some
  86473. * environments so there is an additional option to specify a set of
  86474. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86475. *
  86476. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86477. * opaque structure for a data source.
  86478. *
  86479. * The callback function prototypes are similar (but not identical) to the
  86480. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86481. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86482. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86483. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86484. * is required. \warning You generally CANNOT directly use fseek or ftell
  86485. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86486. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86487. * large files. You will have to find an equivalent function (e.g. ftello),
  86488. * or write a wrapper. The same is true for feof() since this is usually
  86489. * implemented as a macro, not as a function whose address can be taken.
  86490. *
  86491. * \{
  86492. */
  86493. #ifdef __cplusplus
  86494. extern "C" {
  86495. #endif
  86496. /** This is the opaque handle type used by the callbacks. Typically
  86497. * this is a \c FILE* or address of a file descriptor.
  86498. */
  86499. typedef void* FLAC__IOHandle;
  86500. /** Signature for the read callback.
  86501. * The signature and semantics match POSIX fread() implementations
  86502. * and can generally be used interchangeably.
  86503. *
  86504. * \param ptr The address of the read buffer.
  86505. * \param size The size of the records to be read.
  86506. * \param nmemb The number of records to be read.
  86507. * \param handle The handle to the data source.
  86508. * \retval size_t
  86509. * The number of records read.
  86510. */
  86511. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86512. /** Signature for the write callback.
  86513. * The signature and semantics match POSIX fwrite() implementations
  86514. * and can generally be used interchangeably.
  86515. *
  86516. * \param ptr The address of the write buffer.
  86517. * \param size The size of the records to be written.
  86518. * \param nmemb The number of records to be written.
  86519. * \param handle The handle to the data source.
  86520. * \retval size_t
  86521. * The number of records written.
  86522. */
  86523. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86524. /** Signature for the seek callback.
  86525. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86526. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86527. * and 32-bits wide.
  86528. *
  86529. * \param handle The handle to the data source.
  86530. * \param offset The new position, relative to \a whence
  86531. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86532. * \retval int
  86533. * \c 0 on success, \c -1 on error.
  86534. */
  86535. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86536. /** Signature for the tell callback.
  86537. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86538. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86539. * and 32-bits wide.
  86540. *
  86541. * \param handle The handle to the data source.
  86542. * \retval FLAC__int64
  86543. * The current position on success, \c -1 on error.
  86544. */
  86545. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86546. /** Signature for the EOF callback.
  86547. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86548. * on many systems, feof() is a macro, so in this case a wrapper function
  86549. * must be provided instead.
  86550. *
  86551. * \param handle The handle to the data source.
  86552. * \retval int
  86553. * \c 0 if not at end of file, nonzero if at end of file.
  86554. */
  86555. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86556. /** Signature for the close callback.
  86557. * The signature and semantics match POSIX fclose() implementations
  86558. * and can generally be used interchangeably.
  86559. *
  86560. * \param handle The handle to the data source.
  86561. * \retval int
  86562. * \c 0 on success, \c EOF on error.
  86563. */
  86564. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86565. /** A structure for holding a set of callbacks.
  86566. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86567. * describe which of the callbacks are required. The ones that are not
  86568. * required may be set to NULL.
  86569. *
  86570. * If the seek requirement for an interface is optional, you can signify that
  86571. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86572. */
  86573. typedef struct {
  86574. FLAC__IOCallback_Read read;
  86575. FLAC__IOCallback_Write write;
  86576. FLAC__IOCallback_Seek seek;
  86577. FLAC__IOCallback_Tell tell;
  86578. FLAC__IOCallback_Eof eof;
  86579. FLAC__IOCallback_Close close;
  86580. } FLAC__IOCallbacks;
  86581. /* \} */
  86582. #ifdef __cplusplus
  86583. }
  86584. #endif
  86585. #endif
  86586. /*** End of inlined file: callback.h ***/
  86587. /*** Start of inlined file: format.h ***/
  86588. #ifndef FLAC__FORMAT_H
  86589. #define FLAC__FORMAT_H
  86590. #ifdef __cplusplus
  86591. extern "C" {
  86592. #endif
  86593. /** \file include/FLAC/format.h
  86594. *
  86595. * \brief
  86596. * This module contains structure definitions for the representation
  86597. * of FLAC format components in memory. These are the basic
  86598. * structures used by the rest of the interfaces.
  86599. *
  86600. * See the detailed documentation in the
  86601. * \link flac_format format \endlink module.
  86602. */
  86603. /** \defgroup flac_format FLAC/format.h: format components
  86604. * \ingroup flac
  86605. *
  86606. * \brief
  86607. * This module contains structure definitions for the representation
  86608. * of FLAC format components in memory. These are the basic
  86609. * structures used by the rest of the interfaces.
  86610. *
  86611. * First, you should be familiar with the
  86612. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86613. * follow directly from the specification. As a user of libFLAC, the
  86614. * interesting parts really are the structures that describe the frame
  86615. * header and metadata blocks.
  86616. *
  86617. * The format structures here are very primitive, designed to store
  86618. * information in an efficient way. Reading information from the
  86619. * structures is easy but creating or modifying them directly is
  86620. * more complex. For the most part, as a user of a library, editing
  86621. * is not necessary; however, for metadata blocks it is, so there are
  86622. * convenience functions provided in the \link flac_metadata metadata
  86623. * module \endlink to simplify the manipulation of metadata blocks.
  86624. *
  86625. * \note
  86626. * It's not the best convention, but symbols ending in _LEN are in bits
  86627. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86628. * global variables because they are usually used when declaring byte
  86629. * arrays and some compilers require compile-time knowledge of array
  86630. * sizes when declared on the stack.
  86631. *
  86632. * \{
  86633. */
  86634. /*
  86635. Most of the values described in this file are defined by the FLAC
  86636. format specification. There is nothing to tune here.
  86637. */
  86638. /** The largest legal metadata type code. */
  86639. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86640. /** The minimum block size, in samples, permitted by the format. */
  86641. #define FLAC__MIN_BLOCK_SIZE (16u)
  86642. /** The maximum block size, in samples, permitted by the format. */
  86643. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86644. /** The maximum block size, in samples, permitted by the FLAC subset for
  86645. * sample rates up to 48kHz. */
  86646. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86647. /** The maximum number of channels permitted by the format. */
  86648. #define FLAC__MAX_CHANNELS (8u)
  86649. /** The minimum sample resolution permitted by the format. */
  86650. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86651. /** The maximum sample resolution permitted by the format. */
  86652. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86653. /** The maximum sample resolution permitted by libFLAC.
  86654. *
  86655. * \warning
  86656. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86657. * the reference encoder/decoder is currently limited to 24 bits because
  86658. * of prevalent 32-bit math, so make sure and use this value when
  86659. * appropriate.
  86660. */
  86661. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86662. /** The maximum sample rate permitted by the format. The value is
  86663. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86664. * as to why.
  86665. */
  86666. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86667. /** The maximum LPC order permitted by the format. */
  86668. #define FLAC__MAX_LPC_ORDER (32u)
  86669. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86670. * up to 48kHz. */
  86671. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86672. /** The minimum quantized linear predictor coefficient precision
  86673. * permitted by the format.
  86674. */
  86675. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86676. /** The maximum quantized linear predictor coefficient precision
  86677. * permitted by the format.
  86678. */
  86679. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86680. /** The maximum order of the fixed predictors permitted by the format. */
  86681. #define FLAC__MAX_FIXED_ORDER (4u)
  86682. /** The maximum Rice partition order permitted by the format. */
  86683. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86684. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86685. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86686. /** The version string of the release, stamped onto the libraries and binaries.
  86687. *
  86688. * \note
  86689. * This does not correspond to the shared library version number, which
  86690. * is used to determine binary compatibility.
  86691. */
  86692. extern FLAC_API const char *FLAC__VERSION_STRING;
  86693. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86694. * This is a NUL-terminated ASCII string; when inserted into the
  86695. * VORBIS_COMMENT the trailing null is stripped.
  86696. */
  86697. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86698. /** The byte string representation of the beginning of a FLAC stream. */
  86699. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86700. /** The 32-bit integer big-endian representation of the beginning of
  86701. * a FLAC stream.
  86702. */
  86703. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86704. /** The length of the FLAC signature in bits. */
  86705. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86706. /** The length of the FLAC signature in bytes. */
  86707. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86708. /*****************************************************************************
  86709. *
  86710. * Subframe structures
  86711. *
  86712. *****************************************************************************/
  86713. /*****************************************************************************/
  86714. /** An enumeration of the available entropy coding methods. */
  86715. typedef enum {
  86716. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86717. /**< Residual is coded by partitioning into contexts, each with it's own
  86718. * 4-bit Rice parameter. */
  86719. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86720. /**< Residual is coded by partitioning into contexts, each with it's own
  86721. * 5-bit Rice parameter. */
  86722. } FLAC__EntropyCodingMethodType;
  86723. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86724. *
  86725. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86726. * give the string equivalent. The contents should not be modified.
  86727. */
  86728. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86729. /** Contents of a Rice partitioned residual
  86730. */
  86731. typedef struct {
  86732. unsigned *parameters;
  86733. /**< The Rice parameters for each context. */
  86734. unsigned *raw_bits;
  86735. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86736. * partitions and zero for unescaped partitions.
  86737. */
  86738. unsigned capacity_by_order;
  86739. /**< The capacity of the \a parameters and \a raw_bits arrays
  86740. * specified as an order, i.e. the number of array elements
  86741. * allocated is 2 ^ \a capacity_by_order.
  86742. */
  86743. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86744. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86745. */
  86746. typedef struct {
  86747. unsigned order;
  86748. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86749. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86750. /**< The context's Rice parameters and/or raw bits. */
  86751. } FLAC__EntropyCodingMethod_PartitionedRice;
  86752. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86753. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86754. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86755. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86756. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86757. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86758. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86759. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86760. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86761. */
  86762. typedef struct {
  86763. FLAC__EntropyCodingMethodType type;
  86764. union {
  86765. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86766. } data;
  86767. } FLAC__EntropyCodingMethod;
  86768. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86769. /*****************************************************************************/
  86770. /** An enumeration of the available subframe types. */
  86771. typedef enum {
  86772. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86773. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86774. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86775. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86776. } FLAC__SubframeType;
  86777. /** Maps a FLAC__SubframeType to a C string.
  86778. *
  86779. * Using a FLAC__SubframeType as the index to this array will
  86780. * give the string equivalent. The contents should not be modified.
  86781. */
  86782. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86783. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86784. */
  86785. typedef struct {
  86786. FLAC__int32 value; /**< The constant signal value. */
  86787. } FLAC__Subframe_Constant;
  86788. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86789. */
  86790. typedef struct {
  86791. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86792. } FLAC__Subframe_Verbatim;
  86793. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86794. */
  86795. typedef struct {
  86796. FLAC__EntropyCodingMethod entropy_coding_method;
  86797. /**< The residual coding method. */
  86798. unsigned order;
  86799. /**< The polynomial order. */
  86800. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86801. /**< Warmup samples to prime the predictor, length == order. */
  86802. const FLAC__int32 *residual;
  86803. /**< The residual signal, length == (blocksize minus order) samples. */
  86804. } FLAC__Subframe_Fixed;
  86805. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86806. */
  86807. typedef struct {
  86808. FLAC__EntropyCodingMethod entropy_coding_method;
  86809. /**< The residual coding method. */
  86810. unsigned order;
  86811. /**< The FIR order. */
  86812. unsigned qlp_coeff_precision;
  86813. /**< Quantized FIR filter coefficient precision in bits. */
  86814. int quantization_level;
  86815. /**< The qlp coeff shift needed. */
  86816. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86817. /**< FIR filter coefficients. */
  86818. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86819. /**< Warmup samples to prime the predictor, length == order. */
  86820. const FLAC__int32 *residual;
  86821. /**< The residual signal, length == (blocksize minus order) samples. */
  86822. } FLAC__Subframe_LPC;
  86823. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86824. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86825. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86826. */
  86827. typedef struct {
  86828. FLAC__SubframeType type;
  86829. union {
  86830. FLAC__Subframe_Constant constant;
  86831. FLAC__Subframe_Fixed fixed;
  86832. FLAC__Subframe_LPC lpc;
  86833. FLAC__Subframe_Verbatim verbatim;
  86834. } data;
  86835. unsigned wasted_bits;
  86836. } FLAC__Subframe;
  86837. /** == 1 (bit)
  86838. *
  86839. * This used to be a zero-padding bit (hence the name
  86840. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86841. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86842. * to mean something else.
  86843. */
  86844. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86845. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86846. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86847. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86848. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86849. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86850. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86851. /*****************************************************************************/
  86852. /*****************************************************************************
  86853. *
  86854. * Frame structures
  86855. *
  86856. *****************************************************************************/
  86857. /** An enumeration of the available channel assignments. */
  86858. typedef enum {
  86859. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86860. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86861. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86862. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86863. } FLAC__ChannelAssignment;
  86864. /** Maps a FLAC__ChannelAssignment to a C string.
  86865. *
  86866. * Using a FLAC__ChannelAssignment as the index to this array will
  86867. * give the string equivalent. The contents should not be modified.
  86868. */
  86869. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86870. /** An enumeration of the possible frame numbering methods. */
  86871. typedef enum {
  86872. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86873. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86874. } FLAC__FrameNumberType;
  86875. /** Maps a FLAC__FrameNumberType to a C string.
  86876. *
  86877. * Using a FLAC__FrameNumberType as the index to this array will
  86878. * give the string equivalent. The contents should not be modified.
  86879. */
  86880. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86881. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86882. */
  86883. typedef struct {
  86884. unsigned blocksize;
  86885. /**< The number of samples per subframe. */
  86886. unsigned sample_rate;
  86887. /**< The sample rate in Hz. */
  86888. unsigned channels;
  86889. /**< The number of channels (== number of subframes). */
  86890. FLAC__ChannelAssignment channel_assignment;
  86891. /**< The channel assignment for the frame. */
  86892. unsigned bits_per_sample;
  86893. /**< The sample resolution. */
  86894. FLAC__FrameNumberType number_type;
  86895. /**< The numbering scheme used for the frame. As a convenience, the
  86896. * decoder will always convert a frame number to a sample number because
  86897. * the rules are complex. */
  86898. union {
  86899. FLAC__uint32 frame_number;
  86900. FLAC__uint64 sample_number;
  86901. } number;
  86902. /**< The frame number or sample number of first sample in frame;
  86903. * use the \a number_type value to determine which to use. */
  86904. FLAC__uint8 crc;
  86905. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86906. * of the raw frame header bytes, meaning everything before the CRC byte
  86907. * including the sync code.
  86908. */
  86909. } FLAC__FrameHeader;
  86910. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86911. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86912. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86913. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86914. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86915. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86916. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86917. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86918. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86919. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86920. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86921. */
  86922. typedef struct {
  86923. FLAC__uint16 crc;
  86924. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86925. * 0) of the bytes before the crc, back to and including the frame header
  86926. * sync code.
  86927. */
  86928. } FLAC__FrameFooter;
  86929. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86930. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86931. */
  86932. typedef struct {
  86933. FLAC__FrameHeader header;
  86934. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86935. FLAC__FrameFooter footer;
  86936. } FLAC__Frame;
  86937. /*****************************************************************************/
  86938. /*****************************************************************************
  86939. *
  86940. * Meta-data structures
  86941. *
  86942. *****************************************************************************/
  86943. /** An enumeration of the available metadata block types. */
  86944. typedef enum {
  86945. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86946. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86947. FLAC__METADATA_TYPE_PADDING = 1,
  86948. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86949. FLAC__METADATA_TYPE_APPLICATION = 2,
  86950. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86951. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86952. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86953. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86954. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86955. FLAC__METADATA_TYPE_CUESHEET = 5,
  86956. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86957. FLAC__METADATA_TYPE_PICTURE = 6,
  86958. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86959. FLAC__METADATA_TYPE_UNDEFINED = 7
  86960. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86961. } FLAC__MetadataType;
  86962. /** Maps a FLAC__MetadataType to a C string.
  86963. *
  86964. * Using a FLAC__MetadataType as the index to this array will
  86965. * give the string equivalent. The contents should not be modified.
  86966. */
  86967. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86968. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86969. */
  86970. typedef struct {
  86971. unsigned min_blocksize, max_blocksize;
  86972. unsigned min_framesize, max_framesize;
  86973. unsigned sample_rate;
  86974. unsigned channels;
  86975. unsigned bits_per_sample;
  86976. FLAC__uint64 total_samples;
  86977. FLAC__byte md5sum[16];
  86978. } FLAC__StreamMetadata_StreamInfo;
  86979. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86980. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86981. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86982. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86983. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86984. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86985. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86986. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86987. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86988. /** The total stream length of the STREAMINFO block in bytes. */
  86989. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86990. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86991. */
  86992. typedef struct {
  86993. int dummy;
  86994. /**< Conceptually this is an empty struct since we don't store the
  86995. * padding bytes. Empty structs are not allowed by some C compilers,
  86996. * hence the dummy.
  86997. */
  86998. } FLAC__StreamMetadata_Padding;
  86999. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87000. */
  87001. typedef struct {
  87002. FLAC__byte id[4];
  87003. FLAC__byte *data;
  87004. } FLAC__StreamMetadata_Application;
  87005. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87006. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87007. */
  87008. typedef struct {
  87009. FLAC__uint64 sample_number;
  87010. /**< The sample number of the target frame. */
  87011. FLAC__uint64 stream_offset;
  87012. /**< The offset, in bytes, of the target frame with respect to
  87013. * beginning of the first frame. */
  87014. unsigned frame_samples;
  87015. /**< The number of samples in the target frame. */
  87016. } FLAC__StreamMetadata_SeekPoint;
  87017. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87018. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87019. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87020. /** The total stream length of a seek point in bytes. */
  87021. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87022. /** The value used in the \a sample_number field of
  87023. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87024. * point (== 0xffffffffffffffff).
  87025. */
  87026. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87027. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87028. *
  87029. * \note From the format specification:
  87030. * - The seek points must be sorted by ascending sample number.
  87031. * - Each seek point's sample number must be the first sample of the
  87032. * target frame.
  87033. * - Each seek point's sample number must be unique within the table.
  87034. * - Existence of a SEEKTABLE block implies a correct setting of
  87035. * total_samples in the stream_info block.
  87036. * - Behavior is undefined when more than one SEEKTABLE block is
  87037. * present in a stream.
  87038. */
  87039. typedef struct {
  87040. unsigned num_points;
  87041. FLAC__StreamMetadata_SeekPoint *points;
  87042. } FLAC__StreamMetadata_SeekTable;
  87043. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87044. *
  87045. * For convenience, the APIs maintain a trailing NUL character at the end of
  87046. * \a entry which is not counted toward \a length, i.e.
  87047. * \code strlen(entry) == length \endcode
  87048. */
  87049. typedef struct {
  87050. FLAC__uint32 length;
  87051. FLAC__byte *entry;
  87052. } FLAC__StreamMetadata_VorbisComment_Entry;
  87053. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87054. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87055. */
  87056. typedef struct {
  87057. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87058. FLAC__uint32 num_comments;
  87059. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87060. } FLAC__StreamMetadata_VorbisComment;
  87061. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87062. /** FLAC CUESHEET track index structure. (See the
  87063. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87064. * the full description of each field.)
  87065. */
  87066. typedef struct {
  87067. FLAC__uint64 offset;
  87068. /**< Offset in samples, relative to the track offset, of the index
  87069. * point.
  87070. */
  87071. FLAC__byte number;
  87072. /**< The index point number. */
  87073. } FLAC__StreamMetadata_CueSheet_Index;
  87074. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87075. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87076. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87077. /** FLAC CUESHEET track structure. (See the
  87078. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87079. * the full description of each field.)
  87080. */
  87081. typedef struct {
  87082. FLAC__uint64 offset;
  87083. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87084. FLAC__byte number;
  87085. /**< The track number. */
  87086. char isrc[13];
  87087. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87088. unsigned type:1;
  87089. /**< The track type: 0 for audio, 1 for non-audio. */
  87090. unsigned pre_emphasis:1;
  87091. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87092. FLAC__byte num_indices;
  87093. /**< The number of track index points. */
  87094. FLAC__StreamMetadata_CueSheet_Index *indices;
  87095. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87096. } FLAC__StreamMetadata_CueSheet_Track;
  87097. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87101. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87102. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87104. /** FLAC CUESHEET structure. (See the
  87105. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87106. * for the full description of each field.)
  87107. */
  87108. typedef struct {
  87109. char media_catalog_number[129];
  87110. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87111. * general, the media catalog number may be 0 to 128 bytes long; any
  87112. * unused characters should be right-padded with NUL characters.
  87113. */
  87114. FLAC__uint64 lead_in;
  87115. /**< The number of lead-in samples. */
  87116. FLAC__bool is_cd;
  87117. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87118. unsigned num_tracks;
  87119. /**< The number of tracks. */
  87120. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87121. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87122. } FLAC__StreamMetadata_CueSheet;
  87123. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87124. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87125. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87126. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87127. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87128. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87129. typedef enum {
  87130. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87131. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87132. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87133. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87134. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87135. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87136. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87137. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87138. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87139. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87140. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87141. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87142. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87143. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87144. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87145. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87146. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87147. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87148. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87149. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87150. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87151. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87152. } FLAC__StreamMetadata_Picture_Type;
  87153. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87154. *
  87155. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87156. * will give the string equivalent. The contents should not be
  87157. * modified.
  87158. */
  87159. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87160. /** FLAC PICTURE structure. (See the
  87161. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87162. * for the full description of each field.)
  87163. */
  87164. typedef struct {
  87165. FLAC__StreamMetadata_Picture_Type type;
  87166. /**< The kind of picture stored. */
  87167. char *mime_type;
  87168. /**< Picture data's MIME type, in ASCII printable characters
  87169. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87170. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87171. * MIME type of '-->' is also allowed, in which case the picture
  87172. * data should be a complete URL. In file storage, the MIME type is
  87173. * stored as a 32-bit length followed by the ASCII string with no NUL
  87174. * terminator, but is converted to a plain C string in this structure
  87175. * for convenience.
  87176. */
  87177. FLAC__byte *description;
  87178. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87179. * the description is stored as a 32-bit length followed by the UTF-8
  87180. * string with no NUL terminator, but is converted to a plain C string
  87181. * in this structure for convenience.
  87182. */
  87183. FLAC__uint32 width;
  87184. /**< Picture's width in pixels. */
  87185. FLAC__uint32 height;
  87186. /**< Picture's height in pixels. */
  87187. FLAC__uint32 depth;
  87188. /**< Picture's color depth in bits-per-pixel. */
  87189. FLAC__uint32 colors;
  87190. /**< For indexed palettes (like GIF), picture's number of colors (the
  87191. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87192. */
  87193. FLAC__uint32 data_length;
  87194. /**< Length of binary picture data in bytes. */
  87195. FLAC__byte *data;
  87196. /**< Binary picture data. */
  87197. } FLAC__StreamMetadata_Picture;
  87198. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87199. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87200. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87201. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87202. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87203. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87204. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87205. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87206. /** Structure that is used when a metadata block of unknown type is loaded.
  87207. * The contents are opaque. The structure is used only internally to
  87208. * correctly handle unknown metadata.
  87209. */
  87210. typedef struct {
  87211. FLAC__byte *data;
  87212. } FLAC__StreamMetadata_Unknown;
  87213. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87214. */
  87215. typedef struct {
  87216. FLAC__MetadataType type;
  87217. /**< The type of the metadata block; used determine which member of the
  87218. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87219. * then \a data.unknown must be used. */
  87220. FLAC__bool is_last;
  87221. /**< \c true if this metadata block is the last, else \a false */
  87222. unsigned length;
  87223. /**< Length, in bytes, of the block data as it appears in the stream. */
  87224. union {
  87225. FLAC__StreamMetadata_StreamInfo stream_info;
  87226. FLAC__StreamMetadata_Padding padding;
  87227. FLAC__StreamMetadata_Application application;
  87228. FLAC__StreamMetadata_SeekTable seek_table;
  87229. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87230. FLAC__StreamMetadata_CueSheet cue_sheet;
  87231. FLAC__StreamMetadata_Picture picture;
  87232. FLAC__StreamMetadata_Unknown unknown;
  87233. } data;
  87234. /**< Polymorphic block data; use the \a type value to determine which
  87235. * to use. */
  87236. } FLAC__StreamMetadata;
  87237. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87238. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87239. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87240. /** The total stream length of a metadata block header in bytes. */
  87241. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87242. /*****************************************************************************/
  87243. /*****************************************************************************
  87244. *
  87245. * Utility functions
  87246. *
  87247. *****************************************************************************/
  87248. /** Tests that a sample rate is valid for FLAC.
  87249. *
  87250. * \param sample_rate The sample rate to test for compliance.
  87251. * \retval FLAC__bool
  87252. * \c true if the given sample rate conforms to the specification, else
  87253. * \c false.
  87254. */
  87255. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87256. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87257. * for valid sample rates are slightly more complex since the rate has to
  87258. * be expressible completely in the frame header.
  87259. *
  87260. * \param sample_rate The sample rate to test for compliance.
  87261. * \retval FLAC__bool
  87262. * \c true if the given sample rate conforms to the specification for the
  87263. * subset, else \c false.
  87264. */
  87265. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87266. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87267. * comment specification.
  87268. *
  87269. * Vorbis comment names must be composed only of characters from
  87270. * [0x20-0x3C,0x3E-0x7D].
  87271. *
  87272. * \param name A NUL-terminated string to be checked.
  87273. * \assert
  87274. * \code name != NULL \endcode
  87275. * \retval FLAC__bool
  87276. * \c false if entry name is illegal, else \c true.
  87277. */
  87278. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87279. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87280. * comment specification.
  87281. *
  87282. * Vorbis comment values must be valid UTF-8 sequences.
  87283. *
  87284. * \param value A string to be checked.
  87285. * \param length A the length of \a value in bytes. May be
  87286. * \c (unsigned)(-1) to indicate that \a value is a plain
  87287. * UTF-8 NUL-terminated string.
  87288. * \assert
  87289. * \code value != NULL \endcode
  87290. * \retval FLAC__bool
  87291. * \c false if entry name is illegal, else \c true.
  87292. */
  87293. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87294. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87295. * comment specification.
  87296. *
  87297. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87298. * 'value' must be legal according to
  87299. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87300. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87301. *
  87302. * \param entry An entry to be checked.
  87303. * \param length The length of \a entry in bytes.
  87304. * \assert
  87305. * \code value != NULL \endcode
  87306. * \retval FLAC__bool
  87307. * \c false if entry name is illegal, else \c true.
  87308. */
  87309. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87310. /** Check a seek table to see if it conforms to the FLAC specification.
  87311. * See the format specification for limits on the contents of the
  87312. * seek table.
  87313. *
  87314. * \param seek_table A pointer to a seek table to be checked.
  87315. * \assert
  87316. * \code seek_table != NULL \endcode
  87317. * \retval FLAC__bool
  87318. * \c false if seek table is illegal, else \c true.
  87319. */
  87320. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87321. /** Sort a seek table's seek points according to the format specification.
  87322. * This includes a "unique-ification" step to remove duplicates, i.e.
  87323. * seek points with identical \a sample_number values. Duplicate seek
  87324. * points are converted into placeholder points and sorted to the end of
  87325. * the table.
  87326. *
  87327. * \param seek_table A pointer to a seek table to be sorted.
  87328. * \assert
  87329. * \code seek_table != NULL \endcode
  87330. * \retval unsigned
  87331. * The number of duplicate seek points converted into placeholders.
  87332. */
  87333. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87334. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87335. * See the format specification for limits on the contents of the
  87336. * cue sheet.
  87337. *
  87338. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87339. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87340. * stringent requirements for a CD-DA (audio) disc.
  87341. * \param violation Address of a pointer to a string. If there is a
  87342. * violation, a pointer to a string explanation of the
  87343. * violation will be returned here. \a violation may be
  87344. * \c NULL if you don't need the returned string. Do not
  87345. * free the returned string; it will always point to static
  87346. * data.
  87347. * \assert
  87348. * \code cue_sheet != NULL \endcode
  87349. * \retval FLAC__bool
  87350. * \c false if cue sheet is illegal, else \c true.
  87351. */
  87352. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87353. /** Check picture data to see if it conforms to the FLAC specification.
  87354. * See the format specification for limits on the contents of the
  87355. * PICTURE block.
  87356. *
  87357. * \param picture A pointer to existing picture data to be checked.
  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 picture != NULL \endcode
  87366. * \retval FLAC__bool
  87367. * \c false if picture data is illegal, else \c true.
  87368. */
  87369. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87370. /* \} */
  87371. #ifdef __cplusplus
  87372. }
  87373. #endif
  87374. #endif
  87375. /*** End of inlined file: format.h ***/
  87376. /*** Start of inlined file: metadata.h ***/
  87377. #ifndef FLAC__METADATA_H
  87378. #define FLAC__METADATA_H
  87379. #include <sys/types.h> /* for off_t */
  87380. /* --------------------------------------------------------------------
  87381. (For an example of how all these routines are used, see the source
  87382. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87383. metaflac in src/metaflac/)
  87384. ------------------------------------------------------------------*/
  87385. /** \file include/FLAC/metadata.h
  87386. *
  87387. * \brief
  87388. * This module provides functions for creating and manipulating FLAC
  87389. * metadata blocks in memory, and three progressively more powerful
  87390. * interfaces for traversing and editing metadata in FLAC files.
  87391. *
  87392. * See the detailed documentation for each interface in the
  87393. * \link flac_metadata metadata \endlink module.
  87394. */
  87395. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87396. * \ingroup flac
  87397. *
  87398. * \brief
  87399. * This module provides functions for creating and manipulating FLAC
  87400. * metadata blocks in memory, and three progressively more powerful
  87401. * interfaces for traversing and editing metadata in native FLAC files.
  87402. * Note that currently only the Chain interface (level 2) supports Ogg
  87403. * FLAC files, and it is read-only i.e. no writing back changed
  87404. * metadata to file.
  87405. *
  87406. * There are three metadata interfaces of increasing complexity:
  87407. *
  87408. * Level 0:
  87409. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87410. * PICTURE blocks.
  87411. *
  87412. * Level 1:
  87413. * Read-write access to all metadata blocks. This level is write-
  87414. * efficient in most cases (more on this below), and uses less memory
  87415. * than level 2.
  87416. *
  87417. * Level 2:
  87418. * Read-write access to all metadata blocks. This level is write-
  87419. * efficient in all cases, but uses more memory since all metadata for
  87420. * the whole file is read into memory and manipulated before writing
  87421. * out again.
  87422. *
  87423. * What do we mean by efficient? Since FLAC metadata appears at the
  87424. * beginning of the file, when writing metadata back to a FLAC file
  87425. * it is possible to grow or shrink the metadata such that the entire
  87426. * file must be rewritten. However, if the size remains the same during
  87427. * changes or PADDING blocks are utilized, only the metadata needs to be
  87428. * overwritten, which is much faster.
  87429. *
  87430. * Efficient means the whole file is rewritten at most one time, and only
  87431. * when necessary. Level 1 is not efficient only in the case that you
  87432. * cause more than one metadata block to grow or shrink beyond what can
  87433. * be accomodated by padding. In this case you should probably use level
  87434. * 2, which allows you to edit all the metadata for a file in memory and
  87435. * write it out all at once.
  87436. *
  87437. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87438. * front of the file.
  87439. *
  87440. * All levels access files via their filenames. In addition, level 2
  87441. * has additional alternative read and write functions that take an I/O
  87442. * handle and callbacks, for situations where access by filename is not
  87443. * possible.
  87444. *
  87445. * In addition to the three interfaces, this module defines functions for
  87446. * creating and manipulating various metadata objects in memory. As we see
  87447. * from the Format module, FLAC metadata blocks in memory are very primitive
  87448. * structures for storing information in an efficient way. Reading
  87449. * information from the structures is easy but creating or modifying them
  87450. * directly is more complex. The metadata object routines here facilitate
  87451. * this by taking care of the consistency and memory management drudgery.
  87452. *
  87453. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87454. * metadata however, you will not probably not need these.
  87455. *
  87456. * From a dependency standpoint, none of the encoders or decoders require
  87457. * the metadata module. This is so that embedded users can strip out the
  87458. * metadata module from libFLAC to reduce the size and complexity.
  87459. */
  87460. #ifdef __cplusplus
  87461. extern "C" {
  87462. #endif
  87463. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87464. * \ingroup flac_metadata
  87465. *
  87466. * \brief
  87467. * The level 0 interface consists of individual routines to read the
  87468. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87469. * only a filename.
  87470. *
  87471. * They try to skip any ID3v2 tag at the head of the file.
  87472. *
  87473. * \{
  87474. */
  87475. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87476. * will try to skip any ID3v2 tag at the head of the file.
  87477. *
  87478. * \param filename The path to the FLAC file to read.
  87479. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87480. * FLAC__StreamMetadata is a simple structure with no
  87481. * memory allocation involved, you pass the address of
  87482. * an existing structure. It need not be initialized.
  87483. * \assert
  87484. * \code filename != NULL \endcode
  87485. * \code streaminfo != NULL \endcode
  87486. * \retval FLAC__bool
  87487. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87488. * \c false if there was a memory allocation error, a file decoder error,
  87489. * or the file contained no STREAMINFO block. (A memory allocation error
  87490. * is possible because this function must set up a file decoder.)
  87491. */
  87492. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87493. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87494. * function will try to skip any ID3v2 tag at the head of the file.
  87495. *
  87496. * \param filename The path to the FLAC file to read.
  87497. * \param tags The address where the returned pointer will be
  87498. * stored. The \a tags object must be deleted by
  87499. * the caller using FLAC__metadata_object_delete().
  87500. * \assert
  87501. * \code filename != NULL \endcode
  87502. * \code tags != NULL \endcode
  87503. * \retval FLAC__bool
  87504. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87505. * and \a *tags will be set to the address of the metadata structure.
  87506. * Returns \c false if there was a memory allocation error, a file
  87507. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87508. * \a *tags will be set to \c NULL.
  87509. */
  87510. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87511. /** Read the CUESHEET metadata block of the given FLAC file. This
  87512. * function will try to skip any ID3v2 tag at the head of the file.
  87513. *
  87514. * \param filename The path to the FLAC file to read.
  87515. * \param cuesheet The address where the returned pointer will be
  87516. * stored. The \a cuesheet object must be deleted by
  87517. * the caller using FLAC__metadata_object_delete().
  87518. * \assert
  87519. * \code filename != NULL \endcode
  87520. * \code cuesheet != NULL \endcode
  87521. * \retval FLAC__bool
  87522. * \c true if a valid CUESHEET block was read from \a filename,
  87523. * and \a *cuesheet will be set to the address of the metadata
  87524. * structure. Returns \c false if there was a memory allocation
  87525. * error, a file decoder error, or the file contained no CUESHEET
  87526. * block, and \a *cuesheet will be set to \c NULL.
  87527. */
  87528. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87529. /** Read a PICTURE metadata block of the given FLAC file. This
  87530. * function will try to skip any ID3v2 tag at the head of the file.
  87531. * Since there can be more than one PICTURE block in a file, this
  87532. * function takes a number of parameters that act as constraints to
  87533. * the search. The PICTURE block with the largest area matching all
  87534. * the constraints will be returned, or \a *picture will be set to
  87535. * \c NULL if there was no such block.
  87536. *
  87537. * \param filename The path to the FLAC file to read.
  87538. * \param picture The address where the returned pointer will be
  87539. * stored. The \a picture object must be deleted by
  87540. * the caller using FLAC__metadata_object_delete().
  87541. * \param type The desired picture type. Use \c -1 to mean
  87542. * "any type".
  87543. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87544. * string will be matched exactly. Use \c NULL to
  87545. * mean "any MIME type".
  87546. * \param description The desired description. The string will be
  87547. * matched exactly. Use \c NULL to mean "any
  87548. * description".
  87549. * \param max_width The maximum width in pixels desired. Use
  87550. * \c (unsigned)(-1) to mean "any width".
  87551. * \param max_height The maximum height in pixels desired. Use
  87552. * \c (unsigned)(-1) to mean "any height".
  87553. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87554. * Use \c (unsigned)(-1) to mean "any depth".
  87555. * \param max_colors The maximum number of colors desired. Use
  87556. * \c (unsigned)(-1) to mean "any number of colors".
  87557. * \assert
  87558. * \code filename != NULL \endcode
  87559. * \code picture != NULL \endcode
  87560. * \retval FLAC__bool
  87561. * \c true if a valid PICTURE block was read from \a filename,
  87562. * and \a *picture will be set to the address of the metadata
  87563. * structure. Returns \c false if there was a memory allocation
  87564. * error, a file decoder error, or the file contained no PICTURE
  87565. * block, and \a *picture will be set to \c NULL.
  87566. */
  87567. 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);
  87568. /* \} */
  87569. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87570. * \ingroup flac_metadata
  87571. *
  87572. * \brief
  87573. * The level 1 interface provides read-write access to FLAC file metadata and
  87574. * operates directly on the FLAC file.
  87575. *
  87576. * The general usage of this interface is:
  87577. *
  87578. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87579. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87580. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87581. * see if the file is writable, or only read access is allowed.
  87582. * - Use FLAC__metadata_simple_iterator_next() and
  87583. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87584. * This is does not read the actual blocks themselves.
  87585. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87586. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87587. * forward from the front of the file.
  87588. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87589. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87590. * the current iterator position. The returned object is yours to modify
  87591. * and free.
  87592. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87593. * back. You must have write permission to the original file. Make sure to
  87594. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87595. * below.
  87596. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87597. * Use the object creation functions from
  87598. * \link flac_metadata_object here \endlink to generate new objects.
  87599. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87600. * currently referred to by the iterator, or replace it with padding.
  87601. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87602. * finished.
  87603. *
  87604. * \note
  87605. * The FLAC file remains open the whole time between
  87606. * FLAC__metadata_simple_iterator_init() and
  87607. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87608. * the file during this time.
  87609. *
  87610. * \note
  87611. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87612. * FLAC__StreamMetadata objects. These are managed automatically.
  87613. *
  87614. * \note
  87615. * If any of the modification functions
  87616. * (FLAC__metadata_simple_iterator_set_block(),
  87617. * FLAC__metadata_simple_iterator_delete_block(),
  87618. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87619. * you should delete the iterator as it may no longer be valid.
  87620. *
  87621. * \{
  87622. */
  87623. struct FLAC__Metadata_SimpleIterator;
  87624. /** The opaque structure definition for the level 1 iterator type.
  87625. * See the
  87626. * \link flac_metadata_level1 metadata level 1 module \endlink
  87627. * for a detailed description.
  87628. */
  87629. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87630. /** Status type for FLAC__Metadata_SimpleIterator.
  87631. *
  87632. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87633. */
  87634. typedef enum {
  87635. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87636. /**< The iterator is in the normal OK state */
  87637. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87638. /**< The data passed into a function violated the function's usage criteria */
  87639. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87640. /**< The iterator could not open the target file */
  87641. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87642. /**< The iterator could not find the FLAC signature at the start of the file */
  87643. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87644. /**< The iterator tried to write to a file that was not writable */
  87645. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87646. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87647. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87648. /**< The iterator encountered an error while reading the FLAC file */
  87649. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87650. /**< The iterator encountered an error while seeking in the FLAC file */
  87651. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87652. /**< The iterator encountered an error while writing the FLAC file */
  87653. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87654. /**< The iterator encountered an error renaming the FLAC file */
  87655. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87656. /**< The iterator encountered an error removing the temporary file */
  87657. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87658. /**< Memory allocation failed */
  87659. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87660. /**< The caller violated an assertion or an unexpected error occurred */
  87661. } FLAC__Metadata_SimpleIteratorStatus;
  87662. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87663. *
  87664. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87665. * will give the string equivalent. The contents should not be modified.
  87666. */
  87667. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87668. /** Create a new iterator instance.
  87669. *
  87670. * \retval FLAC__Metadata_SimpleIterator*
  87671. * \c NULL if there was an error allocating memory, else the new instance.
  87672. */
  87673. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87674. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87675. *
  87676. * \param iterator A pointer to an existing iterator.
  87677. * \assert
  87678. * \code iterator != NULL \endcode
  87679. */
  87680. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87681. /** Get the current status of the iterator. Call this after a function
  87682. * returns \c false to get the reason for the error. Also resets the status
  87683. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87684. *
  87685. * \param iterator A pointer to an existing iterator.
  87686. * \assert
  87687. * \code iterator != NULL \endcode
  87688. * \retval FLAC__Metadata_SimpleIteratorStatus
  87689. * The current status of the iterator.
  87690. */
  87691. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87692. /** Initialize the iterator to point to the first metadata block in the
  87693. * given FLAC file.
  87694. *
  87695. * \param iterator A pointer to an existing iterator.
  87696. * \param filename The path to the FLAC file.
  87697. * \param read_only If \c true, the FLAC file will be opened
  87698. * in read-only mode; if \c false, the FLAC
  87699. * file will be opened for edit even if no
  87700. * edits are performed.
  87701. * \param preserve_file_stats If \c true, the owner and modification
  87702. * time will be preserved even if the FLAC
  87703. * file is written to.
  87704. * \assert
  87705. * \code iterator != NULL \endcode
  87706. * \code filename != NULL \endcode
  87707. * \retval FLAC__bool
  87708. * \c false if a memory allocation error occurs, the file can't be
  87709. * opened, or another error occurs, else \c true.
  87710. */
  87711. 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);
  87712. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87713. * FLAC__metadata_simple_iterator_set_block() and
  87714. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87715. *
  87716. * \param iterator A pointer to an existing iterator.
  87717. * \assert
  87718. * \code iterator != NULL \endcode
  87719. * \retval FLAC__bool
  87720. * See above.
  87721. */
  87722. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87723. /** Moves the iterator forward one metadata block, returning \c false if
  87724. * already at the end.
  87725. *
  87726. * \param iterator A pointer to an existing initialized iterator.
  87727. * \assert
  87728. * \code iterator != NULL \endcode
  87729. * \a iterator has been successfully initialized with
  87730. * FLAC__metadata_simple_iterator_init()
  87731. * \retval FLAC__bool
  87732. * \c false if already at the last metadata block of the chain, else
  87733. * \c true.
  87734. */
  87735. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87736. /** Moves the iterator backward one metadata block, returning \c false if
  87737. * already at the beginning.
  87738. *
  87739. * \param iterator A pointer to an existing initialized iterator.
  87740. * \assert
  87741. * \code iterator != NULL \endcode
  87742. * \a iterator has been successfully initialized with
  87743. * FLAC__metadata_simple_iterator_init()
  87744. * \retval FLAC__bool
  87745. * \c false if already at the first metadata block of the chain, else
  87746. * \c true.
  87747. */
  87748. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87749. /** Returns a flag telling if the current metadata block is the last.
  87750. *
  87751. * \param iterator A pointer to an existing initialized iterator.
  87752. * \assert
  87753. * \code iterator != NULL \endcode
  87754. * \a iterator has been successfully initialized with
  87755. * FLAC__metadata_simple_iterator_init()
  87756. * \retval FLAC__bool
  87757. * \c true if the current metadata block is the last in the file,
  87758. * else \c false.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87761. /** Get the offset of the metadata block at the current position. This
  87762. * avoids reading the actual block data which can save time for large
  87763. * blocks.
  87764. *
  87765. * \param iterator A pointer to an existing initialized iterator.
  87766. * \assert
  87767. * \code iterator != NULL \endcode
  87768. * \a iterator has been successfully initialized with
  87769. * FLAC__metadata_simple_iterator_init()
  87770. * \retval off_t
  87771. * The offset of the metadata block at the current iterator position.
  87772. * This is the byte offset relative to the beginning of the file of
  87773. * the current metadata block's header.
  87774. */
  87775. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87776. /** Get the type of the metadata block at the current position. This
  87777. * avoids reading the actual block data which can save time for large
  87778. * blocks.
  87779. *
  87780. * \param iterator A pointer to an existing initialized iterator.
  87781. * \assert
  87782. * \code iterator != NULL \endcode
  87783. * \a iterator has been successfully initialized with
  87784. * FLAC__metadata_simple_iterator_init()
  87785. * \retval FLAC__MetadataType
  87786. * The type of the metadata block at the current iterator position.
  87787. */
  87788. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87789. /** Get the length of the metadata block at the current position. This
  87790. * avoids reading the actual block data which can save time for large
  87791. * blocks.
  87792. *
  87793. * \param iterator A pointer to an existing initialized iterator.
  87794. * \assert
  87795. * \code iterator != NULL \endcode
  87796. * \a iterator has been successfully initialized with
  87797. * FLAC__metadata_simple_iterator_init()
  87798. * \retval unsigned
  87799. * The length of the metadata block at the current iterator position.
  87800. * The is same length as that in the
  87801. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87802. * i.e. the length of the metadata body that follows the header.
  87803. */
  87804. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87805. /** Get the application ID of the \c APPLICATION block at the current
  87806. * position. This avoids reading the actual block data which can save
  87807. * time for large blocks.
  87808. *
  87809. * \param iterator A pointer to an existing initialized iterator.
  87810. * \param id A pointer to a buffer of at least \c 4 bytes where
  87811. * the ID will be stored.
  87812. * \assert
  87813. * \code iterator != NULL \endcode
  87814. * \code id != NULL \endcode
  87815. * \a iterator has been successfully initialized with
  87816. * FLAC__metadata_simple_iterator_init()
  87817. * \retval FLAC__bool
  87818. * \c true if the ID was successfully read, else \c false, in which
  87819. * case you should check FLAC__metadata_simple_iterator_status() to
  87820. * find out why. If the status is
  87821. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87822. * current metadata block is not an \c APPLICATION block. Otherwise
  87823. * if the status is
  87824. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87825. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87826. * occurred and the iterator can no longer be used.
  87827. */
  87828. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87829. /** Get the metadata block at the current position. You can modify the
  87830. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87831. * write it back to the FLAC file.
  87832. *
  87833. * You must call FLAC__metadata_object_delete() on the returned object
  87834. * when you are finished with it.
  87835. *
  87836. * \param iterator A pointer to an existing initialized iterator.
  87837. * \assert
  87838. * \code iterator != NULL \endcode
  87839. * \a iterator has been successfully initialized with
  87840. * FLAC__metadata_simple_iterator_init()
  87841. * \retval FLAC__StreamMetadata*
  87842. * The current metadata block, or \c NULL if there was a memory
  87843. * allocation error.
  87844. */
  87845. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87846. /** Write a block back to the FLAC file. This function tries to be
  87847. * as efficient as possible; how the block is actually written is
  87848. * shown by the following:
  87849. *
  87850. * Existing block is a STREAMINFO block and the new block is a
  87851. * STREAMINFO block: the new block is written in place. Make sure
  87852. * you know what you're doing when changing the values of a
  87853. * STREAMINFO block.
  87854. *
  87855. * Existing block is a STREAMINFO block and the new block is a
  87856. * not a STREAMINFO block: this is an error since the first block
  87857. * must be a STREAMINFO block. Returns \c false without altering the
  87858. * file.
  87859. *
  87860. * Existing block is not a STREAMINFO block and the new block is a
  87861. * STREAMINFO block: this is an error since there may be only one
  87862. * STREAMINFO block. Returns \c false without altering the file.
  87863. *
  87864. * Existing block and new block are the same length: the existing
  87865. * block will be replaced by the new block, written in place.
  87866. *
  87867. * Existing block is longer than new block: if use_padding is \c true,
  87868. * the existing block will be overwritten in place with the new
  87869. * block followed by a PADDING block, if possible, to make the total
  87870. * size the same as the existing block. Remember that a padding
  87871. * block requires at least four bytes so if the difference in size
  87872. * between the new block and existing block is less than that, the
  87873. * entire file will have to be rewritten, using the new block's
  87874. * exact size. If use_padding is \c false, the entire file will be
  87875. * rewritten, replacing the existing block by the new block.
  87876. *
  87877. * Existing block is shorter than new block: if use_padding is \c true,
  87878. * the function will try and expand the new block into the following
  87879. * PADDING block, if it exists and doing so won't shrink the PADDING
  87880. * block to less than 4 bytes. If there is no following PADDING
  87881. * block, or it will shrink to less than 4 bytes, or use_padding is
  87882. * \c false, the entire file is rewritten, replacing the existing block
  87883. * with the new block. Note that in this case any following PADDING
  87884. * block is preserved as is.
  87885. *
  87886. * After writing the block, the iterator will remain in the same
  87887. * place, i.e. pointing to the new block.
  87888. *
  87889. * \param iterator A pointer to an existing initialized iterator.
  87890. * \param block The block to set.
  87891. * \param use_padding See above.
  87892. * \assert
  87893. * \code iterator != NULL \endcode
  87894. * \a iterator has been successfully initialized with
  87895. * FLAC__metadata_simple_iterator_init()
  87896. * \code block != NULL \endcode
  87897. * \retval FLAC__bool
  87898. * \c true if successful, else \c false.
  87899. */
  87900. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87901. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87902. * except that instead of writing over an existing block, it appends
  87903. * a block after the existing block. \a use_padding is again used to
  87904. * tell the function to try an expand into following padding in an
  87905. * attempt to avoid rewriting the entire file.
  87906. *
  87907. * This function will fail and return \c false if given a STREAMINFO
  87908. * block.
  87909. *
  87910. * After writing the block, the iterator will be pointing to the
  87911. * new block.
  87912. *
  87913. * \param iterator A pointer to an existing initialized iterator.
  87914. * \param block The block to set.
  87915. * \param use_padding See above.
  87916. * \assert
  87917. * \code iterator != NULL \endcode
  87918. * \a iterator has been successfully initialized with
  87919. * FLAC__metadata_simple_iterator_init()
  87920. * \code block != NULL \endcode
  87921. * \retval FLAC__bool
  87922. * \c true if successful, else \c false.
  87923. */
  87924. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87925. /** Deletes the block at the current position. This will cause the
  87926. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87927. * in which case the block will be replaced by an equal-sized PADDING
  87928. * block. The iterator will be left pointing to the block before the
  87929. * one just deleted.
  87930. *
  87931. * You may not delete the STREAMINFO block.
  87932. *
  87933. * \param iterator A pointer to an existing initialized iterator.
  87934. * \param use_padding See above.
  87935. * \assert
  87936. * \code iterator != NULL \endcode
  87937. * \a iterator has been successfully initialized with
  87938. * FLAC__metadata_simple_iterator_init()
  87939. * \retval FLAC__bool
  87940. * \c true if successful, else \c false.
  87941. */
  87942. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87943. /* \} */
  87944. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87945. * \ingroup flac_metadata
  87946. *
  87947. * \brief
  87948. * The level 2 interface provides read-write access to FLAC file metadata;
  87949. * all metadata is read into memory, operated on in memory, and then written
  87950. * to file, which is more efficient than level 1 when editing multiple blocks.
  87951. *
  87952. * Currently Ogg FLAC is supported for read only, via
  87953. * FLAC__metadata_chain_read_ogg() but a subsequent
  87954. * FLAC__metadata_chain_write() will fail.
  87955. *
  87956. * The general usage of this interface is:
  87957. *
  87958. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87959. * linked list of FLAC metadata blocks.
  87960. * - Read all metadata into the the chain from a FLAC file using
  87961. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87962. * check the status.
  87963. * - Optionally, consolidate the padding using
  87964. * FLAC__metadata_chain_merge_padding() or
  87965. * FLAC__metadata_chain_sort_padding().
  87966. * - Create a new iterator using FLAC__metadata_iterator_new()
  87967. * - Initialize the iterator to point to the first element in the chain
  87968. * using FLAC__metadata_iterator_init()
  87969. * - Traverse the chain using FLAC__metadata_iterator_next and
  87970. * FLAC__metadata_iterator_prev().
  87971. * - Get a block for reading or modification using
  87972. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87973. * inside the chain is returned, so the block is yours to modify.
  87974. * Changes will be reflected in the FLAC file when you write the
  87975. * chain. You can also add and delete blocks (see functions below).
  87976. * - When done, write out the chain using FLAC__metadata_chain_write().
  87977. * Make sure to read the whole comment to the function below.
  87978. * - Delete the chain using FLAC__metadata_chain_delete().
  87979. *
  87980. * \note
  87981. * Even though the FLAC file is not open while the chain is being
  87982. * manipulated, you must not alter the file externally during
  87983. * this time. The chain assumes the FLAC file will not change
  87984. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87985. * and FLAC__metadata_chain_write().
  87986. *
  87987. * \note
  87988. * Do not modify the is_last, length, or type fields of returned
  87989. * FLAC__StreamMetadata objects. These are managed automatically.
  87990. *
  87991. * \note
  87992. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87993. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87994. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87995. * become owned by the chain and they will be deleted when the chain is
  87996. * deleted.
  87997. *
  87998. * \{
  87999. */
  88000. struct FLAC__Metadata_Chain;
  88001. /** The opaque structure definition for the level 2 chain type.
  88002. */
  88003. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88004. struct FLAC__Metadata_Iterator;
  88005. /** The opaque structure definition for the level 2 iterator type.
  88006. */
  88007. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88008. typedef enum {
  88009. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88010. /**< The chain is in the normal OK state */
  88011. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88012. /**< The data passed into a function violated the function's usage criteria */
  88013. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88014. /**< The chain could not open the target file */
  88015. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88016. /**< The chain could not find the FLAC signature at the start of the file */
  88017. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88018. /**< The chain tried to write to a file that was not writable */
  88019. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88020. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88021. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88022. /**< The chain encountered an error while reading the FLAC file */
  88023. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88024. /**< The chain encountered an error while seeking in the FLAC file */
  88025. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88026. /**< The chain encountered an error while writing the FLAC file */
  88027. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88028. /**< The chain encountered an error renaming the FLAC file */
  88029. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88030. /**< The chain encountered an error removing the temporary file */
  88031. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88032. /**< Memory allocation failed */
  88033. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88034. /**< The caller violated an assertion or an unexpected error occurred */
  88035. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88036. /**< One or more of the required callbacks was NULL */
  88037. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88038. /**< FLAC__metadata_chain_write() was called on a chain read by
  88039. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88040. * or
  88041. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88042. * was called on a chain read by
  88043. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88044. * Matching read/write methods must always be used. */
  88045. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88046. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88047. * chain write requires a tempfile; use
  88048. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88049. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88050. * called when the chain write does not require a tempfile; use
  88051. * FLAC__metadata_chain_write_with_callbacks() instead.
  88052. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88053. * before writing via callbacks. */
  88054. } FLAC__Metadata_ChainStatus;
  88055. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88056. *
  88057. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88058. * will give the string equivalent. The contents should not be modified.
  88059. */
  88060. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88061. /*********** FLAC__Metadata_Chain ***********/
  88062. /** Create a new chain instance.
  88063. *
  88064. * \retval FLAC__Metadata_Chain*
  88065. * \c NULL if there was an error allocating memory, else the new instance.
  88066. */
  88067. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88068. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88069. *
  88070. * \param chain A pointer to an existing chain.
  88071. * \assert
  88072. * \code chain != NULL \endcode
  88073. */
  88074. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88075. /** Get the current status of the chain. Call this after a function
  88076. * returns \c false to get the reason for the error. Also resets the
  88077. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88078. *
  88079. * \param chain A pointer to an existing chain.
  88080. * \assert
  88081. * \code chain != NULL \endcode
  88082. * \retval FLAC__Metadata_ChainStatus
  88083. * The current status of the chain.
  88084. */
  88085. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88086. /** Read all metadata from a FLAC file into the chain.
  88087. *
  88088. * \param chain A pointer to an existing chain.
  88089. * \param filename The path to the FLAC file to read.
  88090. * \assert
  88091. * \code chain != NULL \endcode
  88092. * \code filename != NULL \endcode
  88093. * \retval FLAC__bool
  88094. * \c true if a valid list of metadata blocks was read from
  88095. * \a filename, else \c false. On failure, check the status with
  88096. * FLAC__metadata_chain_status().
  88097. */
  88098. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88099. /** Read all metadata from an Ogg FLAC file into the chain.
  88100. *
  88101. * \note Ogg FLAC metadata data writing is not supported yet and
  88102. * FLAC__metadata_chain_write() will fail.
  88103. *
  88104. * \param chain A pointer to an existing chain.
  88105. * \param filename The path to the Ogg FLAC file to read.
  88106. * \assert
  88107. * \code chain != NULL \endcode
  88108. * \code filename != NULL \endcode
  88109. * \retval FLAC__bool
  88110. * \c true if a valid list of metadata blocks was read from
  88111. * \a filename, else \c false. On failure, check the status with
  88112. * FLAC__metadata_chain_status().
  88113. */
  88114. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88115. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88116. *
  88117. * The \a handle need only be open for reading, but must be seekable.
  88118. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88119. * for Windows).
  88120. *
  88121. * \param chain A pointer to an existing chain.
  88122. * \param handle The I/O handle of the FLAC stream to read. The
  88123. * handle will NOT be closed after the metadata is read;
  88124. * that is the duty of the caller.
  88125. * \param callbacks
  88126. * A set of callbacks to use for I/O. The mandatory
  88127. * callbacks are \a read, \a seek, and \a tell.
  88128. * \assert
  88129. * \code chain != NULL \endcode
  88130. * \retval FLAC__bool
  88131. * \c true if a valid list of metadata blocks was read from
  88132. * \a handle, else \c false. On failure, check the status with
  88133. * FLAC__metadata_chain_status().
  88134. */
  88135. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88136. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88137. *
  88138. * The \a handle need only be open for reading, but must be seekable.
  88139. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88140. * for Windows).
  88141. *
  88142. * \note Ogg FLAC metadata data writing is not supported yet and
  88143. * FLAC__metadata_chain_write() will fail.
  88144. *
  88145. * \param chain A pointer to an existing chain.
  88146. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88147. * handle will NOT be closed after the metadata is read;
  88148. * that is the duty of the caller.
  88149. * \param callbacks
  88150. * A set of callbacks to use for I/O. The mandatory
  88151. * callbacks are \a read, \a seek, and \a tell.
  88152. * \assert
  88153. * \code chain != NULL \endcode
  88154. * \retval FLAC__bool
  88155. * \c true if a valid list of metadata blocks was read from
  88156. * \a handle, else \c false. On failure, check the status with
  88157. * FLAC__metadata_chain_status().
  88158. */
  88159. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88160. /** Checks if writing the given chain would require the use of a
  88161. * temporary file, or if it could be written in place.
  88162. *
  88163. * Under certain conditions, padding can be utilized so that writing
  88164. * edited metadata back to the FLAC file does not require rewriting the
  88165. * entire file. If rewriting is required, then a temporary workfile is
  88166. * required. When writing metadata using callbacks, you must check
  88167. * this function to know whether to call
  88168. * FLAC__metadata_chain_write_with_callbacks() or
  88169. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88170. * writing with FLAC__metadata_chain_write(), the temporary file is
  88171. * handled internally.
  88172. *
  88173. * \param chain A pointer to an existing chain.
  88174. * \param use_padding
  88175. * Whether or not padding will be allowed to be used
  88176. * during the write. The value of \a use_padding given
  88177. * here must match the value later passed to
  88178. * FLAC__metadata_chain_write_with_callbacks() or
  88179. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88180. * \assert
  88181. * \code chain != NULL \endcode
  88182. * \retval FLAC__bool
  88183. * \c true if writing the current chain would require a tempfile, or
  88184. * \c false if metadata can be written in place.
  88185. */
  88186. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88187. /** Write all metadata out to the FLAC file. This function tries to be as
  88188. * efficient as possible; how the metadata is actually written is shown by
  88189. * the following:
  88190. *
  88191. * If the current chain is the same size as the existing metadata, the new
  88192. * data is written in place.
  88193. *
  88194. * If the current chain is longer than the existing metadata, and
  88195. * \a use_padding is \c true, and the last block is a PADDING block of
  88196. * sufficient length, the function will truncate the final padding block
  88197. * so that the overall size of the metadata is the same as the existing
  88198. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88199. * the above conditions are met, the entire FLAC file must be rewritten.
  88200. * If you want to use padding this way it is a good idea to call
  88201. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88202. * amount of padding to work with, unless you need to preserve ordering
  88203. * of the PADDING blocks for some reason.
  88204. *
  88205. * If the current chain is shorter than the existing metadata, and
  88206. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88207. * is extended to make the overall size the same as the existing data. If
  88208. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88209. * PADDING block is added to the end of the new data to make it the same
  88210. * size as the existing data (if possible, see the note to
  88211. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88212. * and the new data is written in place. If none of the above apply or
  88213. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88214. *
  88215. * If \a preserve_file_stats is \c true, the owner and modification time will
  88216. * be preserved even if the FLAC file is written.
  88217. *
  88218. * For this write function to be used, the chain must have been read with
  88219. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88220. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88221. *
  88222. * \param chain A pointer to an existing chain.
  88223. * \param use_padding See above.
  88224. * \param preserve_file_stats See above.
  88225. * \assert
  88226. * \code chain != NULL \endcode
  88227. * \retval FLAC__bool
  88228. * \c true if the write succeeded, else \c false. On failure,
  88229. * check the status with FLAC__metadata_chain_status().
  88230. */
  88231. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88232. /** Write all metadata out to a FLAC stream via callbacks.
  88233. *
  88234. * (See FLAC__metadata_chain_write() for the details on how padding is
  88235. * used to write metadata in place if possible.)
  88236. *
  88237. * The \a handle must be open for updating and be seekable. The
  88238. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88239. * for Windows).
  88240. *
  88241. * For this write function to be used, the chain must have been read with
  88242. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88243. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88244. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88245. * \c false.
  88246. *
  88247. * \param chain A pointer to an existing chain.
  88248. * \param use_padding See FLAC__metadata_chain_write()
  88249. * \param handle The I/O handle of the FLAC stream to write. The
  88250. * handle will NOT be closed after the metadata is
  88251. * written; that is the duty of the caller.
  88252. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88253. * callbacks are \a write and \a seek.
  88254. * \assert
  88255. * \code chain != NULL \endcode
  88256. * \retval FLAC__bool
  88257. * \c true if the write succeeded, else \c false. On failure,
  88258. * check the status with FLAC__metadata_chain_status().
  88259. */
  88260. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88261. /** Write all metadata out to a FLAC stream via callbacks.
  88262. *
  88263. * (See FLAC__metadata_chain_write() for the details on how padding is
  88264. * used to write metadata in place if possible.)
  88265. *
  88266. * This version of the write-with-callbacks function must be used when
  88267. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88268. * this function, you must supply an I/O handle corresponding to the
  88269. * FLAC file to edit, and a temporary handle to which the new FLAC
  88270. * file will be written. It is the caller's job to move this temporary
  88271. * FLAC file on top of the original FLAC file to complete the metadata
  88272. * edit.
  88273. *
  88274. * The \a handle must be open for reading and be seekable. The
  88275. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88276. * for Windows).
  88277. *
  88278. * The \a temp_handle must be open for writing. The
  88279. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88280. * for Windows). It should be an empty stream, or at least positioned
  88281. * at the start-of-file (in which case it is the caller's duty to
  88282. * truncate it on return).
  88283. *
  88284. * For this write function to be used, the chain must have been read with
  88285. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88286. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88287. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88288. * \c true.
  88289. *
  88290. * \param chain A pointer to an existing chain.
  88291. * \param use_padding See FLAC__metadata_chain_write()
  88292. * \param handle The I/O handle of the original FLAC stream to read.
  88293. * The handle will NOT be closed after the metadata is
  88294. * written; that is the duty of the caller.
  88295. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88296. * The mandatory callbacks are \a read, \a seek, and
  88297. * \a eof.
  88298. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88299. * handle will NOT be closed after the metadata is
  88300. * written; that is the duty of the caller.
  88301. * \param temp_callbacks
  88302. * A set of callbacks to use for I/O on temp_handle.
  88303. * The only mandatory callback is \a write.
  88304. * \assert
  88305. * \code chain != NULL \endcode
  88306. * \retval FLAC__bool
  88307. * \c true if the write succeeded, else \c false. On failure,
  88308. * check the status with FLAC__metadata_chain_status().
  88309. */
  88310. 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);
  88311. /** Merge adjacent PADDING blocks into a single block.
  88312. *
  88313. * \note This function does not write to the FLAC file, it only
  88314. * modifies the chain.
  88315. *
  88316. * \warning Any iterator on the current chain will become invalid after this
  88317. * call. You should delete the iterator and get a new one.
  88318. *
  88319. * \param chain A pointer to an existing chain.
  88320. * \assert
  88321. * \code chain != NULL \endcode
  88322. */
  88323. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88324. /** This function will move all PADDING blocks to the end on the metadata,
  88325. * then merge them into a single block.
  88326. *
  88327. * \note This function does not write to the FLAC file, it only
  88328. * modifies the chain.
  88329. *
  88330. * \warning Any iterator on the current chain will become invalid after this
  88331. * call. You should delete the iterator and get a new one.
  88332. *
  88333. * \param chain A pointer to an existing chain.
  88334. * \assert
  88335. * \code chain != NULL \endcode
  88336. */
  88337. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88338. /*********** FLAC__Metadata_Iterator ***********/
  88339. /** Create a new iterator instance.
  88340. *
  88341. * \retval FLAC__Metadata_Iterator*
  88342. * \c NULL if there was an error allocating memory, else the new instance.
  88343. */
  88344. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88345. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88346. *
  88347. * \param iterator A pointer to an existing iterator.
  88348. * \assert
  88349. * \code iterator != NULL \endcode
  88350. */
  88351. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88352. /** Initialize the iterator to point to the first metadata block in the
  88353. * given chain.
  88354. *
  88355. * \param iterator A pointer to an existing iterator.
  88356. * \param chain A pointer to an existing and initialized (read) chain.
  88357. * \assert
  88358. * \code iterator != NULL \endcode
  88359. * \code chain != NULL \endcode
  88360. */
  88361. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88362. /** Moves the iterator forward one metadata block, returning \c false if
  88363. * already at the end.
  88364. *
  88365. * \param iterator A pointer to an existing initialized iterator.
  88366. * \assert
  88367. * \code iterator != NULL \endcode
  88368. * \a iterator has been successfully initialized with
  88369. * FLAC__metadata_iterator_init()
  88370. * \retval FLAC__bool
  88371. * \c false if already at the last metadata block of the chain, else
  88372. * \c true.
  88373. */
  88374. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88375. /** Moves the iterator backward one metadata block, returning \c false if
  88376. * already at the beginning.
  88377. *
  88378. * \param iterator A pointer to an existing initialized iterator.
  88379. * \assert
  88380. * \code iterator != NULL \endcode
  88381. * \a iterator has been successfully initialized with
  88382. * FLAC__metadata_iterator_init()
  88383. * \retval FLAC__bool
  88384. * \c false if already at the first metadata block of the chain, else
  88385. * \c true.
  88386. */
  88387. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88388. /** Get the type of the metadata block at the current position.
  88389. *
  88390. * \param iterator A pointer to an existing initialized iterator.
  88391. * \assert
  88392. * \code iterator != NULL \endcode
  88393. * \a iterator has been successfully initialized with
  88394. * FLAC__metadata_iterator_init()
  88395. * \retval FLAC__MetadataType
  88396. * The type of the metadata block at the current iterator position.
  88397. */
  88398. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88399. /** Get the metadata block at the current position. You can modify
  88400. * the block in place but must write the chain before the changes
  88401. * are reflected to the FLAC file. You do not need to call
  88402. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88403. * the pointer returned by FLAC__metadata_iterator_get_block()
  88404. * points directly into the chain.
  88405. *
  88406. * \warning
  88407. * Do not call FLAC__metadata_object_delete() on the returned object;
  88408. * to delete a block use FLAC__metadata_iterator_delete_block().
  88409. *
  88410. * \param iterator A pointer to an existing initialized iterator.
  88411. * \assert
  88412. * \code iterator != NULL \endcode
  88413. * \a iterator has been successfully initialized with
  88414. * FLAC__metadata_iterator_init()
  88415. * \retval FLAC__StreamMetadata*
  88416. * The current metadata block.
  88417. */
  88418. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88419. /** Set the metadata block at the current position, replacing the existing
  88420. * block. The new block passed in becomes owned by the chain and it will be
  88421. * deleted when the chain is deleted.
  88422. *
  88423. * \param iterator A pointer to an existing initialized iterator.
  88424. * \param block A pointer to a metadata block.
  88425. * \assert
  88426. * \code iterator != NULL \endcode
  88427. * \a iterator has been successfully initialized with
  88428. * FLAC__metadata_iterator_init()
  88429. * \code block != NULL \endcode
  88430. * \retval FLAC__bool
  88431. * \c false if the conditions in the above description are not met, or
  88432. * a memory allocation error occurs, otherwise \c true.
  88433. */
  88434. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88435. /** Removes the current block from the chain. If \a replace_with_padding is
  88436. * \c true, the block will instead be replaced with a padding block of equal
  88437. * size. You can not delete the STREAMINFO block. The iterator will be
  88438. * left pointing to the block before the one just "deleted", even if
  88439. * \a replace_with_padding is \c true.
  88440. *
  88441. * \param iterator A pointer to an existing initialized iterator.
  88442. * \param replace_with_padding See above.
  88443. * \assert
  88444. * \code iterator != NULL \endcode
  88445. * \a iterator has been successfully initialized with
  88446. * FLAC__metadata_iterator_init()
  88447. * \retval FLAC__bool
  88448. * \c false if the conditions in the above description are not met,
  88449. * otherwise \c true.
  88450. */
  88451. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88452. /** Insert a new block before the current block. You cannot insert a block
  88453. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88454. * as there can be only one, the one that already exists at the head when you
  88455. * read in a chain. The chain takes ownership of the new block and it will be
  88456. * deleted when the chain is deleted. The iterator will be left pointing to
  88457. * the new block.
  88458. *
  88459. * \param iterator A pointer to an existing initialized iterator.
  88460. * \param block A pointer to a metadata block to insert.
  88461. * \assert
  88462. * \code iterator != NULL \endcode
  88463. * \a iterator has been successfully initialized with
  88464. * FLAC__metadata_iterator_init()
  88465. * \retval FLAC__bool
  88466. * \c false if the conditions in the above description are not met, or
  88467. * a memory allocation error occurs, otherwise \c true.
  88468. */
  88469. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88470. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88471. * block as there can be only one, the one that already exists at the head when
  88472. * you read in a chain. The chain takes ownership of the new block and it will
  88473. * be 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_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88487. /* \} */
  88488. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88489. * \ingroup flac_metadata
  88490. *
  88491. * \brief
  88492. * This module contains methods for manipulating FLAC metadata objects.
  88493. *
  88494. * Since many are variable length we have to be careful about the memory
  88495. * management. We decree that all pointers to data in the object are
  88496. * owned by the object and memory-managed by the object.
  88497. *
  88498. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88499. * functions to create all instances. When using the
  88500. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88501. * \a copy to \c true to have the function make it's own copy of the data, or
  88502. * to \c false to give the object ownership of your data. In the latter case
  88503. * your pointer must be freeable by free() and will be free()d when the object
  88504. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88505. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88506. * the length argument is 0 and the \a copy argument is \c false.
  88507. *
  88508. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88509. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88510. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88511. * case of a memory allocation error.
  88512. *
  88513. * We don't have the convenience of C++ here, so note that the library relies
  88514. * on you to keep the types straight. In other words, if you pass, for
  88515. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88516. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88517. * failure.
  88518. *
  88519. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88520. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88521. * toward the length or stored in the stream, but it can make working with plain
  88522. * comments (those that don't contain embedded-NULs in the value) easier.
  88523. * Entries passed into these functions have trailing NULs added if missing, and
  88524. * returned entries are guaranteed to have a trailing NUL.
  88525. *
  88526. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88527. * comment entry/name/value will first validate that it complies with the Vorbis
  88528. * comment specification and return false if it does not.
  88529. *
  88530. * There is no need to recalculate the length field on metadata blocks you
  88531. * have modified. They will be calculated automatically before they are
  88532. * written back to a file.
  88533. *
  88534. * \{
  88535. */
  88536. /** Create a new metadata object instance of the given type.
  88537. *
  88538. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88539. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88540. * the vendor string set (but zero comments).
  88541. *
  88542. * Do not pass in a value greater than or equal to
  88543. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88544. * doing.
  88545. *
  88546. * \param type Type of object to create
  88547. * \retval FLAC__StreamMetadata*
  88548. * \c NULL if there was an error allocating memory or the type code is
  88549. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88550. */
  88551. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88552. /** Create a copy of an existing metadata object.
  88553. *
  88554. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88555. * object is also copied. The caller takes ownership of the new block and
  88556. * is responsible for freeing it with FLAC__metadata_object_delete().
  88557. *
  88558. * \param object Pointer to object to copy.
  88559. * \assert
  88560. * \code object != NULL \endcode
  88561. * \retval FLAC__StreamMetadata*
  88562. * \c NULL if there was an error allocating memory, else the new instance.
  88563. */
  88564. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88565. /** Free a metadata object. Deletes the object pointed to by \a object.
  88566. *
  88567. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88568. * object is also deleted.
  88569. *
  88570. * \param object A pointer to an existing object.
  88571. * \assert
  88572. * \code object != NULL \endcode
  88573. */
  88574. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88575. /** Compares two metadata objects.
  88576. *
  88577. * The compare is "deep", i.e. dynamically allocated data within the
  88578. * object is also compared.
  88579. *
  88580. * \param block1 A pointer to an existing object.
  88581. * \param block2 A pointer to an existing object.
  88582. * \assert
  88583. * \code block1 != NULL \endcode
  88584. * \code block2 != NULL \endcode
  88585. * \retval FLAC__bool
  88586. * \c true if objects are identical, else \c false.
  88587. */
  88588. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88589. /** Sets the application data of an APPLICATION block.
  88590. *
  88591. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88592. * takes ownership of the pointer. The existing data will be freed if this
  88593. * function is successful, otherwise the original data will remain if \a copy
  88594. * is \c true and malloc() fails.
  88595. *
  88596. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88597. *
  88598. * \param object A pointer to an existing APPLICATION object.
  88599. * \param data A pointer to the data to set.
  88600. * \param length The length of \a data in bytes.
  88601. * \param copy See above.
  88602. * \assert
  88603. * \code object != NULL \endcode
  88604. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88605. * \code (data != NULL && length > 0) ||
  88606. * (data == NULL && length == 0 && copy == false) \endcode
  88607. * \retval FLAC__bool
  88608. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88609. */
  88610. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88611. /** Resize the seekpoint array.
  88612. *
  88613. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88614. * points will be added to the end.
  88615. *
  88616. * \param object A pointer to an existing SEEKTABLE object.
  88617. * \param new_num_points The desired length of the array; may be \c 0.
  88618. * \assert
  88619. * \code object != NULL \endcode
  88620. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88621. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88622. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88623. * \retval FLAC__bool
  88624. * \c false if memory allocation error, else \c true.
  88625. */
  88626. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88627. /** Set a seekpoint in a seektable.
  88628. *
  88629. * \param object A pointer to an existing SEEKTABLE object.
  88630. * \param point_num Index into seekpoint array to set.
  88631. * \param point The point to set.
  88632. * \assert
  88633. * \code object != NULL \endcode
  88634. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88635. * \code object->data.seek_table.num_points > point_num \endcode
  88636. */
  88637. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88638. /** Insert a seekpoint into a seektable.
  88639. *
  88640. * \param object A pointer to an existing SEEKTABLE object.
  88641. * \param point_num Index into seekpoint array to set.
  88642. * \param point The point to set.
  88643. * \assert
  88644. * \code object != NULL \endcode
  88645. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88646. * \code object->data.seek_table.num_points >= point_num \endcode
  88647. * \retval FLAC__bool
  88648. * \c false if memory allocation error, else \c true.
  88649. */
  88650. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88651. /** Delete a seekpoint from a seektable.
  88652. *
  88653. * \param object A pointer to an existing SEEKTABLE object.
  88654. * \param point_num Index into seekpoint array to set.
  88655. * \assert
  88656. * \code object != NULL \endcode
  88657. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88658. * \code object->data.seek_table.num_points > point_num \endcode
  88659. * \retval FLAC__bool
  88660. * \c false if memory allocation error, else \c true.
  88661. */
  88662. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88663. /** Check a seektable to see if it conforms to the FLAC specification.
  88664. * See the format specification for limits on the contents of the
  88665. * seektable.
  88666. *
  88667. * \param object A pointer to an existing SEEKTABLE object.
  88668. * \assert
  88669. * \code object != NULL \endcode
  88670. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88671. * \retval FLAC__bool
  88672. * \c false if seek table is illegal, else \c true.
  88673. */
  88674. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88675. /** Append a number of placeholder points to the end of a seek table.
  88676. *
  88677. * \note
  88678. * As with the other ..._seektable_template_... functions, you should
  88679. * call FLAC__metadata_object_seektable_template_sort() when finished
  88680. * to make the seek table legal.
  88681. *
  88682. * \param object A pointer to an existing SEEKTABLE object.
  88683. * \param num The number of placeholder points to append.
  88684. * \assert
  88685. * \code object != NULL \endcode
  88686. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88687. * \retval FLAC__bool
  88688. * \c false if memory allocation fails, else \c true.
  88689. */
  88690. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88691. /** Append a specific seek point template to the end of a seek table.
  88692. *
  88693. * \note
  88694. * As with the other ..._seektable_template_... functions, you should
  88695. * call FLAC__metadata_object_seektable_template_sort() when finished
  88696. * to make the seek table legal.
  88697. *
  88698. * \param object A pointer to an existing SEEKTABLE object.
  88699. * \param sample_number The sample number of the seek point template.
  88700. * \assert
  88701. * \code object != NULL \endcode
  88702. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88703. * \retval FLAC__bool
  88704. * \c false if memory allocation fails, else \c true.
  88705. */
  88706. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88707. /** Append specific seek point templates to the end of a seek table.
  88708. *
  88709. * \note
  88710. * As with the other ..._seektable_template_... functions, you should
  88711. * call FLAC__metadata_object_seektable_template_sort() when finished
  88712. * to make the seek table legal.
  88713. *
  88714. * \param object A pointer to an existing SEEKTABLE object.
  88715. * \param sample_numbers An array of sample numbers for the seek points.
  88716. * \param num The number of seek point templates to append.
  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_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88724. /** Append a set of evenly-spaced seek point templates to the end of a
  88725. * seek table.
  88726. *
  88727. * \note
  88728. * As with the other ..._seektable_template_... functions, you should
  88729. * call FLAC__metadata_object_seektable_template_sort() when finished
  88730. * to make the seek table legal.
  88731. *
  88732. * \param object A pointer to an existing SEEKTABLE object.
  88733. * \param num The number of placeholder points to append.
  88734. * \param total_samples The total number of samples to be encoded;
  88735. * the seekpoints will be spaced approximately
  88736. * \a total_samples / \a num samples apart.
  88737. * \assert
  88738. * \code object != NULL \endcode
  88739. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88740. * \code total_samples > 0 \endcode
  88741. * \retval FLAC__bool
  88742. * \c false if memory allocation fails, else \c true.
  88743. */
  88744. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88745. /** Append a set of evenly-spaced seek point templates to the end of a
  88746. * seek table.
  88747. *
  88748. * \note
  88749. * As with the other ..._seektable_template_... functions, you should
  88750. * call FLAC__metadata_object_seektable_template_sort() when finished
  88751. * to make the seek table legal.
  88752. *
  88753. * \param object A pointer to an existing SEEKTABLE object.
  88754. * \param samples The number of samples apart to space the placeholder
  88755. * points. The first point will be at sample \c 0, the
  88756. * second at sample \a samples, then 2*\a samples, and
  88757. * so on. As long as \a samples and \a total_samples
  88758. * are greater than \c 0, there will always be at least
  88759. * one seekpoint at sample \c 0.
  88760. * \param total_samples The total number of samples to be encoded;
  88761. * the seekpoints will be spaced
  88762. * \a samples samples apart.
  88763. * \assert
  88764. * \code object != NULL \endcode
  88765. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88766. * \code samples > 0 \endcode
  88767. * \code total_samples > 0 \endcode
  88768. * \retval FLAC__bool
  88769. * \c false if memory allocation fails, else \c true.
  88770. */
  88771. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88772. /** Sort a seek table's seek points according to the format specification,
  88773. * removing duplicates.
  88774. *
  88775. * \param object A pointer to a seek table to be sorted.
  88776. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88777. * If \c true, duplicates are deleted and the seek table is
  88778. * shrunk appropriately; the number of placeholder points
  88779. * present in the seek table will be the same after the call
  88780. * as before.
  88781. * \assert
  88782. * \code object != NULL \endcode
  88783. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88784. * \retval FLAC__bool
  88785. * \c false if realloc() fails, else \c true.
  88786. */
  88787. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88788. /** Sets the vendor string in a VORBIS_COMMENT block.
  88789. *
  88790. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88791. * one already.
  88792. *
  88793. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88794. * takes ownership of the \c entry.entry pointer.
  88795. *
  88796. * \note If this function returns \c false, the caller still owns the
  88797. * pointer.
  88798. *
  88799. * \param object A pointer to an existing VORBIS_COMMENT object.
  88800. * \param entry The entry to set the vendor string to.
  88801. * \param copy See above.
  88802. * \assert
  88803. * \code object != NULL \endcode
  88804. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88805. * \code (entry.entry != NULL && entry.length > 0) ||
  88806. * (entry.entry == NULL && entry.length == 0) \endcode
  88807. * \retval FLAC__bool
  88808. * \c false if memory allocation fails or \a entry does not comply with the
  88809. * Vorbis comment specification, else \c true.
  88810. */
  88811. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88812. /** Resize the comment array.
  88813. *
  88814. * If the size shrinks, elements will truncated; if it grows, new empty
  88815. * fields will be added to the end.
  88816. *
  88817. * \param object A pointer to an existing VORBIS_COMMENT object.
  88818. * \param new_num_comments The desired length of the array; may be \c 0.
  88819. * \assert
  88820. * \code object != NULL \endcode
  88821. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88822. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88823. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88824. * \retval FLAC__bool
  88825. * \c false if memory allocation fails, else \c true.
  88826. */
  88827. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88828. /** Sets a comment in a VORBIS_COMMENT block.
  88829. *
  88830. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88831. * one already.
  88832. *
  88833. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88834. * takes ownership of the \c entry.entry pointer.
  88835. *
  88836. * \note If this function returns \c false, the caller still owns the
  88837. * pointer.
  88838. *
  88839. * \param object A pointer to an existing VORBIS_COMMENT object.
  88840. * \param comment_num Index into comment array to set.
  88841. * \param entry The entry to set the comment to.
  88842. * \param copy See above.
  88843. * \assert
  88844. * \code object != NULL \endcode
  88845. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88846. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88847. * \code (entry.entry != NULL && entry.length > 0) ||
  88848. * (entry.entry == NULL && entry.length == 0) \endcode
  88849. * \retval FLAC__bool
  88850. * \c false if memory allocation fails or \a entry does not comply with the
  88851. * Vorbis comment specification, else \c true.
  88852. */
  88853. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88854. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88855. *
  88856. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88857. * one already.
  88858. *
  88859. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88860. * takes ownership of the \c entry.entry pointer.
  88861. *
  88862. * \note If this function returns \c false, the caller still owns the
  88863. * pointer.
  88864. *
  88865. * \param object A pointer to an existing VORBIS_COMMENT object.
  88866. * \param comment_num The index at which to insert the comment. The comments
  88867. * at and after \a comment_num move right one position.
  88868. * To append a comment to the end, set \a comment_num to
  88869. * \c object->data.vorbis_comment.num_comments .
  88870. * \param entry The comment to insert.
  88871. * \param copy See above.
  88872. * \assert
  88873. * \code object != NULL \endcode
  88874. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88875. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88876. * \code (entry.entry != NULL && entry.length > 0) ||
  88877. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88878. * \retval FLAC__bool
  88879. * \c false if memory allocation fails or \a entry does not comply with the
  88880. * Vorbis comment specification, else \c true.
  88881. */
  88882. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88883. /** Appends a comment to a VORBIS_COMMENT block.
  88884. *
  88885. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88886. * one already.
  88887. *
  88888. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88889. * takes ownership of the \c entry.entry pointer.
  88890. *
  88891. * \note If this function returns \c false, the caller still owns the
  88892. * pointer.
  88893. *
  88894. * \param object A pointer to an existing VORBIS_COMMENT object.
  88895. * \param entry The comment to insert.
  88896. * \param copy See above.
  88897. * \assert
  88898. * \code object != NULL \endcode
  88899. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88900. * \code (entry.entry != NULL && entry.length > 0) ||
  88901. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88902. * \retval FLAC__bool
  88903. * \c false if memory allocation fails or \a entry does not comply with the
  88904. * Vorbis comment specification, else \c true.
  88905. */
  88906. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88907. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88908. *
  88909. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88910. * one already.
  88911. *
  88912. * Depending on the the value of \a all, either all or just the first comment
  88913. * whose field name(s) match the given entry's name will be replaced by the
  88914. * given entry. If no comments match, \a entry will simply be appended.
  88915. *
  88916. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88917. * takes ownership of the \c entry.entry pointer.
  88918. *
  88919. * \note If this function returns \c false, the caller still owns the
  88920. * pointer.
  88921. *
  88922. * \param object A pointer to an existing VORBIS_COMMENT object.
  88923. * \param entry The comment to insert.
  88924. * \param all If \c true, all comments whose field name matches
  88925. * \a entry's field name will be removed, and \a entry will
  88926. * be inserted at the position of the first matching
  88927. * comment. If \c false, only the first comment whose
  88928. * field name matches \a entry's field name will be
  88929. * replaced with \a entry.
  88930. * \param copy See above.
  88931. * \assert
  88932. * \code object != NULL \endcode
  88933. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88934. * \code (entry.entry != NULL && entry.length > 0) ||
  88935. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88936. * \retval FLAC__bool
  88937. * \c false if memory allocation fails or \a entry does not comply with the
  88938. * Vorbis comment specification, else \c true.
  88939. */
  88940. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88941. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88942. *
  88943. * \param object A pointer to an existing VORBIS_COMMENT object.
  88944. * \param comment_num The index of the comment to delete.
  88945. * \assert
  88946. * \code object != NULL \endcode
  88947. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88948. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88949. * \retval FLAC__bool
  88950. * \c false if realloc() fails, else \c true.
  88951. */
  88952. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88953. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88954. *
  88955. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88956. * memory and shall be owned by the caller. For convenience the entry will
  88957. * have a terminating NUL.
  88958. *
  88959. * \param entry A pointer to a Vorbis comment entry. The entry's
  88960. * \c entry pointer should not point to allocated
  88961. * memory as it will be overwritten.
  88962. * \param field_name The field name in ASCII, \c NUL terminated.
  88963. * \param field_value The field value in UTF-8, \c NUL terminated.
  88964. * \assert
  88965. * \code entry != NULL \endcode
  88966. * \code field_name != NULL \endcode
  88967. * \code field_value != NULL \endcode
  88968. * \retval FLAC__bool
  88969. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88970. * not comply with the Vorbis comment specification, else \c true.
  88971. */
  88972. 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);
  88973. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88974. *
  88975. * The returned pointers to name and value will be allocated by malloc()
  88976. * and shall be owned by the caller.
  88977. *
  88978. * \param entry An existing Vorbis comment entry.
  88979. * \param field_name The address of where the returned pointer to the
  88980. * field name will be stored.
  88981. * \param field_value The address of where the returned pointer to the
  88982. * field value will be stored.
  88983. * \assert
  88984. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88985. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88986. * \code field_name != NULL \endcode
  88987. * \code field_value != NULL \endcode
  88988. * \retval FLAC__bool
  88989. * \c false if memory allocation fails or \a entry does not comply with the
  88990. * Vorbis comment specification, else \c true.
  88991. */
  88992. 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);
  88993. /** Check if the given Vorbis comment entry's field name matches the given
  88994. * field name.
  88995. *
  88996. * \param entry An existing Vorbis comment entry.
  88997. * \param field_name The field name to check.
  88998. * \param field_name_length The length of \a field_name, not including the
  88999. * terminating \c NUL.
  89000. * \assert
  89001. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89002. * \retval FLAC__bool
  89003. * \c true if the field names match, else \c false
  89004. */
  89005. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89006. /** Find a Vorbis comment with the given field name.
  89007. *
  89008. * The search begins at entry number \a offset; use an offset of 0 to
  89009. * search from the beginning of the comment array.
  89010. *
  89011. * \param object A pointer to an existing VORBIS_COMMENT object.
  89012. * \param offset The offset into the comment array from where to start
  89013. * the search.
  89014. * \param field_name The field name of the comment to find.
  89015. * \assert
  89016. * \code object != NULL \endcode
  89017. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89018. * \code field_name != NULL \endcode
  89019. * \retval int
  89020. * The offset in the comment array of the first comment whose field
  89021. * name matches \a field_name, or \c -1 if no match was found.
  89022. */
  89023. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89024. /** Remove first Vorbis comment matching the given field name.
  89025. *
  89026. * \param object A pointer to an existing VORBIS_COMMENT object.
  89027. * \param field_name The field name of comment to delete.
  89028. * \assert
  89029. * \code object != NULL \endcode
  89030. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89031. * \retval int
  89032. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89033. * \c 1 for one matching entry deleted.
  89034. */
  89035. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89036. /** Remove all Vorbis comments matching the given field name.
  89037. *
  89038. * \param object A pointer to an existing VORBIS_COMMENT object.
  89039. * \param field_name The field name of comments to delete.
  89040. * \assert
  89041. * \code object != NULL \endcode
  89042. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89043. * \retval int
  89044. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89045. * else the number of matching entries deleted.
  89046. */
  89047. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89048. /** Create a new CUESHEET track instance.
  89049. *
  89050. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89051. *
  89052. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89053. * \c NULL if there was an error allocating memory, else the new instance.
  89054. */
  89055. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89056. /** Create a copy of an existing CUESHEET track object.
  89057. *
  89058. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89059. * object is also copied. The caller takes ownership of the new object and
  89060. * is responsible for freeing it with
  89061. * FLAC__metadata_object_cuesheet_track_delete().
  89062. *
  89063. * \param object Pointer to object to copy.
  89064. * \assert
  89065. * \code object != NULL \endcode
  89066. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89067. * \c NULL if there was an error allocating memory, else the new instance.
  89068. */
  89069. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89070. /** Delete a CUESHEET track object
  89071. *
  89072. * \param object A pointer to an existing CUESHEET track object.
  89073. * \assert
  89074. * \code object != NULL \endcode
  89075. */
  89076. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89077. /** Resize a track's index point array.
  89078. *
  89079. * If the size shrinks, elements will truncated; if it grows, new blank
  89080. * indices will be added to the end.
  89081. *
  89082. * \param object A pointer to an existing CUESHEET object.
  89083. * \param track_num The index of the track to modify. NOTE: this is not
  89084. * necessarily the same as the track's \a number field.
  89085. * \param new_num_indices The desired length of the array; may be \c 0.
  89086. * \assert
  89087. * \code object != NULL \endcode
  89088. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89089. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89090. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89091. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89092. * \retval FLAC__bool
  89093. * \c false if memory allocation error, else \c true.
  89094. */
  89095. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89096. /** Insert an index point in a CUESHEET track at the given index.
  89097. *
  89098. * \param object A pointer to an existing CUESHEET object.
  89099. * \param track_num The index of the track to modify. NOTE: this is not
  89100. * necessarily the same as the track's \a number field.
  89101. * \param index_num The index into the track's index array at which to
  89102. * insert the index point. NOTE: this is not necessarily
  89103. * the same as the index point's \a number field. The
  89104. * indices at and after \a index_num move right one
  89105. * position. To append an index point to the end, set
  89106. * \a index_num to
  89107. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89108. * \param index The index point to insert.
  89109. * \assert
  89110. * \code object != NULL \endcode
  89111. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89112. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89113. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89114. * \retval FLAC__bool
  89115. * \c false if realloc() fails, else \c true.
  89116. */
  89117. 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);
  89118. /** Insert a blank index point in a CUESHEET track at the given index.
  89119. *
  89120. * A blank index point is one in which all field values are zero.
  89121. *
  89122. * \param object A pointer to an existing CUESHEET object.
  89123. * \param track_num The index of the track to modify. NOTE: this is not
  89124. * necessarily the same as the track's \a number field.
  89125. * \param index_num The index into the track's index array at which to
  89126. * insert the index point. NOTE: this is not necessarily
  89127. * the same as the index point's \a number field. The
  89128. * indices at and after \a index_num move right one
  89129. * position. To append an index point to the end, set
  89130. * \a index_num to
  89131. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89132. * \assert
  89133. * \code object != NULL \endcode
  89134. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89135. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89136. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89137. * \retval FLAC__bool
  89138. * \c false if realloc() fails, else \c true.
  89139. */
  89140. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89141. /** Delete an index point in a CUESHEET track at the given index.
  89142. *
  89143. * \param object A pointer to an existing CUESHEET object.
  89144. * \param track_num The index into the track array of the track to
  89145. * modify. NOTE: this is not necessarily the same
  89146. * as the track's \a number field.
  89147. * \param index_num The index into the track's index array of the index
  89148. * to delete. NOTE: this is not necessarily the same
  89149. * as the index's \a number field.
  89150. * \assert
  89151. * \code object != NULL \endcode
  89152. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89153. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89154. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89155. * \retval FLAC__bool
  89156. * \c false if realloc() fails, else \c true.
  89157. */
  89158. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89159. /** Resize the track array.
  89160. *
  89161. * If the size shrinks, elements will truncated; if it grows, new blank
  89162. * tracks will be added to the end.
  89163. *
  89164. * \param object A pointer to an existing CUESHEET object.
  89165. * \param new_num_tracks The desired length of the array; may be \c 0.
  89166. * \assert
  89167. * \code object != NULL \endcode
  89168. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89169. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89170. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89171. * \retval FLAC__bool
  89172. * \c false if memory allocation error, else \c true.
  89173. */
  89174. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89175. /** Sets a track in a CUESHEET block.
  89176. *
  89177. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89178. * takes ownership of the \a track pointer.
  89179. *
  89180. * \param object A pointer to an existing CUESHEET object.
  89181. * \param track_num Index into track array to set. NOTE: this is not
  89182. * necessarily the same as the track's \a number field.
  89183. * \param track The track to set the track to. You may safely pass in
  89184. * a const pointer if \a copy is \c true.
  89185. * \param copy See above.
  89186. * \assert
  89187. * \code object != NULL \endcode
  89188. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89189. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89190. * \code (track->indices != NULL && track->num_indices > 0) ||
  89191. * (track->indices == NULL && track->num_indices == 0)
  89192. * \retval FLAC__bool
  89193. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89194. */
  89195. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89196. /** Insert a track in a CUESHEET block at the given index.
  89197. *
  89198. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89199. * takes ownership of the \a track pointer.
  89200. *
  89201. * \param object A pointer to an existing CUESHEET object.
  89202. * \param track_num The index at which to insert the track. NOTE: this
  89203. * is not necessarily the same as the track's \a number
  89204. * field. The tracks at and after \a track_num move right
  89205. * one position. To append a track to the end, set
  89206. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89207. * \param track The track to insert. You may safely pass in a const
  89208. * pointer if \a copy is \c true.
  89209. * \param copy See above.
  89210. * \assert
  89211. * \code object != NULL \endcode
  89212. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89213. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89214. * \retval FLAC__bool
  89215. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89216. */
  89217. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89218. /** Insert a blank track in a CUESHEET block at the given index.
  89219. *
  89220. * A blank track is one in which all field values are zero.
  89221. *
  89222. * \param object A pointer to an existing CUESHEET object.
  89223. * \param track_num The index at which to insert the track. NOTE: this
  89224. * is not necessarily the same as the track's \a number
  89225. * field. The tracks at and after \a track_num move right
  89226. * one position. To append a track to the end, set
  89227. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89228. * \assert
  89229. * \code object != NULL \endcode
  89230. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89231. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89232. * \retval FLAC__bool
  89233. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89234. */
  89235. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89236. /** Delete a track in a CUESHEET block at the given index.
  89237. *
  89238. * \param object A pointer to an existing CUESHEET object.
  89239. * \param track_num The index into the track array of the track to
  89240. * delete. NOTE: this is not necessarily the same
  89241. * as the track's \a number field.
  89242. * \assert
  89243. * \code object != NULL \endcode
  89244. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89245. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89246. * \retval FLAC__bool
  89247. * \c false if realloc() fails, else \c true.
  89248. */
  89249. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89250. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89251. * See the format specification for limits on the contents of the
  89252. * cue sheet.
  89253. *
  89254. * \param object A pointer to an existing CUESHEET object.
  89255. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89256. * stringent requirements for a CD-DA (audio) disc.
  89257. * \param violation Address of a pointer to a string. If there is a
  89258. * violation, a pointer to a string explanation of the
  89259. * violation will be returned here. \a violation may be
  89260. * \c NULL if you don't need the returned string. Do not
  89261. * free the returned string; it will always point to static
  89262. * data.
  89263. * \assert
  89264. * \code object != NULL \endcode
  89265. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89266. * \retval FLAC__bool
  89267. * \c false if cue sheet is illegal, else \c true.
  89268. */
  89269. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89270. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89271. * assumes the cue sheet corresponds to a CD; the result is undefined
  89272. * if the cuesheet's is_cd bit is not set.
  89273. *
  89274. * \param object A pointer to an existing CUESHEET object.
  89275. * \assert
  89276. * \code object != NULL \endcode
  89277. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89278. * \retval FLAC__uint32
  89279. * The unsigned integer representation of the CDDB/freedb ID
  89280. */
  89281. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89282. /** Sets the MIME type of a PICTURE block.
  89283. *
  89284. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89285. * takes ownership of the pointer. The existing string will be freed if this
  89286. * function is successful, otherwise the original string will remain if \a copy
  89287. * is \c true and malloc() fails.
  89288. *
  89289. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89290. *
  89291. * \param object A pointer to an existing PICTURE object.
  89292. * \param mime_type A pointer to the MIME type string. The string must be
  89293. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89294. * is done.
  89295. * \param copy See above.
  89296. * \assert
  89297. * \code object != NULL \endcode
  89298. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89299. * \code (mime_type != NULL) \endcode
  89300. * \retval FLAC__bool
  89301. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89302. */
  89303. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89304. /** Sets the description of a PICTURE block.
  89305. *
  89306. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89307. * takes ownership of the pointer. The existing string will be freed if this
  89308. * function is successful, otherwise the original string will remain if \a copy
  89309. * is \c true and malloc() fails.
  89310. *
  89311. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89312. *
  89313. * \param object A pointer to an existing PICTURE object.
  89314. * \param description A pointer to the description string. The string must be
  89315. * valid UTF-8, NUL-terminated. No validation is done.
  89316. * \param copy See above.
  89317. * \assert
  89318. * \code object != NULL \endcode
  89319. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89320. * \code (description != NULL) \endcode
  89321. * \retval FLAC__bool
  89322. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89323. */
  89324. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89325. /** Sets the picture data of a PICTURE block.
  89326. *
  89327. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89328. * takes ownership of the pointer. Also sets the \a data_length field of the
  89329. * metadata object to what is passed in as the \a length parameter. The
  89330. * existing data will be freed if this function is successful, otherwise the
  89331. * original data and data_length will remain if \a copy is \c true and
  89332. * malloc() fails.
  89333. *
  89334. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89335. *
  89336. * \param object A pointer to an existing PICTURE object.
  89337. * \param data A pointer to the data to set.
  89338. * \param length The length of \a data in bytes.
  89339. * \param copy See above.
  89340. * \assert
  89341. * \code object != NULL \endcode
  89342. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89343. * \code (data != NULL && length > 0) ||
  89344. * (data == NULL && length == 0 && copy == false) \endcode
  89345. * \retval FLAC__bool
  89346. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89347. */
  89348. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89349. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89350. * See the format specification for limits on the contents of the
  89351. * PICTURE block.
  89352. *
  89353. * \param object A pointer to existing PICTURE block to be checked.
  89354. * \param violation Address of a pointer to a string. If there is a
  89355. * violation, a pointer to a string explanation of the
  89356. * violation will be returned here. \a violation may be
  89357. * \c NULL if you don't need the returned string. Do not
  89358. * free the returned string; it will always point to static
  89359. * data.
  89360. * \assert
  89361. * \code object != NULL \endcode
  89362. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89363. * \retval FLAC__bool
  89364. * \c false if PICTURE block is illegal, else \c true.
  89365. */
  89366. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89367. /* \} */
  89368. #ifdef __cplusplus
  89369. }
  89370. #endif
  89371. #endif
  89372. /*** End of inlined file: metadata.h ***/
  89373. /*** Start of inlined file: stream_decoder.h ***/
  89374. #ifndef FLAC__STREAM_DECODER_H
  89375. #define FLAC__STREAM_DECODER_H
  89376. #include <stdio.h> /* for FILE */
  89377. #ifdef __cplusplus
  89378. extern "C" {
  89379. #endif
  89380. /** \file include/FLAC/stream_decoder.h
  89381. *
  89382. * \brief
  89383. * This module contains the functions which implement the stream
  89384. * decoder.
  89385. *
  89386. * See the detailed documentation in the
  89387. * \link flac_stream_decoder stream decoder \endlink module.
  89388. */
  89389. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89390. * \ingroup flac
  89391. *
  89392. * \brief
  89393. * This module describes the decoder layers provided by libFLAC.
  89394. *
  89395. * The stream decoder can be used to decode complete streams either from
  89396. * the client via callbacks, or directly from a file, depending on how
  89397. * it is initialized. When decoding via callbacks, the client provides
  89398. * callbacks for reading FLAC data and writing decoded samples, and
  89399. * handling metadata and errors. If the client also supplies seek-related
  89400. * callback, the decoder function for sample-accurate seeking within the
  89401. * FLAC input is also available. When decoding from a file, the client
  89402. * needs only supply a filename or open \c FILE* and write/metadata/error
  89403. * callbacks; the rest of the callbacks are supplied internally. For more
  89404. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89405. */
  89406. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89407. * \ingroup flac_decoder
  89408. *
  89409. * \brief
  89410. * This module contains the functions which implement the stream
  89411. * decoder.
  89412. *
  89413. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89414. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89415. *
  89416. * The basic usage of this decoder is as follows:
  89417. * - The program creates an instance of a decoder using
  89418. * FLAC__stream_decoder_new().
  89419. * - The program overrides the default settings using
  89420. * FLAC__stream_decoder_set_*() functions.
  89421. * - The program initializes the instance to validate the settings and
  89422. * prepare for decoding using
  89423. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89424. * or FLAC__stream_decoder_init_file() for native FLAC,
  89425. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89426. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89427. * - The program calls the FLAC__stream_decoder_process_*() functions
  89428. * to decode data, which subsequently calls the callbacks.
  89429. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89430. * which flushes the input and output and resets the decoder to the
  89431. * uninitialized state.
  89432. * - The instance may be used again or deleted with
  89433. * FLAC__stream_decoder_delete().
  89434. *
  89435. * In more detail, the program will create a new instance by calling
  89436. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89437. * functions to override the default decoder options, and call
  89438. * one of the FLAC__stream_decoder_init_*() functions.
  89439. *
  89440. * There are three initialization functions for native FLAC, one for
  89441. * setting up the decoder to decode FLAC data from the client via
  89442. * callbacks, and two for decoding directly from a FLAC file.
  89443. *
  89444. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89445. * You must also supply several callbacks for handling I/O. Some (like
  89446. * seeking) are optional, depending on the capabilities of the input.
  89447. *
  89448. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89449. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89450. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89451. * the other callbacks internally.
  89452. *
  89453. * There are three similarly-named init functions for decoding from Ogg
  89454. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89455. * library has been built with Ogg support.
  89456. *
  89457. * Once the decoder is initialized, your program will call one of several
  89458. * functions to start the decoding process:
  89459. *
  89460. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89461. * most one metadata block or audio frame and return, calling either the
  89462. * metadata callback or write callback, respectively, once. If the decoder
  89463. * loses sync it will return with only the error callback being called.
  89464. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89465. * to process the stream from the current location and stop upon reaching
  89466. * the first audio frame. The client will get one metadata, write, or error
  89467. * callback per metadata block, audio frame, or sync error, respectively.
  89468. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89469. * to process the stream from the current location until the read callback
  89470. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89471. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89472. * write, or error callback per metadata block, audio frame, or sync error,
  89473. * respectively.
  89474. *
  89475. * When the decoder has finished decoding (normally or through an abort),
  89476. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89477. * ensures the decoder is in the correct state and frees memory. Then the
  89478. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89479. * again to decode another stream.
  89480. *
  89481. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89482. * At any point after the stream decoder has been initialized, the client can
  89483. * call this function to seek to an exact sample within the stream.
  89484. * Subsequently, the first time the write callback is called it will be
  89485. * passed a (possibly partial) block starting at that sample.
  89486. *
  89487. * If the client cannot seek via the callback interface provided, but still
  89488. * has another way of seeking, it can flush the decoder using
  89489. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89490. * through the read callback.
  89491. *
  89492. * The stream decoder also provides MD5 signature checking. If this is
  89493. * turned on before initialization, FLAC__stream_decoder_finish() will
  89494. * report when the decoded MD5 signature does not match the one stored
  89495. * in the STREAMINFO block. MD5 checking is automatically turned off
  89496. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89497. * in the STREAMINFO block or when a seek is attempted.
  89498. *
  89499. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89500. * attention. By default, the decoder only calls the metadata_callback for
  89501. * the STREAMINFO block. These functions allow you to tell the decoder
  89502. * explicitly which blocks to parse and return via the metadata_callback
  89503. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89504. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89505. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89506. * which blocks to return. Remember that metadata blocks can potentially
  89507. * be big (for example, cover art) so filtering out the ones you don't
  89508. * use can reduce the memory requirements of the decoder. Also note the
  89509. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89510. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89511. * filtering APPLICATION blocks based on the application ID.
  89512. *
  89513. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89514. * they still can legally be filtered from the metadata_callback.
  89515. *
  89516. * \note
  89517. * The "set" functions may only be called when the decoder is in the
  89518. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89519. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89520. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89521. * return \c true, otherwise \c false.
  89522. *
  89523. * \note
  89524. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89525. * defaults, including the callbacks.
  89526. *
  89527. * \{
  89528. */
  89529. /** State values for a FLAC__StreamDecoder
  89530. *
  89531. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89532. */
  89533. typedef enum {
  89534. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89535. /**< The decoder is ready to search for metadata. */
  89536. FLAC__STREAM_DECODER_READ_METADATA,
  89537. /**< The decoder is ready to or is in the process of reading metadata. */
  89538. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89539. /**< The decoder is ready to or is in the process of searching for the
  89540. * frame sync code.
  89541. */
  89542. FLAC__STREAM_DECODER_READ_FRAME,
  89543. /**< The decoder is ready to or is in the process of reading a frame. */
  89544. FLAC__STREAM_DECODER_END_OF_STREAM,
  89545. /**< The decoder has reached the end of the stream. */
  89546. FLAC__STREAM_DECODER_OGG_ERROR,
  89547. /**< An error occurred in the underlying Ogg layer. */
  89548. FLAC__STREAM_DECODER_SEEK_ERROR,
  89549. /**< An error occurred while seeking. The decoder must be flushed
  89550. * with FLAC__stream_decoder_flush() or reset with
  89551. * FLAC__stream_decoder_reset() before decoding can continue.
  89552. */
  89553. FLAC__STREAM_DECODER_ABORTED,
  89554. /**< The decoder was aborted by the read callback. */
  89555. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89556. /**< An error occurred allocating memory. The decoder is in an invalid
  89557. * state and can no longer be used.
  89558. */
  89559. FLAC__STREAM_DECODER_UNINITIALIZED
  89560. /**< The decoder is in the uninitialized state; one of the
  89561. * FLAC__stream_decoder_init_*() functions must be called before samples
  89562. * can be processed.
  89563. */
  89564. } FLAC__StreamDecoderState;
  89565. /** Maps a FLAC__StreamDecoderState to a C string.
  89566. *
  89567. * Using a FLAC__StreamDecoderState as the index to this array
  89568. * will give the string equivalent. The contents should not be modified.
  89569. */
  89570. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89571. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89572. */
  89573. typedef enum {
  89574. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89575. /**< Initialization was successful. */
  89576. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89577. /**< The library was not compiled with support for the given container
  89578. * format.
  89579. */
  89580. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89581. /**< A required callback was not supplied. */
  89582. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89583. /**< An error occurred allocating memory. */
  89584. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89585. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89586. * FLAC__stream_decoder_init_ogg_file(). */
  89587. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89588. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89589. * already initialized, usually because
  89590. * FLAC__stream_decoder_finish() was not called.
  89591. */
  89592. } FLAC__StreamDecoderInitStatus;
  89593. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89594. *
  89595. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89596. * will give the string equivalent. The contents should not be modified.
  89597. */
  89598. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89599. /** Return values for the FLAC__StreamDecoder read callback.
  89600. */
  89601. typedef enum {
  89602. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89603. /**< The read was OK and decoding can continue. */
  89604. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89605. /**< The read was attempted while at the end of the stream. Note that
  89606. * the client must only return this value when the read callback was
  89607. * called when already at the end of the stream. Otherwise, if the read
  89608. * itself moves to the end of the stream, the client should still return
  89609. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89610. * the next read callback it should return
  89611. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89612. * of \c 0.
  89613. */
  89614. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89615. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89616. } FLAC__StreamDecoderReadStatus;
  89617. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89618. *
  89619. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89620. * will give the string equivalent. The contents should not be modified.
  89621. */
  89622. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89623. /** Return values for the FLAC__StreamDecoder seek callback.
  89624. */
  89625. typedef enum {
  89626. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89627. /**< The seek was OK and decoding can continue. */
  89628. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89629. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89630. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89631. /**< Client does not support seeking. */
  89632. } FLAC__StreamDecoderSeekStatus;
  89633. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89634. *
  89635. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89636. * will give the string equivalent. The contents should not be modified.
  89637. */
  89638. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89639. /** Return values for the FLAC__StreamDecoder tell callback.
  89640. */
  89641. typedef enum {
  89642. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89643. /**< The tell was OK and decoding can continue. */
  89644. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89645. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89646. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89647. /**< Client does not support telling the position. */
  89648. } FLAC__StreamDecoderTellStatus;
  89649. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89650. *
  89651. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89652. * will give the string equivalent. The contents should not be modified.
  89653. */
  89654. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89655. /** Return values for the FLAC__StreamDecoder length callback.
  89656. */
  89657. typedef enum {
  89658. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89659. /**< The length call was OK and decoding can continue. */
  89660. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89661. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89662. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89663. /**< Client does not support reporting the length. */
  89664. } FLAC__StreamDecoderLengthStatus;
  89665. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89666. *
  89667. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89668. * will give the string equivalent. The contents should not be modified.
  89669. */
  89670. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89671. /** Return values for the FLAC__StreamDecoder write callback.
  89672. */
  89673. typedef enum {
  89674. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89675. /**< The write was OK and decoding can continue. */
  89676. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89677. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89678. } FLAC__StreamDecoderWriteStatus;
  89679. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89680. *
  89681. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89682. * will give the string equivalent. The contents should not be modified.
  89683. */
  89684. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89685. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89686. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89687. * all. The rest could be caused by bad sync (false synchronization on
  89688. * data that is not the start of a frame) or corrupted data. The error
  89689. * itself is the decoder's best guess at what happened assuming a correct
  89690. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89691. * could be caused by a correct sync on the start of a frame, but some
  89692. * data in the frame header was corrupted. Or it could be the result of
  89693. * syncing on a point the stream that looked like the starting of a frame
  89694. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89695. * could be because the decoder encountered a valid frame made by a future
  89696. * version of the encoder which it cannot parse, or because of a false
  89697. * sync making it appear as though an encountered frame was generated by
  89698. * a future encoder.
  89699. */
  89700. typedef enum {
  89701. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89702. /**< An error in the stream caused the decoder to lose synchronization. */
  89703. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89704. /**< The decoder encountered a corrupted frame header. */
  89705. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89706. /**< The frame's data did not match the CRC in the footer. */
  89707. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89708. /**< The decoder encountered reserved fields in use in the stream. */
  89709. } FLAC__StreamDecoderErrorStatus;
  89710. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89711. *
  89712. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89713. * will give the string equivalent. The contents should not be modified.
  89714. */
  89715. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89716. /***********************************************************************
  89717. *
  89718. * class FLAC__StreamDecoder
  89719. *
  89720. ***********************************************************************/
  89721. struct FLAC__StreamDecoderProtected;
  89722. struct FLAC__StreamDecoderPrivate;
  89723. /** The opaque structure definition for the stream decoder type.
  89724. * See the \link flac_stream_decoder stream decoder module \endlink
  89725. * for a detailed description.
  89726. */
  89727. typedef struct {
  89728. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89729. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89730. } FLAC__StreamDecoder;
  89731. /** Signature for the read callback.
  89732. *
  89733. * A function pointer matching this signature must be passed to
  89734. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89735. * called when the decoder needs more input data. The address of the
  89736. * buffer to be filled is supplied, along with the number of bytes the
  89737. * buffer can hold. The callback may choose to supply less data and
  89738. * modify the byte count but must be careful not to overflow the buffer.
  89739. * The callback then returns a status code chosen from
  89740. * FLAC__StreamDecoderReadStatus.
  89741. *
  89742. * Here is an example of a read callback for stdio streams:
  89743. * \code
  89744. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89745. * {
  89746. * FILE *file = ((MyClientData*)client_data)->file;
  89747. * if(*bytes > 0) {
  89748. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89749. * if(ferror(file))
  89750. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89751. * else if(*bytes == 0)
  89752. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89753. * else
  89754. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89755. * }
  89756. * else
  89757. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89758. * }
  89759. * \endcode
  89760. *
  89761. * \note In general, FLAC__StreamDecoder functions which change the
  89762. * state should not be called on the \a decoder while in the callback.
  89763. *
  89764. * \param decoder The decoder instance calling the callback.
  89765. * \param buffer A pointer to a location for the callee to store
  89766. * data to be decoded.
  89767. * \param bytes A pointer to the size of the buffer. On entry
  89768. * to the callback, it contains the maximum number
  89769. * of bytes that may be stored in \a buffer. The
  89770. * callee must set it to the actual number of bytes
  89771. * stored (0 in case of error or end-of-stream) before
  89772. * returning.
  89773. * \param client_data The callee's client data set through
  89774. * FLAC__stream_decoder_init_*().
  89775. * \retval FLAC__StreamDecoderReadStatus
  89776. * The callee's return status. Note that the callback should return
  89777. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89778. * zero bytes were read and there is no more data to be read.
  89779. */
  89780. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89781. /** Signature for the seek callback.
  89782. *
  89783. * A function pointer matching this signature may be passed to
  89784. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89785. * called when the decoder needs to seek the input stream. The decoder
  89786. * will pass the absolute byte offset to seek to, 0 meaning the
  89787. * beginning of the stream.
  89788. *
  89789. * Here is an example of a seek callback for stdio streams:
  89790. * \code
  89791. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89792. * {
  89793. * FILE *file = ((MyClientData*)client_data)->file;
  89794. * if(file == stdin)
  89795. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89796. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89797. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89798. * else
  89799. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89800. * }
  89801. * \endcode
  89802. *
  89803. * \note In general, FLAC__StreamDecoder functions which change the
  89804. * state should not be called on the \a decoder while in the callback.
  89805. *
  89806. * \param decoder The decoder instance calling the callback.
  89807. * \param absolute_byte_offset The offset from the beginning of the stream
  89808. * to seek to.
  89809. * \param client_data The callee's client data set through
  89810. * FLAC__stream_decoder_init_*().
  89811. * \retval FLAC__StreamDecoderSeekStatus
  89812. * The callee's return status.
  89813. */
  89814. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89815. /** Signature for the tell callback.
  89816. *
  89817. * A function pointer matching this signature may be passed to
  89818. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89819. * called when the decoder wants to know the current position of the
  89820. * stream. The callback should return the byte offset from the
  89821. * beginning of the stream.
  89822. *
  89823. * Here is an example of a tell callback for stdio streams:
  89824. * \code
  89825. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89826. * {
  89827. * FILE *file = ((MyClientData*)client_data)->file;
  89828. * off_t pos;
  89829. * if(file == stdin)
  89830. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89831. * else if((pos = ftello(file)) < 0)
  89832. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89833. * else {
  89834. * *absolute_byte_offset = (FLAC__uint64)pos;
  89835. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89836. * }
  89837. * }
  89838. * \endcode
  89839. *
  89840. * \note In general, FLAC__StreamDecoder functions which change the
  89841. * state should not be called on the \a decoder while in the callback.
  89842. *
  89843. * \param decoder The decoder instance calling the callback.
  89844. * \param absolute_byte_offset A pointer to storage for the current offset
  89845. * from the beginning of the stream.
  89846. * \param client_data The callee's client data set through
  89847. * FLAC__stream_decoder_init_*().
  89848. * \retval FLAC__StreamDecoderTellStatus
  89849. * The callee's return status.
  89850. */
  89851. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89852. /** Signature for the length callback.
  89853. *
  89854. * A function pointer matching this signature may be passed to
  89855. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89856. * called when the decoder wants to know the total length of the stream
  89857. * in bytes.
  89858. *
  89859. * Here is an example of a length callback for stdio streams:
  89860. * \code
  89861. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89862. * {
  89863. * FILE *file = ((MyClientData*)client_data)->file;
  89864. * struct stat filestats;
  89865. *
  89866. * if(file == stdin)
  89867. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89868. * else if(fstat(fileno(file), &filestats) != 0)
  89869. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89870. * else {
  89871. * *stream_length = (FLAC__uint64)filestats.st_size;
  89872. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89873. * }
  89874. * }
  89875. * \endcode
  89876. *
  89877. * \note In general, FLAC__StreamDecoder functions which change the
  89878. * state should not be called on the \a decoder while in the callback.
  89879. *
  89880. * \param decoder The decoder instance calling the callback.
  89881. * \param stream_length A pointer to storage for the length of the stream
  89882. * in bytes.
  89883. * \param client_data The callee's client data set through
  89884. * FLAC__stream_decoder_init_*().
  89885. * \retval FLAC__StreamDecoderLengthStatus
  89886. * The callee's return status.
  89887. */
  89888. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89889. /** Signature for the EOF callback.
  89890. *
  89891. * A function pointer matching this signature may be passed to
  89892. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89893. * called when the decoder needs to know if the end of the stream has
  89894. * been reached.
  89895. *
  89896. * Here is an example of a EOF callback for stdio streams:
  89897. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89898. * \code
  89899. * {
  89900. * FILE *file = ((MyClientData*)client_data)->file;
  89901. * return feof(file)? true : false;
  89902. * }
  89903. * \endcode
  89904. *
  89905. * \note In general, FLAC__StreamDecoder functions which change the
  89906. * state should not be called on the \a decoder while in the callback.
  89907. *
  89908. * \param decoder The decoder instance calling the callback.
  89909. * \param client_data The callee's client data set through
  89910. * FLAC__stream_decoder_init_*().
  89911. * \retval FLAC__bool
  89912. * \c true if the currently at the end of the stream, else \c false.
  89913. */
  89914. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89915. /** Signature for the write callback.
  89916. *
  89917. * A function pointer matching this signature must be passed to one of
  89918. * the FLAC__stream_decoder_init_*() functions.
  89919. * The supplied function will be called when the decoder has decoded a
  89920. * single audio frame. The decoder will pass the frame metadata as well
  89921. * as an array of pointers (one for each channel) pointing to the
  89922. * decoded audio.
  89923. *
  89924. * \note In general, FLAC__StreamDecoder functions which change the
  89925. * state should not be called on the \a decoder while in the callback.
  89926. *
  89927. * \param decoder The decoder instance calling the callback.
  89928. * \param frame The description of the decoded frame. See
  89929. * FLAC__Frame.
  89930. * \param buffer An array of pointers to decoded channels of data.
  89931. * Each pointer will point to an array of signed
  89932. * samples of length \a frame->header.blocksize.
  89933. * Channels will be ordered according to the FLAC
  89934. * specification; see the documentation for the
  89935. * <A HREF="../format.html#frame_header">frame header</A>.
  89936. * \param client_data The callee's client data set through
  89937. * FLAC__stream_decoder_init_*().
  89938. * \retval FLAC__StreamDecoderWriteStatus
  89939. * The callee's return status.
  89940. */
  89941. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89942. /** Signature for the metadata callback.
  89943. *
  89944. * A function pointer matching this signature must be passed to one of
  89945. * the FLAC__stream_decoder_init_*() functions.
  89946. * The supplied function will be called when the decoder has decoded a
  89947. * metadata block. In a valid FLAC file there will always be one
  89948. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89949. * These will be supplied by the decoder in the same order as they
  89950. * appear in the stream and always before the first audio frame (i.e.
  89951. * write callback). The metadata block that is passed in must not be
  89952. * modified, and it doesn't live beyond the callback, so you should make
  89953. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89954. * elsewhere. Since metadata blocks can potentially be large, by
  89955. * default the decoder only calls the metadata callback for the
  89956. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89957. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89958. *
  89959. * \note In general, FLAC__StreamDecoder functions which change the
  89960. * state should not be called on the \a decoder while in the callback.
  89961. *
  89962. * \param decoder The decoder instance calling the callback.
  89963. * \param metadata The decoded metadata block.
  89964. * \param client_data The callee's client data set through
  89965. * FLAC__stream_decoder_init_*().
  89966. */
  89967. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89968. /** Signature for the error callback.
  89969. *
  89970. * A function pointer matching this signature must be passed to one of
  89971. * the FLAC__stream_decoder_init_*() functions.
  89972. * The supplied function will be called whenever an error occurs during
  89973. * decoding.
  89974. *
  89975. * \note In general, FLAC__StreamDecoder functions which change the
  89976. * state should not be called on the \a decoder while in the callback.
  89977. *
  89978. * \param decoder The decoder instance calling the callback.
  89979. * \param status The error encountered by the decoder.
  89980. * \param client_data The callee's client data set through
  89981. * FLAC__stream_decoder_init_*().
  89982. */
  89983. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89984. /***********************************************************************
  89985. *
  89986. * Class constructor/destructor
  89987. *
  89988. ***********************************************************************/
  89989. /** Create a new stream decoder instance. The instance is created with
  89990. * default settings; see the individual FLAC__stream_decoder_set_*()
  89991. * functions for each setting's default.
  89992. *
  89993. * \retval FLAC__StreamDecoder*
  89994. * \c NULL if there was an error allocating memory, else the new instance.
  89995. */
  89996. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89997. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89998. *
  89999. * \param decoder A pointer to an existing decoder.
  90000. * \assert
  90001. * \code decoder != NULL \endcode
  90002. */
  90003. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90004. /***********************************************************************
  90005. *
  90006. * Public class method prototypes
  90007. *
  90008. ***********************************************************************/
  90009. /** Set the serial number for the FLAC stream within the Ogg container.
  90010. * The default behavior is to use the serial number of the first Ogg
  90011. * page. Setting a serial number here will explicitly specify which
  90012. * stream is to be decoded.
  90013. *
  90014. * \note
  90015. * This does not need to be set for native FLAC decoding.
  90016. *
  90017. * \default \c use serial number of first page
  90018. * \param decoder A decoder instance to set.
  90019. * \param serial_number See above.
  90020. * \assert
  90021. * \code decoder != NULL \endcode
  90022. * \retval FLAC__bool
  90023. * \c false if the decoder is already initialized, else \c true.
  90024. */
  90025. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90026. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90027. * compute the MD5 signature of the unencoded audio data while decoding
  90028. * and compare it to the signature from the STREAMINFO block, if it
  90029. * exists, during FLAC__stream_decoder_finish().
  90030. *
  90031. * MD5 signature checking will be turned off (until the next
  90032. * FLAC__stream_decoder_reset()) if there is no signature in the
  90033. * STREAMINFO block or when a seek is attempted.
  90034. *
  90035. * Clients that do not use the MD5 check should leave this off to speed
  90036. * up decoding.
  90037. *
  90038. * \default \c false
  90039. * \param decoder A decoder instance to set.
  90040. * \param value Flag value (see above).
  90041. * \assert
  90042. * \code decoder != NULL \endcode
  90043. * \retval FLAC__bool
  90044. * \c false if the decoder is already initialized, else \c true.
  90045. */
  90046. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90047. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90048. *
  90049. * \default By default, only the \c STREAMINFO block is returned via the
  90050. * metadata callback.
  90051. * \param decoder A decoder instance to set.
  90052. * \param type See above.
  90053. * \assert
  90054. * \code decoder != NULL \endcode
  90055. * \a type is valid
  90056. * \retval FLAC__bool
  90057. * \c false if the decoder is already initialized, else \c true.
  90058. */
  90059. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90060. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90061. * given \a id.
  90062. *
  90063. * \default By default, only the \c STREAMINFO block is returned via the
  90064. * metadata callback.
  90065. * \param decoder A decoder instance to set.
  90066. * \param id See above.
  90067. * \assert
  90068. * \code decoder != NULL \endcode
  90069. * \code id != NULL \endcode
  90070. * \retval FLAC__bool
  90071. * \c false if the decoder is already initialized, else \c true.
  90072. */
  90073. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90074. /** Direct the decoder to pass on all metadata blocks of any type.
  90075. *
  90076. * \default By default, only the \c STREAMINFO block is returned via the
  90077. * metadata callback.
  90078. * \param decoder A decoder instance to set.
  90079. * \assert
  90080. * \code decoder != NULL \endcode
  90081. * \retval FLAC__bool
  90082. * \c false if the decoder is already initialized, else \c true.
  90083. */
  90084. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90085. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90086. *
  90087. * \default By default, only the \c STREAMINFO block is returned via the
  90088. * metadata callback.
  90089. * \param decoder A decoder instance to set.
  90090. * \param type See above.
  90091. * \assert
  90092. * \code decoder != NULL \endcode
  90093. * \a type is valid
  90094. * \retval FLAC__bool
  90095. * \c false if the decoder is already initialized, else \c true.
  90096. */
  90097. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90098. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90099. * the given \a id.
  90100. *
  90101. * \default By default, only the \c STREAMINFO block is returned via the
  90102. * metadata callback.
  90103. * \param decoder A decoder instance to set.
  90104. * \param id See above.
  90105. * \assert
  90106. * \code decoder != NULL \endcode
  90107. * \code id != NULL \endcode
  90108. * \retval FLAC__bool
  90109. * \c false if the decoder is already initialized, else \c true.
  90110. */
  90111. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90112. /** Direct the decoder to filter out all metadata blocks of any type.
  90113. *
  90114. * \default By default, only the \c STREAMINFO block is returned via the
  90115. * metadata callback.
  90116. * \param decoder A decoder instance to set.
  90117. * \assert
  90118. * \code decoder != NULL \endcode
  90119. * \retval FLAC__bool
  90120. * \c false if the decoder is already initialized, else \c true.
  90121. */
  90122. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90123. /** Get the current decoder state.
  90124. *
  90125. * \param decoder A decoder instance to query.
  90126. * \assert
  90127. * \code decoder != NULL \endcode
  90128. * \retval FLAC__StreamDecoderState
  90129. * The current decoder state.
  90130. */
  90131. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90132. /** Get the current decoder state as a C string.
  90133. *
  90134. * \param decoder A decoder instance to query.
  90135. * \assert
  90136. * \code decoder != NULL \endcode
  90137. * \retval const char *
  90138. * The decoder state as a C string. Do not modify the contents.
  90139. */
  90140. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90141. /** Get the "MD5 signature checking" flag.
  90142. * This is the value of the setting, not whether or not the decoder is
  90143. * currently checking the MD5 (remember, it can be turned off automatically
  90144. * by a seek). When the decoder is reset the flag will be restored to the
  90145. * value returned by this function.
  90146. *
  90147. * \param decoder A decoder instance to query.
  90148. * \assert
  90149. * \code decoder != NULL \endcode
  90150. * \retval FLAC__bool
  90151. * See above.
  90152. */
  90153. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90154. /** Get the total number of samples in the stream being decoded.
  90155. * Will only be valid after decoding has started and will contain the
  90156. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90157. *
  90158. * \param decoder A decoder instance to query.
  90159. * \assert
  90160. * \code decoder != NULL \endcode
  90161. * \retval unsigned
  90162. * See above.
  90163. */
  90164. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90165. /** Get the current number of channels in the stream being decoded.
  90166. * Will only be valid after decoding has started and will contain the
  90167. * value from the most recently decoded frame header.
  90168. *
  90169. * \param decoder A decoder instance to query.
  90170. * \assert
  90171. * \code decoder != NULL \endcode
  90172. * \retval unsigned
  90173. * See above.
  90174. */
  90175. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90176. /** Get the current channel assignment in the stream being decoded.
  90177. * Will only be valid after decoding has started and will contain the
  90178. * value from the most recently decoded frame header.
  90179. *
  90180. * \param decoder A decoder instance to query.
  90181. * \assert
  90182. * \code decoder != NULL \endcode
  90183. * \retval FLAC__ChannelAssignment
  90184. * See above.
  90185. */
  90186. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90187. /** Get the current sample resolution in the stream being decoded.
  90188. * Will only be valid after decoding has started and will contain the
  90189. * value from the most recently decoded frame header.
  90190. *
  90191. * \param decoder A decoder instance to query.
  90192. * \assert
  90193. * \code decoder != NULL \endcode
  90194. * \retval unsigned
  90195. * See above.
  90196. */
  90197. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90198. /** Get the current sample rate in Hz of the stream being decoded.
  90199. * Will only be valid after decoding has started and will contain the
  90200. * value from the most recently decoded frame header.
  90201. *
  90202. * \param decoder A decoder instance to query.
  90203. * \assert
  90204. * \code decoder != NULL \endcode
  90205. * \retval unsigned
  90206. * See above.
  90207. */
  90208. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90209. /** Get the current blocksize of the stream being decoded.
  90210. * Will only be valid after decoding has started and will contain the
  90211. * value from the most recently decoded frame header.
  90212. *
  90213. * \param decoder A decoder instance to query.
  90214. * \assert
  90215. * \code decoder != NULL \endcode
  90216. * \retval unsigned
  90217. * See above.
  90218. */
  90219. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90220. /** Returns the decoder's current read position within the stream.
  90221. * The position is the byte offset from the start of the stream.
  90222. * Bytes before this position have been fully decoded. Note that
  90223. * there may still be undecoded bytes in the decoder's read FIFO.
  90224. * The returned position is correct even after a seek.
  90225. *
  90226. * \warning This function currently only works for native FLAC,
  90227. * not Ogg FLAC streams.
  90228. *
  90229. * \param decoder A decoder instance to query.
  90230. * \param position Address at which to return the desired position.
  90231. * \assert
  90232. * \code decoder != NULL \endcode
  90233. * \code position != NULL \endcode
  90234. * \retval FLAC__bool
  90235. * \c true if successful, \c false if the stream is not native FLAC,
  90236. * or there was an error from the 'tell' callback or it returned
  90237. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90238. */
  90239. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90240. /** Initialize the decoder instance to decode native FLAC streams.
  90241. *
  90242. * This flavor of initialization sets up the decoder to decode from a
  90243. * native FLAC stream. I/O is performed via callbacks to the client.
  90244. * For decoding from a plain file via filename or open FILE*,
  90245. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90246. * provide a simpler interface.
  90247. *
  90248. * This function should be called after FLAC__stream_decoder_new() and
  90249. * FLAC__stream_decoder_set_*() but before any of the
  90250. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90251. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90252. * if initialization succeeded.
  90253. *
  90254. * \param decoder An uninitialized decoder instance.
  90255. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90256. * pointer must not be \c NULL.
  90257. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90258. * pointer may be \c NULL if seeking is not
  90259. * supported. If \a seek_callback is not \c NULL then a
  90260. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90261. * Alternatively, a dummy seek callback that just
  90262. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90263. * may also be supplied, all though this is slightly
  90264. * less efficient for the decoder.
  90265. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90266. * pointer may be \c NULL if not supported by the client. If
  90267. * \a seek_callback is not \c NULL then a
  90268. * \a tell_callback must also be supplied.
  90269. * Alternatively, a dummy tell callback that just
  90270. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90271. * may also be supplied, all though this is slightly
  90272. * less efficient for the decoder.
  90273. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90274. * pointer may be \c NULL if not supported by the client. If
  90275. * \a seek_callback is not \c NULL then a
  90276. * \a length_callback must also be supplied.
  90277. * Alternatively, a dummy length callback that just
  90278. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90279. * may also be supplied, all though this is slightly
  90280. * less efficient for the decoder.
  90281. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90282. * pointer may be \c NULL if not supported by the client. If
  90283. * \a seek_callback is not \c NULL then a
  90284. * \a eof_callback must also be supplied.
  90285. * Alternatively, a dummy length callback that just
  90286. * returns \c false
  90287. * may also be supplied, all though this is slightly
  90288. * less efficient for the decoder.
  90289. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90290. * pointer must not be \c NULL.
  90291. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90292. * pointer may be \c NULL if the callback is not
  90293. * desired.
  90294. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90295. * pointer must not be \c NULL.
  90296. * \param client_data This value will be supplied to callbacks in their
  90297. * \a client_data argument.
  90298. * \assert
  90299. * \code decoder != NULL \endcode
  90300. * \retval FLAC__StreamDecoderInitStatus
  90301. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90302. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90303. */
  90304. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90305. FLAC__StreamDecoder *decoder,
  90306. FLAC__StreamDecoderReadCallback read_callback,
  90307. FLAC__StreamDecoderSeekCallback seek_callback,
  90308. FLAC__StreamDecoderTellCallback tell_callback,
  90309. FLAC__StreamDecoderLengthCallback length_callback,
  90310. FLAC__StreamDecoderEofCallback eof_callback,
  90311. FLAC__StreamDecoderWriteCallback write_callback,
  90312. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90313. FLAC__StreamDecoderErrorCallback error_callback,
  90314. void *client_data
  90315. );
  90316. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90317. *
  90318. * This flavor of initialization sets up the decoder to decode from a
  90319. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90320. * client. For decoding from a plain file via filename or open FILE*,
  90321. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90322. * provide a simpler interface.
  90323. *
  90324. * This function should be called after FLAC__stream_decoder_new() and
  90325. * FLAC__stream_decoder_set_*() but before any of the
  90326. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90327. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90328. * if initialization succeeded.
  90329. *
  90330. * \note Support for Ogg FLAC in the library is optional. If this
  90331. * library has been built without support for Ogg FLAC, this function
  90332. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90333. *
  90334. * \param decoder An uninitialized decoder instance.
  90335. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90336. * pointer must not be \c NULL.
  90337. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90338. * pointer may be \c NULL if seeking is not
  90339. * supported. If \a seek_callback is not \c NULL then a
  90340. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90341. * Alternatively, a dummy seek callback that just
  90342. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90343. * may also be supplied, all though this is slightly
  90344. * less efficient for the decoder.
  90345. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90346. * pointer may be \c NULL if not supported by the client. If
  90347. * \a seek_callback is not \c NULL then a
  90348. * \a tell_callback must also be supplied.
  90349. * Alternatively, a dummy tell callback that just
  90350. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90351. * may also be supplied, all though this is slightly
  90352. * less efficient for the decoder.
  90353. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90354. * pointer may be \c NULL if not supported by the client. If
  90355. * \a seek_callback is not \c NULL then a
  90356. * \a length_callback must also be supplied.
  90357. * Alternatively, a dummy length callback that just
  90358. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90359. * may also be supplied, all though this is slightly
  90360. * less efficient for the decoder.
  90361. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90362. * pointer may be \c NULL if not supported by the client. If
  90363. * \a seek_callback is not \c NULL then a
  90364. * \a eof_callback must also be supplied.
  90365. * Alternatively, a dummy length callback that just
  90366. * returns \c false
  90367. * may also be supplied, all though this is slightly
  90368. * less efficient for the decoder.
  90369. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90370. * pointer must not be \c NULL.
  90371. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90372. * pointer may be \c NULL if the callback is not
  90373. * desired.
  90374. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90375. * pointer must not be \c NULL.
  90376. * \param client_data This value will be supplied to callbacks in their
  90377. * \a client_data argument.
  90378. * \assert
  90379. * \code decoder != NULL \endcode
  90380. * \retval FLAC__StreamDecoderInitStatus
  90381. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90382. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90383. */
  90384. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90385. FLAC__StreamDecoder *decoder,
  90386. FLAC__StreamDecoderReadCallback read_callback,
  90387. FLAC__StreamDecoderSeekCallback seek_callback,
  90388. FLAC__StreamDecoderTellCallback tell_callback,
  90389. FLAC__StreamDecoderLengthCallback length_callback,
  90390. FLAC__StreamDecoderEofCallback eof_callback,
  90391. FLAC__StreamDecoderWriteCallback write_callback,
  90392. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90393. FLAC__StreamDecoderErrorCallback error_callback,
  90394. void *client_data
  90395. );
  90396. /** Initialize the decoder instance to decode native FLAC files.
  90397. *
  90398. * This flavor of initialization sets up the decoder to decode from a
  90399. * plain native FLAC file. For non-stdio streams, you must use
  90400. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90401. *
  90402. * This function should be called after FLAC__stream_decoder_new() and
  90403. * FLAC__stream_decoder_set_*() but before any of the
  90404. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90405. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90406. * if initialization succeeded.
  90407. *
  90408. * \param decoder An uninitialized decoder instance.
  90409. * \param file An open FLAC file. The file should have been
  90410. * opened with mode \c "rb" and rewound. The file
  90411. * becomes owned by the decoder and should not be
  90412. * manipulated by the client while decoding.
  90413. * Unless \a file is \c stdin, it will be closed
  90414. * when FLAC__stream_decoder_finish() is called.
  90415. * Note however that seeking will not work when
  90416. * decoding from \c stdout since it is not seekable.
  90417. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90418. * pointer must not be \c NULL.
  90419. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90420. * pointer may be \c NULL if the callback is not
  90421. * desired.
  90422. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90423. * pointer must not be \c NULL.
  90424. * \param client_data This value will be supplied to callbacks in their
  90425. * \a client_data argument.
  90426. * \assert
  90427. * \code decoder != NULL \endcode
  90428. * \code file != NULL \endcode
  90429. * \retval FLAC__StreamDecoderInitStatus
  90430. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90431. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90432. */
  90433. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90434. FLAC__StreamDecoder *decoder,
  90435. FILE *file,
  90436. FLAC__StreamDecoderWriteCallback write_callback,
  90437. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90438. FLAC__StreamDecoderErrorCallback error_callback,
  90439. void *client_data
  90440. );
  90441. /** Initialize the decoder instance to decode Ogg FLAC files.
  90442. *
  90443. * This flavor of initialization sets up the decoder to decode from a
  90444. * plain Ogg FLAC file. For non-stdio streams, you must use
  90445. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90446. *
  90447. * This function should be called after FLAC__stream_decoder_new() and
  90448. * FLAC__stream_decoder_set_*() but before any of the
  90449. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90450. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90451. * if initialization succeeded.
  90452. *
  90453. * \note Support for Ogg FLAC in the library is optional. If this
  90454. * library has been built without support for Ogg FLAC, this function
  90455. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90456. *
  90457. * \param decoder An uninitialized decoder instance.
  90458. * \param file An open FLAC file. The file should have been
  90459. * opened with mode \c "rb" and rewound. The file
  90460. * becomes owned by the decoder and should not be
  90461. * manipulated by the client while decoding.
  90462. * Unless \a file is \c stdin, it will be closed
  90463. * when FLAC__stream_decoder_finish() is called.
  90464. * Note however that seeking will not work when
  90465. * decoding from \c stdout since it is not seekable.
  90466. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90467. * pointer must not be \c NULL.
  90468. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90469. * pointer may be \c NULL if the callback is not
  90470. * desired.
  90471. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90472. * pointer must not be \c NULL.
  90473. * \param client_data This value will be supplied to callbacks in their
  90474. * \a client_data argument.
  90475. * \assert
  90476. * \code decoder != NULL \endcode
  90477. * \code file != NULL \endcode
  90478. * \retval FLAC__StreamDecoderInitStatus
  90479. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90480. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90481. */
  90482. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90483. FLAC__StreamDecoder *decoder,
  90484. FILE *file,
  90485. FLAC__StreamDecoderWriteCallback write_callback,
  90486. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90487. FLAC__StreamDecoderErrorCallback error_callback,
  90488. void *client_data
  90489. );
  90490. /** Initialize the decoder instance to decode native FLAC files.
  90491. *
  90492. * This flavor of initialization sets up the decoder to decode from a plain
  90493. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90494. * example, with Unicode filenames on Windows), you must use
  90495. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90496. * and provide callbacks for the I/O.
  90497. *
  90498. * This function should be called after FLAC__stream_decoder_new() and
  90499. * FLAC__stream_decoder_set_*() but before any of the
  90500. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90501. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90502. * if initialization succeeded.
  90503. *
  90504. * \param decoder An uninitialized decoder instance.
  90505. * \param filename The name of the file to decode from. The file will
  90506. * be opened with fopen(). Use \c NULL to decode from
  90507. * \c stdin. Note that \c stdin is not seekable.
  90508. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90509. * pointer must not be \c NULL.
  90510. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90511. * pointer may be \c NULL if the callback is not
  90512. * desired.
  90513. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90514. * pointer must not be \c NULL.
  90515. * \param client_data This value will be supplied to callbacks in their
  90516. * \a client_data argument.
  90517. * \assert
  90518. * \code decoder != NULL \endcode
  90519. * \retval FLAC__StreamDecoderInitStatus
  90520. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90521. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90522. */
  90523. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90524. FLAC__StreamDecoder *decoder,
  90525. const char *filename,
  90526. FLAC__StreamDecoderWriteCallback write_callback,
  90527. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90528. FLAC__StreamDecoderErrorCallback error_callback,
  90529. void *client_data
  90530. );
  90531. /** Initialize the decoder instance to decode Ogg FLAC files.
  90532. *
  90533. * This flavor of initialization sets up the decoder to decode from a plain
  90534. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90535. * example, with Unicode filenames on Windows), you must use
  90536. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90537. * and provide callbacks for the I/O.
  90538. *
  90539. * This function should be called after FLAC__stream_decoder_new() and
  90540. * FLAC__stream_decoder_set_*() but before any of the
  90541. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90542. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90543. * if initialization succeeded.
  90544. *
  90545. * \note Support for Ogg FLAC in the library is optional. If this
  90546. * library has been built without support for Ogg FLAC, this function
  90547. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90548. *
  90549. * \param decoder An uninitialized decoder instance.
  90550. * \param filename The name of the file to decode from. The file will
  90551. * be opened with fopen(). Use \c NULL to decode from
  90552. * \c stdin. Note that \c stdin is not seekable.
  90553. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90554. * pointer must not be \c NULL.
  90555. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90556. * pointer may be \c NULL if the callback is not
  90557. * desired.
  90558. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90559. * pointer must not be \c NULL.
  90560. * \param client_data This value will be supplied to callbacks in their
  90561. * \a client_data argument.
  90562. * \assert
  90563. * \code decoder != NULL \endcode
  90564. * \retval FLAC__StreamDecoderInitStatus
  90565. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90566. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90567. */
  90568. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90569. FLAC__StreamDecoder *decoder,
  90570. const char *filename,
  90571. FLAC__StreamDecoderWriteCallback write_callback,
  90572. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90573. FLAC__StreamDecoderErrorCallback error_callback,
  90574. void *client_data
  90575. );
  90576. /** Finish the decoding process.
  90577. * Flushes the decoding buffer, releases resources, resets the decoder
  90578. * settings to their defaults, and returns the decoder state to
  90579. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90580. *
  90581. * In the event of a prematurely-terminated decode, it is not strictly
  90582. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90583. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90584. * with a FLAC__stream_decoder_finish().
  90585. *
  90586. * \param decoder An uninitialized decoder instance.
  90587. * \assert
  90588. * \code decoder != NULL \endcode
  90589. * \retval FLAC__bool
  90590. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90591. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90592. * signature does not match the one computed by the decoder; else
  90593. * \c true.
  90594. */
  90595. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90596. /** Flush the stream input.
  90597. * The decoder's input buffer will be cleared and the state set to
  90598. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90599. * off MD5 checking.
  90600. *
  90601. * \param decoder A decoder instance.
  90602. * \assert
  90603. * \code decoder != NULL \endcode
  90604. * \retval FLAC__bool
  90605. * \c true if successful, else \c false if a memory allocation
  90606. * error occurs (in which case the state will be set to
  90607. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90608. */
  90609. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90610. /** Reset the decoding process.
  90611. * The decoder's input buffer will be cleared and the state set to
  90612. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90613. * FLAC__stream_decoder_finish() except that the settings are
  90614. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90615. * before decoding again. MD5 checking will be restored to its original
  90616. * setting.
  90617. *
  90618. * If the decoder is seekable, or was initialized with
  90619. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90620. * the decoder will also attempt to seek to the beginning of the file.
  90621. * If this rewind fails, this function will return \c false. It follows
  90622. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90623. * \c stdin.
  90624. *
  90625. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90626. * and is not seekable (i.e. no seek callback was provided or the seek
  90627. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90628. * is the duty of the client to start feeding data from the beginning of
  90629. * the stream on the next FLAC__stream_decoder_process() or
  90630. * FLAC__stream_decoder_process_interleaved() call.
  90631. *
  90632. * \param decoder A decoder instance.
  90633. * \assert
  90634. * \code decoder != NULL \endcode
  90635. * \retval FLAC__bool
  90636. * \c true if successful, else \c false if a memory allocation occurs
  90637. * (in which case the state will be set to
  90638. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90639. * occurs (the state will be unchanged).
  90640. */
  90641. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90642. /** Decode one metadata block or audio frame.
  90643. * This version instructs the decoder to decode a either a single metadata
  90644. * block or a single frame and stop, unless the callbacks return a fatal
  90645. * error or the read callback returns
  90646. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90647. *
  90648. * As the decoder needs more input it will call the read callback.
  90649. * Depending on what was decoded, the metadata or write callback will be
  90650. * called with the decoded metadata block or audio frame.
  90651. *
  90652. * Unless there is a fatal read error or end of stream, this function
  90653. * will return once one whole frame is decoded. In other words, if the
  90654. * stream is not synchronized or points to a corrupt frame header, the
  90655. * decoder will continue to try and resync until it gets to a valid
  90656. * frame, then decode one frame, then return. If the decoder points to
  90657. * a frame whose frame CRC in the frame footer does not match the
  90658. * computed frame CRC, this function will issue a
  90659. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90660. * error callback, and return, having decoded one complete, although
  90661. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90662. * correct length to the write callback.)
  90663. *
  90664. * \param decoder An initialized decoder instance.
  90665. * \assert
  90666. * \code decoder != NULL \endcode
  90667. * \retval FLAC__bool
  90668. * \c false if any fatal read, write, or memory allocation error
  90669. * occurred (meaning decoding must stop), else \c true; for more
  90670. * information about the decoder, check the decoder state with
  90671. * FLAC__stream_decoder_get_state().
  90672. */
  90673. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90674. /** Decode until the end of the metadata.
  90675. * This version instructs the decoder to decode from the current position
  90676. * and continue until all the metadata has been read, or until the
  90677. * callbacks return a fatal error or the read callback returns
  90678. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90679. *
  90680. * As the decoder needs more input it will call the read callback.
  90681. * As each metadata block is decoded, the metadata callback will be called
  90682. * with the decoded metadata.
  90683. *
  90684. * \param decoder An initialized decoder instance.
  90685. * \assert
  90686. * \code decoder != NULL \endcode
  90687. * \retval FLAC__bool
  90688. * \c false if any fatal read, write, or memory allocation error
  90689. * occurred (meaning decoding must stop), else \c true; for more
  90690. * information about the decoder, check the decoder state with
  90691. * FLAC__stream_decoder_get_state().
  90692. */
  90693. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90694. /** Decode until the end of the stream.
  90695. * This version instructs the decoder to decode from the current position
  90696. * and continue until the end of stream (the read callback returns
  90697. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90698. * callbacks return a fatal error.
  90699. *
  90700. * As the decoder needs more input it will call the read callback.
  90701. * As each metadata block and frame is decoded, the metadata or write
  90702. * callback will be called with the decoded metadata or frame.
  90703. *
  90704. * \param decoder An initialized decoder instance.
  90705. * \assert
  90706. * \code decoder != NULL \endcode
  90707. * \retval FLAC__bool
  90708. * \c false if any fatal read, write, or memory allocation error
  90709. * occurred (meaning decoding must stop), else \c true; for more
  90710. * information about the decoder, check the decoder state with
  90711. * FLAC__stream_decoder_get_state().
  90712. */
  90713. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90714. /** Skip one audio frame.
  90715. * This version instructs the decoder to 'skip' a single frame and stop,
  90716. * unless the callbacks return a fatal error or the read callback returns
  90717. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90718. *
  90719. * The decoding flow is the same as what occurs when
  90720. * FLAC__stream_decoder_process_single() is called to process an audio
  90721. * frame, except that this function does not decode the parsed data into
  90722. * PCM or call the write callback. The integrity of the frame is still
  90723. * checked the same way as in the other process functions.
  90724. *
  90725. * This function will return once one whole frame is skipped, in the
  90726. * same way that FLAC__stream_decoder_process_single() will return once
  90727. * one whole frame is decoded.
  90728. *
  90729. * This function can be used in more quickly determining FLAC frame
  90730. * boundaries when decoding of the actual data is not needed, for
  90731. * example when an application is separating a FLAC stream into frames
  90732. * for editing or storing in a container. To do this, the application
  90733. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90734. * to the next frame, then use
  90735. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90736. * boundary.
  90737. *
  90738. * This function should only be called when the stream has advanced
  90739. * past all the metadata, otherwise it will return \c false.
  90740. *
  90741. * \param decoder An initialized decoder instance not in a metadata
  90742. * state.
  90743. * \assert
  90744. * \code decoder != NULL \endcode
  90745. * \retval FLAC__bool
  90746. * \c false if any fatal read, write, or memory allocation error
  90747. * occurred (meaning decoding must stop), or if the decoder
  90748. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90749. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90750. * information about the decoder, check the decoder state with
  90751. * FLAC__stream_decoder_get_state().
  90752. */
  90753. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90754. /** Flush the input and seek to an absolute sample.
  90755. * Decoding will resume at the given sample. Note that because of
  90756. * this, the next write callback may contain a partial block. The
  90757. * client must support seeking the input or this function will fail
  90758. * and return \c false. Furthermore, if the decoder state is
  90759. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90760. * with FLAC__stream_decoder_flush() or reset with
  90761. * FLAC__stream_decoder_reset() before decoding can continue.
  90762. *
  90763. * \param decoder A decoder instance.
  90764. * \param sample The target sample number to seek to.
  90765. * \assert
  90766. * \code decoder != NULL \endcode
  90767. * \retval FLAC__bool
  90768. * \c true if successful, else \c false.
  90769. */
  90770. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90771. /* \} */
  90772. #ifdef __cplusplus
  90773. }
  90774. #endif
  90775. #endif
  90776. /*** End of inlined file: stream_decoder.h ***/
  90777. /*** Start of inlined file: stream_encoder.h ***/
  90778. #ifndef FLAC__STREAM_ENCODER_H
  90779. #define FLAC__STREAM_ENCODER_H
  90780. #include <stdio.h> /* for FILE */
  90781. #ifdef __cplusplus
  90782. extern "C" {
  90783. #endif
  90784. /** \file include/FLAC/stream_encoder.h
  90785. *
  90786. * \brief
  90787. * This module contains the functions which implement the stream
  90788. * encoder.
  90789. *
  90790. * See the detailed documentation in the
  90791. * \link flac_stream_encoder stream encoder \endlink module.
  90792. */
  90793. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90794. * \ingroup flac
  90795. *
  90796. * \brief
  90797. * This module describes the encoder layers provided by libFLAC.
  90798. *
  90799. * The stream encoder can be used to encode complete streams either to the
  90800. * client via callbacks, or directly to a file, depending on how it is
  90801. * initialized. When encoding via callbacks, the client provides a write
  90802. * callback which will be called whenever FLAC data is ready to be written.
  90803. * If the client also supplies a seek callback, the encoder will also
  90804. * automatically handle the writing back of metadata discovered while
  90805. * encoding, like stream info, seek points offsets, etc. When encoding to
  90806. * a file, the client needs only supply a filename or open \c FILE* and an
  90807. * optional progress callback for periodic notification of progress; the
  90808. * write and seek callbacks are supplied internally. For more info see the
  90809. * \link flac_stream_encoder stream encoder \endlink module.
  90810. */
  90811. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90812. * \ingroup flac_encoder
  90813. *
  90814. * \brief
  90815. * This module contains the functions which implement the stream
  90816. * encoder.
  90817. *
  90818. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90819. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90820. *
  90821. * The basic usage of this encoder is as follows:
  90822. * - The program creates an instance of an encoder using
  90823. * FLAC__stream_encoder_new().
  90824. * - The program overrides the default settings using
  90825. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90826. * functions should be called:
  90827. * - FLAC__stream_encoder_set_channels()
  90828. * - FLAC__stream_encoder_set_bits_per_sample()
  90829. * - FLAC__stream_encoder_set_sample_rate()
  90830. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90831. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90832. * - If the application wants to control the compression level or set its own
  90833. * metadata, then the following should also be called:
  90834. * - FLAC__stream_encoder_set_compression_level()
  90835. * - FLAC__stream_encoder_set_verify()
  90836. * - FLAC__stream_encoder_set_metadata()
  90837. * - The rest of the set functions should only be called if the client needs
  90838. * exact control over how the audio is compressed; thorough understanding
  90839. * of the FLAC format is necessary to achieve good results.
  90840. * - The program initializes the instance to validate the settings and
  90841. * prepare for encoding using
  90842. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90843. * or FLAC__stream_encoder_init_file() for native FLAC
  90844. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90845. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90846. * - The program calls FLAC__stream_encoder_process() or
  90847. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90848. * subsequently calls the callbacks when there is encoder data ready
  90849. * to be written.
  90850. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90851. * which causes the encoder to encode any data still in its input pipe,
  90852. * update the metadata with the final encoding statistics if output
  90853. * seeking is possible, and finally reset the encoder to the
  90854. * uninitialized state.
  90855. * - The instance may be used again or deleted with
  90856. * FLAC__stream_encoder_delete().
  90857. *
  90858. * In more detail, the stream encoder functions similarly to the
  90859. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90860. * callbacks and more options. Typically the client will create a new
  90861. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90862. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90863. * calling one of the FLAC__stream_encoder_init_*() functions.
  90864. *
  90865. * Unlike the decoders, the stream encoder has many options that can
  90866. * affect the speed and compression ratio. When setting these parameters
  90867. * you should have some basic knowledge of the format (see the
  90868. * <A HREF="../documentation.html#format">user-level documentation</A>
  90869. * or the <A HREF="../format.html">formal description</A>). The
  90870. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90871. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90872. * functions will do this, so make sure to pay attention to the state
  90873. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90874. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90875. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90876. * the constructor.
  90877. *
  90878. * There are three initialization functions for native FLAC, one for
  90879. * setting up the encoder to encode FLAC data to the client via
  90880. * callbacks, and two for encoding directly to a file.
  90881. *
  90882. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90883. * You must also supply a write callback which will be called anytime
  90884. * there is raw encoded data to write. If the client can seek the output
  90885. * it is best to also supply seek and tell callbacks, as this allows the
  90886. * encoder to go back after encoding is finished to write back
  90887. * information that was collected while encoding, like seek point offsets,
  90888. * frame sizes, etc.
  90889. *
  90890. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90891. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90892. * filename or open \c FILE*; the encoder will handle all the callbacks
  90893. * internally. You may also supply a progress callback for periodic
  90894. * notification of the encoding progress.
  90895. *
  90896. * There are three similarly-named init functions for encoding to Ogg
  90897. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90898. * library has been built with Ogg support.
  90899. *
  90900. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90901. * call the write callback several times, once with the \c fLaC signature,
  90902. * and once for each encoded metadata block. Note that for Ogg FLAC
  90903. * encoding you will usually get at least twice the number of callbacks than
  90904. * with native FLAC, one for the Ogg page header and one for the page body.
  90905. *
  90906. * After initializing the instance, the client may feed audio data to the
  90907. * encoder in one of two ways:
  90908. *
  90909. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90910. * will pass an array of pointers to buffers, one for each channel, to
  90911. * the encoder, each of the same length. The samples need not be
  90912. * block-aligned, but each channel should have the same number of samples.
  90913. * - Channel interleaved, through
  90914. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90915. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90916. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90917. * Again, the samples need not be block-aligned but they must be
  90918. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90919. * the last value channelN_sampleM.
  90920. *
  90921. * Note that for either process call, each sample in the buffers should be a
  90922. * signed integer, right-justified to the resolution set by
  90923. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90924. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90925. *
  90926. * When the client is finished encoding data, it calls
  90927. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90928. * data still in its input pipe, and call the metadata callback with the
  90929. * final encoding statistics. Then the instance may be deleted with
  90930. * FLAC__stream_encoder_delete() or initialized again to encode another
  90931. * stream.
  90932. *
  90933. * For programs that write their own metadata, but that do not know the
  90934. * actual metadata until after encoding, it is advantageous to instruct
  90935. * the encoder to write a PADDING block of the correct size, so that
  90936. * instead of rewriting the whole stream after encoding, the program can
  90937. * just overwrite the PADDING block. If only the maximum size of the
  90938. * metadata is known, the program can write a slightly larger padding
  90939. * block, then split it after encoding.
  90940. *
  90941. * Make sure you understand how lengths are calculated. All FLAC metadata
  90942. * blocks have a 4 byte header which contains the type and length. This
  90943. * length does not include the 4 bytes of the header. See the format page
  90944. * for the specification of metadata blocks and their lengths.
  90945. *
  90946. * \note
  90947. * If you are writing the FLAC data to a file via callbacks, make sure it
  90948. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90949. * after the first encoding pass, the encoder will try to seek back to the
  90950. * beginning of the stream, to the STREAMINFO block, to write some data
  90951. * there. (If using FLAC__stream_encoder_init*_file() or
  90952. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90953. *
  90954. * \note
  90955. * The "set" functions may only be called when the encoder is in the
  90956. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90957. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90958. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90959. * return \c true, otherwise \c false.
  90960. *
  90961. * \note
  90962. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90963. * defaults.
  90964. *
  90965. * \{
  90966. */
  90967. /** State values for a FLAC__StreamEncoder.
  90968. *
  90969. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90970. *
  90971. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90972. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90973. * must be deleted with FLAC__stream_encoder_delete().
  90974. */
  90975. typedef enum {
  90976. FLAC__STREAM_ENCODER_OK = 0,
  90977. /**< The encoder is in the normal OK state and samples can be processed. */
  90978. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90979. /**< The encoder is in the uninitialized state; one of the
  90980. * FLAC__stream_encoder_init_*() functions must be called before samples
  90981. * can be processed.
  90982. */
  90983. FLAC__STREAM_ENCODER_OGG_ERROR,
  90984. /**< An error occurred in the underlying Ogg layer. */
  90985. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90986. /**< An error occurred in the underlying verify stream decoder;
  90987. * check FLAC__stream_encoder_get_verify_decoder_state().
  90988. */
  90989. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90990. /**< The verify decoder detected a mismatch between the original
  90991. * audio signal and the decoded audio signal.
  90992. */
  90993. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90994. /**< One of the callbacks returned a fatal error. */
  90995. FLAC__STREAM_ENCODER_IO_ERROR,
  90996. /**< An I/O error occurred while opening/reading/writing a file.
  90997. * Check \c errno.
  90998. */
  90999. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91000. /**< An error occurred while writing the stream; usually, the
  91001. * write_callback returned an error.
  91002. */
  91003. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91004. /**< Memory allocation failed. */
  91005. } FLAC__StreamEncoderState;
  91006. /** Maps a FLAC__StreamEncoderState to a C string.
  91007. *
  91008. * Using a FLAC__StreamEncoderState as the index to this array
  91009. * will give the string equivalent. The contents should not be modified.
  91010. */
  91011. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91012. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91013. */
  91014. typedef enum {
  91015. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91016. /**< Initialization was successful. */
  91017. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91018. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91019. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91020. /**< The library was not compiled with support for the given container
  91021. * format.
  91022. */
  91023. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91024. /**< A required callback was not supplied. */
  91025. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91026. /**< The encoder has an invalid setting for number of channels. */
  91027. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91028. /**< The encoder has an invalid setting for bits-per-sample.
  91029. * FLAC supports 4-32 bps but the reference encoder currently supports
  91030. * only up to 24 bps.
  91031. */
  91032. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91033. /**< The encoder has an invalid setting for the input sample rate. */
  91034. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91035. /**< The encoder has an invalid setting for the block size. */
  91036. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91037. /**< The encoder has an invalid setting for the maximum LPC order. */
  91038. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91039. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91040. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91041. /**< The specified block size is less than the maximum LPC order. */
  91042. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91043. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91044. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91045. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91046. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91047. * - One of the metadata blocks contains an undefined type
  91048. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91049. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91050. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91051. */
  91052. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91053. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91054. * already initialized, usually because
  91055. * FLAC__stream_encoder_finish() was not called.
  91056. */
  91057. } FLAC__StreamEncoderInitStatus;
  91058. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91059. *
  91060. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91061. * will give the string equivalent. The contents should not be modified.
  91062. */
  91063. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91064. /** Return values for the FLAC__StreamEncoder read callback.
  91065. */
  91066. typedef enum {
  91067. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91068. /**< The read was OK and decoding can continue. */
  91069. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91070. /**< The read was attempted at the end of the stream. */
  91071. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91072. /**< An unrecoverable error occurred. */
  91073. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91074. /**< Client does not support reading back from the output. */
  91075. } FLAC__StreamEncoderReadStatus;
  91076. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91077. *
  91078. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91079. * will give the string equivalent. The contents should not be modified.
  91080. */
  91081. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91082. /** Return values for the FLAC__StreamEncoder write callback.
  91083. */
  91084. typedef enum {
  91085. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91086. /**< The write was OK and encoding can continue. */
  91087. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91088. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91089. } FLAC__StreamEncoderWriteStatus;
  91090. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91091. *
  91092. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91093. * will give the string equivalent. The contents should not be modified.
  91094. */
  91095. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91096. /** Return values for the FLAC__StreamEncoder seek callback.
  91097. */
  91098. typedef enum {
  91099. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91100. /**< The seek was OK and encoding can continue. */
  91101. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91102. /**< An unrecoverable error occurred. */
  91103. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91104. /**< Client does not support seeking. */
  91105. } FLAC__StreamEncoderSeekStatus;
  91106. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91107. *
  91108. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91109. * will give the string equivalent. The contents should not be modified.
  91110. */
  91111. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91112. /** Return values for the FLAC__StreamEncoder tell callback.
  91113. */
  91114. typedef enum {
  91115. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91116. /**< The tell was OK and encoding can continue. */
  91117. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91118. /**< An unrecoverable error occurred. */
  91119. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91120. /**< Client does not support seeking. */
  91121. } FLAC__StreamEncoderTellStatus;
  91122. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91123. *
  91124. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91125. * will give the string equivalent. The contents should not be modified.
  91126. */
  91127. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91128. /***********************************************************************
  91129. *
  91130. * class FLAC__StreamEncoder
  91131. *
  91132. ***********************************************************************/
  91133. struct FLAC__StreamEncoderProtected;
  91134. struct FLAC__StreamEncoderPrivate;
  91135. /** The opaque structure definition for the stream encoder type.
  91136. * See the \link flac_stream_encoder stream encoder module \endlink
  91137. * for a detailed description.
  91138. */
  91139. typedef struct {
  91140. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91141. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91142. } FLAC__StreamEncoder;
  91143. /** Signature for the read callback.
  91144. *
  91145. * A function pointer matching this signature must be passed to
  91146. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91147. * The supplied function will be called when the encoder needs to read back
  91148. * encoded data. This happens during the metadata callback, when the encoder
  91149. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91150. * while encoding. The address of the buffer to be filled is supplied, along
  91151. * with the number of bytes the buffer can hold. The callback may choose to
  91152. * supply less data and modify the byte count but must be careful not to
  91153. * overflow the buffer. The callback then returns a status code chosen from
  91154. * FLAC__StreamEncoderReadStatus.
  91155. *
  91156. * Here is an example of a read callback for stdio streams:
  91157. * \code
  91158. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91159. * {
  91160. * FILE *file = ((MyClientData*)client_data)->file;
  91161. * if(*bytes > 0) {
  91162. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91163. * if(ferror(file))
  91164. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91165. * else if(*bytes == 0)
  91166. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91167. * else
  91168. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91169. * }
  91170. * else
  91171. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91172. * }
  91173. * \endcode
  91174. *
  91175. * \note In general, FLAC__StreamEncoder functions which change the
  91176. * state should not be called on the \a encoder while in the callback.
  91177. *
  91178. * \param encoder The encoder instance calling the callback.
  91179. * \param buffer A pointer to a location for the callee to store
  91180. * data to be encoded.
  91181. * \param bytes A pointer to the size of the buffer. On entry
  91182. * to the callback, it contains the maximum number
  91183. * of bytes that may be stored in \a buffer. The
  91184. * callee must set it to the actual number of bytes
  91185. * stored (0 in case of error or end-of-stream) before
  91186. * returning.
  91187. * \param client_data The callee's client data set through
  91188. * FLAC__stream_encoder_set_client_data().
  91189. * \retval FLAC__StreamEncoderReadStatus
  91190. * The callee's return status.
  91191. */
  91192. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91193. /** Signature for the write callback.
  91194. *
  91195. * A function pointer matching this signature must be passed to
  91196. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91197. * by the encoder anytime there is raw encoded data ready to write. It may
  91198. * include metadata mixed with encoded audio frames and the data is not
  91199. * guaranteed to be aligned on frame or metadata block boundaries.
  91200. *
  91201. * The only duty of the callback is to write out the \a bytes worth of data
  91202. * in \a buffer to the current position in the output stream. The arguments
  91203. * \a samples and \a current_frame are purely informational. If \a samples
  91204. * is greater than \c 0, then \a current_frame will hold the current frame
  91205. * number that is being written; otherwise it indicates that the write
  91206. * callback is being called to write metadata.
  91207. *
  91208. * \note
  91209. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91210. * write callback will be called twice when writing each audio
  91211. * frame; once for the page header, and once for the page body.
  91212. * When writing the page header, the \a samples argument to the
  91213. * write callback will be \c 0.
  91214. *
  91215. * \note In general, FLAC__StreamEncoder functions which change the
  91216. * state should not be called on the \a encoder while in the callback.
  91217. *
  91218. * \param encoder The encoder instance calling the callback.
  91219. * \param buffer An array of encoded data of length \a bytes.
  91220. * \param bytes The byte length of \a buffer.
  91221. * \param samples The number of samples encoded by \a buffer.
  91222. * \c 0 has a special meaning; see above.
  91223. * \param current_frame The number of the current frame being encoded.
  91224. * \param client_data The callee's client data set through
  91225. * FLAC__stream_encoder_init_*().
  91226. * \retval FLAC__StreamEncoderWriteStatus
  91227. * The callee's return status.
  91228. */
  91229. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91230. /** Signature for the seek callback.
  91231. *
  91232. * A function pointer matching this signature may be passed to
  91233. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91234. * when the encoder needs to seek the output stream. The encoder will pass
  91235. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91236. *
  91237. * Here is an example of a seek callback for stdio streams:
  91238. * \code
  91239. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91240. * {
  91241. * FILE *file = ((MyClientData*)client_data)->file;
  91242. * if(file == stdin)
  91243. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91244. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91245. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91246. * else
  91247. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91248. * }
  91249. * \endcode
  91250. *
  91251. * \note In general, FLAC__StreamEncoder functions which change the
  91252. * state should not be called on the \a encoder while in the callback.
  91253. *
  91254. * \param encoder The encoder instance calling the callback.
  91255. * \param absolute_byte_offset The offset from the beginning of the stream
  91256. * to seek to.
  91257. * \param client_data The callee's client data set through
  91258. * FLAC__stream_encoder_init_*().
  91259. * \retval FLAC__StreamEncoderSeekStatus
  91260. * The callee's return status.
  91261. */
  91262. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91263. /** Signature for the tell callback.
  91264. *
  91265. * A function pointer matching this signature may be passed to
  91266. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91267. * when the encoder needs to know the current position of the output stream.
  91268. *
  91269. * \warning
  91270. * The callback must return the true current byte offset of the output to
  91271. * which the encoder is writing. If you are buffering the output, make
  91272. * sure and take this into account. If you are writing directly to a
  91273. * FILE* from your write callback, ftell() is sufficient. If you are
  91274. * writing directly to a file descriptor from your write callback, you
  91275. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91276. * these points to rewrite metadata after encoding.
  91277. *
  91278. * Here is an example of a tell callback for stdio streams:
  91279. * \code
  91280. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91281. * {
  91282. * FILE *file = ((MyClientData*)client_data)->file;
  91283. * off_t pos;
  91284. * if(file == stdin)
  91285. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91286. * else if((pos = ftello(file)) < 0)
  91287. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91288. * else {
  91289. * *absolute_byte_offset = (FLAC__uint64)pos;
  91290. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91291. * }
  91292. * }
  91293. * \endcode
  91294. *
  91295. * \note In general, FLAC__StreamEncoder functions which change the
  91296. * state should not be called on the \a encoder while in the callback.
  91297. *
  91298. * \param encoder The encoder instance calling the callback.
  91299. * \param absolute_byte_offset The address at which to store the current
  91300. * position of the output.
  91301. * \param client_data The callee's client data set through
  91302. * FLAC__stream_encoder_init_*().
  91303. * \retval FLAC__StreamEncoderTellStatus
  91304. * The callee's return status.
  91305. */
  91306. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91307. /** Signature for the metadata callback.
  91308. *
  91309. * A function pointer matching this signature may be passed to
  91310. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91311. * once at the end of encoding with the populated STREAMINFO structure. This
  91312. * is so the client can seek back to the beginning of the file and write the
  91313. * STREAMINFO block with the correct statistics after encoding (like
  91314. * minimum/maximum frame size and total samples).
  91315. *
  91316. * \note In general, FLAC__StreamEncoder functions which change the
  91317. * state should not be called on the \a encoder while in the callback.
  91318. *
  91319. * \param encoder The encoder instance calling the callback.
  91320. * \param metadata The final populated STREAMINFO block.
  91321. * \param client_data The callee's client data set through
  91322. * FLAC__stream_encoder_init_*().
  91323. */
  91324. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91325. /** Signature for the progress callback.
  91326. *
  91327. * A function pointer matching this signature may be passed to
  91328. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91329. * The supplied function will be called when the encoder has finished
  91330. * writing a frame. The \c total_frames_estimate argument to the
  91331. * callback will be based on the value from
  91332. * FLAC__stream_encoder_set_total_samples_estimate().
  91333. *
  91334. * \note In general, FLAC__StreamEncoder functions which change the
  91335. * state should not be called on the \a encoder while in the callback.
  91336. *
  91337. * \param encoder The encoder instance calling the callback.
  91338. * \param bytes_written Bytes written so far.
  91339. * \param samples_written Samples written so far.
  91340. * \param frames_written Frames written so far.
  91341. * \param total_frames_estimate The estimate of the total number of
  91342. * frames to be written.
  91343. * \param client_data The callee's client data set through
  91344. * FLAC__stream_encoder_init_*().
  91345. */
  91346. 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);
  91347. /***********************************************************************
  91348. *
  91349. * Class constructor/destructor
  91350. *
  91351. ***********************************************************************/
  91352. /** Create a new stream encoder instance. The instance is created with
  91353. * default settings; see the individual FLAC__stream_encoder_set_*()
  91354. * functions for each setting's default.
  91355. *
  91356. * \retval FLAC__StreamEncoder*
  91357. * \c NULL if there was an error allocating memory, else the new instance.
  91358. */
  91359. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91360. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91361. *
  91362. * \param encoder A pointer to an existing encoder.
  91363. * \assert
  91364. * \code encoder != NULL \endcode
  91365. */
  91366. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91367. /***********************************************************************
  91368. *
  91369. * Public class method prototypes
  91370. *
  91371. ***********************************************************************/
  91372. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91373. *
  91374. * \note
  91375. * This does not need to be set for native FLAC encoding.
  91376. *
  91377. * \note
  91378. * It is recommended to set a serial number explicitly as the default of '0'
  91379. * may collide with other streams.
  91380. *
  91381. * \default \c 0
  91382. * \param encoder An encoder instance to set.
  91383. * \param serial_number See above.
  91384. * \assert
  91385. * \code encoder != NULL \endcode
  91386. * \retval FLAC__bool
  91387. * \c false if the encoder is already initialized, else \c true.
  91388. */
  91389. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91390. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91391. * encoded output by feeding it through an internal decoder and comparing
  91392. * the original signal against the decoded signal. If a mismatch occurs,
  91393. * the process call will return \c false. Note that this will slow the
  91394. * encoding process by the extra time required for decoding and comparison.
  91395. *
  91396. * \default \c false
  91397. * \param encoder An encoder instance to set.
  91398. * \param value Flag value (see above).
  91399. * \assert
  91400. * \code encoder != NULL \endcode
  91401. * \retval FLAC__bool
  91402. * \c false if the encoder is already initialized, else \c true.
  91403. */
  91404. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91405. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91406. * the encoder will comply with the Subset and will check the
  91407. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91408. * comply. If \c false, the settings may take advantage of the full
  91409. * range that the format allows.
  91410. *
  91411. * Make sure you know what it entails before setting this to \c false.
  91412. *
  91413. * \default \c true
  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_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91422. /** Set the number of channels to be encoded.
  91423. *
  91424. * \default \c 2
  91425. * \param encoder An encoder instance to set.
  91426. * \param value See above.
  91427. * \assert
  91428. * \code encoder != NULL \endcode
  91429. * \retval FLAC__bool
  91430. * \c false if the encoder is already initialized, else \c true.
  91431. */
  91432. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91433. /** Set the sample resolution of the input to be encoded.
  91434. *
  91435. * \warning
  91436. * Do not feed the encoder data that is wider than the value you
  91437. * set here or you will generate an invalid stream.
  91438. *
  91439. * \default \c 16
  91440. * \param encoder An encoder instance to set.
  91441. * \param value See above.
  91442. * \assert
  91443. * \code encoder != NULL \endcode
  91444. * \retval FLAC__bool
  91445. * \c false if the encoder is already initialized, else \c true.
  91446. */
  91447. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91448. /** Set the sample rate (in Hz) of the input to be encoded.
  91449. *
  91450. * \default \c 44100
  91451. * \param encoder An encoder instance to set.
  91452. * \param value See above.
  91453. * \assert
  91454. * \code encoder != NULL \endcode
  91455. * \retval FLAC__bool
  91456. * \c false if the encoder is already initialized, else \c true.
  91457. */
  91458. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91459. /** Set the compression level
  91460. *
  91461. * The compression level is roughly proportional to the amount of effort
  91462. * the encoder expends to compress the file. A higher level usually
  91463. * means more computation but higher compression. The default level is
  91464. * suitable for most applications.
  91465. *
  91466. * Currently the levels range from \c 0 (fastest, least compression) to
  91467. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91468. * treated as \c 8.
  91469. *
  91470. * This function automatically calls the following other \c _set_
  91471. * functions with appropriate values, so the client does not need to
  91472. * unless it specifically wants to override them:
  91473. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91474. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91475. * - FLAC__stream_encoder_set_apodization()
  91476. * - FLAC__stream_encoder_set_max_lpc_order()
  91477. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91478. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91479. * - FLAC__stream_encoder_set_do_escape_coding()
  91480. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91481. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91482. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91483. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91484. *
  91485. * The actual values set for each level are:
  91486. * <table>
  91487. * <tr>
  91488. * <td><b>level</b><td>
  91489. * <td>do mid-side stereo<td>
  91490. * <td>loose mid-side stereo<td>
  91491. * <td>apodization<td>
  91492. * <td>max lpc order<td>
  91493. * <td>qlp coeff precision<td>
  91494. * <td>qlp coeff prec search<td>
  91495. * <td>escape coding<td>
  91496. * <td>exhaustive model search<td>
  91497. * <td>min residual partition order<td>
  91498. * <td>max residual partition order<td>
  91499. * <td>rice parameter search dist<td>
  91500. * </tr>
  91501. * <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>
  91502. * <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>
  91503. * <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>
  91504. * <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>
  91505. * <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>
  91506. * <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>
  91507. * <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>
  91508. * <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>
  91509. * <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>
  91510. * </table>
  91511. *
  91512. * \default \c 5
  91513. * \param encoder An encoder instance to set.
  91514. * \param value See above.
  91515. * \assert
  91516. * \code encoder != NULL \endcode
  91517. * \retval FLAC__bool
  91518. * \c false if the encoder is already initialized, else \c true.
  91519. */
  91520. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91521. /** Set the blocksize to use while encoding.
  91522. *
  91523. * The number of samples to use per frame. Use \c 0 to let the encoder
  91524. * estimate a blocksize; this is usually best.
  91525. *
  91526. * \default \c 0
  91527. * \param encoder An encoder instance to set.
  91528. * \param value See above.
  91529. * \assert
  91530. * \code encoder != NULL \endcode
  91531. * \retval FLAC__bool
  91532. * \c false if the encoder is already initialized, else \c true.
  91533. */
  91534. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91535. /** Set to \c true to enable mid-side encoding on stereo input. The
  91536. * number of channels must be 2 for this to have any effect. Set to
  91537. * \c false to use only independent channel coding.
  91538. *
  91539. * \default \c false
  91540. * \param encoder An encoder instance to set.
  91541. * \param value Flag value (see above).
  91542. * \assert
  91543. * \code encoder != NULL \endcode
  91544. * \retval FLAC__bool
  91545. * \c false if the encoder is already initialized, else \c true.
  91546. */
  91547. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91548. /** Set to \c true to enable adaptive switching between mid-side and
  91549. * left-right encoding on stereo input. Set to \c false to use
  91550. * exhaustive searching. Setting this to \c true requires
  91551. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91552. * \c true in order to have any effect.
  91553. *
  91554. * \default \c false
  91555. * \param encoder An encoder instance to set.
  91556. * \param value Flag value (see above).
  91557. * \assert
  91558. * \code encoder != NULL \endcode
  91559. * \retval FLAC__bool
  91560. * \c false if the encoder is already initialized, else \c true.
  91561. */
  91562. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91563. /** Sets the apodization function(s) the encoder will use when windowing
  91564. * audio data for LPC analysis.
  91565. *
  91566. * The \a specification is a plain ASCII string which specifies exactly
  91567. * which functions to use. There may be more than one (up to 32),
  91568. * separated by \c ';' characters. Some functions take one or more
  91569. * comma-separated arguments in parentheses.
  91570. *
  91571. * The available functions are \c bartlett, \c bartlett_hann,
  91572. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91573. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91574. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91575. *
  91576. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91577. * (0<STDDEV<=0.5).
  91578. *
  91579. * For \c tukey(P), P specifies the fraction of the window that is
  91580. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91581. * corresponds to \c hann.
  91582. *
  91583. * Example specifications are \c "blackman" or
  91584. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91585. *
  91586. * Any function that is specified erroneously is silently dropped. Up
  91587. * to 32 functions are kept, the rest are dropped. If the specification
  91588. * is empty the encoder defaults to \c "tukey(0.5)".
  91589. *
  91590. * When more than one function is specified, then for every subframe the
  91591. * encoder will try each of them separately and choose the window that
  91592. * results in the smallest compressed subframe.
  91593. *
  91594. * Note that each function specified causes the encoder to occupy a
  91595. * floating point array in which to store the window.
  91596. *
  91597. * \default \c "tukey(0.5)"
  91598. * \param encoder An encoder instance to set.
  91599. * \param specification See above.
  91600. * \assert
  91601. * \code encoder != NULL \endcode
  91602. * \code specification != NULL \endcode
  91603. * \retval FLAC__bool
  91604. * \c false if the encoder is already initialized, else \c true.
  91605. */
  91606. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91607. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91608. *
  91609. * \default \c 0
  91610. * \param encoder An encoder instance to set.
  91611. * \param value See above.
  91612. * \assert
  91613. * \code encoder != NULL \endcode
  91614. * \retval FLAC__bool
  91615. * \c false if the encoder is already initialized, else \c true.
  91616. */
  91617. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91618. /** Set the precision, in bits, of the quantized linear predictor
  91619. * coefficients, or \c 0 to let the encoder select it based on the
  91620. * blocksize.
  91621. *
  91622. * \note
  91623. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91624. * be less than 32.
  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_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91635. /** Set to \c false to use only the specified quantized linear predictor
  91636. * coefficient precision, or \c true to search neighboring precision
  91637. * values and use the best one.
  91638. *
  91639. * \default \c false
  91640. * \param encoder An encoder instance to set.
  91641. * \param value See above.
  91642. * \assert
  91643. * \code encoder != NULL \endcode
  91644. * \retval FLAC__bool
  91645. * \c false if the encoder is already initialized, else \c true.
  91646. */
  91647. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91648. /** Deprecated. Setting this value has no effect.
  91649. *
  91650. * \default \c false
  91651. * \param encoder An encoder instance to set.
  91652. * \param value See above.
  91653. * \assert
  91654. * \code encoder != NULL \endcode
  91655. * \retval FLAC__bool
  91656. * \c false if the encoder is already initialized, else \c true.
  91657. */
  91658. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91659. /** Set to \c false to let the encoder estimate the best model order
  91660. * based on the residual signal energy, or \c true to force the
  91661. * encoder to evaluate all order models and select the best.
  91662. *
  91663. * \default \c false
  91664. * \param encoder An encoder instance to set.
  91665. * \param value See above.
  91666. * \assert
  91667. * \code encoder != NULL \endcode
  91668. * \retval FLAC__bool
  91669. * \c false if the encoder is already initialized, else \c true.
  91670. */
  91671. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91672. /** Set the minimum partition order to search when coding the residual.
  91673. * This is used in tandem with
  91674. * FLAC__stream_encoder_set_max_residual_partition_order().
  91675. *
  91676. * The partition order determines the context size in the residual.
  91677. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91678. *
  91679. * Set both min and max values to \c 0 to force a single context,
  91680. * whose Rice parameter is based on the residual signal variance.
  91681. * Otherwise, set a min and max order, and the encoder will search
  91682. * all orders, using the mean of each context for its Rice parameter,
  91683. * and use the best.
  91684. *
  91685. * \default \c 0
  91686. * \param encoder An encoder instance to set.
  91687. * \param value See above.
  91688. * \assert
  91689. * \code encoder != NULL \endcode
  91690. * \retval FLAC__bool
  91691. * \c false if the encoder is already initialized, else \c true.
  91692. */
  91693. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91694. /** Set the maximum partition order to search when coding the residual.
  91695. * This is used in tandem with
  91696. * FLAC__stream_encoder_set_min_residual_partition_order().
  91697. *
  91698. * The partition order determines the context size in the residual.
  91699. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91700. *
  91701. * Set both min and max values to \c 0 to force a single context,
  91702. * whose Rice parameter is based on the residual signal variance.
  91703. * Otherwise, set a min and max order, and the encoder will search
  91704. * all orders, using the mean of each context for its Rice parameter,
  91705. * and use the best.
  91706. *
  91707. * \default \c 0
  91708. * \param encoder An encoder instance to set.
  91709. * \param value See above.
  91710. * \assert
  91711. * \code encoder != NULL \endcode
  91712. * \retval FLAC__bool
  91713. * \c false if the encoder is already initialized, else \c true.
  91714. */
  91715. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91716. /** Deprecated. Setting this value has no effect.
  91717. *
  91718. * \default \c 0
  91719. * \param encoder An encoder instance to set.
  91720. * \param value See above.
  91721. * \assert
  91722. * \code encoder != NULL \endcode
  91723. * \retval FLAC__bool
  91724. * \c false if the encoder is already initialized, else \c true.
  91725. */
  91726. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91727. /** Set an estimate of the total samples that will be encoded.
  91728. * This is merely an estimate and may be set to \c 0 if unknown.
  91729. * This value will be written to the STREAMINFO block before encoding,
  91730. * and can remove the need for the caller to rewrite the value later
  91731. * if the value is known before encoding.
  91732. *
  91733. * \default \c 0
  91734. * \param encoder An encoder instance to set.
  91735. * \param value See above.
  91736. * \assert
  91737. * \code encoder != NULL \endcode
  91738. * \retval FLAC__bool
  91739. * \c false if the encoder is already initialized, else \c true.
  91740. */
  91741. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91742. /** Set the metadata blocks to be emitted to the stream before encoding.
  91743. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91744. * array of pointers to metadata blocks. The array is non-const since
  91745. * the encoder may need to change the \a is_last flag inside them, and
  91746. * in some cases update seek point offsets. Otherwise, the encoder will
  91747. * not modify or free the blocks. It is up to the caller to free the
  91748. * metadata blocks after encoding finishes.
  91749. *
  91750. * \note
  91751. * The encoder stores only copies of the pointers in the \a metadata array;
  91752. * the metadata blocks themselves must survive at least until after
  91753. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91754. *
  91755. * \note
  91756. * The STREAMINFO block is always written and no STREAMINFO block may
  91757. * occur in the supplied array.
  91758. *
  91759. * \note
  91760. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91761. * in the \a metadata array, but the client has specified that it does not
  91762. * support seeking, then the SEEKTABLE will be written verbatim. However
  91763. * by itself this is not very useful as the client will not know the stream
  91764. * offsets for the seekpoints ahead of time. In order to get a proper
  91765. * seektable the client must support seeking. See next note.
  91766. *
  91767. * \note
  91768. * SEEKTABLE blocks are handled specially. Since you will not know
  91769. * the values for the seek point stream offsets, you should pass in
  91770. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91771. * required sample numbers (or placeholder points), with \c 0 for the
  91772. * \a frame_samples and \a stream_offset fields for each point. If the
  91773. * client has specified that it supports seeking by providing a seek
  91774. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91775. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91776. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91777. * then while it is encoding the encoder will fill the stream offsets in
  91778. * for you and when encoding is finished, it will seek back and write the
  91779. * real values into the SEEKTABLE block in the stream. There are helper
  91780. * routines for manipulating seektable template blocks; see metadata.h:
  91781. * FLAC__metadata_object_seektable_template_*(). If the client does
  91782. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91783. * will slow down or remove the ability to seek in the FLAC stream.
  91784. *
  91785. * \note
  91786. * The encoder instance \b will modify the first \c SEEKTABLE block
  91787. * as it transforms the template to a valid seektable while encoding,
  91788. * but it is still up to the caller to free all metadata blocks after
  91789. * encoding.
  91790. *
  91791. * \note
  91792. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91793. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91794. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91795. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91796. * block is present in the \a metadata array, libFLAC will write an
  91797. * empty one, containing only the vendor string.
  91798. *
  91799. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91800. * the second metadata block of the stream. The encoder already supplies
  91801. * the STREAMINFO block automatically. If \a metadata does not contain a
  91802. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91803. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91804. * first, the init function will reorder \a metadata by moving the
  91805. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91806. * blocks will remain as they were.
  91807. *
  91808. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91809. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91810. * return \c false.
  91811. *
  91812. * \default \c NULL, 0
  91813. * \param encoder An encoder instance to set.
  91814. * \param metadata See above.
  91815. * \param num_blocks See above.
  91816. * \assert
  91817. * \code encoder != NULL \endcode
  91818. * \retval FLAC__bool
  91819. * \c false if the encoder is already initialized, else \c true.
  91820. * \c false if the encoder is already initialized, or if
  91821. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91822. */
  91823. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91824. /** Get the current encoder state.
  91825. *
  91826. * \param encoder An encoder instance to query.
  91827. * \assert
  91828. * \code encoder != NULL \endcode
  91829. * \retval FLAC__StreamEncoderState
  91830. * The current encoder state.
  91831. */
  91832. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91833. /** Get the state of the verify stream decoder.
  91834. * Useful when the stream encoder state is
  91835. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91836. *
  91837. * \param encoder An encoder instance to query.
  91838. * \assert
  91839. * \code encoder != NULL \endcode
  91840. * \retval FLAC__StreamDecoderState
  91841. * The verify stream decoder state.
  91842. */
  91843. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91844. /** Get the current encoder state as a C string.
  91845. * This version automatically resolves
  91846. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91847. * verify decoder's state.
  91848. *
  91849. * \param encoder A encoder instance to query.
  91850. * \assert
  91851. * \code encoder != NULL \endcode
  91852. * \retval const char *
  91853. * The encoder state as a C string. Do not modify the contents.
  91854. */
  91855. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91856. /** Get relevant values about the nature of a verify decoder error.
  91857. * Useful when the stream encoder state is
  91858. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91859. * be addresses in which the stats will be returned, or NULL if value
  91860. * is not desired.
  91861. *
  91862. * \param encoder An encoder instance to query.
  91863. * \param absolute_sample The absolute sample number of the mismatch.
  91864. * \param frame_number The number of the frame in which the mismatch occurred.
  91865. * \param channel The channel in which the mismatch occurred.
  91866. * \param sample The number of the sample (relative to the frame) in
  91867. * which the mismatch occurred.
  91868. * \param expected The expected value for the sample in question.
  91869. * \param got The actual value returned by the decoder.
  91870. * \assert
  91871. * \code encoder != NULL \endcode
  91872. */
  91873. 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);
  91874. /** Get the "verify" flag.
  91875. *
  91876. * \param encoder An encoder instance to query.
  91877. * \assert
  91878. * \code encoder != NULL \endcode
  91879. * \retval FLAC__bool
  91880. * See FLAC__stream_encoder_set_verify().
  91881. */
  91882. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91883. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91884. *
  91885. * \param encoder An encoder instance to query.
  91886. * \assert
  91887. * \code encoder != NULL \endcode
  91888. * \retval FLAC__bool
  91889. * See FLAC__stream_encoder_set_streamable_subset().
  91890. */
  91891. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91892. /** Get the number of input channels being processed.
  91893. *
  91894. * \param encoder An encoder instance to query.
  91895. * \assert
  91896. * \code encoder != NULL \endcode
  91897. * \retval unsigned
  91898. * See FLAC__stream_encoder_set_channels().
  91899. */
  91900. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91901. /** Get the input sample resolution setting.
  91902. *
  91903. * \param encoder An encoder instance to query.
  91904. * \assert
  91905. * \code encoder != NULL \endcode
  91906. * \retval unsigned
  91907. * See FLAC__stream_encoder_set_bits_per_sample().
  91908. */
  91909. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91910. /** Get the input sample rate setting.
  91911. *
  91912. * \param encoder An encoder instance to query.
  91913. * \assert
  91914. * \code encoder != NULL \endcode
  91915. * \retval unsigned
  91916. * See FLAC__stream_encoder_set_sample_rate().
  91917. */
  91918. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91919. /** Get the blocksize setting.
  91920. *
  91921. * \param encoder An encoder instance to query.
  91922. * \assert
  91923. * \code encoder != NULL \endcode
  91924. * \retval unsigned
  91925. * See FLAC__stream_encoder_set_blocksize().
  91926. */
  91927. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91928. /** Get the "mid/side stereo coding" flag.
  91929. *
  91930. * \param encoder An encoder instance to query.
  91931. * \assert
  91932. * \code encoder != NULL \endcode
  91933. * \retval FLAC__bool
  91934. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91935. */
  91936. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91937. /** Get the "adaptive mid/side switching" flag.
  91938. *
  91939. * \param encoder An encoder instance to query.
  91940. * \assert
  91941. * \code encoder != NULL \endcode
  91942. * \retval FLAC__bool
  91943. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91944. */
  91945. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91946. /** Get the maximum LPC order setting.
  91947. *
  91948. * \param encoder An encoder instance to query.
  91949. * \assert
  91950. * \code encoder != NULL \endcode
  91951. * \retval unsigned
  91952. * See FLAC__stream_encoder_set_max_lpc_order().
  91953. */
  91954. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91955. /** Get the quantized linear predictor coefficient precision setting.
  91956. *
  91957. * \param encoder An encoder instance to query.
  91958. * \assert
  91959. * \code encoder != NULL \endcode
  91960. * \retval unsigned
  91961. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91962. */
  91963. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91964. /** Get the qlp coefficient precision search flag.
  91965. *
  91966. * \param encoder An encoder instance to query.
  91967. * \assert
  91968. * \code encoder != NULL \endcode
  91969. * \retval FLAC__bool
  91970. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91971. */
  91972. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91973. /** Get the "escape coding" flag.
  91974. *
  91975. * \param encoder An encoder instance to query.
  91976. * \assert
  91977. * \code encoder != NULL \endcode
  91978. * \retval FLAC__bool
  91979. * See FLAC__stream_encoder_set_do_escape_coding().
  91980. */
  91981. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91982. /** Get the exhaustive model search flag.
  91983. *
  91984. * \param encoder An encoder instance to query.
  91985. * \assert
  91986. * \code encoder != NULL \endcode
  91987. * \retval FLAC__bool
  91988. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91989. */
  91990. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91991. /** Get the minimum residual partition order setting.
  91992. *
  91993. * \param encoder An encoder instance to query.
  91994. * \assert
  91995. * \code encoder != NULL \endcode
  91996. * \retval unsigned
  91997. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91998. */
  91999. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92000. /** Get maximum residual partition order setting.
  92001. *
  92002. * \param encoder An encoder instance to query.
  92003. * \assert
  92004. * \code encoder != NULL \endcode
  92005. * \retval unsigned
  92006. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92007. */
  92008. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92009. /** Get the Rice parameter search distance setting.
  92010. *
  92011. * \param encoder An encoder instance to query.
  92012. * \assert
  92013. * \code encoder != NULL \endcode
  92014. * \retval unsigned
  92015. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92016. */
  92017. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92018. /** Get the previously set estimate of the total samples to be encoded.
  92019. * The encoder merely mimics back the value given to
  92020. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92021. * other way of knowing how many samples the client will encode.
  92022. *
  92023. * \param encoder An encoder instance to set.
  92024. * \assert
  92025. * \code encoder != NULL \endcode
  92026. * \retval FLAC__uint64
  92027. * See FLAC__stream_encoder_get_total_samples_estimate().
  92028. */
  92029. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92030. /** Initialize the encoder instance to encode native FLAC streams.
  92031. *
  92032. * This flavor of initialization sets up the encoder to encode to a
  92033. * native FLAC stream. I/O is performed via callbacks to the client.
  92034. * For encoding to a plain file via filename or open \c FILE*,
  92035. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92036. * provide a simpler interface.
  92037. *
  92038. * This function should be called after FLAC__stream_encoder_new() and
  92039. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92040. * or FLAC__stream_encoder_process_interleaved().
  92041. * initialization succeeded.
  92042. *
  92043. * The call to FLAC__stream_encoder_init_stream() currently will also
  92044. * immediately call the write callback several times, once with the \c fLaC
  92045. * signature, and once for each encoded metadata block.
  92046. *
  92047. * \param encoder An uninitialized encoder instance.
  92048. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92049. * pointer must not be \c NULL.
  92050. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92051. * pointer may be \c NULL if seeking is not
  92052. * supported. The encoder uses seeking to go back
  92053. * and write some some stream statistics to the
  92054. * STREAMINFO block; this is recommended but not
  92055. * necessary to create a valid FLAC stream. If
  92056. * \a seek_callback is not \c NULL then a
  92057. * \a tell_callback must also be supplied.
  92058. * Alternatively, a dummy seek callback that just
  92059. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92060. * may also be supplied, all though this is slightly
  92061. * less efficient for the encoder.
  92062. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92063. * pointer may be \c NULL if seeking is not
  92064. * supported. If \a seek_callback is \c NULL then
  92065. * this argument will be ignored. If
  92066. * \a seek_callback is not \c NULL then a
  92067. * \a tell_callback must also be supplied.
  92068. * Alternatively, a dummy tell callback that just
  92069. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92070. * may also be supplied, all though this is slightly
  92071. * less efficient for the encoder.
  92072. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92073. * pointer may be \c NULL if the callback is not
  92074. * desired. If the client provides a seek callback,
  92075. * this function is not necessary as the encoder
  92076. * will automatically seek back and update the
  92077. * STREAMINFO block. It may also be \c NULL if the
  92078. * client does not support seeking, since it will
  92079. * have no way of going back to update the
  92080. * STREAMINFO. However the client can still supply
  92081. * a callback if it would like to know the details
  92082. * from the STREAMINFO.
  92083. * \param client_data This value will be supplied to callbacks in their
  92084. * \a client_data argument.
  92085. * \assert
  92086. * \code encoder != NULL \endcode
  92087. * \retval FLAC__StreamEncoderInitStatus
  92088. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92089. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92090. */
  92091. 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);
  92092. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92093. *
  92094. * This flavor of initialization sets up the encoder to encode to a FLAC
  92095. * stream in an Ogg container. I/O is performed via callbacks to the
  92096. * client. For encoding to a plain file via filename or open \c FILE*,
  92097. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92098. * provide a simpler interface.
  92099. *
  92100. * This function should be called after FLAC__stream_encoder_new() and
  92101. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92102. * or FLAC__stream_encoder_process_interleaved().
  92103. * initialization succeeded.
  92104. *
  92105. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92106. * immediately call the write callback several times to write the metadata
  92107. * packets.
  92108. *
  92109. * \param encoder An uninitialized encoder instance.
  92110. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92111. * pointer must not be \c NULL if \a seek_callback
  92112. * is non-NULL since they are both needed to be
  92113. * able to write data back to the Ogg FLAC stream
  92114. * in the post-encode phase.
  92115. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92116. * pointer must not be \c NULL.
  92117. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92118. * pointer may be \c NULL if seeking is not
  92119. * supported. The encoder uses seeking to go back
  92120. * and write some some stream statistics to the
  92121. * STREAMINFO block; this is recommended but not
  92122. * necessary to create a valid FLAC stream. If
  92123. * \a seek_callback is not \c NULL then a
  92124. * \a tell_callback must also be supplied.
  92125. * Alternatively, a dummy seek callback that just
  92126. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92127. * may also be supplied, all though this is slightly
  92128. * less efficient for the encoder.
  92129. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92130. * pointer may be \c NULL if seeking is not
  92131. * supported. If \a seek_callback is \c NULL then
  92132. * this argument will be ignored. If
  92133. * \a seek_callback is not \c NULL then a
  92134. * \a tell_callback must also be supplied.
  92135. * Alternatively, a dummy tell callback that just
  92136. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92137. * may also be supplied, all though this is slightly
  92138. * less efficient for the encoder.
  92139. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92140. * pointer may be \c NULL if the callback is not
  92141. * desired. If the client provides a seek callback,
  92142. * this function is not necessary as the encoder
  92143. * will automatically seek back and update the
  92144. * STREAMINFO block. It may also be \c NULL if the
  92145. * client does not support seeking, since it will
  92146. * have no way of going back to update the
  92147. * STREAMINFO. However the client can still supply
  92148. * a callback if it would like to know the details
  92149. * from the STREAMINFO.
  92150. * \param client_data This value will be supplied to callbacks in their
  92151. * \a client_data argument.
  92152. * \assert
  92153. * \code encoder != NULL \endcode
  92154. * \retval FLAC__StreamEncoderInitStatus
  92155. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92156. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92157. */
  92158. 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);
  92159. /** Initialize the encoder instance to encode native FLAC files.
  92160. *
  92161. * This flavor of initialization sets up the encoder to encode to a
  92162. * plain native FLAC file. For non-stdio streams, you must use
  92163. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92164. *
  92165. * This function should be called after FLAC__stream_encoder_new() and
  92166. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92167. * or FLAC__stream_encoder_process_interleaved().
  92168. * initialization succeeded.
  92169. *
  92170. * \param encoder An uninitialized encoder instance.
  92171. * \param file An open file. The file should have been opened
  92172. * with mode \c "w+b" and rewound. The file
  92173. * becomes owned by the encoder and should not be
  92174. * manipulated by the client while encoding.
  92175. * Unless \a file is \c stdout, it will be closed
  92176. * when FLAC__stream_encoder_finish() is called.
  92177. * Note however that a proper SEEKTABLE cannot be
  92178. * created when encoding to \c stdout since it is
  92179. * not seekable.
  92180. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92181. * pointer may be \c NULL if the callback is not
  92182. * desired.
  92183. * \param client_data This value will be supplied to callbacks in their
  92184. * \a client_data argument.
  92185. * \assert
  92186. * \code encoder != NULL \endcode
  92187. * \code file != NULL \endcode
  92188. * \retval FLAC__StreamEncoderInitStatus
  92189. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92190. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92191. */
  92192. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92193. /** Initialize the encoder instance to encode Ogg FLAC files.
  92194. *
  92195. * This flavor of initialization sets up the encoder to encode to a
  92196. * plain Ogg FLAC file. For non-stdio streams, you must use
  92197. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92198. *
  92199. * This function should be called after FLAC__stream_encoder_new() and
  92200. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92201. * or FLAC__stream_encoder_process_interleaved().
  92202. * initialization succeeded.
  92203. *
  92204. * \param encoder An uninitialized encoder instance.
  92205. * \param file An open file. The file should have been opened
  92206. * with mode \c "w+b" and rewound. The file
  92207. * becomes owned by the encoder and should not be
  92208. * manipulated by the client while encoding.
  92209. * Unless \a file is \c stdout, it will be closed
  92210. * when FLAC__stream_encoder_finish() is called.
  92211. * Note however that a proper SEEKTABLE cannot be
  92212. * created when encoding to \c stdout since it is
  92213. * not seekable.
  92214. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92215. * pointer may be \c NULL if the callback is not
  92216. * desired.
  92217. * \param client_data This value will be supplied to callbacks in their
  92218. * \a client_data argument.
  92219. * \assert
  92220. * \code encoder != NULL \endcode
  92221. * \code file != NULL \endcode
  92222. * \retval FLAC__StreamEncoderInitStatus
  92223. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92224. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92225. */
  92226. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92227. /** Initialize the encoder instance to encode native FLAC files.
  92228. *
  92229. * This flavor of initialization sets up the encoder to encode to a plain
  92230. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92231. * with Unicode filenames on Windows), you must use
  92232. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92233. * and provide callbacks for the I/O.
  92234. *
  92235. * This function should be called after FLAC__stream_encoder_new() and
  92236. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92237. * or FLAC__stream_encoder_process_interleaved().
  92238. * initialization succeeded.
  92239. *
  92240. * \param encoder An uninitialized encoder instance.
  92241. * \param filename The name of the file to encode to. The file will
  92242. * be opened with fopen(). Use \c NULL to encode to
  92243. * \c stdout. Note however that a proper SEEKTABLE
  92244. * cannot be created when encoding to \c stdout since
  92245. * it is not seekable.
  92246. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92247. * pointer may be \c NULL if the callback is not
  92248. * desired.
  92249. * \param client_data This value will be supplied to callbacks in their
  92250. * \a client_data argument.
  92251. * \assert
  92252. * \code encoder != NULL \endcode
  92253. * \retval FLAC__StreamEncoderInitStatus
  92254. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92255. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92256. */
  92257. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92258. /** Initialize the encoder instance to encode Ogg FLAC files.
  92259. *
  92260. * This flavor of initialization sets up the encoder to encode to a plain
  92261. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92262. * with Unicode filenames on Windows), you must use
  92263. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92264. * and provide callbacks for the I/O.
  92265. *
  92266. * This function should be called after FLAC__stream_encoder_new() and
  92267. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92268. * or FLAC__stream_encoder_process_interleaved().
  92269. * initialization succeeded.
  92270. *
  92271. * \param encoder An uninitialized encoder instance.
  92272. * \param filename The name of the file to encode to. The file will
  92273. * be opened with fopen(). Use \c NULL to encode to
  92274. * \c stdout. Note however that a proper SEEKTABLE
  92275. * cannot be created when encoding to \c stdout since
  92276. * it is not seekable.
  92277. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92278. * pointer may be \c NULL if the callback is not
  92279. * desired.
  92280. * \param client_data This value will be supplied to callbacks in their
  92281. * \a client_data argument.
  92282. * \assert
  92283. * \code encoder != NULL \endcode
  92284. * \retval FLAC__StreamEncoderInitStatus
  92285. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92286. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92287. */
  92288. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92289. /** Finish the encoding process.
  92290. * Flushes the encoding buffer, releases resources, resets the encoder
  92291. * settings to their defaults, and returns the encoder state to
  92292. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92293. * one or more write callbacks before returning, and will generate
  92294. * a metadata callback.
  92295. *
  92296. * Note that in the course of processing the last frame, errors can
  92297. * occur, so the caller should be sure to check the return value to
  92298. * ensure the file was encoded properly.
  92299. *
  92300. * In the event of a prematurely-terminated encode, it is not strictly
  92301. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92302. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92303. * with a FLAC__stream_encoder_finish().
  92304. *
  92305. * \param encoder An uninitialized encoder instance.
  92306. * \assert
  92307. * \code encoder != NULL \endcode
  92308. * \retval FLAC__bool
  92309. * \c false if an error occurred processing the last frame; or if verify
  92310. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92311. * verify mismatch; else \c true. If \c false, caller should check the
  92312. * state with FLAC__stream_encoder_get_state() for more information
  92313. * about the error.
  92314. */
  92315. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92316. /** Submit data for encoding.
  92317. * This version allows you to supply the input data via an array of
  92318. * pointers, each pointer pointing to an array of \a samples samples
  92319. * representing one channel. The samples need not be block-aligned,
  92320. * but each channel should have the same number of samples. Each sample
  92321. * should be a signed integer, right-justified to the resolution set by
  92322. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92323. * resolution is 16 bits per sample, the samples should all be in the
  92324. * range [-32768,32767].
  92325. *
  92326. * For applications where channel order is important, channels must
  92327. * follow the order as described in the
  92328. * <A HREF="../format.html#frame_header">frame header</A>.
  92329. *
  92330. * \param encoder An initialized encoder instance in the OK state.
  92331. * \param buffer An array of pointers to each channel's signal.
  92332. * \param samples The number of samples in one channel.
  92333. * \assert
  92334. * \code encoder != NULL \endcode
  92335. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92336. * \retval FLAC__bool
  92337. * \c true if successful, else \c false; in this case, check the
  92338. * encoder state with FLAC__stream_encoder_get_state() to see what
  92339. * went wrong.
  92340. */
  92341. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92342. /** Submit data for encoding.
  92343. * This version allows you to supply the input data where the channels
  92344. * are interleaved into a single array (i.e. channel0_sample0,
  92345. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92346. * The samples need not be block-aligned but they must be
  92347. * sample-aligned, i.e. the first value should be channel0_sample0
  92348. * and the last value channelN_sampleM. Each sample should be a signed
  92349. * integer, right-justified to the resolution set by
  92350. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92351. * resolution is 16 bits per sample, the samples should all be in the
  92352. * range [-32768,32767].
  92353. *
  92354. * For applications where channel order is important, channels must
  92355. * follow the order as described in the
  92356. * <A HREF="../format.html#frame_header">frame header</A>.
  92357. *
  92358. * \param encoder An initialized encoder instance in the OK state.
  92359. * \param buffer An array of channel-interleaved data (see above).
  92360. * \param samples The number of samples in one channel, the same as for
  92361. * FLAC__stream_encoder_process(). For example, if
  92362. * encoding two channels, \c 1000 \a samples corresponds
  92363. * to a \a buffer of 2000 values.
  92364. * \assert
  92365. * \code encoder != NULL \endcode
  92366. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92367. * \retval FLAC__bool
  92368. * \c true if successful, else \c false; in this case, check the
  92369. * encoder state with FLAC__stream_encoder_get_state() to see what
  92370. * went wrong.
  92371. */
  92372. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92373. /* \} */
  92374. #ifdef __cplusplus
  92375. }
  92376. #endif
  92377. #endif
  92378. /*** End of inlined file: stream_encoder.h ***/
  92379. #ifdef _MSC_VER
  92380. /* OPT: an MSVC built-in would be better */
  92381. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92382. {
  92383. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92384. return (x>>16) | (x<<16);
  92385. }
  92386. #endif
  92387. #if defined(_MSC_VER) && defined(_X86_)
  92388. /* OPT: an MSVC built-in would be better */
  92389. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92390. {
  92391. __asm {
  92392. mov edx, start
  92393. mov ecx, len
  92394. test ecx, ecx
  92395. loop1:
  92396. jz done1
  92397. mov eax, [edx]
  92398. bswap eax
  92399. mov [edx], eax
  92400. add edx, 4
  92401. dec ecx
  92402. jmp short loop1
  92403. done1:
  92404. }
  92405. }
  92406. #endif
  92407. /** \mainpage
  92408. *
  92409. * \section intro Introduction
  92410. *
  92411. * This is the documentation for the FLAC C and C++ APIs. It is
  92412. * highly interconnected; this introduction should give you a top
  92413. * level idea of the structure and how to find the information you
  92414. * need. As a prerequisite you should have at least a basic
  92415. * knowledge of the FLAC format, documented
  92416. * <A HREF="../format.html">here</A>.
  92417. *
  92418. * \section c_api FLAC C API
  92419. *
  92420. * The FLAC C API is the interface to libFLAC, a set of structures
  92421. * describing the components of FLAC streams, and functions for
  92422. * encoding and decoding streams, as well as manipulating FLAC
  92423. * metadata in files. The public include files will be installed
  92424. * in your include area (for example /usr/include/FLAC/...).
  92425. *
  92426. * By writing a little code and linking against libFLAC, it is
  92427. * relatively easy to add FLAC support to another program. The
  92428. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92429. * Complete source code of libFLAC as well as the command-line
  92430. * encoder and plugins is available and is a useful source of
  92431. * examples.
  92432. *
  92433. * Aside from encoders and decoders, libFLAC provides a powerful
  92434. * metadata interface for manipulating metadata in FLAC files. It
  92435. * allows the user to add, delete, and modify FLAC metadata blocks
  92436. * and it can automatically take advantage of PADDING blocks to avoid
  92437. * rewriting the entire FLAC file when changing the size of the
  92438. * metadata.
  92439. *
  92440. * libFLAC usually only requires the standard C library and C math
  92441. * library. In particular, threading is not used so there is no
  92442. * dependency on a thread library. However, libFLAC does not use
  92443. * global variables and should be thread-safe.
  92444. *
  92445. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92446. * However the metadata editing interfaces currently have limited
  92447. * read-only support for Ogg FLAC files.
  92448. *
  92449. * \section cpp_api FLAC C++ API
  92450. *
  92451. * The FLAC C++ API is a set of classes that encapsulate the
  92452. * structures and functions in libFLAC. They provide slightly more
  92453. * functionality with respect to metadata but are otherwise
  92454. * equivalent. For the most part, they share the same usage as
  92455. * their counterparts in libFLAC, and the FLAC C API documentation
  92456. * can be used as a supplement. The public include files
  92457. * for the C++ API will be installed in your include area (for
  92458. * example /usr/include/FLAC++/...).
  92459. *
  92460. * libFLAC++ is also licensed under
  92461. * <A HREF="../license.html">Xiph's BSD license</A>.
  92462. *
  92463. * \section getting_started Getting Started
  92464. *
  92465. * A good starting point for learning the API is to browse through
  92466. * the <A HREF="modules.html">modules</A>. Modules are logical
  92467. * groupings of related functions or classes, which correspond roughly
  92468. * to header files or sections of header files. Each module includes a
  92469. * detailed description of the general usage of its functions or
  92470. * classes.
  92471. *
  92472. * From there you can go on to look at the documentation of
  92473. * individual functions. You can see different views of the individual
  92474. * functions through the links in top bar across this page.
  92475. *
  92476. * If you prefer a more hands-on approach, you can jump right to some
  92477. * <A HREF="../documentation_example_code.html">example code</A>.
  92478. *
  92479. * \section porting_guide Porting Guide
  92480. *
  92481. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92482. * has been introduced which gives detailed instructions on how to
  92483. * port your code to newer versions of FLAC.
  92484. *
  92485. * \section embedded_developers Embedded Developers
  92486. *
  92487. * libFLAC has grown larger over time as more functionality has been
  92488. * included, but much of it may be unnecessary for a particular embedded
  92489. * implementation. Unused parts may be pruned by some simple editing of
  92490. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92491. * metadata interface are all independent from each other.
  92492. *
  92493. * It is easiest to just describe the dependencies:
  92494. *
  92495. * - All modules depend on the \link flac_format Format \endlink module.
  92496. * - The decoders and encoders depend on the bitbuffer.
  92497. * - The decoder is independent of the encoder. The encoder uses the
  92498. * decoder because of the verify feature, but this can be removed if
  92499. * not needed.
  92500. * - Parts of the metadata interface require the stream decoder (but not
  92501. * the encoder).
  92502. * - Ogg support is selectable through the compile time macro
  92503. * \c FLAC__HAS_OGG.
  92504. *
  92505. * For example, if your application only requires the stream decoder, no
  92506. * encoder, and no metadata interface, you can remove the stream encoder
  92507. * and the metadata interface, which will greatly reduce the size of the
  92508. * library.
  92509. *
  92510. * Also, there are several places in the libFLAC code with comments marked
  92511. * with "OPT:" where a #define can be changed to enable code that might be
  92512. * faster on a specific platform. Experimenting with these can yield faster
  92513. * binaries.
  92514. */
  92515. /** \defgroup porting Porting Guide for New Versions
  92516. *
  92517. * This module describes differences in the library interfaces from
  92518. * version to version. It assists in the porting of code that uses
  92519. * the libraries to newer versions of FLAC.
  92520. *
  92521. * One simple facility for making porting easier that has been added
  92522. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92523. * library's includes (e.g. \c include/FLAC/export.h). The
  92524. * \c #defines mirror the libraries'
  92525. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92526. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92527. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92528. * These can be used to support multiple versions of an API during the
  92529. * transition phase, e.g.
  92530. *
  92531. * \code
  92532. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92533. * legacy code
  92534. * #else
  92535. * new code
  92536. * #endif
  92537. * \endcode
  92538. *
  92539. * The the source will work for multiple versions and the legacy code can
  92540. * easily be removed when the transition is complete.
  92541. *
  92542. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92543. * include/FLAC/export.h), which can be used to determine whether or not
  92544. * the library has been compiled with support for Ogg FLAC. This is
  92545. * simpler than trying to call an Ogg init function and catching the
  92546. * error.
  92547. */
  92548. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92549. * \ingroup porting
  92550. *
  92551. * \brief
  92552. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92553. *
  92554. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92555. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92556. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92557. * decoding layers and three encoding layers have been merged into a
  92558. * single stream decoder and stream encoder. That is, the functionality
  92559. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92560. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92561. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92562. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92563. * is there is now a single API that can be used to encode or decode
  92564. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92565. * on both seekable and non-seekable streams.
  92566. *
  92567. * Instead of creating an encoder or decoder of a certain layer, now the
  92568. * client will always create a FLAC__StreamEncoder or
  92569. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92570. * initialization function. For example, for the decoder,
  92571. * FLAC__stream_decoder_init() has been replaced by
  92572. * FLAC__stream_decoder_init_stream(). This init function takes
  92573. * callbacks for the I/O, and the seeking callbacks are optional. This
  92574. * allows the client to use the same object for seekable and
  92575. * non-seekable streams. For decoding a FLAC file directly, the client
  92576. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92577. * and fewer callbacks; most of the other callbacks are supplied
  92578. * internally. For situations where fopen()ing by filename is not
  92579. * possible (e.g. Unicode filenames on Windows) the client can instead
  92580. * open the file itself and supply the FILE* to
  92581. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92582. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92583. * Since the callbacks and client data are now passed to the init
  92584. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92585. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92586. * rest of the calls to the decoder are the same as before.
  92587. *
  92588. * There are counterpart init functions for Ogg FLAC, e.g.
  92589. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92590. * and callbacks are the same as for native FLAC.
  92591. *
  92592. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92593. * been set up like so:
  92594. *
  92595. * \code
  92596. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92597. * if(decoder == NULL) do_something;
  92598. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92599. * [... other settings ...]
  92600. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92601. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92602. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92603. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92604. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92605. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92606. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92607. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92608. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92609. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92610. * \endcode
  92611. *
  92612. * In FLAC 1.1.3 it is like this:
  92613. *
  92614. * \code
  92615. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92616. * if(decoder == NULL) do_something;
  92617. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92618. * [... other settings ...]
  92619. * if(FLAC__stream_decoder_init_stream(
  92620. * decoder,
  92621. * my_read_callback,
  92622. * my_seek_callback, // or NULL
  92623. * my_tell_callback, // or NULL
  92624. * my_length_callback, // or NULL
  92625. * my_eof_callback, // or NULL
  92626. * my_write_callback,
  92627. * my_metadata_callback, // or NULL
  92628. * my_error_callback,
  92629. * my_client_data
  92630. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92631. * \endcode
  92632. *
  92633. * or you could do;
  92634. *
  92635. * \code
  92636. * [...]
  92637. * FILE *file = fopen("somefile.flac","rb");
  92638. * if(file == NULL) do_somthing;
  92639. * if(FLAC__stream_decoder_init_FILE(
  92640. * decoder,
  92641. * file,
  92642. * my_write_callback,
  92643. * my_metadata_callback, // or NULL
  92644. * my_error_callback,
  92645. * my_client_data
  92646. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92647. * \endcode
  92648. *
  92649. * or just:
  92650. *
  92651. * \code
  92652. * [...]
  92653. * if(FLAC__stream_decoder_init_file(
  92654. * decoder,
  92655. * "somefile.flac",
  92656. * my_write_callback,
  92657. * my_metadata_callback, // or NULL
  92658. * my_error_callback,
  92659. * my_client_data
  92660. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92661. * \endcode
  92662. *
  92663. * Another small change to the decoder is in how it handles unparseable
  92664. * streams. Before, when the decoder found an unparseable stream
  92665. * (reserved for when the decoder encounters a stream from a future
  92666. * encoder that it can't parse), it changed the state to
  92667. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92668. * drops sync and calls the error callback with a new error code
  92669. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92670. * more robust. If your error callback does not discriminate on the the
  92671. * error state, your code does not need to be changed.
  92672. *
  92673. * The encoder now has a new setting:
  92674. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92675. * method used to window the data before LPC analysis. You only need to
  92676. * add a call to this function if the default is not suitable. There
  92677. * are also two new convenience functions that may be useful:
  92678. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92679. * FLAC__metadata_get_cuesheet().
  92680. *
  92681. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92682. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92683. * is now \c size_t instead of \c unsigned.
  92684. */
  92685. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92686. * \ingroup porting
  92687. *
  92688. * \brief
  92689. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92690. *
  92691. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92692. * There was a slight change in the implementation of
  92693. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92694. * of the \a metadata array of pointers so the client no longer needs
  92695. * to maintain it after the call. The objects themselves that are
  92696. * pointed to by the array are still not copied though and must be
  92697. * maintained until the call to FLAC__stream_encoder_finish().
  92698. */
  92699. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92700. * \ingroup porting
  92701. *
  92702. * \brief
  92703. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92704. *
  92705. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92706. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92707. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92708. *
  92709. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92710. * has changed to reflect the conversion of one of the reserved bits
  92711. * into active use. It used to be \c 2 and now is \c 1. However the
  92712. * FLAC frame header length has not changed, so to skip the proper
  92713. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92714. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92715. */
  92716. /** \defgroup flac FLAC C API
  92717. *
  92718. * The FLAC C API is the interface to libFLAC, a set of structures
  92719. * describing the components of FLAC streams, and functions for
  92720. * encoding and decoding streams, as well as manipulating FLAC
  92721. * metadata in files.
  92722. *
  92723. * You should start with the format components as all other modules
  92724. * are dependent on it.
  92725. */
  92726. #endif
  92727. /*** End of inlined file: all.h ***/
  92728. /*** Start of inlined file: bitmath.c ***/
  92729. /*** Start of inlined file: juce_FlacHeader.h ***/
  92730. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92731. // tasks..
  92732. #define VERSION "1.2.1"
  92733. #define FLAC__NO_DLL 1
  92734. #if JUCE_MSVC
  92735. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92736. #endif
  92737. #if JUCE_MAC
  92738. #define FLAC__SYS_DARWIN 1
  92739. #endif
  92740. /*** End of inlined file: juce_FlacHeader.h ***/
  92741. #if JUCE_USE_FLAC
  92742. #if HAVE_CONFIG_H
  92743. # include <config.h>
  92744. #endif
  92745. /*** Start of inlined file: bitmath.h ***/
  92746. #ifndef FLAC__PRIVATE__BITMATH_H
  92747. #define FLAC__PRIVATE__BITMATH_H
  92748. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92749. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92750. unsigned FLAC__bitmath_silog2(int v);
  92751. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92752. #endif
  92753. /*** End of inlined file: bitmath.h ***/
  92754. /* An example of what FLAC__bitmath_ilog2() computes:
  92755. *
  92756. * ilog2( 0) = assertion failure
  92757. * ilog2( 1) = 0
  92758. * ilog2( 2) = 1
  92759. * ilog2( 3) = 1
  92760. * ilog2( 4) = 2
  92761. * ilog2( 5) = 2
  92762. * ilog2( 6) = 2
  92763. * ilog2( 7) = 2
  92764. * ilog2( 8) = 3
  92765. * ilog2( 9) = 3
  92766. * ilog2(10) = 3
  92767. * ilog2(11) = 3
  92768. * ilog2(12) = 3
  92769. * ilog2(13) = 3
  92770. * ilog2(14) = 3
  92771. * ilog2(15) = 3
  92772. * ilog2(16) = 4
  92773. * ilog2(17) = 4
  92774. * ilog2(18) = 4
  92775. */
  92776. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92777. {
  92778. unsigned l = 0;
  92779. FLAC__ASSERT(v > 0);
  92780. while(v >>= 1)
  92781. l++;
  92782. return l;
  92783. }
  92784. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92785. {
  92786. unsigned l = 0;
  92787. FLAC__ASSERT(v > 0);
  92788. while(v >>= 1)
  92789. l++;
  92790. return l;
  92791. }
  92792. /* An example of what FLAC__bitmath_silog2() computes:
  92793. *
  92794. * silog2(-10) = 5
  92795. * silog2(- 9) = 5
  92796. * silog2(- 8) = 4
  92797. * silog2(- 7) = 4
  92798. * silog2(- 6) = 4
  92799. * silog2(- 5) = 4
  92800. * silog2(- 4) = 3
  92801. * silog2(- 3) = 3
  92802. * silog2(- 2) = 2
  92803. * silog2(- 1) = 2
  92804. * silog2( 0) = 0
  92805. * silog2( 1) = 2
  92806. * silog2( 2) = 3
  92807. * silog2( 3) = 3
  92808. * silog2( 4) = 4
  92809. * silog2( 5) = 4
  92810. * silog2( 6) = 4
  92811. * silog2( 7) = 4
  92812. * silog2( 8) = 5
  92813. * silog2( 9) = 5
  92814. * silog2( 10) = 5
  92815. */
  92816. unsigned FLAC__bitmath_silog2(int v)
  92817. {
  92818. while(1) {
  92819. if(v == 0) {
  92820. return 0;
  92821. }
  92822. else if(v > 0) {
  92823. unsigned l = 0;
  92824. while(v) {
  92825. l++;
  92826. v >>= 1;
  92827. }
  92828. return l+1;
  92829. }
  92830. else if(v == -1) {
  92831. return 2;
  92832. }
  92833. else {
  92834. v++;
  92835. v = -v;
  92836. }
  92837. }
  92838. }
  92839. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92840. {
  92841. while(1) {
  92842. if(v == 0) {
  92843. return 0;
  92844. }
  92845. else if(v > 0) {
  92846. unsigned l = 0;
  92847. while(v) {
  92848. l++;
  92849. v >>= 1;
  92850. }
  92851. return l+1;
  92852. }
  92853. else if(v == -1) {
  92854. return 2;
  92855. }
  92856. else {
  92857. v++;
  92858. v = -v;
  92859. }
  92860. }
  92861. }
  92862. #endif
  92863. /*** End of inlined file: bitmath.c ***/
  92864. /*** Start of inlined file: bitreader.c ***/
  92865. /*** Start of inlined file: juce_FlacHeader.h ***/
  92866. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92867. // tasks..
  92868. #define VERSION "1.2.1"
  92869. #define FLAC__NO_DLL 1
  92870. #if JUCE_MSVC
  92871. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92872. #endif
  92873. #if JUCE_MAC
  92874. #define FLAC__SYS_DARWIN 1
  92875. #endif
  92876. /*** End of inlined file: juce_FlacHeader.h ***/
  92877. #if JUCE_USE_FLAC
  92878. #if HAVE_CONFIG_H
  92879. # include <config.h>
  92880. #endif
  92881. #include <stdlib.h> /* for malloc() */
  92882. #include <string.h> /* for memcpy(), memset() */
  92883. #ifdef _MSC_VER
  92884. #include <winsock.h> /* for ntohl() */
  92885. #elif defined FLAC__SYS_DARWIN
  92886. #include <machine/endian.h> /* for ntohl() */
  92887. #elif defined __MINGW32__
  92888. #include <winsock.h> /* for ntohl() */
  92889. #else
  92890. #include <netinet/in.h> /* for ntohl() */
  92891. #endif
  92892. /*** Start of inlined file: bitreader.h ***/
  92893. #ifndef FLAC__PRIVATE__BITREADER_H
  92894. #define FLAC__PRIVATE__BITREADER_H
  92895. #include <stdio.h> /* for FILE */
  92896. /*** Start of inlined file: cpu.h ***/
  92897. #ifndef FLAC__PRIVATE__CPU_H
  92898. #define FLAC__PRIVATE__CPU_H
  92899. #ifdef HAVE_CONFIG_H
  92900. #include <config.h>
  92901. #endif
  92902. typedef enum {
  92903. FLAC__CPUINFO_TYPE_IA32,
  92904. FLAC__CPUINFO_TYPE_PPC,
  92905. FLAC__CPUINFO_TYPE_UNKNOWN
  92906. } FLAC__CPUInfo_Type;
  92907. typedef struct {
  92908. FLAC__bool cpuid;
  92909. FLAC__bool bswap;
  92910. FLAC__bool cmov;
  92911. FLAC__bool mmx;
  92912. FLAC__bool fxsr;
  92913. FLAC__bool sse;
  92914. FLAC__bool sse2;
  92915. FLAC__bool sse3;
  92916. FLAC__bool ssse3;
  92917. FLAC__bool _3dnow;
  92918. FLAC__bool ext3dnow;
  92919. FLAC__bool extmmx;
  92920. } FLAC__CPUInfo_IA32;
  92921. typedef struct {
  92922. FLAC__bool altivec;
  92923. FLAC__bool ppc64;
  92924. } FLAC__CPUInfo_PPC;
  92925. typedef struct {
  92926. FLAC__bool use_asm;
  92927. FLAC__CPUInfo_Type type;
  92928. union {
  92929. FLAC__CPUInfo_IA32 ia32;
  92930. FLAC__CPUInfo_PPC ppc;
  92931. } data;
  92932. } FLAC__CPUInfo;
  92933. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92934. #ifndef FLAC__NO_ASM
  92935. #ifdef FLAC__CPU_IA32
  92936. #ifdef FLAC__HAS_NASM
  92937. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92938. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92939. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92940. #endif
  92941. #endif
  92942. #endif
  92943. #endif
  92944. /*** End of inlined file: cpu.h ***/
  92945. /*
  92946. * opaque structure definition
  92947. */
  92948. struct FLAC__BitReader;
  92949. typedef struct FLAC__BitReader FLAC__BitReader;
  92950. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92951. /*
  92952. * construction, deletion, initialization, etc functions
  92953. */
  92954. FLAC__BitReader *FLAC__bitreader_new(void);
  92955. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92956. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92957. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92958. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92959. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92960. /*
  92961. * CRC functions
  92962. */
  92963. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92964. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92965. /*
  92966. * info functions
  92967. */
  92968. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92969. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92970. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92971. /*
  92972. * read functions
  92973. */
  92974. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92975. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92976. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92977. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92978. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92979. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92980. 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! */
  92981. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92982. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92983. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92984. #ifndef FLAC__NO_ASM
  92985. # ifdef FLAC__CPU_IA32
  92986. # ifdef FLAC__HAS_NASM
  92987. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92988. # endif
  92989. # endif
  92990. #endif
  92991. #if 0 /* UNUSED */
  92992. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92993. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92994. #endif
  92995. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92996. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92997. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92998. #endif
  92999. /*** End of inlined file: bitreader.h ***/
  93000. /*** Start of inlined file: crc.h ***/
  93001. #ifndef FLAC__PRIVATE__CRC_H
  93002. #define FLAC__PRIVATE__CRC_H
  93003. /* 8 bit CRC generator, MSB shifted first
  93004. ** polynomial = x^8 + x^2 + x^1 + x^0
  93005. ** init = 0
  93006. */
  93007. extern FLAC__byte const FLAC__crc8_table[256];
  93008. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93009. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93010. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93011. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93012. /* 16 bit CRC generator, MSB shifted first
  93013. ** polynomial = x^16 + x^15 + x^2 + x^0
  93014. ** init = 0
  93015. */
  93016. extern unsigned FLAC__crc16_table[256];
  93017. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93018. /* this alternate may be faster on some systems/compilers */
  93019. #if 0
  93020. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93021. #endif
  93022. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93023. #endif
  93024. /*** End of inlined file: crc.h ***/
  93025. /* Things should be fastest when this matches the machine word size */
  93026. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93027. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93028. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93029. typedef FLAC__uint32 brword;
  93030. #define FLAC__BYTES_PER_WORD 4
  93031. #define FLAC__BITS_PER_WORD 32
  93032. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93033. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93034. #if WORDS_BIGENDIAN
  93035. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93036. #else
  93037. #if defined (_MSC_VER) && defined (_X86_)
  93038. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93039. #else
  93040. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93041. #endif
  93042. #endif
  93043. /* counts the # of zero MSBs in a word */
  93044. #define COUNT_ZERO_MSBS(word) ( \
  93045. (word) <= 0xffff ? \
  93046. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93047. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93048. )
  93049. /* this alternate might be slightly faster on some systems/compilers: */
  93050. #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])) )
  93051. /*
  93052. * This should be at least twice as large as the largest number of words
  93053. * required to represent any 'number' (in any encoding) you are going to
  93054. * read. With FLAC this is on the order of maybe a few hundred bits.
  93055. * If the buffer is smaller than that, the decoder won't be able to read
  93056. * in a whole number that is in a variable length encoding (e.g. Rice).
  93057. * But to be practical it should be at least 1K bytes.
  93058. *
  93059. * Increase this number to decrease the number of read callbacks, at the
  93060. * expense of using more memory. Or decrease for the reverse effect,
  93061. * keeping in mind the limit from the first paragraph. The optimal size
  93062. * also depends on the CPU cache size and other factors; some twiddling
  93063. * may be necessary to squeeze out the best performance.
  93064. */
  93065. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93066. static const unsigned char byte_to_unary_table[] = {
  93067. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93068. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93069. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93070. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93071. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93072. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93073. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93074. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93083. };
  93084. #ifdef min
  93085. #undef min
  93086. #endif
  93087. #define min(x,y) ((x)<(y)?(x):(y))
  93088. #ifdef max
  93089. #undef max
  93090. #endif
  93091. #define max(x,y) ((x)>(y)?(x):(y))
  93092. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93093. #ifdef _MSC_VER
  93094. #define FLAC__U64L(x) x
  93095. #else
  93096. #define FLAC__U64L(x) x##LLU
  93097. #endif
  93098. #ifndef FLaC__INLINE
  93099. #define FLaC__INLINE
  93100. #endif
  93101. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93102. struct FLAC__BitReader {
  93103. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93104. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93105. brword *buffer;
  93106. unsigned capacity; /* in words */
  93107. unsigned words; /* # of completed words in buffer */
  93108. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93109. unsigned consumed_words; /* #words ... */
  93110. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93111. unsigned read_crc16; /* the running frame CRC */
  93112. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93113. FLAC__BitReaderReadCallback read_callback;
  93114. void *client_data;
  93115. FLAC__CPUInfo cpu_info;
  93116. };
  93117. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93118. {
  93119. register unsigned crc = br->read_crc16;
  93120. #if FLAC__BYTES_PER_WORD == 4
  93121. switch(br->crc16_align) {
  93122. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93123. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93124. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93125. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93126. }
  93127. #elif FLAC__BYTES_PER_WORD == 8
  93128. switch(br->crc16_align) {
  93129. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93130. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93131. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93132. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93133. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93134. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93135. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93136. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93137. }
  93138. #else
  93139. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93140. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93141. br->read_crc16 = crc;
  93142. #endif
  93143. br->crc16_align = 0;
  93144. }
  93145. /* would be static except it needs to be called by asm routines */
  93146. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93147. {
  93148. unsigned start, end;
  93149. size_t bytes;
  93150. FLAC__byte *target;
  93151. /* first shift the unconsumed buffer data toward the front as much as possible */
  93152. if(br->consumed_words > 0) {
  93153. start = br->consumed_words;
  93154. end = br->words + (br->bytes? 1:0);
  93155. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93156. br->words -= start;
  93157. br->consumed_words = 0;
  93158. }
  93159. /*
  93160. * set the target for reading, taking into account word alignment and endianness
  93161. */
  93162. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93163. if(bytes == 0)
  93164. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93165. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93166. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93167. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93168. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93169. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93170. * ^^-------target, bytes=3
  93171. * on LE machines, have to byteswap the odd tail word so nothing is
  93172. * overwritten:
  93173. */
  93174. #if WORDS_BIGENDIAN
  93175. #else
  93176. if(br->bytes)
  93177. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93178. #endif
  93179. /* now it looks like:
  93180. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93181. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93182. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93183. * ^^-------target, bytes=3
  93184. */
  93185. /* read in the data; note that the callback may return a smaller number of bytes */
  93186. if(!br->read_callback(target, &bytes, br->client_data))
  93187. return false;
  93188. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93189. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93190. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93191. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93192. * now have to byteswap on LE machines:
  93193. */
  93194. #if WORDS_BIGENDIAN
  93195. #else
  93196. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93197. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93198. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93199. start = br->words;
  93200. local_swap32_block_(br->buffer + start, end - start);
  93201. }
  93202. else
  93203. # endif
  93204. for(start = br->words; start < end; start++)
  93205. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93206. #endif
  93207. /* now it looks like:
  93208. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93209. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93210. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93211. * finally we'll update the reader values:
  93212. */
  93213. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93214. br->words = end / FLAC__BYTES_PER_WORD;
  93215. br->bytes = end % FLAC__BYTES_PER_WORD;
  93216. return true;
  93217. }
  93218. /***********************************************************************
  93219. *
  93220. * Class constructor/destructor
  93221. *
  93222. ***********************************************************************/
  93223. FLAC__BitReader *FLAC__bitreader_new(void)
  93224. {
  93225. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93226. /* calloc() implies:
  93227. memset(br, 0, sizeof(FLAC__BitReader));
  93228. br->buffer = 0;
  93229. br->capacity = 0;
  93230. br->words = br->bytes = 0;
  93231. br->consumed_words = br->consumed_bits = 0;
  93232. br->read_callback = 0;
  93233. br->client_data = 0;
  93234. */
  93235. return br;
  93236. }
  93237. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93238. {
  93239. FLAC__ASSERT(0 != br);
  93240. FLAC__bitreader_free(br);
  93241. free(br);
  93242. }
  93243. /***********************************************************************
  93244. *
  93245. * Public class methods
  93246. *
  93247. ***********************************************************************/
  93248. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93249. {
  93250. FLAC__ASSERT(0 != br);
  93251. br->words = br->bytes = 0;
  93252. br->consumed_words = br->consumed_bits = 0;
  93253. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93254. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93255. if(br->buffer == 0)
  93256. return false;
  93257. br->read_callback = rcb;
  93258. br->client_data = cd;
  93259. br->cpu_info = cpu;
  93260. return true;
  93261. }
  93262. void FLAC__bitreader_free(FLAC__BitReader *br)
  93263. {
  93264. FLAC__ASSERT(0 != br);
  93265. if(0 != br->buffer)
  93266. free(br->buffer);
  93267. br->buffer = 0;
  93268. br->capacity = 0;
  93269. br->words = br->bytes = 0;
  93270. br->consumed_words = br->consumed_bits = 0;
  93271. br->read_callback = 0;
  93272. br->client_data = 0;
  93273. }
  93274. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93275. {
  93276. br->words = br->bytes = 0;
  93277. br->consumed_words = br->consumed_bits = 0;
  93278. return true;
  93279. }
  93280. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93281. {
  93282. unsigned i, j;
  93283. if(br == 0) {
  93284. fprintf(out, "bitreader is NULL\n");
  93285. }
  93286. else {
  93287. 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);
  93288. for(i = 0; i < br->words; i++) {
  93289. fprintf(out, "%08X: ", i);
  93290. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93291. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93292. fprintf(out, ".");
  93293. else
  93294. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93295. fprintf(out, "\n");
  93296. }
  93297. if(br->bytes > 0) {
  93298. fprintf(out, "%08X: ", i);
  93299. for(j = 0; j < br->bytes*8; j++)
  93300. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93301. fprintf(out, ".");
  93302. else
  93303. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93304. fprintf(out, "\n");
  93305. }
  93306. }
  93307. }
  93308. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93309. {
  93310. FLAC__ASSERT(0 != br);
  93311. FLAC__ASSERT(0 != br->buffer);
  93312. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93313. br->read_crc16 = (unsigned)seed;
  93314. br->crc16_align = br->consumed_bits;
  93315. }
  93316. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93317. {
  93318. FLAC__ASSERT(0 != br);
  93319. FLAC__ASSERT(0 != br->buffer);
  93320. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93321. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93322. /* CRC any tail bytes in a partially-consumed word */
  93323. if(br->consumed_bits) {
  93324. const brword tail = br->buffer[br->consumed_words];
  93325. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93326. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93327. }
  93328. return br->read_crc16;
  93329. }
  93330. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93331. {
  93332. return ((br->consumed_bits & 7) == 0);
  93333. }
  93334. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93335. {
  93336. return 8 - (br->consumed_bits & 7);
  93337. }
  93338. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93339. {
  93340. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93341. }
  93342. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93343. {
  93344. FLAC__ASSERT(0 != br);
  93345. FLAC__ASSERT(0 != br->buffer);
  93346. FLAC__ASSERT(bits <= 32);
  93347. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93348. FLAC__ASSERT(br->consumed_words <= br->words);
  93349. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93350. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93351. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93352. *val = 0;
  93353. return true;
  93354. }
  93355. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93356. if(!bitreader_read_from_client_(br))
  93357. return false;
  93358. }
  93359. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93360. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93361. if(br->consumed_bits) {
  93362. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93363. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93364. const brword word = br->buffer[br->consumed_words];
  93365. if(bits < n) {
  93366. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93367. br->consumed_bits += bits;
  93368. return true;
  93369. }
  93370. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93371. bits -= n;
  93372. crc16_update_word_(br, word);
  93373. br->consumed_words++;
  93374. br->consumed_bits = 0;
  93375. 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 */
  93376. *val <<= bits;
  93377. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93378. br->consumed_bits = bits;
  93379. }
  93380. return true;
  93381. }
  93382. else {
  93383. const brword word = br->buffer[br->consumed_words];
  93384. if(bits < FLAC__BITS_PER_WORD) {
  93385. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93386. br->consumed_bits = bits;
  93387. return true;
  93388. }
  93389. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93390. *val = word;
  93391. crc16_update_word_(br, word);
  93392. br->consumed_words++;
  93393. return true;
  93394. }
  93395. }
  93396. else {
  93397. /* in this case we're starting our read at a partial tail word;
  93398. * the reader has guaranteed that we have at least 'bits' bits
  93399. * available to read, which makes this case simpler.
  93400. */
  93401. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93402. if(br->consumed_bits) {
  93403. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93404. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93405. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93406. br->consumed_bits += bits;
  93407. return true;
  93408. }
  93409. else {
  93410. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93411. br->consumed_bits += bits;
  93412. return true;
  93413. }
  93414. }
  93415. }
  93416. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93417. {
  93418. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93419. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93420. return false;
  93421. /* sign-extend: */
  93422. *val <<= (32-bits);
  93423. *val >>= (32-bits);
  93424. return true;
  93425. }
  93426. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93427. {
  93428. FLAC__uint32 hi, lo;
  93429. if(bits > 32) {
  93430. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93431. return false;
  93432. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93433. return false;
  93434. *val = hi;
  93435. *val <<= 32;
  93436. *val |= lo;
  93437. }
  93438. else {
  93439. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93440. return false;
  93441. *val = lo;
  93442. }
  93443. return true;
  93444. }
  93445. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93446. {
  93447. FLAC__uint32 x8, x32 = 0;
  93448. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93449. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93450. return false;
  93451. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93452. return false;
  93453. x32 |= (x8 << 8);
  93454. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93455. return false;
  93456. x32 |= (x8 << 16);
  93457. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93458. return false;
  93459. x32 |= (x8 << 24);
  93460. *val = x32;
  93461. return true;
  93462. }
  93463. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93464. {
  93465. /*
  93466. * OPT: a faster implementation is possible but probably not that useful
  93467. * since this is only called a couple of times in the metadata readers.
  93468. */
  93469. FLAC__ASSERT(0 != br);
  93470. FLAC__ASSERT(0 != br->buffer);
  93471. if(bits > 0) {
  93472. const unsigned n = br->consumed_bits & 7;
  93473. unsigned m;
  93474. FLAC__uint32 x;
  93475. if(n != 0) {
  93476. m = min(8-n, bits);
  93477. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93478. return false;
  93479. bits -= m;
  93480. }
  93481. m = bits / 8;
  93482. if(m > 0) {
  93483. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93484. return false;
  93485. bits %= 8;
  93486. }
  93487. if(bits > 0) {
  93488. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93489. return false;
  93490. }
  93491. }
  93492. return true;
  93493. }
  93494. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93495. {
  93496. FLAC__uint32 x;
  93497. FLAC__ASSERT(0 != br);
  93498. FLAC__ASSERT(0 != br->buffer);
  93499. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93500. /* step 1: skip over partial head word to get word aligned */
  93501. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93502. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93503. return false;
  93504. nvals--;
  93505. }
  93506. if(0 == nvals)
  93507. return true;
  93508. /* step 2: skip whole words in chunks */
  93509. while(nvals >= FLAC__BYTES_PER_WORD) {
  93510. if(br->consumed_words < br->words) {
  93511. br->consumed_words++;
  93512. nvals -= FLAC__BYTES_PER_WORD;
  93513. }
  93514. else if(!bitreader_read_from_client_(br))
  93515. return false;
  93516. }
  93517. /* step 3: skip any remainder from partial tail bytes */
  93518. while(nvals) {
  93519. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93520. return false;
  93521. nvals--;
  93522. }
  93523. return true;
  93524. }
  93525. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93526. {
  93527. FLAC__uint32 x;
  93528. FLAC__ASSERT(0 != br);
  93529. FLAC__ASSERT(0 != br->buffer);
  93530. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93531. /* step 1: read from partial head word to get word aligned */
  93532. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93533. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93534. return false;
  93535. *val++ = (FLAC__byte)x;
  93536. nvals--;
  93537. }
  93538. if(0 == nvals)
  93539. return true;
  93540. /* step 2: read whole words in chunks */
  93541. while(nvals >= FLAC__BYTES_PER_WORD) {
  93542. if(br->consumed_words < br->words) {
  93543. const brword word = br->buffer[br->consumed_words++];
  93544. #if FLAC__BYTES_PER_WORD == 4
  93545. val[0] = (FLAC__byte)(word >> 24);
  93546. val[1] = (FLAC__byte)(word >> 16);
  93547. val[2] = (FLAC__byte)(word >> 8);
  93548. val[3] = (FLAC__byte)word;
  93549. #elif FLAC__BYTES_PER_WORD == 8
  93550. val[0] = (FLAC__byte)(word >> 56);
  93551. val[1] = (FLAC__byte)(word >> 48);
  93552. val[2] = (FLAC__byte)(word >> 40);
  93553. val[3] = (FLAC__byte)(word >> 32);
  93554. val[4] = (FLAC__byte)(word >> 24);
  93555. val[5] = (FLAC__byte)(word >> 16);
  93556. val[6] = (FLAC__byte)(word >> 8);
  93557. val[7] = (FLAC__byte)word;
  93558. #else
  93559. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93560. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93561. #endif
  93562. val += FLAC__BYTES_PER_WORD;
  93563. nvals -= FLAC__BYTES_PER_WORD;
  93564. }
  93565. else if(!bitreader_read_from_client_(br))
  93566. return false;
  93567. }
  93568. /* step 3: read any remainder from partial tail bytes */
  93569. while(nvals) {
  93570. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93571. return false;
  93572. *val++ = (FLAC__byte)x;
  93573. nvals--;
  93574. }
  93575. return true;
  93576. }
  93577. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93578. #if 0 /* slow but readable version */
  93579. {
  93580. unsigned bit;
  93581. FLAC__ASSERT(0 != br);
  93582. FLAC__ASSERT(0 != br->buffer);
  93583. *val = 0;
  93584. while(1) {
  93585. if(!FLAC__bitreader_read_bit(br, &bit))
  93586. return false;
  93587. if(bit)
  93588. break;
  93589. else
  93590. *val++;
  93591. }
  93592. return true;
  93593. }
  93594. #else
  93595. {
  93596. unsigned i;
  93597. FLAC__ASSERT(0 != br);
  93598. FLAC__ASSERT(0 != br->buffer);
  93599. *val = 0;
  93600. while(1) {
  93601. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93602. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93603. if(b) {
  93604. i = COUNT_ZERO_MSBS(b);
  93605. *val += i;
  93606. i++;
  93607. br->consumed_bits += i;
  93608. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93609. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93610. br->consumed_words++;
  93611. br->consumed_bits = 0;
  93612. }
  93613. return true;
  93614. }
  93615. else {
  93616. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93617. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93618. br->consumed_words++;
  93619. br->consumed_bits = 0;
  93620. /* didn't find stop bit yet, have to keep going... */
  93621. }
  93622. }
  93623. /* at this point we've eaten up all the whole words; have to try
  93624. * reading through any tail bytes before calling the read callback.
  93625. * this is a repeat of the above logic adjusted for the fact we
  93626. * don't have a whole word. note though if the client is feeding
  93627. * us data a byte at a time (unlikely), br->consumed_bits may not
  93628. * be zero.
  93629. */
  93630. if(br->bytes) {
  93631. const unsigned end = br->bytes * 8;
  93632. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93633. if(b) {
  93634. i = COUNT_ZERO_MSBS(b);
  93635. *val += i;
  93636. i++;
  93637. br->consumed_bits += i;
  93638. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93639. return true;
  93640. }
  93641. else {
  93642. *val += end - br->consumed_bits;
  93643. br->consumed_bits += end;
  93644. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93645. /* didn't find stop bit yet, have to keep going... */
  93646. }
  93647. }
  93648. if(!bitreader_read_from_client_(br))
  93649. return false;
  93650. }
  93651. }
  93652. #endif
  93653. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93654. {
  93655. FLAC__uint32 lsbs = 0, msbs = 0;
  93656. unsigned uval;
  93657. FLAC__ASSERT(0 != br);
  93658. FLAC__ASSERT(0 != br->buffer);
  93659. FLAC__ASSERT(parameter <= 31);
  93660. /* read the unary MSBs and end bit */
  93661. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93662. return false;
  93663. /* read the binary LSBs */
  93664. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93665. return false;
  93666. /* compose the value */
  93667. uval = (msbs << parameter) | lsbs;
  93668. if(uval & 1)
  93669. *val = -((int)(uval >> 1)) - 1;
  93670. else
  93671. *val = (int)(uval >> 1);
  93672. return true;
  93673. }
  93674. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93675. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93676. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93677. /* OPT: possibly faster version for use with MSVC */
  93678. #ifdef _MSC_VER
  93679. {
  93680. unsigned i;
  93681. unsigned uval = 0;
  93682. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93683. /* try and get br->consumed_words and br->consumed_bits into register;
  93684. * must remember to flush them back to *br before calling other
  93685. * bitwriter functions that use them, and before returning */
  93686. register unsigned cwords;
  93687. register unsigned cbits;
  93688. FLAC__ASSERT(0 != br);
  93689. FLAC__ASSERT(0 != br->buffer);
  93690. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93691. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93692. FLAC__ASSERT(parameter < 32);
  93693. /* 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 */
  93694. if(nvals == 0)
  93695. return true;
  93696. cbits = br->consumed_bits;
  93697. cwords = br->consumed_words;
  93698. while(1) {
  93699. /* read unary part */
  93700. while(1) {
  93701. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93702. brword b = br->buffer[cwords] << cbits;
  93703. if(b) {
  93704. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93705. __asm {
  93706. bsr eax, b
  93707. not eax
  93708. and eax, 31
  93709. mov i, eax
  93710. }
  93711. #else
  93712. i = COUNT_ZERO_MSBS(b);
  93713. #endif
  93714. uval += i;
  93715. bits = parameter;
  93716. i++;
  93717. cbits += i;
  93718. if(cbits == FLAC__BITS_PER_WORD) {
  93719. crc16_update_word_(br, br->buffer[cwords]);
  93720. cwords++;
  93721. cbits = 0;
  93722. }
  93723. goto break1;
  93724. }
  93725. else {
  93726. uval += FLAC__BITS_PER_WORD - cbits;
  93727. crc16_update_word_(br, br->buffer[cwords]);
  93728. cwords++;
  93729. cbits = 0;
  93730. /* didn't find stop bit yet, have to keep going... */
  93731. }
  93732. }
  93733. /* at this point we've eaten up all the whole words; have to try
  93734. * reading through any tail bytes before calling the read callback.
  93735. * this is a repeat of the above logic adjusted for the fact we
  93736. * don't have a whole word. note though if the client is feeding
  93737. * us data a byte at a time (unlikely), br->consumed_bits may not
  93738. * be zero.
  93739. */
  93740. if(br->bytes) {
  93741. const unsigned end = br->bytes * 8;
  93742. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93743. if(b) {
  93744. i = COUNT_ZERO_MSBS(b);
  93745. uval += i;
  93746. bits = parameter;
  93747. i++;
  93748. cbits += i;
  93749. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93750. goto break1;
  93751. }
  93752. else {
  93753. uval += end - cbits;
  93754. cbits += end;
  93755. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93756. /* didn't find stop bit yet, have to keep going... */
  93757. }
  93758. }
  93759. /* flush registers and read; bitreader_read_from_client_() does
  93760. * not touch br->consumed_bits at all but we still need to set
  93761. * it in case it fails and we have to return false.
  93762. */
  93763. br->consumed_bits = cbits;
  93764. br->consumed_words = cwords;
  93765. if(!bitreader_read_from_client_(br))
  93766. return false;
  93767. cwords = br->consumed_words;
  93768. }
  93769. break1:
  93770. /* read binary part */
  93771. FLAC__ASSERT(cwords <= br->words);
  93772. if(bits) {
  93773. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93774. /* flush registers and read; bitreader_read_from_client_() does
  93775. * not touch br->consumed_bits at all but we still need to set
  93776. * it in case it fails and we have to return false.
  93777. */
  93778. br->consumed_bits = cbits;
  93779. br->consumed_words = cwords;
  93780. if(!bitreader_read_from_client_(br))
  93781. return false;
  93782. cwords = br->consumed_words;
  93783. }
  93784. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93785. if(cbits) {
  93786. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93787. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93788. const brword word = br->buffer[cwords];
  93789. if(bits < n) {
  93790. uval <<= bits;
  93791. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93792. cbits += bits;
  93793. goto break2;
  93794. }
  93795. uval <<= n;
  93796. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93797. bits -= n;
  93798. crc16_update_word_(br, word);
  93799. cwords++;
  93800. cbits = 0;
  93801. 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 */
  93802. uval <<= bits;
  93803. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93804. cbits = bits;
  93805. }
  93806. goto break2;
  93807. }
  93808. else {
  93809. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93810. uval <<= bits;
  93811. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93812. cbits = bits;
  93813. goto break2;
  93814. }
  93815. }
  93816. else {
  93817. /* in this case we're starting our read at a partial tail word;
  93818. * the reader has guaranteed that we have at least 'bits' bits
  93819. * available to read, which makes this case simpler.
  93820. */
  93821. uval <<= bits;
  93822. if(cbits) {
  93823. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93824. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93825. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93826. cbits += bits;
  93827. goto break2;
  93828. }
  93829. else {
  93830. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93831. cbits += bits;
  93832. goto break2;
  93833. }
  93834. }
  93835. }
  93836. break2:
  93837. /* compose the value */
  93838. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93839. /* are we done? */
  93840. --nvals;
  93841. if(nvals == 0) {
  93842. br->consumed_bits = cbits;
  93843. br->consumed_words = cwords;
  93844. return true;
  93845. }
  93846. uval = 0;
  93847. ++vals;
  93848. }
  93849. }
  93850. #else
  93851. {
  93852. unsigned i;
  93853. unsigned uval = 0;
  93854. /* try and get br->consumed_words and br->consumed_bits into register;
  93855. * must remember to flush them back to *br before calling other
  93856. * bitwriter functions that use them, and before returning */
  93857. register unsigned cwords;
  93858. register unsigned cbits;
  93859. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93860. FLAC__ASSERT(0 != br);
  93861. FLAC__ASSERT(0 != br->buffer);
  93862. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93863. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93864. FLAC__ASSERT(parameter < 32);
  93865. /* 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 */
  93866. if(nvals == 0)
  93867. return true;
  93868. cbits = br->consumed_bits;
  93869. cwords = br->consumed_words;
  93870. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93871. while(1) {
  93872. /* read unary part */
  93873. while(1) {
  93874. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93875. brword b = br->buffer[cwords] << cbits;
  93876. if(b) {
  93877. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93878. asm volatile (
  93879. "bsrl %1, %0;"
  93880. "notl %0;"
  93881. "andl $31, %0;"
  93882. : "=r"(i)
  93883. : "r"(b)
  93884. );
  93885. #else
  93886. i = COUNT_ZERO_MSBS(b);
  93887. #endif
  93888. uval += i;
  93889. cbits += i;
  93890. cbits++; /* skip over stop bit */
  93891. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93892. crc16_update_word_(br, br->buffer[cwords]);
  93893. cwords++;
  93894. cbits = 0;
  93895. }
  93896. goto break1;
  93897. }
  93898. else {
  93899. uval += FLAC__BITS_PER_WORD - cbits;
  93900. crc16_update_word_(br, br->buffer[cwords]);
  93901. cwords++;
  93902. cbits = 0;
  93903. /* didn't find stop bit yet, have to keep going... */
  93904. }
  93905. }
  93906. /* at this point we've eaten up all the whole words; have to try
  93907. * reading through any tail bytes before calling the read callback.
  93908. * this is a repeat of the above logic adjusted for the fact we
  93909. * don't have a whole word. note though if the client is feeding
  93910. * us data a byte at a time (unlikely), br->consumed_bits may not
  93911. * be zero.
  93912. */
  93913. if(br->bytes) {
  93914. const unsigned end = br->bytes * 8;
  93915. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93916. if(b) {
  93917. i = COUNT_ZERO_MSBS(b);
  93918. uval += i;
  93919. cbits += i;
  93920. cbits++; /* skip over stop bit */
  93921. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93922. goto break1;
  93923. }
  93924. else {
  93925. uval += end - cbits;
  93926. cbits += end;
  93927. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93928. /* didn't find stop bit yet, have to keep going... */
  93929. }
  93930. }
  93931. /* flush registers and read; bitreader_read_from_client_() does
  93932. * not touch br->consumed_bits at all but we still need to set
  93933. * it in case it fails and we have to return false.
  93934. */
  93935. br->consumed_bits = cbits;
  93936. br->consumed_words = cwords;
  93937. if(!bitreader_read_from_client_(br))
  93938. return false;
  93939. cwords = br->consumed_words;
  93940. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93941. /* + uval to offset our count by the # of unary bits already
  93942. * consumed before the read, because we will add these back
  93943. * in all at once at break1
  93944. */
  93945. }
  93946. break1:
  93947. ucbits -= uval;
  93948. ucbits--; /* account for stop bit */
  93949. /* read binary part */
  93950. FLAC__ASSERT(cwords <= br->words);
  93951. if(parameter) {
  93952. while(ucbits < parameter) {
  93953. /* flush registers and read; bitreader_read_from_client_() does
  93954. * not touch br->consumed_bits at all but we still need to set
  93955. * it in case it fails and we have to return false.
  93956. */
  93957. br->consumed_bits = cbits;
  93958. br->consumed_words = cwords;
  93959. if(!bitreader_read_from_client_(br))
  93960. return false;
  93961. cwords = br->consumed_words;
  93962. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93963. }
  93964. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93965. if(cbits) {
  93966. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93967. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93968. const brword word = br->buffer[cwords];
  93969. if(parameter < n) {
  93970. uval <<= parameter;
  93971. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93972. cbits += parameter;
  93973. }
  93974. else {
  93975. uval <<= n;
  93976. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93977. crc16_update_word_(br, word);
  93978. cwords++;
  93979. cbits = parameter - n;
  93980. 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 */
  93981. uval <<= cbits;
  93982. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93983. }
  93984. }
  93985. }
  93986. else {
  93987. cbits = parameter;
  93988. uval <<= parameter;
  93989. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93990. }
  93991. }
  93992. else {
  93993. /* in this case we're starting our read at a partial tail word;
  93994. * the reader has guaranteed that we have at least 'parameter'
  93995. * bits available to read, which makes this case simpler.
  93996. */
  93997. uval <<= parameter;
  93998. if(cbits) {
  93999. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94000. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94001. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94002. cbits += parameter;
  94003. }
  94004. else {
  94005. cbits = parameter;
  94006. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94007. }
  94008. }
  94009. }
  94010. ucbits -= parameter;
  94011. /* compose the value */
  94012. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94013. /* are we done? */
  94014. --nvals;
  94015. if(nvals == 0) {
  94016. br->consumed_bits = cbits;
  94017. br->consumed_words = cwords;
  94018. return true;
  94019. }
  94020. uval = 0;
  94021. ++vals;
  94022. }
  94023. }
  94024. #endif
  94025. #if 0 /* UNUSED */
  94026. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94027. {
  94028. FLAC__uint32 lsbs = 0, msbs = 0;
  94029. unsigned bit, uval, k;
  94030. FLAC__ASSERT(0 != br);
  94031. FLAC__ASSERT(0 != br->buffer);
  94032. k = FLAC__bitmath_ilog2(parameter);
  94033. /* read the unary MSBs and end bit */
  94034. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94035. return false;
  94036. /* read the binary LSBs */
  94037. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94038. return false;
  94039. if(parameter == 1u<<k) {
  94040. /* compose the value */
  94041. uval = (msbs << k) | lsbs;
  94042. }
  94043. else {
  94044. unsigned d = (1 << (k+1)) - parameter;
  94045. if(lsbs >= d) {
  94046. if(!FLAC__bitreader_read_bit(br, &bit))
  94047. return false;
  94048. lsbs <<= 1;
  94049. lsbs |= bit;
  94050. lsbs -= d;
  94051. }
  94052. /* compose the value */
  94053. uval = msbs * parameter + lsbs;
  94054. }
  94055. /* unfold unsigned to signed */
  94056. if(uval & 1)
  94057. *val = -((int)(uval >> 1)) - 1;
  94058. else
  94059. *val = (int)(uval >> 1);
  94060. return true;
  94061. }
  94062. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94063. {
  94064. FLAC__uint32 lsbs, msbs = 0;
  94065. unsigned bit, k;
  94066. FLAC__ASSERT(0 != br);
  94067. FLAC__ASSERT(0 != br->buffer);
  94068. k = FLAC__bitmath_ilog2(parameter);
  94069. /* read the unary MSBs and end bit */
  94070. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94071. return false;
  94072. /* read the binary LSBs */
  94073. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94074. return false;
  94075. if(parameter == 1u<<k) {
  94076. /* compose the value */
  94077. *val = (msbs << k) | lsbs;
  94078. }
  94079. else {
  94080. unsigned d = (1 << (k+1)) - parameter;
  94081. if(lsbs >= d) {
  94082. if(!FLAC__bitreader_read_bit(br, &bit))
  94083. return false;
  94084. lsbs <<= 1;
  94085. lsbs |= bit;
  94086. lsbs -= d;
  94087. }
  94088. /* compose the value */
  94089. *val = msbs * parameter + lsbs;
  94090. }
  94091. return true;
  94092. }
  94093. #endif /* UNUSED */
  94094. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94095. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94096. {
  94097. FLAC__uint32 v = 0;
  94098. FLAC__uint32 x;
  94099. unsigned i;
  94100. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94101. return false;
  94102. if(raw)
  94103. raw[(*rawlen)++] = (FLAC__byte)x;
  94104. if(!(x & 0x80)) { /* 0xxxxxxx */
  94105. v = x;
  94106. i = 0;
  94107. }
  94108. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94109. v = x & 0x1F;
  94110. i = 1;
  94111. }
  94112. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94113. v = x & 0x0F;
  94114. i = 2;
  94115. }
  94116. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94117. v = x & 0x07;
  94118. i = 3;
  94119. }
  94120. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94121. v = x & 0x03;
  94122. i = 4;
  94123. }
  94124. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94125. v = x & 0x01;
  94126. i = 5;
  94127. }
  94128. else {
  94129. *val = 0xffffffff;
  94130. return true;
  94131. }
  94132. for( ; i; i--) {
  94133. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94134. return false;
  94135. if(raw)
  94136. raw[(*rawlen)++] = (FLAC__byte)x;
  94137. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94138. *val = 0xffffffff;
  94139. return true;
  94140. }
  94141. v <<= 6;
  94142. v |= (x & 0x3F);
  94143. }
  94144. *val = v;
  94145. return true;
  94146. }
  94147. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94148. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94149. {
  94150. FLAC__uint64 v = 0;
  94151. FLAC__uint32 x;
  94152. unsigned i;
  94153. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94154. return false;
  94155. if(raw)
  94156. raw[(*rawlen)++] = (FLAC__byte)x;
  94157. if(!(x & 0x80)) { /* 0xxxxxxx */
  94158. v = x;
  94159. i = 0;
  94160. }
  94161. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94162. v = x & 0x1F;
  94163. i = 1;
  94164. }
  94165. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94166. v = x & 0x0F;
  94167. i = 2;
  94168. }
  94169. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94170. v = x & 0x07;
  94171. i = 3;
  94172. }
  94173. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94174. v = x & 0x03;
  94175. i = 4;
  94176. }
  94177. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94178. v = x & 0x01;
  94179. i = 5;
  94180. }
  94181. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94182. v = 0;
  94183. i = 6;
  94184. }
  94185. else {
  94186. *val = FLAC__U64L(0xffffffffffffffff);
  94187. return true;
  94188. }
  94189. for( ; i; i--) {
  94190. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94191. return false;
  94192. if(raw)
  94193. raw[(*rawlen)++] = (FLAC__byte)x;
  94194. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94195. *val = FLAC__U64L(0xffffffffffffffff);
  94196. return true;
  94197. }
  94198. v <<= 6;
  94199. v |= (x & 0x3F);
  94200. }
  94201. *val = v;
  94202. return true;
  94203. }
  94204. #endif
  94205. /*** End of inlined file: bitreader.c ***/
  94206. /*** Start of inlined file: bitwriter.c ***/
  94207. /*** Start of inlined file: juce_FlacHeader.h ***/
  94208. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94209. // tasks..
  94210. #define VERSION "1.2.1"
  94211. #define FLAC__NO_DLL 1
  94212. #if JUCE_MSVC
  94213. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94214. #endif
  94215. #if JUCE_MAC
  94216. #define FLAC__SYS_DARWIN 1
  94217. #endif
  94218. /*** End of inlined file: juce_FlacHeader.h ***/
  94219. #if JUCE_USE_FLAC
  94220. #if HAVE_CONFIG_H
  94221. # include <config.h>
  94222. #endif
  94223. #include <stdlib.h> /* for malloc() */
  94224. #include <string.h> /* for memcpy(), memset() */
  94225. #ifdef _MSC_VER
  94226. #include <winsock.h> /* for ntohl() */
  94227. #elif defined FLAC__SYS_DARWIN
  94228. #include <machine/endian.h> /* for ntohl() */
  94229. #elif defined __MINGW32__
  94230. #include <winsock.h> /* for ntohl() */
  94231. #else
  94232. #include <netinet/in.h> /* for ntohl() */
  94233. #endif
  94234. #if 0 /* UNUSED */
  94235. #endif
  94236. /*** Start of inlined file: bitwriter.h ***/
  94237. #ifndef FLAC__PRIVATE__BITWRITER_H
  94238. #define FLAC__PRIVATE__BITWRITER_H
  94239. #include <stdio.h> /* for FILE */
  94240. /*
  94241. * opaque structure definition
  94242. */
  94243. struct FLAC__BitWriter;
  94244. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94245. /*
  94246. * construction, deletion, initialization, etc functions
  94247. */
  94248. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94249. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94250. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94251. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94252. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94253. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94254. /*
  94255. * CRC functions
  94256. *
  94257. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94258. */
  94259. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94260. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94261. /*
  94262. * info functions
  94263. */
  94264. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94265. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94266. /*
  94267. * direct buffer access
  94268. *
  94269. * there may be no calls on the bitwriter between get and release.
  94270. * the bitwriter continues to own the returned buffer.
  94271. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94272. */
  94273. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94274. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94275. /*
  94276. * write functions
  94277. */
  94278. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94279. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94280. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94281. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94282. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94283. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94284. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94285. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94286. #if 0 /* UNUSED */
  94287. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94288. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94289. #endif
  94290. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94291. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94292. #if 0 /* UNUSED */
  94293. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94294. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94295. #endif
  94296. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94297. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94298. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94299. #endif
  94300. /*** End of inlined file: bitwriter.h ***/
  94301. /*** Start of inlined file: alloc.h ***/
  94302. #ifndef FLAC__SHARE__ALLOC_H
  94303. #define FLAC__SHARE__ALLOC_H
  94304. #if HAVE_CONFIG_H
  94305. # include <config.h>
  94306. #endif
  94307. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94308. * before #including this file, otherwise SIZE_MAX might not be defined
  94309. */
  94310. #include <limits.h> /* for SIZE_MAX */
  94311. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94312. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94313. #endif
  94314. #include <stdlib.h> /* for size_t, malloc(), etc */
  94315. #ifndef SIZE_MAX
  94316. # ifndef SIZE_T_MAX
  94317. # ifdef _MSC_VER
  94318. # define SIZE_T_MAX UINT_MAX
  94319. # else
  94320. # error
  94321. # endif
  94322. # endif
  94323. # define SIZE_MAX SIZE_T_MAX
  94324. #endif
  94325. #ifndef FLaC__INLINE
  94326. #define FLaC__INLINE
  94327. #endif
  94328. /* avoid malloc()ing 0 bytes, see:
  94329. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94330. */
  94331. static FLaC__INLINE void *safe_malloc_(size_t size)
  94332. {
  94333. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94334. if(!size)
  94335. size++;
  94336. return malloc(size);
  94337. }
  94338. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94339. {
  94340. if(!nmemb || !size)
  94341. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94342. return calloc(nmemb, size);
  94343. }
  94344. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94345. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94346. {
  94347. size2 += size1;
  94348. if(size2 < size1)
  94349. return 0;
  94350. return safe_malloc_(size2);
  94351. }
  94352. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94353. {
  94354. size2 += size1;
  94355. if(size2 < size1)
  94356. return 0;
  94357. size3 += size2;
  94358. if(size3 < size2)
  94359. return 0;
  94360. return safe_malloc_(size3);
  94361. }
  94362. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94363. {
  94364. size2 += size1;
  94365. if(size2 < size1)
  94366. return 0;
  94367. size3 += size2;
  94368. if(size3 < size2)
  94369. return 0;
  94370. size4 += size3;
  94371. if(size4 < size3)
  94372. return 0;
  94373. return safe_malloc_(size4);
  94374. }
  94375. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94376. #if 0
  94377. needs support for cases where sizeof(size_t) != 4
  94378. {
  94379. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94380. if(sizeof(size_t) == 4) {
  94381. if ((double)size1 * (double)size2 < 4294967296.0)
  94382. return malloc(size1*size2);
  94383. }
  94384. return 0;
  94385. }
  94386. #else
  94387. /* better? */
  94388. {
  94389. if(!size1 || !size2)
  94390. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94391. if(size1 > SIZE_MAX / size2)
  94392. return 0;
  94393. return malloc(size1*size2);
  94394. }
  94395. #endif
  94396. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94397. {
  94398. if(!size1 || !size2 || !size3)
  94399. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94400. if(size1 > SIZE_MAX / size2)
  94401. return 0;
  94402. size1 *= size2;
  94403. if(size1 > SIZE_MAX / size3)
  94404. return 0;
  94405. return malloc(size1*size3);
  94406. }
  94407. /* size1*size2 + size3 */
  94408. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94409. {
  94410. if(!size1 || !size2)
  94411. return safe_malloc_(size3);
  94412. if(size1 > SIZE_MAX / size2)
  94413. return 0;
  94414. return safe_malloc_add_2op_(size1*size2, size3);
  94415. }
  94416. /* size1 * (size2 + size3) */
  94417. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94418. {
  94419. if(!size1 || (!size2 && !size3))
  94420. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94421. size2 += size3;
  94422. if(size2 < size3)
  94423. return 0;
  94424. return safe_malloc_mul_2op_(size1, size2);
  94425. }
  94426. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94427. {
  94428. size2 += size1;
  94429. if(size2 < size1)
  94430. return 0;
  94431. return realloc(ptr, size2);
  94432. }
  94433. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94434. {
  94435. size2 += size1;
  94436. if(size2 < size1)
  94437. return 0;
  94438. size3 += size2;
  94439. if(size3 < size2)
  94440. return 0;
  94441. return realloc(ptr, size3);
  94442. }
  94443. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94444. {
  94445. size2 += size1;
  94446. if(size2 < size1)
  94447. return 0;
  94448. size3 += size2;
  94449. if(size3 < size2)
  94450. return 0;
  94451. size4 += size3;
  94452. if(size4 < size3)
  94453. return 0;
  94454. return realloc(ptr, size4);
  94455. }
  94456. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94457. {
  94458. if(!size1 || !size2)
  94459. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94460. if(size1 > SIZE_MAX / size2)
  94461. return 0;
  94462. return realloc(ptr, size1*size2);
  94463. }
  94464. /* size1 * (size2 + size3) */
  94465. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94466. {
  94467. if(!size1 || (!size2 && !size3))
  94468. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94469. size2 += size3;
  94470. if(size2 < size3)
  94471. return 0;
  94472. return safe_realloc_mul_2op_(ptr, size1, size2);
  94473. }
  94474. #endif
  94475. /*** End of inlined file: alloc.h ***/
  94476. /* Things should be fastest when this matches the machine word size */
  94477. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94478. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94479. typedef FLAC__uint32 bwword;
  94480. #define FLAC__BYTES_PER_WORD 4
  94481. #define FLAC__BITS_PER_WORD 32
  94482. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94483. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94484. #if WORDS_BIGENDIAN
  94485. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94486. #else
  94487. #ifdef _MSC_VER
  94488. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94489. #else
  94490. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94491. #endif
  94492. #endif
  94493. /*
  94494. * The default capacity here doesn't matter too much. The buffer always grows
  94495. * to hold whatever is written to it. Usually the encoder will stop adding at
  94496. * a frame or metadata block, then write that out and clear the buffer for the
  94497. * next one.
  94498. */
  94499. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94500. /* When growing, increment 4K at a time */
  94501. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94502. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94503. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94504. #ifdef min
  94505. #undef min
  94506. #endif
  94507. #define min(x,y) ((x)<(y)?(x):(y))
  94508. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94509. #ifdef _MSC_VER
  94510. #define FLAC__U64L(x) x
  94511. #else
  94512. #define FLAC__U64L(x) x##LLU
  94513. #endif
  94514. #ifndef FLaC__INLINE
  94515. #define FLaC__INLINE
  94516. #endif
  94517. struct FLAC__BitWriter {
  94518. bwword *buffer;
  94519. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94520. unsigned capacity; /* capacity of buffer in words */
  94521. unsigned words; /* # of complete words in buffer */
  94522. unsigned bits; /* # of used bits in accum */
  94523. };
  94524. /* * WATCHOUT: The current implementation only grows the buffer. */
  94525. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94526. {
  94527. unsigned new_capacity;
  94528. bwword *new_buffer;
  94529. FLAC__ASSERT(0 != bw);
  94530. FLAC__ASSERT(0 != bw->buffer);
  94531. /* calculate total words needed to store 'bits_to_add' additional bits */
  94532. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94533. /* it's possible (due to pessimism in the growth estimation that
  94534. * leads to this call) that we don't actually need to grow
  94535. */
  94536. if(bw->capacity >= new_capacity)
  94537. return true;
  94538. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94539. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94540. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94541. /* make sure we got everything right */
  94542. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94543. FLAC__ASSERT(new_capacity > bw->capacity);
  94544. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94545. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94546. if(new_buffer == 0)
  94547. return false;
  94548. bw->buffer = new_buffer;
  94549. bw->capacity = new_capacity;
  94550. return true;
  94551. }
  94552. /***********************************************************************
  94553. *
  94554. * Class constructor/destructor
  94555. *
  94556. ***********************************************************************/
  94557. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94558. {
  94559. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94560. /* note that calloc() sets all members to 0 for us */
  94561. return bw;
  94562. }
  94563. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94564. {
  94565. FLAC__ASSERT(0 != bw);
  94566. FLAC__bitwriter_free(bw);
  94567. free(bw);
  94568. }
  94569. /***********************************************************************
  94570. *
  94571. * Public class methods
  94572. *
  94573. ***********************************************************************/
  94574. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94575. {
  94576. FLAC__ASSERT(0 != bw);
  94577. bw->words = bw->bits = 0;
  94578. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94579. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94580. if(bw->buffer == 0)
  94581. return false;
  94582. return true;
  94583. }
  94584. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94585. {
  94586. FLAC__ASSERT(0 != bw);
  94587. if(0 != bw->buffer)
  94588. free(bw->buffer);
  94589. bw->buffer = 0;
  94590. bw->capacity = 0;
  94591. bw->words = bw->bits = 0;
  94592. }
  94593. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94594. {
  94595. bw->words = bw->bits = 0;
  94596. }
  94597. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94598. {
  94599. unsigned i, j;
  94600. if(bw == 0) {
  94601. fprintf(out, "bitwriter is NULL\n");
  94602. }
  94603. else {
  94604. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94605. for(i = 0; i < bw->words; i++) {
  94606. fprintf(out, "%08X: ", i);
  94607. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94608. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94609. fprintf(out, "\n");
  94610. }
  94611. if(bw->bits > 0) {
  94612. fprintf(out, "%08X: ", i);
  94613. for(j = 0; j < bw->bits; j++)
  94614. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94615. fprintf(out, "\n");
  94616. }
  94617. }
  94618. }
  94619. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94620. {
  94621. const FLAC__byte *buffer;
  94622. size_t bytes;
  94623. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94624. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94625. return false;
  94626. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94627. FLAC__bitwriter_release_buffer(bw);
  94628. return true;
  94629. }
  94630. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94631. {
  94632. const FLAC__byte *buffer;
  94633. size_t bytes;
  94634. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94635. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94636. return false;
  94637. *crc = FLAC__crc8(buffer, bytes);
  94638. FLAC__bitwriter_release_buffer(bw);
  94639. return true;
  94640. }
  94641. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94642. {
  94643. return ((bw->bits & 7) == 0);
  94644. }
  94645. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94646. {
  94647. return FLAC__TOTAL_BITS(bw);
  94648. }
  94649. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94650. {
  94651. FLAC__ASSERT((bw->bits & 7) == 0);
  94652. /* double protection */
  94653. if(bw->bits & 7)
  94654. return false;
  94655. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94656. if(bw->bits) {
  94657. FLAC__ASSERT(bw->words <= bw->capacity);
  94658. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94659. return false;
  94660. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94661. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94662. }
  94663. /* now we can just return what we have */
  94664. *buffer = (FLAC__byte*)bw->buffer;
  94665. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94666. return true;
  94667. }
  94668. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94669. {
  94670. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94671. * get-mode' flag could be added everywhere and then cleared here
  94672. */
  94673. (void)bw;
  94674. }
  94675. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94676. {
  94677. unsigned n;
  94678. FLAC__ASSERT(0 != bw);
  94679. FLAC__ASSERT(0 != bw->buffer);
  94680. if(bits == 0)
  94681. return true;
  94682. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94683. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94684. return false;
  94685. /* first part gets to word alignment */
  94686. if(bw->bits) {
  94687. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94688. bw->accum <<= n;
  94689. bits -= n;
  94690. bw->bits += n;
  94691. if(bw->bits == FLAC__BITS_PER_WORD) {
  94692. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94693. bw->bits = 0;
  94694. }
  94695. else
  94696. return true;
  94697. }
  94698. /* do whole words */
  94699. while(bits >= FLAC__BITS_PER_WORD) {
  94700. bw->buffer[bw->words++] = 0;
  94701. bits -= FLAC__BITS_PER_WORD;
  94702. }
  94703. /* do any leftovers */
  94704. if(bits > 0) {
  94705. bw->accum = 0;
  94706. bw->bits = bits;
  94707. }
  94708. return true;
  94709. }
  94710. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94711. {
  94712. register unsigned left;
  94713. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94714. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94715. FLAC__ASSERT(0 != bw);
  94716. FLAC__ASSERT(0 != bw->buffer);
  94717. FLAC__ASSERT(bits <= 32);
  94718. if(bits == 0)
  94719. return true;
  94720. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94721. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94722. return false;
  94723. left = FLAC__BITS_PER_WORD - bw->bits;
  94724. if(bits < left) {
  94725. bw->accum <<= bits;
  94726. bw->accum |= val;
  94727. bw->bits += bits;
  94728. }
  94729. 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 */
  94730. bw->accum <<= left;
  94731. bw->accum |= val >> (bw->bits = bits - left);
  94732. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94733. bw->accum = val;
  94734. }
  94735. else {
  94736. bw->accum = val;
  94737. bw->bits = 0;
  94738. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94739. }
  94740. return true;
  94741. }
  94742. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94743. {
  94744. /* zero-out unused bits */
  94745. if(bits < 32)
  94746. val &= (~(0xffffffff << bits));
  94747. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94748. }
  94749. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94750. {
  94751. /* this could be a little faster but it's not used for much */
  94752. if(bits > 32) {
  94753. return
  94754. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94755. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94756. }
  94757. else
  94758. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94759. }
  94760. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94761. {
  94762. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94763. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94764. return false;
  94765. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94766. return false;
  94767. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94768. return false;
  94769. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94770. return false;
  94771. return true;
  94772. }
  94773. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94774. {
  94775. unsigned i;
  94776. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94777. for(i = 0; i < nvals; i++) {
  94778. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94779. return false;
  94780. }
  94781. return true;
  94782. }
  94783. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94784. {
  94785. if(val < 32)
  94786. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94787. else
  94788. return
  94789. FLAC__bitwriter_write_zeroes(bw, val) &&
  94790. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94791. }
  94792. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94793. {
  94794. FLAC__uint32 uval;
  94795. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94796. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94797. uval = (val<<1) ^ (val>>31);
  94798. return 1 + parameter + (uval >> parameter);
  94799. }
  94800. #if 0 /* UNUSED */
  94801. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94802. {
  94803. unsigned bits, msbs, uval;
  94804. unsigned k;
  94805. FLAC__ASSERT(parameter > 0);
  94806. /* fold signed to unsigned */
  94807. if(val < 0)
  94808. uval = (unsigned)(((-(++val)) << 1) + 1);
  94809. else
  94810. uval = (unsigned)(val << 1);
  94811. k = FLAC__bitmath_ilog2(parameter);
  94812. if(parameter == 1u<<k) {
  94813. FLAC__ASSERT(k <= 30);
  94814. msbs = uval >> k;
  94815. bits = 1 + k + msbs;
  94816. }
  94817. else {
  94818. unsigned q, r, d;
  94819. d = (1 << (k+1)) - parameter;
  94820. q = uval / parameter;
  94821. r = uval - (q * parameter);
  94822. bits = 1 + q + k;
  94823. if(r >= d)
  94824. bits++;
  94825. }
  94826. return bits;
  94827. }
  94828. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94829. {
  94830. unsigned bits, msbs;
  94831. unsigned k;
  94832. FLAC__ASSERT(parameter > 0);
  94833. k = FLAC__bitmath_ilog2(parameter);
  94834. if(parameter == 1u<<k) {
  94835. FLAC__ASSERT(k <= 30);
  94836. msbs = uval >> k;
  94837. bits = 1 + k + msbs;
  94838. }
  94839. else {
  94840. unsigned q, r, d;
  94841. d = (1 << (k+1)) - parameter;
  94842. q = uval / parameter;
  94843. r = uval - (q * parameter);
  94844. bits = 1 + q + k;
  94845. if(r >= d)
  94846. bits++;
  94847. }
  94848. return bits;
  94849. }
  94850. #endif /* UNUSED */
  94851. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94852. {
  94853. unsigned total_bits, interesting_bits, msbs;
  94854. FLAC__uint32 uval, pattern;
  94855. FLAC__ASSERT(0 != bw);
  94856. FLAC__ASSERT(0 != bw->buffer);
  94857. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94858. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94859. uval = (val<<1) ^ (val>>31);
  94860. msbs = uval >> parameter;
  94861. interesting_bits = 1 + parameter;
  94862. total_bits = interesting_bits + msbs;
  94863. pattern = 1 << parameter; /* the unary end bit */
  94864. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94865. if(total_bits <= 32)
  94866. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94867. else
  94868. return
  94869. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94870. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94871. }
  94872. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94873. {
  94874. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94875. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94876. FLAC__uint32 uval;
  94877. unsigned left;
  94878. const unsigned lsbits = 1 + parameter;
  94879. unsigned msbits;
  94880. FLAC__ASSERT(0 != bw);
  94881. FLAC__ASSERT(0 != bw->buffer);
  94882. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94883. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94884. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94885. while(nvals) {
  94886. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94887. uval = (*vals<<1) ^ (*vals>>31);
  94888. msbits = uval >> parameter;
  94889. #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) */
  94890. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94891. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94892. bw->bits = bw->bits + msbits + lsbits;
  94893. uval |= mask1; /* set stop bit */
  94894. uval &= mask2; /* mask off unused top bits */
  94895. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94896. bw->accum <<= msbits;
  94897. bw->accum <<= lsbits;
  94898. bw->accum |= uval;
  94899. if(bw->bits == FLAC__BITS_PER_WORD) {
  94900. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94901. bw->bits = 0;
  94902. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94903. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94904. FLAC__ASSERT(bw->capacity == bw->words);
  94905. return false;
  94906. }
  94907. }
  94908. }
  94909. else {
  94910. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94911. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94912. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94913. bw->bits = bw->bits + msbits + lsbits;
  94914. uval |= mask1; /* set stop bit */
  94915. uval &= mask2; /* mask off unused top bits */
  94916. bw->accum <<= msbits + lsbits;
  94917. bw->accum |= uval;
  94918. }
  94919. else {
  94920. #endif
  94921. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94922. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94923. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94924. return false;
  94925. if(msbits) {
  94926. /* first part gets to word alignment */
  94927. if(bw->bits) {
  94928. left = FLAC__BITS_PER_WORD - bw->bits;
  94929. if(msbits < left) {
  94930. bw->accum <<= msbits;
  94931. bw->bits += msbits;
  94932. goto break1;
  94933. }
  94934. else {
  94935. bw->accum <<= left;
  94936. msbits -= left;
  94937. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94938. bw->bits = 0;
  94939. }
  94940. }
  94941. /* do whole words */
  94942. while(msbits >= FLAC__BITS_PER_WORD) {
  94943. bw->buffer[bw->words++] = 0;
  94944. msbits -= FLAC__BITS_PER_WORD;
  94945. }
  94946. /* do any leftovers */
  94947. if(msbits > 0) {
  94948. bw->accum = 0;
  94949. bw->bits = msbits;
  94950. }
  94951. }
  94952. break1:
  94953. uval |= mask1; /* set stop bit */
  94954. uval &= mask2; /* mask off unused top bits */
  94955. left = FLAC__BITS_PER_WORD - bw->bits;
  94956. if(lsbits < left) {
  94957. bw->accum <<= lsbits;
  94958. bw->accum |= uval;
  94959. bw->bits += lsbits;
  94960. }
  94961. else {
  94962. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94963. * be > lsbits (because of previous assertions) so it would have
  94964. * triggered the (lsbits<left) case above.
  94965. */
  94966. FLAC__ASSERT(bw->bits);
  94967. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94968. bw->accum <<= left;
  94969. bw->accum |= uval >> (bw->bits = lsbits - left);
  94970. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94971. bw->accum = uval;
  94972. }
  94973. #if 1
  94974. }
  94975. #endif
  94976. vals++;
  94977. nvals--;
  94978. }
  94979. return true;
  94980. }
  94981. #if 0 /* UNUSED */
  94982. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94983. {
  94984. unsigned total_bits, msbs, uval;
  94985. unsigned k;
  94986. FLAC__ASSERT(0 != bw);
  94987. FLAC__ASSERT(0 != bw->buffer);
  94988. FLAC__ASSERT(parameter > 0);
  94989. /* fold signed to unsigned */
  94990. if(val < 0)
  94991. uval = (unsigned)(((-(++val)) << 1) + 1);
  94992. else
  94993. uval = (unsigned)(val << 1);
  94994. k = FLAC__bitmath_ilog2(parameter);
  94995. if(parameter == 1u<<k) {
  94996. unsigned pattern;
  94997. FLAC__ASSERT(k <= 30);
  94998. msbs = uval >> k;
  94999. total_bits = 1 + k + msbs;
  95000. pattern = 1 << k; /* the unary end bit */
  95001. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95002. if(total_bits <= 32) {
  95003. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95004. return false;
  95005. }
  95006. else {
  95007. /* write the unary MSBs */
  95008. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95009. return false;
  95010. /* write the unary end bit and binary LSBs */
  95011. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95012. return false;
  95013. }
  95014. }
  95015. else {
  95016. unsigned q, r, d;
  95017. d = (1 << (k+1)) - parameter;
  95018. q = uval / parameter;
  95019. r = uval - (q * parameter);
  95020. /* write the unary MSBs */
  95021. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95022. return false;
  95023. /* write the unary end bit */
  95024. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95025. return false;
  95026. /* write the binary LSBs */
  95027. if(r >= d) {
  95028. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95029. return false;
  95030. }
  95031. else {
  95032. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95033. return false;
  95034. }
  95035. }
  95036. return true;
  95037. }
  95038. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95039. {
  95040. unsigned total_bits, msbs;
  95041. unsigned k;
  95042. FLAC__ASSERT(0 != bw);
  95043. FLAC__ASSERT(0 != bw->buffer);
  95044. FLAC__ASSERT(parameter > 0);
  95045. k = FLAC__bitmath_ilog2(parameter);
  95046. if(parameter == 1u<<k) {
  95047. unsigned pattern;
  95048. FLAC__ASSERT(k <= 30);
  95049. msbs = uval >> k;
  95050. total_bits = 1 + k + msbs;
  95051. pattern = 1 << k; /* the unary end bit */
  95052. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95053. if(total_bits <= 32) {
  95054. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95055. return false;
  95056. }
  95057. else {
  95058. /* write the unary MSBs */
  95059. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95060. return false;
  95061. /* write the unary end bit and binary LSBs */
  95062. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95063. return false;
  95064. }
  95065. }
  95066. else {
  95067. unsigned q, r, d;
  95068. d = (1 << (k+1)) - parameter;
  95069. q = uval / parameter;
  95070. r = uval - (q * parameter);
  95071. /* write the unary MSBs */
  95072. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95073. return false;
  95074. /* write the unary end bit */
  95075. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95076. return false;
  95077. /* write the binary LSBs */
  95078. if(r >= d) {
  95079. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95080. return false;
  95081. }
  95082. else {
  95083. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95084. return false;
  95085. }
  95086. }
  95087. return true;
  95088. }
  95089. #endif /* UNUSED */
  95090. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95091. {
  95092. FLAC__bool ok = 1;
  95093. FLAC__ASSERT(0 != bw);
  95094. FLAC__ASSERT(0 != bw->buffer);
  95095. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95096. if(val < 0x80) {
  95097. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95098. }
  95099. else if(val < 0x800) {
  95100. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95101. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95102. }
  95103. else if(val < 0x10000) {
  95104. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95105. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95107. }
  95108. else if(val < 0x200000) {
  95109. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95110. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95111. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95112. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95113. }
  95114. else if(val < 0x4000000) {
  95115. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95116. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95117. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95118. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95119. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95120. }
  95121. else {
  95122. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95123. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95124. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95125. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95128. }
  95129. return ok;
  95130. }
  95131. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95132. {
  95133. FLAC__bool ok = 1;
  95134. FLAC__ASSERT(0 != bw);
  95135. FLAC__ASSERT(0 != bw->buffer);
  95136. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95137. if(val < 0x80) {
  95138. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95139. }
  95140. else if(val < 0x800) {
  95141. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95142. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95143. }
  95144. else if(val < 0x10000) {
  95145. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95148. }
  95149. else if(val < 0x200000) {
  95150. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95151. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95152. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95153. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95154. }
  95155. else if(val < 0x4000000) {
  95156. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95157. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95158. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95159. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95160. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95161. }
  95162. else if(val < 0x80000000) {
  95163. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95165. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95166. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95167. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95168. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95169. }
  95170. else {
  95171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95172. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95173. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 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. return ok;
  95180. }
  95181. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95182. {
  95183. /* 0-pad to byte boundary */
  95184. if(bw->bits & 7u)
  95185. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95186. else
  95187. return true;
  95188. }
  95189. #endif
  95190. /*** End of inlined file: bitwriter.c ***/
  95191. /*** Start of inlined file: cpu.c ***/
  95192. /*** Start of inlined file: juce_FlacHeader.h ***/
  95193. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95194. // tasks..
  95195. #define VERSION "1.2.1"
  95196. #define FLAC__NO_DLL 1
  95197. #if JUCE_MSVC
  95198. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95199. #endif
  95200. #if JUCE_MAC
  95201. #define FLAC__SYS_DARWIN 1
  95202. #endif
  95203. /*** End of inlined file: juce_FlacHeader.h ***/
  95204. #if JUCE_USE_FLAC
  95205. #if HAVE_CONFIG_H
  95206. # include <config.h>
  95207. #endif
  95208. #include <stdlib.h>
  95209. #include <stdio.h>
  95210. #if defined FLAC__CPU_IA32
  95211. # include <signal.h>
  95212. #elif defined FLAC__CPU_PPC
  95213. # if !defined FLAC__NO_ASM
  95214. # if defined FLAC__SYS_DARWIN
  95215. # include <sys/sysctl.h>
  95216. # include <mach/mach.h>
  95217. # include <mach/mach_host.h>
  95218. # include <mach/host_info.h>
  95219. # include <mach/machine.h>
  95220. # ifndef CPU_SUBTYPE_POWERPC_970
  95221. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95222. # endif
  95223. # else /* FLAC__SYS_DARWIN */
  95224. # include <signal.h>
  95225. # include <setjmp.h>
  95226. static sigjmp_buf jmpbuf;
  95227. static volatile sig_atomic_t canjump = 0;
  95228. static void sigill_handler (int sig)
  95229. {
  95230. if (!canjump) {
  95231. signal (sig, SIG_DFL);
  95232. raise (sig);
  95233. }
  95234. canjump = 0;
  95235. siglongjmp (jmpbuf, 1);
  95236. }
  95237. # endif /* FLAC__SYS_DARWIN */
  95238. # endif /* FLAC__NO_ASM */
  95239. #endif /* FLAC__CPU_PPC */
  95240. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95241. #include <sys/param.h>
  95242. #include <sys/sysctl.h>
  95243. #include <machine/cpu.h>
  95244. #endif
  95245. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95246. #include <sys/types.h>
  95247. #include <sys/sysctl.h>
  95248. #endif
  95249. #if defined(__APPLE__)
  95250. /* how to get sysctlbyname()? */
  95251. #endif
  95252. /* these are flags in EDX of CPUID AX=00000001 */
  95253. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95254. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95255. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95256. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95257. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95258. /* these are flags in ECX of CPUID AX=00000001 */
  95259. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95260. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95261. /* these are flags in EDX of CPUID AX=80000001 */
  95262. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95263. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95264. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95265. /*
  95266. * Extra stuff needed for detection of OS support for SSE on IA-32
  95267. */
  95268. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95269. # if defined(__linux__)
  95270. /*
  95271. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95272. * modify the return address to jump over the offending SSE instruction
  95273. * and also the operation following it that indicates the instruction
  95274. * executed successfully. In this way we use no global variables and
  95275. * stay thread-safe.
  95276. *
  95277. * 3 + 3 + 6:
  95278. * 3 bytes for "xorps xmm0,xmm0"
  95279. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95280. * 6 bytes extra in case our estimate is wrong
  95281. * 12 bytes puts us in the NOP "landing zone"
  95282. */
  95283. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95284. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95285. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95286. {
  95287. (void)signal;
  95288. sc.eip += 3 + 3 + 6;
  95289. }
  95290. # else
  95291. # include <sys/ucontext.h>
  95292. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95293. {
  95294. (void)signal, (void)si;
  95295. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95296. }
  95297. # endif
  95298. # elif defined(_MSC_VER)
  95299. # include <windows.h>
  95300. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95301. # ifdef USE_TRY_CATCH_FLAVOR
  95302. # else
  95303. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95304. {
  95305. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95306. ep->ContextRecord->Eip += 3 + 3 + 6;
  95307. return EXCEPTION_CONTINUE_EXECUTION;
  95308. }
  95309. return EXCEPTION_CONTINUE_SEARCH;
  95310. }
  95311. # endif
  95312. # endif
  95313. #endif
  95314. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95315. {
  95316. /*
  95317. * IA32-specific
  95318. */
  95319. #ifdef FLAC__CPU_IA32
  95320. info->type = FLAC__CPUINFO_TYPE_IA32;
  95321. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95322. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95323. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95324. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95325. info->data.ia32.cmov = false;
  95326. info->data.ia32.mmx = false;
  95327. info->data.ia32.fxsr = false;
  95328. info->data.ia32.sse = false;
  95329. info->data.ia32.sse2 = false;
  95330. info->data.ia32.sse3 = false;
  95331. info->data.ia32.ssse3 = false;
  95332. info->data.ia32._3dnow = false;
  95333. info->data.ia32.ext3dnow = false;
  95334. info->data.ia32.extmmx = false;
  95335. if(info->data.ia32.cpuid) {
  95336. /* http://www.sandpile.org/ia32/cpuid.htm */
  95337. FLAC__uint32 flags_edx, flags_ecx;
  95338. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95339. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95340. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95341. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95342. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95343. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95344. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95345. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95346. #ifdef FLAC__USE_3DNOW
  95347. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95348. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95349. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95350. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95351. #else
  95352. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95353. #endif
  95354. #ifdef DEBUG
  95355. fprintf(stderr, "CPU info (IA-32):\n");
  95356. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95357. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95358. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95359. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95360. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95361. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95362. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95363. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95364. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95365. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95366. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95367. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95368. #endif
  95369. /*
  95370. * now have to check for OS support of SSE/SSE2
  95371. */
  95372. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95373. #if defined FLAC__NO_SSE_OS
  95374. /* assume user knows better than us; turn it off */
  95375. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95376. #elif defined FLAC__SSE_OS
  95377. /* assume user knows better than us; leave as detected above */
  95378. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95379. int sse = 0;
  95380. size_t len;
  95381. /* at least one of these must work: */
  95382. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95383. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95384. if(!sse)
  95385. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95386. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95387. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95388. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95389. size_t len = sizeof(val);
  95390. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95391. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95392. else { /* double-check SSE2 */
  95393. mib[1] = CPU_SSE2;
  95394. len = sizeof(val);
  95395. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95396. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95397. }
  95398. # else
  95399. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95400. # endif
  95401. #elif defined(__linux__)
  95402. int sse = 0;
  95403. struct sigaction sigill_save;
  95404. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95405. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95406. #else
  95407. struct sigaction sigill_sse;
  95408. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95409. __sigemptyset(&sigill_sse.sa_mask);
  95410. 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 */
  95411. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95412. #endif
  95413. {
  95414. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95415. /* see sigill_handler_sse_os() for an explanation of the following: */
  95416. asm volatile (
  95417. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95418. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95419. "incl %0\n\t" /* SIGILL handler will jump over this */
  95420. /* landing zone */
  95421. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95422. "nop\n\t"
  95423. "nop\n\t"
  95424. "nop\n\t"
  95425. "nop\n\t"
  95426. "nop\n\t"
  95427. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95428. "nop\n\t"
  95429. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95430. : "=r"(sse)
  95431. : "r"(sse)
  95432. );
  95433. sigaction(SIGILL, &sigill_save, NULL);
  95434. }
  95435. if(!sse)
  95436. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95437. #elif defined(_MSC_VER)
  95438. # ifdef USE_TRY_CATCH_FLAVOR
  95439. _try {
  95440. __asm {
  95441. # if _MSC_VER <= 1200
  95442. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95443. _emit 0x0F
  95444. _emit 0x57
  95445. _emit 0xC0
  95446. # else
  95447. xorps xmm0,xmm0
  95448. # endif
  95449. }
  95450. }
  95451. _except(EXCEPTION_EXECUTE_HANDLER) {
  95452. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95453. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95454. }
  95455. # else
  95456. int sse = 0;
  95457. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95458. /* see GCC version above for explanation */
  95459. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95460. /* http://www.codeproject.com/cpp/gccasm.asp */
  95461. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95462. __asm {
  95463. # if _MSC_VER <= 1200
  95464. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95465. _emit 0x0F
  95466. _emit 0x57
  95467. _emit 0xC0
  95468. # else
  95469. xorps xmm0,xmm0
  95470. # endif
  95471. inc sse
  95472. nop
  95473. nop
  95474. nop
  95475. nop
  95476. nop
  95477. nop
  95478. nop
  95479. nop
  95480. nop
  95481. }
  95482. SetUnhandledExceptionFilter(save);
  95483. if(!sse)
  95484. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95485. # endif
  95486. #else
  95487. /* no way to test, disable to be safe */
  95488. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95489. #endif
  95490. #ifdef DEBUG
  95491. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95492. #endif
  95493. }
  95494. }
  95495. #else
  95496. info->use_asm = false;
  95497. #endif
  95498. /*
  95499. * PPC-specific
  95500. */
  95501. #elif defined FLAC__CPU_PPC
  95502. info->type = FLAC__CPUINFO_TYPE_PPC;
  95503. # if !defined FLAC__NO_ASM
  95504. info->use_asm = true;
  95505. # ifdef FLAC__USE_ALTIVEC
  95506. # if defined FLAC__SYS_DARWIN
  95507. {
  95508. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95509. size_t len = sizeof(val);
  95510. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95511. }
  95512. {
  95513. host_basic_info_data_t hostInfo;
  95514. mach_msg_type_number_t infoCount;
  95515. infoCount = HOST_BASIC_INFO_COUNT;
  95516. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95517. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95518. }
  95519. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95520. {
  95521. /* no Darwin, do it the brute-force way */
  95522. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95523. info->data.ppc.altivec = 0;
  95524. info->data.ppc.ppc64 = 0;
  95525. signal (SIGILL, sigill_handler);
  95526. canjump = 0;
  95527. if (!sigsetjmp (jmpbuf, 1)) {
  95528. canjump = 1;
  95529. asm volatile (
  95530. "mtspr 256, %0\n\t"
  95531. "vand %%v0, %%v0, %%v0"
  95532. :
  95533. : "r" (-1)
  95534. );
  95535. info->data.ppc.altivec = 1;
  95536. }
  95537. canjump = 0;
  95538. if (!sigsetjmp (jmpbuf, 1)) {
  95539. int x = 0;
  95540. canjump = 1;
  95541. /* PPC64 hardware implements the cntlzd instruction */
  95542. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95543. info->data.ppc.ppc64 = 1;
  95544. }
  95545. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95546. }
  95547. # endif
  95548. # else /* !FLAC__USE_ALTIVEC */
  95549. info->data.ppc.altivec = 0;
  95550. info->data.ppc.ppc64 = 0;
  95551. # endif
  95552. # else
  95553. info->use_asm = false;
  95554. # endif
  95555. /*
  95556. * unknown CPI
  95557. */
  95558. #else
  95559. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95560. info->use_asm = false;
  95561. #endif
  95562. }
  95563. #endif
  95564. /*** End of inlined file: cpu.c ***/
  95565. /*** Start of inlined file: crc.c ***/
  95566. /*** Start of inlined file: juce_FlacHeader.h ***/
  95567. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95568. // tasks..
  95569. #define VERSION "1.2.1"
  95570. #define FLAC__NO_DLL 1
  95571. #if JUCE_MSVC
  95572. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95573. #endif
  95574. #if JUCE_MAC
  95575. #define FLAC__SYS_DARWIN 1
  95576. #endif
  95577. /*** End of inlined file: juce_FlacHeader.h ***/
  95578. #if JUCE_USE_FLAC
  95579. #if HAVE_CONFIG_H
  95580. # include <config.h>
  95581. #endif
  95582. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95583. FLAC__byte const FLAC__crc8_table[256] = {
  95584. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95585. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95586. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95587. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95588. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95589. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95590. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95591. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95592. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95593. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95594. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95595. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95596. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95597. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95598. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95599. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95600. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95601. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95602. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95603. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95604. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95605. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95606. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95607. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95608. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95609. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95610. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95611. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95612. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95613. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95614. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95615. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95616. };
  95617. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95618. unsigned FLAC__crc16_table[256] = {
  95619. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95620. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95621. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95622. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95623. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95624. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95625. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95626. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95627. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95628. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95629. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95630. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95631. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95632. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95633. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95634. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95635. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95636. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95637. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95638. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95639. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95640. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95641. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95642. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95643. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95644. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95645. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95646. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95647. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95648. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95649. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95650. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95651. };
  95652. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95653. {
  95654. *crc = FLAC__crc8_table[*crc ^ data];
  95655. }
  95656. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95657. {
  95658. while(len--)
  95659. *crc = FLAC__crc8_table[*crc ^ *data++];
  95660. }
  95661. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95662. {
  95663. FLAC__uint8 crc = 0;
  95664. while(len--)
  95665. crc = FLAC__crc8_table[crc ^ *data++];
  95666. return crc;
  95667. }
  95668. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95669. {
  95670. unsigned crc = 0;
  95671. while(len--)
  95672. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95673. return crc;
  95674. }
  95675. #endif
  95676. /*** End of inlined file: crc.c ***/
  95677. /*** Start of inlined file: fixed.c ***/
  95678. /*** Start of inlined file: juce_FlacHeader.h ***/
  95679. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95680. // tasks..
  95681. #define VERSION "1.2.1"
  95682. #define FLAC__NO_DLL 1
  95683. #if JUCE_MSVC
  95684. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95685. #endif
  95686. #if JUCE_MAC
  95687. #define FLAC__SYS_DARWIN 1
  95688. #endif
  95689. /*** End of inlined file: juce_FlacHeader.h ***/
  95690. #if JUCE_USE_FLAC
  95691. #if HAVE_CONFIG_H
  95692. # include <config.h>
  95693. #endif
  95694. #include <math.h>
  95695. #include <string.h>
  95696. /*** Start of inlined file: fixed.h ***/
  95697. #ifndef FLAC__PRIVATE__FIXED_H
  95698. #define FLAC__PRIVATE__FIXED_H
  95699. #ifdef HAVE_CONFIG_H
  95700. #include <config.h>
  95701. #endif
  95702. /*** Start of inlined file: float.h ***/
  95703. #ifndef FLAC__PRIVATE__FLOAT_H
  95704. #define FLAC__PRIVATE__FLOAT_H
  95705. #ifdef HAVE_CONFIG_H
  95706. #include <config.h>
  95707. #endif
  95708. /*
  95709. * These typedefs make it easier to ensure that integer versions of
  95710. * the library really only contain integer operations. All the code
  95711. * in libFLAC should use FLAC__float and FLAC__double in place of
  95712. * float and double, and be protected by checks of the macro
  95713. * FLAC__INTEGER_ONLY_LIBRARY.
  95714. *
  95715. * FLAC__real is the basic floating point type used in LPC analysis.
  95716. */
  95717. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95718. typedef double FLAC__double;
  95719. typedef float FLAC__float;
  95720. /*
  95721. * WATCHOUT: changing FLAC__real will change the signatures of many
  95722. * functions that have assembly language equivalents and break them.
  95723. */
  95724. typedef float FLAC__real;
  95725. #else
  95726. /*
  95727. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95728. * for the integer part and lower 16 bits for the fractional part.
  95729. */
  95730. typedef FLAC__int32 FLAC__fixedpoint;
  95731. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95732. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95733. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95734. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95735. extern const FLAC__fixedpoint FLAC__FP_E;
  95736. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95737. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95738. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95739. /*
  95740. * FLAC__fixedpoint_log2()
  95741. * --------------------------------------------------------------------
  95742. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95743. * algorithm by Knuth for x >= 1.0
  95744. *
  95745. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95746. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95747. *
  95748. * 'precision' roughly limits the number of iterations that are done;
  95749. * use (unsigned)(-1) for maximum precision.
  95750. *
  95751. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95752. * function will punt and return 0.
  95753. *
  95754. * The return value will also have 'fracbits' fractional bits.
  95755. */
  95756. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95757. #endif
  95758. #endif
  95759. /*** End of inlined file: float.h ***/
  95760. /*** Start of inlined file: format.h ***/
  95761. #ifndef FLAC__PRIVATE__FORMAT_H
  95762. #define FLAC__PRIVATE__FORMAT_H
  95763. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95764. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95765. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95766. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95767. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95768. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95769. #endif
  95770. /*** End of inlined file: format.h ***/
  95771. /*
  95772. * FLAC__fixed_compute_best_predictor()
  95773. * --------------------------------------------------------------------
  95774. * Compute the best fixed predictor and the expected bits-per-sample
  95775. * of the residual signal for each order. The _wide() version uses
  95776. * 64-bit integers which is statistically necessary when bits-per-
  95777. * sample + log2(blocksize) > 30
  95778. *
  95779. * IN data[0,data_len-1]
  95780. * IN data_len
  95781. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95782. */
  95783. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95784. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95785. # ifndef FLAC__NO_ASM
  95786. # ifdef FLAC__CPU_IA32
  95787. # ifdef FLAC__HAS_NASM
  95788. 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]);
  95789. # endif
  95790. # endif
  95791. # endif
  95792. 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]);
  95793. #else
  95794. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95795. 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]);
  95796. #endif
  95797. /*
  95798. * FLAC__fixed_compute_residual()
  95799. * --------------------------------------------------------------------
  95800. * Compute the residual signal obtained from sutracting the predicted
  95801. * signal from the original.
  95802. *
  95803. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95804. * IN data_len length of original signal
  95805. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95806. * OUT residual[0,data_len-1] residual signal
  95807. */
  95808. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95809. /*
  95810. * FLAC__fixed_restore_signal()
  95811. * --------------------------------------------------------------------
  95812. * Restore the original signal by summing the residual and the
  95813. * predictor.
  95814. *
  95815. * IN residual[0,data_len-1] residual signal
  95816. * IN data_len length of original signal
  95817. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95818. * *** IMPORTANT: the caller must pass in the historical samples:
  95819. * IN data[-order,-1] previously-reconstructed historical samples
  95820. * OUT data[0,data_len-1] original signal
  95821. */
  95822. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95823. #endif
  95824. /*** End of inlined file: fixed.h ***/
  95825. #ifndef M_LN2
  95826. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95827. #define M_LN2 0.69314718055994530942
  95828. #endif
  95829. #ifdef min
  95830. #undef min
  95831. #endif
  95832. #define min(x,y) ((x) < (y)? (x) : (y))
  95833. #ifdef local_abs
  95834. #undef local_abs
  95835. #endif
  95836. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95837. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95838. /* rbps stands for residual bits per sample
  95839. *
  95840. * (ln(2) * err)
  95841. * rbps = log (-----------)
  95842. * 2 ( n )
  95843. */
  95844. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95845. {
  95846. FLAC__uint32 rbps;
  95847. unsigned bits; /* the number of bits required to represent a number */
  95848. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95849. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95850. FLAC__ASSERT(err > 0);
  95851. FLAC__ASSERT(n > 0);
  95852. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95853. if(err <= n)
  95854. return 0;
  95855. /*
  95856. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95857. * These allow us later to know we won't lose too much precision in the
  95858. * fixed-point division (err<<fracbits)/n.
  95859. */
  95860. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95861. err <<= fracbits;
  95862. err /= n;
  95863. /* err now holds err/n with fracbits fractional bits */
  95864. /*
  95865. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95866. * our purposes.
  95867. */
  95868. FLAC__ASSERT(err > 0);
  95869. bits = FLAC__bitmath_ilog2(err)+1;
  95870. if(bits > 16) {
  95871. err >>= (bits-16);
  95872. fracbits -= (bits-16);
  95873. }
  95874. rbps = (FLAC__uint32)err;
  95875. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95876. rbps *= FLAC__FP_LN2;
  95877. fracbits += 16;
  95878. FLAC__ASSERT(fracbits >= 0);
  95879. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95880. {
  95881. const int f = fracbits & 3;
  95882. if(f) {
  95883. rbps >>= f;
  95884. fracbits -= f;
  95885. }
  95886. }
  95887. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95888. if(rbps == 0)
  95889. return 0;
  95890. /*
  95891. * The return value must have 16 fractional bits. Since the whole part
  95892. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95893. * must be >= -3, these assertion allows us to be able to shift rbps
  95894. * left if necessary to get 16 fracbits without losing any bits of the
  95895. * whole part of rbps.
  95896. *
  95897. * There is a slight chance due to accumulated error that the whole part
  95898. * will require 6 bits, so we use 6 in the assertion. Really though as
  95899. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95900. */
  95901. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95902. FLAC__ASSERT(fracbits >= -3);
  95903. /* now shift the decimal point into place */
  95904. if(fracbits < 16)
  95905. return rbps << (16-fracbits);
  95906. else if(fracbits > 16)
  95907. return rbps >> (fracbits-16);
  95908. else
  95909. return rbps;
  95910. }
  95911. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95912. {
  95913. FLAC__uint32 rbps;
  95914. unsigned bits; /* the number of bits required to represent a number */
  95915. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95916. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95917. FLAC__ASSERT(err > 0);
  95918. FLAC__ASSERT(n > 0);
  95919. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95920. if(err <= n)
  95921. return 0;
  95922. /*
  95923. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95924. * These allow us later to know we won't lose too much precision in the
  95925. * fixed-point division (err<<fracbits)/n.
  95926. */
  95927. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95928. err <<= fracbits;
  95929. err /= n;
  95930. /* err now holds err/n with fracbits fractional bits */
  95931. /*
  95932. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95933. * our purposes.
  95934. */
  95935. FLAC__ASSERT(err > 0);
  95936. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95937. if(bits > 16) {
  95938. err >>= (bits-16);
  95939. fracbits -= (bits-16);
  95940. }
  95941. rbps = (FLAC__uint32)err;
  95942. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95943. rbps *= FLAC__FP_LN2;
  95944. fracbits += 16;
  95945. FLAC__ASSERT(fracbits >= 0);
  95946. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95947. {
  95948. const int f = fracbits & 3;
  95949. if(f) {
  95950. rbps >>= f;
  95951. fracbits -= f;
  95952. }
  95953. }
  95954. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95955. if(rbps == 0)
  95956. return 0;
  95957. /*
  95958. * The return value must have 16 fractional bits. Since the whole part
  95959. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95960. * must be >= -3, these assertion allows us to be able to shift rbps
  95961. * left if necessary to get 16 fracbits without losing any bits of the
  95962. * whole part of rbps.
  95963. *
  95964. * There is a slight chance due to accumulated error that the whole part
  95965. * will require 6 bits, so we use 6 in the assertion. Really though as
  95966. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95967. */
  95968. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95969. FLAC__ASSERT(fracbits >= -3);
  95970. /* now shift the decimal point into place */
  95971. if(fracbits < 16)
  95972. return rbps << (16-fracbits);
  95973. else if(fracbits > 16)
  95974. return rbps >> (fracbits-16);
  95975. else
  95976. return rbps;
  95977. }
  95978. #endif
  95979. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95980. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95981. #else
  95982. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95983. #endif
  95984. {
  95985. FLAC__int32 last_error_0 = data[-1];
  95986. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95987. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95988. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95989. FLAC__int32 error, save;
  95990. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95991. unsigned i, order;
  95992. for(i = 0; i < data_len; i++) {
  95993. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95994. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95995. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95996. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95997. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95998. }
  95999. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96000. order = 0;
  96001. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96002. order = 1;
  96003. else if(total_error_2 < min(total_error_3, total_error_4))
  96004. order = 2;
  96005. else if(total_error_3 < total_error_4)
  96006. order = 3;
  96007. else
  96008. order = 4;
  96009. /* Estimate the expected number of bits per residual signal sample. */
  96010. /* 'total_error*' is linearly related to the variance of the residual */
  96011. /* signal, so we use it directly to compute E(|x|) */
  96012. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96013. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96014. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96015. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96016. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96017. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96018. 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);
  96019. 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);
  96020. 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);
  96021. 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);
  96022. 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);
  96023. #else
  96024. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96025. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96026. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96027. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96028. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96029. #endif
  96030. return order;
  96031. }
  96032. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96033. 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])
  96034. #else
  96035. 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])
  96036. #endif
  96037. {
  96038. FLAC__int32 last_error_0 = data[-1];
  96039. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96040. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96041. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96042. FLAC__int32 error, save;
  96043. /* total_error_* are 64-bits to avoid overflow when encoding
  96044. * erratic signals when the bits-per-sample and blocksize are
  96045. * large.
  96046. */
  96047. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96048. unsigned i, order;
  96049. for(i = 0; i < data_len; i++) {
  96050. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96051. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96052. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96053. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96054. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96055. }
  96056. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96057. order = 0;
  96058. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96059. order = 1;
  96060. else if(total_error_2 < min(total_error_3, total_error_4))
  96061. order = 2;
  96062. else if(total_error_3 < total_error_4)
  96063. order = 3;
  96064. else
  96065. order = 4;
  96066. /* Estimate the expected number of bits per residual signal sample. */
  96067. /* 'total_error*' is linearly related to the variance of the residual */
  96068. /* signal, so we use it directly to compute E(|x|) */
  96069. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96070. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96071. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96072. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96073. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96074. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96075. #if defined _MSC_VER || defined __MINGW32__
  96076. /* with MSVC you have to spoon feed it the casting */
  96077. 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);
  96078. 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);
  96079. 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);
  96080. 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);
  96081. 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);
  96082. #else
  96083. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  96084. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  96085. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  96086. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  96087. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  96088. #endif
  96089. #else
  96090. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96091. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96092. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96093. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96094. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96095. #endif
  96096. return order;
  96097. }
  96098. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96099. {
  96100. const int idata_len = (int)data_len;
  96101. int i;
  96102. switch(order) {
  96103. case 0:
  96104. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96105. memcpy(residual, data, sizeof(residual[0])*data_len);
  96106. break;
  96107. case 1:
  96108. for(i = 0; i < idata_len; i++)
  96109. residual[i] = data[i] - data[i-1];
  96110. break;
  96111. case 2:
  96112. for(i = 0; i < idata_len; i++)
  96113. #if 1 /* OPT: may be faster with some compilers on some systems */
  96114. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96115. #else
  96116. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96117. #endif
  96118. break;
  96119. case 3:
  96120. for(i = 0; i < idata_len; i++)
  96121. #if 1 /* OPT: may be faster with some compilers on some systems */
  96122. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96123. #else
  96124. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96125. #endif
  96126. break;
  96127. case 4:
  96128. for(i = 0; i < idata_len; i++)
  96129. #if 1 /* OPT: may be faster with some compilers on some systems */
  96130. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96131. #else
  96132. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96133. #endif
  96134. break;
  96135. default:
  96136. FLAC__ASSERT(0);
  96137. }
  96138. }
  96139. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96140. {
  96141. int i, idata_len = (int)data_len;
  96142. switch(order) {
  96143. case 0:
  96144. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96145. memcpy(data, residual, sizeof(residual[0])*data_len);
  96146. break;
  96147. case 1:
  96148. for(i = 0; i < idata_len; i++)
  96149. data[i] = residual[i] + data[i-1];
  96150. break;
  96151. case 2:
  96152. for(i = 0; i < idata_len; i++)
  96153. #if 1 /* OPT: may be faster with some compilers on some systems */
  96154. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96155. #else
  96156. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96157. #endif
  96158. break;
  96159. case 3:
  96160. for(i = 0; i < idata_len; i++)
  96161. #if 1 /* OPT: may be faster with some compilers on some systems */
  96162. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96163. #else
  96164. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96165. #endif
  96166. break;
  96167. case 4:
  96168. for(i = 0; i < idata_len; i++)
  96169. #if 1 /* OPT: may be faster with some compilers on some systems */
  96170. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96171. #else
  96172. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96173. #endif
  96174. break;
  96175. default:
  96176. FLAC__ASSERT(0);
  96177. }
  96178. }
  96179. #endif
  96180. /*** End of inlined file: fixed.c ***/
  96181. /*** Start of inlined file: float.c ***/
  96182. /*** Start of inlined file: juce_FlacHeader.h ***/
  96183. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96184. // tasks..
  96185. #define VERSION "1.2.1"
  96186. #define FLAC__NO_DLL 1
  96187. #if JUCE_MSVC
  96188. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96189. #endif
  96190. #if JUCE_MAC
  96191. #define FLAC__SYS_DARWIN 1
  96192. #endif
  96193. /*** End of inlined file: juce_FlacHeader.h ***/
  96194. #if JUCE_USE_FLAC
  96195. #if HAVE_CONFIG_H
  96196. # include <config.h>
  96197. #endif
  96198. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96199. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96200. #ifdef _MSC_VER
  96201. #define FLAC__U64L(x) x
  96202. #else
  96203. #define FLAC__U64L(x) x##LLU
  96204. #endif
  96205. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96206. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96207. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96208. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96209. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96210. /* Lookup tables for Knuth's logarithm algorithm */
  96211. #define LOG2_LOOKUP_PRECISION 16
  96212. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96213. {
  96214. /*
  96215. * 0 fraction bits
  96216. */
  96217. /* undefined */ 0x00000000,
  96218. /* lg(2/1) = */ 0x00000001,
  96219. /* lg(4/3) = */ 0x00000000,
  96220. /* lg(8/7) = */ 0x00000000,
  96221. /* lg(16/15) = */ 0x00000000,
  96222. /* lg(32/31) = */ 0x00000000,
  96223. /* lg(64/63) = */ 0x00000000,
  96224. /* lg(128/127) = */ 0x00000000,
  96225. /* lg(256/255) = */ 0x00000000,
  96226. /* lg(512/511) = */ 0x00000000,
  96227. /* lg(1024/1023) = */ 0x00000000,
  96228. /* lg(2048/2047) = */ 0x00000000,
  96229. /* lg(4096/4095) = */ 0x00000000,
  96230. /* lg(8192/8191) = */ 0x00000000,
  96231. /* lg(16384/16383) = */ 0x00000000,
  96232. /* lg(32768/32767) = */ 0x00000000
  96233. },
  96234. {
  96235. /*
  96236. * 4 fraction bits
  96237. */
  96238. /* undefined */ 0x00000000,
  96239. /* lg(2/1) = */ 0x00000010,
  96240. /* lg(4/3) = */ 0x00000007,
  96241. /* lg(8/7) = */ 0x00000003,
  96242. /* lg(16/15) = */ 0x00000001,
  96243. /* lg(32/31) = */ 0x00000001,
  96244. /* lg(64/63) = */ 0x00000000,
  96245. /* lg(128/127) = */ 0x00000000,
  96246. /* lg(256/255) = */ 0x00000000,
  96247. /* lg(512/511) = */ 0x00000000,
  96248. /* lg(1024/1023) = */ 0x00000000,
  96249. /* lg(2048/2047) = */ 0x00000000,
  96250. /* lg(4096/4095) = */ 0x00000000,
  96251. /* lg(8192/8191) = */ 0x00000000,
  96252. /* lg(16384/16383) = */ 0x00000000,
  96253. /* lg(32768/32767) = */ 0x00000000
  96254. },
  96255. {
  96256. /*
  96257. * 8 fraction bits
  96258. */
  96259. /* undefined */ 0x00000000,
  96260. /* lg(2/1) = */ 0x00000100,
  96261. /* lg(4/3) = */ 0x0000006a,
  96262. /* lg(8/7) = */ 0x00000031,
  96263. /* lg(16/15) = */ 0x00000018,
  96264. /* lg(32/31) = */ 0x0000000c,
  96265. /* lg(64/63) = */ 0x00000006,
  96266. /* lg(128/127) = */ 0x00000003,
  96267. /* lg(256/255) = */ 0x00000001,
  96268. /* lg(512/511) = */ 0x00000001,
  96269. /* lg(1024/1023) = */ 0x00000000,
  96270. /* lg(2048/2047) = */ 0x00000000,
  96271. /* lg(4096/4095) = */ 0x00000000,
  96272. /* lg(8192/8191) = */ 0x00000000,
  96273. /* lg(16384/16383) = */ 0x00000000,
  96274. /* lg(32768/32767) = */ 0x00000000
  96275. },
  96276. {
  96277. /*
  96278. * 12 fraction bits
  96279. */
  96280. /* undefined */ 0x00000000,
  96281. /* lg(2/1) = */ 0x00001000,
  96282. /* lg(4/3) = */ 0x000006a4,
  96283. /* lg(8/7) = */ 0x00000315,
  96284. /* lg(16/15) = */ 0x0000017d,
  96285. /* lg(32/31) = */ 0x000000bc,
  96286. /* lg(64/63) = */ 0x0000005d,
  96287. /* lg(128/127) = */ 0x0000002e,
  96288. /* lg(256/255) = */ 0x00000017,
  96289. /* lg(512/511) = */ 0x0000000c,
  96290. /* lg(1024/1023) = */ 0x00000006,
  96291. /* lg(2048/2047) = */ 0x00000003,
  96292. /* lg(4096/4095) = */ 0x00000001,
  96293. /* lg(8192/8191) = */ 0x00000001,
  96294. /* lg(16384/16383) = */ 0x00000000,
  96295. /* lg(32768/32767) = */ 0x00000000
  96296. },
  96297. {
  96298. /*
  96299. * 16 fraction bits
  96300. */
  96301. /* undefined */ 0x00000000,
  96302. /* lg(2/1) = */ 0x00010000,
  96303. /* lg(4/3) = */ 0x00006a40,
  96304. /* lg(8/7) = */ 0x00003151,
  96305. /* lg(16/15) = */ 0x000017d6,
  96306. /* lg(32/31) = */ 0x00000bba,
  96307. /* lg(64/63) = */ 0x000005d1,
  96308. /* lg(128/127) = */ 0x000002e6,
  96309. /* lg(256/255) = */ 0x00000172,
  96310. /* lg(512/511) = */ 0x000000b9,
  96311. /* lg(1024/1023) = */ 0x0000005c,
  96312. /* lg(2048/2047) = */ 0x0000002e,
  96313. /* lg(4096/4095) = */ 0x00000017,
  96314. /* lg(8192/8191) = */ 0x0000000c,
  96315. /* lg(16384/16383) = */ 0x00000006,
  96316. /* lg(32768/32767) = */ 0x00000003
  96317. },
  96318. {
  96319. /*
  96320. * 20 fraction bits
  96321. */
  96322. /* undefined */ 0x00000000,
  96323. /* lg(2/1) = */ 0x00100000,
  96324. /* lg(4/3) = */ 0x0006a3fe,
  96325. /* lg(8/7) = */ 0x00031513,
  96326. /* lg(16/15) = */ 0x00017d60,
  96327. /* lg(32/31) = */ 0x0000bb9d,
  96328. /* lg(64/63) = */ 0x00005d10,
  96329. /* lg(128/127) = */ 0x00002e59,
  96330. /* lg(256/255) = */ 0x00001721,
  96331. /* lg(512/511) = */ 0x00000b8e,
  96332. /* lg(1024/1023) = */ 0x000005c6,
  96333. /* lg(2048/2047) = */ 0x000002e3,
  96334. /* lg(4096/4095) = */ 0x00000171,
  96335. /* lg(8192/8191) = */ 0x000000b9,
  96336. /* lg(16384/16383) = */ 0x0000005c,
  96337. /* lg(32768/32767) = */ 0x0000002e
  96338. },
  96339. {
  96340. /*
  96341. * 24 fraction bits
  96342. */
  96343. /* undefined */ 0x00000000,
  96344. /* lg(2/1) = */ 0x01000000,
  96345. /* lg(4/3) = */ 0x006a3fe6,
  96346. /* lg(8/7) = */ 0x00315130,
  96347. /* lg(16/15) = */ 0x0017d605,
  96348. /* lg(32/31) = */ 0x000bb9ca,
  96349. /* lg(64/63) = */ 0x0005d0fc,
  96350. /* lg(128/127) = */ 0x0002e58f,
  96351. /* lg(256/255) = */ 0x0001720e,
  96352. /* lg(512/511) = */ 0x0000b8d8,
  96353. /* lg(1024/1023) = */ 0x00005c61,
  96354. /* lg(2048/2047) = */ 0x00002e2d,
  96355. /* lg(4096/4095) = */ 0x00001716,
  96356. /* lg(8192/8191) = */ 0x00000b8b,
  96357. /* lg(16384/16383) = */ 0x000005c5,
  96358. /* lg(32768/32767) = */ 0x000002e3
  96359. },
  96360. {
  96361. /*
  96362. * 28 fraction bits
  96363. */
  96364. /* undefined */ 0x00000000,
  96365. /* lg(2/1) = */ 0x10000000,
  96366. /* lg(4/3) = */ 0x06a3fe5c,
  96367. /* lg(8/7) = */ 0x03151301,
  96368. /* lg(16/15) = */ 0x017d6049,
  96369. /* lg(32/31) = */ 0x00bb9ca6,
  96370. /* lg(64/63) = */ 0x005d0fba,
  96371. /* lg(128/127) = */ 0x002e58f7,
  96372. /* lg(256/255) = */ 0x001720da,
  96373. /* lg(512/511) = */ 0x000b8d87,
  96374. /* lg(1024/1023) = */ 0x0005c60b,
  96375. /* lg(2048/2047) = */ 0x0002e2d7,
  96376. /* lg(4096/4095) = */ 0x00017160,
  96377. /* lg(8192/8191) = */ 0x0000b8ad,
  96378. /* lg(16384/16383) = */ 0x00005c56,
  96379. /* lg(32768/32767) = */ 0x00002e2b
  96380. }
  96381. };
  96382. #if 0
  96383. static const FLAC__uint64 log2_lookup_wide[] = {
  96384. {
  96385. /*
  96386. * 32 fraction bits
  96387. */
  96388. /* undefined */ 0x00000000,
  96389. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96390. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96391. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96392. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96393. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96394. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96395. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96396. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96397. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96398. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96399. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96400. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96401. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96402. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96403. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96404. },
  96405. {
  96406. /*
  96407. * 48 fraction bits
  96408. */
  96409. /* undefined */ 0x00000000,
  96410. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96411. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96412. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96413. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96414. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96415. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96416. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96417. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96418. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96419. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96420. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96421. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96422. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96423. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96424. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96425. }
  96426. };
  96427. #endif
  96428. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96429. {
  96430. const FLAC__uint32 ONE = (1u << fracbits);
  96431. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96432. FLAC__ASSERT(fracbits < 32);
  96433. FLAC__ASSERT((fracbits & 0x3) == 0);
  96434. if(x < ONE)
  96435. return 0;
  96436. if(precision > LOG2_LOOKUP_PRECISION)
  96437. precision = LOG2_LOOKUP_PRECISION;
  96438. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96439. {
  96440. FLAC__uint32 y = 0;
  96441. FLAC__uint32 z = x >> 1, k = 1;
  96442. while (x > ONE && k < precision) {
  96443. if (x - z >= ONE) {
  96444. x -= z;
  96445. z = x >> k;
  96446. y += table[k];
  96447. }
  96448. else {
  96449. z >>= 1;
  96450. k++;
  96451. }
  96452. }
  96453. return y;
  96454. }
  96455. }
  96456. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96457. #endif
  96458. /*** End of inlined file: float.c ***/
  96459. /*** Start of inlined file: format.c ***/
  96460. /*** Start of inlined file: juce_FlacHeader.h ***/
  96461. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96462. // tasks..
  96463. #define VERSION "1.2.1"
  96464. #define FLAC__NO_DLL 1
  96465. #if JUCE_MSVC
  96466. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96467. #endif
  96468. #if JUCE_MAC
  96469. #define FLAC__SYS_DARWIN 1
  96470. #endif
  96471. /*** End of inlined file: juce_FlacHeader.h ***/
  96472. #if JUCE_USE_FLAC
  96473. #if HAVE_CONFIG_H
  96474. # include <config.h>
  96475. #endif
  96476. #include <stdio.h>
  96477. #include <stdlib.h> /* for qsort() */
  96478. #include <string.h> /* for memset() */
  96479. #ifndef FLaC__INLINE
  96480. #define FLaC__INLINE
  96481. #endif
  96482. #ifdef min
  96483. #undef min
  96484. #endif
  96485. #define min(a,b) ((a)<(b)?(a):(b))
  96486. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96487. #ifdef _MSC_VER
  96488. #define FLAC__U64L(x) x
  96489. #else
  96490. #define FLAC__U64L(x) x##LLU
  96491. #endif
  96492. /* VERSION should come from configure */
  96493. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96494. ;
  96495. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96496. /* yet one more hack because of MSVC6: */
  96497. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96498. #else
  96499. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96500. #endif
  96501. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96502. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96503. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96504. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96505. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96506. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96507. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96508. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96509. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96510. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96511. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96512. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96513. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96514. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96515. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96516. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96517. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96518. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96519. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96520. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96521. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96522. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96523. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96524. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96525. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96526. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96527. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96528. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96529. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96530. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96531. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96532. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96533. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96534. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96535. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96536. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96537. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96538. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96539. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96540. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96541. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96542. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96543. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96544. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96545. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96546. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96547. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96548. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96549. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96550. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96551. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96552. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96553. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96554. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96555. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96556. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96557. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96558. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96559. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96560. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96561. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96562. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96563. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96564. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96565. "PARTITIONED_RICE",
  96566. "PARTITIONED_RICE2"
  96567. };
  96568. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96569. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96570. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96571. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96572. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96573. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96574. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96575. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96576. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96577. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96578. "CONSTANT",
  96579. "VERBATIM",
  96580. "FIXED",
  96581. "LPC"
  96582. };
  96583. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96584. "INDEPENDENT",
  96585. "LEFT_SIDE",
  96586. "RIGHT_SIDE",
  96587. "MID_SIDE"
  96588. };
  96589. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96590. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96591. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96592. };
  96593. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96594. "STREAMINFO",
  96595. "PADDING",
  96596. "APPLICATION",
  96597. "SEEKTABLE",
  96598. "VORBIS_COMMENT",
  96599. "CUESHEET",
  96600. "PICTURE"
  96601. };
  96602. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96603. "Other",
  96604. "32x32 pixels 'file icon' (PNG only)",
  96605. "Other file icon",
  96606. "Cover (front)",
  96607. "Cover (back)",
  96608. "Leaflet page",
  96609. "Media (e.g. label side of CD)",
  96610. "Lead artist/lead performer/soloist",
  96611. "Artist/performer",
  96612. "Conductor",
  96613. "Band/Orchestra",
  96614. "Composer",
  96615. "Lyricist/text writer",
  96616. "Recording Location",
  96617. "During recording",
  96618. "During performance",
  96619. "Movie/video screen capture",
  96620. "A bright coloured fish",
  96621. "Illustration",
  96622. "Band/artist logotype",
  96623. "Publisher/Studio logotype"
  96624. };
  96625. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96626. {
  96627. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96628. return false;
  96629. }
  96630. else
  96631. return true;
  96632. }
  96633. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96634. {
  96635. if(
  96636. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96637. (
  96638. sample_rate >= (1u << 16) &&
  96639. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96640. )
  96641. ) {
  96642. return false;
  96643. }
  96644. else
  96645. return true;
  96646. }
  96647. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96648. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96649. {
  96650. unsigned i;
  96651. FLAC__uint64 prev_sample_number = 0;
  96652. FLAC__bool got_prev = false;
  96653. FLAC__ASSERT(0 != seek_table);
  96654. for(i = 0; i < seek_table->num_points; i++) {
  96655. if(got_prev) {
  96656. if(
  96657. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96658. seek_table->points[i].sample_number <= prev_sample_number
  96659. )
  96660. return false;
  96661. }
  96662. prev_sample_number = seek_table->points[i].sample_number;
  96663. got_prev = true;
  96664. }
  96665. return true;
  96666. }
  96667. /* used as the sort predicate for qsort() */
  96668. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96669. {
  96670. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96671. if(l->sample_number == r->sample_number)
  96672. return 0;
  96673. else if(l->sample_number < r->sample_number)
  96674. return -1;
  96675. else
  96676. return 1;
  96677. }
  96678. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96679. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96680. {
  96681. unsigned i, j;
  96682. FLAC__bool first;
  96683. FLAC__ASSERT(0 != seek_table);
  96684. /* sort the seekpoints */
  96685. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96686. /* uniquify the seekpoints */
  96687. first = true;
  96688. for(i = j = 0; i < seek_table->num_points; i++) {
  96689. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96690. if(!first) {
  96691. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96692. continue;
  96693. }
  96694. }
  96695. first = false;
  96696. seek_table->points[j++] = seek_table->points[i];
  96697. }
  96698. for(i = j; i < seek_table->num_points; i++) {
  96699. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96700. seek_table->points[i].stream_offset = 0;
  96701. seek_table->points[i].frame_samples = 0;
  96702. }
  96703. return j;
  96704. }
  96705. /*
  96706. * also disallows non-shortest-form encodings, c.f.
  96707. * http://www.unicode.org/versions/corrigendum1.html
  96708. * and a more clear explanation at the end of this section:
  96709. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96710. */
  96711. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96712. {
  96713. FLAC__ASSERT(0 != utf8);
  96714. if ((utf8[0] & 0x80) == 0) {
  96715. return 1;
  96716. }
  96717. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96718. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96719. return 0;
  96720. return 2;
  96721. }
  96722. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96723. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96724. return 0;
  96725. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96726. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96727. return 0;
  96728. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96729. return 0;
  96730. return 3;
  96731. }
  96732. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96733. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96734. return 0;
  96735. return 4;
  96736. }
  96737. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96738. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96739. return 0;
  96740. return 5;
  96741. }
  96742. 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) {
  96743. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96744. return 0;
  96745. return 6;
  96746. }
  96747. else {
  96748. return 0;
  96749. }
  96750. }
  96751. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96752. {
  96753. char c;
  96754. for(c = *name; c; c = *(++name))
  96755. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96756. return false;
  96757. return true;
  96758. }
  96759. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96760. {
  96761. if(length == (unsigned)(-1)) {
  96762. while(*value) {
  96763. unsigned n = utf8len_(value);
  96764. if(n == 0)
  96765. return false;
  96766. value += n;
  96767. }
  96768. }
  96769. else {
  96770. const FLAC__byte *end = value + length;
  96771. while(value < end) {
  96772. unsigned n = utf8len_(value);
  96773. if(n == 0)
  96774. return false;
  96775. value += n;
  96776. }
  96777. if(value != end)
  96778. return false;
  96779. }
  96780. return true;
  96781. }
  96782. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96783. {
  96784. const FLAC__byte *s, *end;
  96785. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96786. if(*s < 0x20 || *s > 0x7D)
  96787. return false;
  96788. }
  96789. if(s == end)
  96790. return false;
  96791. s++; /* skip '=' */
  96792. while(s < end) {
  96793. unsigned n = utf8len_(s);
  96794. if(n == 0)
  96795. return false;
  96796. s += n;
  96797. }
  96798. if(s != end)
  96799. return false;
  96800. return true;
  96801. }
  96802. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96803. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96804. {
  96805. unsigned i, j;
  96806. if(check_cd_da_subset) {
  96807. if(cue_sheet->lead_in < 2 * 44100) {
  96808. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96809. return false;
  96810. }
  96811. if(cue_sheet->lead_in % 588 != 0) {
  96812. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96813. return false;
  96814. }
  96815. }
  96816. if(cue_sheet->num_tracks == 0) {
  96817. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96818. return false;
  96819. }
  96820. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96821. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96822. return false;
  96823. }
  96824. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96825. if(cue_sheet->tracks[i].number == 0) {
  96826. if(violation) *violation = "cue sheet may not have a track number 0";
  96827. return false;
  96828. }
  96829. if(check_cd_da_subset) {
  96830. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96831. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96832. return false;
  96833. }
  96834. }
  96835. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96836. if(violation) {
  96837. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96838. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96839. else
  96840. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96841. }
  96842. return false;
  96843. }
  96844. if(i < cue_sheet->num_tracks - 1) {
  96845. if(cue_sheet->tracks[i].num_indices == 0) {
  96846. if(violation) *violation = "cue sheet track must have at least one index point";
  96847. return false;
  96848. }
  96849. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96850. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96851. return false;
  96852. }
  96853. }
  96854. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96855. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96856. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96857. return false;
  96858. }
  96859. if(j > 0) {
  96860. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96861. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96862. return false;
  96863. }
  96864. }
  96865. }
  96866. }
  96867. return true;
  96868. }
  96869. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96870. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96871. {
  96872. char *p;
  96873. FLAC__byte *b;
  96874. for(p = picture->mime_type; *p; p++) {
  96875. if(*p < 0x20 || *p > 0x7e) {
  96876. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96877. return false;
  96878. }
  96879. }
  96880. for(b = picture->description; *b; ) {
  96881. unsigned n = utf8len_(b);
  96882. if(n == 0) {
  96883. if(violation) *violation = "description string must be valid UTF-8";
  96884. return false;
  96885. }
  96886. b += n;
  96887. }
  96888. return true;
  96889. }
  96890. /*
  96891. * These routines are private to libFLAC
  96892. */
  96893. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96894. {
  96895. return
  96896. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96897. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96898. blocksize,
  96899. predictor_order
  96900. );
  96901. }
  96902. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96903. {
  96904. unsigned max_rice_partition_order = 0;
  96905. while(!(blocksize & 1)) {
  96906. max_rice_partition_order++;
  96907. blocksize >>= 1;
  96908. }
  96909. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96910. }
  96911. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96912. {
  96913. unsigned max_rice_partition_order = limit;
  96914. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96915. max_rice_partition_order--;
  96916. FLAC__ASSERT(
  96917. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96918. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96919. );
  96920. return max_rice_partition_order;
  96921. }
  96922. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96923. {
  96924. FLAC__ASSERT(0 != object);
  96925. object->parameters = 0;
  96926. object->raw_bits = 0;
  96927. object->capacity_by_order = 0;
  96928. }
  96929. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96930. {
  96931. FLAC__ASSERT(0 != object);
  96932. if(0 != object->parameters)
  96933. free(object->parameters);
  96934. if(0 != object->raw_bits)
  96935. free(object->raw_bits);
  96936. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96937. }
  96938. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96939. {
  96940. FLAC__ASSERT(0 != object);
  96941. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96942. if(object->capacity_by_order < max_partition_order) {
  96943. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96944. return false;
  96945. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96946. return false;
  96947. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96948. object->capacity_by_order = max_partition_order;
  96949. }
  96950. return true;
  96951. }
  96952. #endif
  96953. /*** End of inlined file: format.c ***/
  96954. /*** Start of inlined file: lpc_flac.c ***/
  96955. /*** Start of inlined file: juce_FlacHeader.h ***/
  96956. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96957. // tasks..
  96958. #define VERSION "1.2.1"
  96959. #define FLAC__NO_DLL 1
  96960. #if JUCE_MSVC
  96961. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96962. #endif
  96963. #if JUCE_MAC
  96964. #define FLAC__SYS_DARWIN 1
  96965. #endif
  96966. /*** End of inlined file: juce_FlacHeader.h ***/
  96967. #if JUCE_USE_FLAC
  96968. #if HAVE_CONFIG_H
  96969. # include <config.h>
  96970. #endif
  96971. #include <math.h>
  96972. /*** Start of inlined file: lpc.h ***/
  96973. #ifndef FLAC__PRIVATE__LPC_H
  96974. #define FLAC__PRIVATE__LPC_H
  96975. #ifdef HAVE_CONFIG_H
  96976. #include <config.h>
  96977. #endif
  96978. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96979. /*
  96980. * FLAC__lpc_window_data()
  96981. * --------------------------------------------------------------------
  96982. * Applies the given window to the data.
  96983. * OPT: asm implementation
  96984. *
  96985. * IN in[0,data_len-1]
  96986. * IN window[0,data_len-1]
  96987. * OUT out[0,lag-1]
  96988. * IN data_len
  96989. */
  96990. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96991. /*
  96992. * FLAC__lpc_compute_autocorrelation()
  96993. * --------------------------------------------------------------------
  96994. * Compute the autocorrelation for lags between 0 and lag-1.
  96995. * Assumes data[] outside of [0,data_len-1] == 0.
  96996. * Asserts that lag > 0.
  96997. *
  96998. * IN data[0,data_len-1]
  96999. * IN data_len
  97000. * IN 0 < lag <= data_len
  97001. * OUT autoc[0,lag-1]
  97002. */
  97003. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97004. #ifndef FLAC__NO_ASM
  97005. # ifdef FLAC__CPU_IA32
  97006. # ifdef FLAC__HAS_NASM
  97007. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97008. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97009. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97010. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97011. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97012. # endif
  97013. # endif
  97014. #endif
  97015. /*
  97016. * FLAC__lpc_compute_lp_coefficients()
  97017. * --------------------------------------------------------------------
  97018. * Computes LP coefficients for orders 1..max_order.
  97019. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97020. * and there is no point in calculating a predictor.
  97021. *
  97022. * IN autoc[0,max_order] autocorrelation values
  97023. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97024. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97025. * *** IMPORTANT:
  97026. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97027. * OUT error[0,max_order-1] error for each order (more
  97028. * specifically, the variance of
  97029. * the error signal times # of
  97030. * samples in the signal)
  97031. *
  97032. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97033. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97034. * in lp_coeff[7][0,7], etc.
  97035. */
  97036. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97037. /*
  97038. * FLAC__lpc_quantize_coefficients()
  97039. * --------------------------------------------------------------------
  97040. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97041. * must be less than 32 (sizeof(FLAC__int32)*8).
  97042. *
  97043. * IN lp_coeff[0,order-1] LP coefficients
  97044. * IN order LP order
  97045. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97046. * desired precision (in bits, including sign
  97047. * bit) of largest coefficient
  97048. * OUT qlp_coeff[0,order-1] quantized coefficients
  97049. * OUT shift # of bits to shift right to get approximated
  97050. * LP coefficients. NOTE: could be negative.
  97051. * RETURN 0 => quantization OK
  97052. * 1 => coefficients require too much shifting for *shift to
  97053. * fit in the LPC subframe header. 'shift' is unset.
  97054. * 2 => coefficients are all zero, which is bad. 'shift' is
  97055. * unset.
  97056. */
  97057. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97058. /*
  97059. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97060. * --------------------------------------------------------------------
  97061. * Compute the residual signal obtained from sutracting the predicted
  97062. * signal from the original.
  97063. *
  97064. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97065. * IN data_len length of original signal
  97066. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97067. * IN order > 0 LP order
  97068. * IN lp_quantization quantization of LP coefficients in bits
  97069. * OUT residual[0,data_len-1] residual signal
  97070. */
  97071. 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[]);
  97072. 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[]);
  97073. #ifndef FLAC__NO_ASM
  97074. # ifdef FLAC__CPU_IA32
  97075. # ifdef FLAC__HAS_NASM
  97076. 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[]);
  97077. 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[]);
  97078. # endif
  97079. # endif
  97080. #endif
  97081. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97082. /*
  97083. * FLAC__lpc_restore_signal()
  97084. * --------------------------------------------------------------------
  97085. * Restore the original signal by summing the residual and the
  97086. * predictor.
  97087. *
  97088. * IN residual[0,data_len-1] residual signal
  97089. * IN data_len length of original signal
  97090. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97091. * IN order > 0 LP order
  97092. * IN lp_quantization quantization of LP coefficients in bits
  97093. * *** IMPORTANT: the caller must pass in the historical samples:
  97094. * IN data[-order,-1] previously-reconstructed historical samples
  97095. * OUT data[0,data_len-1] original signal
  97096. */
  97097. 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[]);
  97098. 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[]);
  97099. #ifndef FLAC__NO_ASM
  97100. # ifdef FLAC__CPU_IA32
  97101. # ifdef FLAC__HAS_NASM
  97102. 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[]);
  97103. 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[]);
  97104. # endif /* FLAC__HAS_NASM */
  97105. # elif defined FLAC__CPU_PPC
  97106. 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[]);
  97107. 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[]);
  97108. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97109. #endif /* FLAC__NO_ASM */
  97110. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97111. /*
  97112. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97113. * --------------------------------------------------------------------
  97114. * Compute the expected number of bits per residual signal sample
  97115. * based on the LP error (which is related to the residual variance).
  97116. *
  97117. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97118. * IN total_samples > 0 # of samples in residual signal
  97119. * RETURN expected bits per sample
  97120. */
  97121. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97122. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97123. /*
  97124. * FLAC__lpc_compute_best_order()
  97125. * --------------------------------------------------------------------
  97126. * Compute the best order from the array of signal errors returned
  97127. * during coefficient computation.
  97128. *
  97129. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97130. * IN max_order > 0 max LP order
  97131. * IN total_samples > 0 # of samples in residual signal
  97132. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97133. * (includes warmup sample size and quantized LP coefficient)
  97134. * RETURN [1,max_order] best order
  97135. */
  97136. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97137. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97138. #endif
  97139. /*** End of inlined file: lpc.h ***/
  97140. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97141. #include <stdio.h>
  97142. #endif
  97143. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97144. #ifndef M_LN2
  97145. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97146. #define M_LN2 0.69314718055994530942
  97147. #endif
  97148. /* OPT: #undef'ing this may improve the speed on some architectures */
  97149. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97150. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97151. {
  97152. unsigned i;
  97153. for(i = 0; i < data_len; i++)
  97154. out[i] = in[i] * window[i];
  97155. }
  97156. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97157. {
  97158. /* a readable, but slower, version */
  97159. #if 0
  97160. FLAC__real d;
  97161. unsigned i;
  97162. FLAC__ASSERT(lag > 0);
  97163. FLAC__ASSERT(lag <= data_len);
  97164. /*
  97165. * Technically we should subtract the mean first like so:
  97166. * for(i = 0; i < data_len; i++)
  97167. * data[i] -= mean;
  97168. * but it appears not to make enough of a difference to matter, and
  97169. * most signals are already closely centered around zero
  97170. */
  97171. while(lag--) {
  97172. for(i = lag, d = 0.0; i < data_len; i++)
  97173. d += data[i] * data[i - lag];
  97174. autoc[lag] = d;
  97175. }
  97176. #endif
  97177. /*
  97178. * this version tends to run faster because of better data locality
  97179. * ('data_len' is usually much larger than 'lag')
  97180. */
  97181. FLAC__real d;
  97182. unsigned sample, coeff;
  97183. const unsigned limit = data_len - lag;
  97184. FLAC__ASSERT(lag > 0);
  97185. FLAC__ASSERT(lag <= data_len);
  97186. for(coeff = 0; coeff < lag; coeff++)
  97187. autoc[coeff] = 0.0;
  97188. for(sample = 0; sample <= limit; sample++) {
  97189. d = data[sample];
  97190. for(coeff = 0; coeff < lag; coeff++)
  97191. autoc[coeff] += d * data[sample+coeff];
  97192. }
  97193. for(; sample < data_len; sample++) {
  97194. d = data[sample];
  97195. for(coeff = 0; coeff < data_len - sample; coeff++)
  97196. autoc[coeff] += d * data[sample+coeff];
  97197. }
  97198. }
  97199. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97200. {
  97201. unsigned i, j;
  97202. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97203. FLAC__ASSERT(0 != max_order);
  97204. FLAC__ASSERT(0 < *max_order);
  97205. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97206. FLAC__ASSERT(autoc[0] != 0.0);
  97207. err = autoc[0];
  97208. for(i = 0; i < *max_order; i++) {
  97209. /* Sum up this iteration's reflection coefficient. */
  97210. r = -autoc[i+1];
  97211. for(j = 0; j < i; j++)
  97212. r -= lpc[j] * autoc[i-j];
  97213. ref[i] = (r/=err);
  97214. /* Update LPC coefficients and total error. */
  97215. lpc[i]=r;
  97216. for(j = 0; j < (i>>1); j++) {
  97217. FLAC__double tmp = lpc[j];
  97218. lpc[j] += r * lpc[i-1-j];
  97219. lpc[i-1-j] += r * tmp;
  97220. }
  97221. if(i & 1)
  97222. lpc[j] += lpc[j] * r;
  97223. err *= (1.0 - r * r);
  97224. /* save this order */
  97225. for(j = 0; j <= i; j++)
  97226. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97227. error[i] = err;
  97228. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97229. if(err == 0.0) {
  97230. *max_order = i+1;
  97231. return;
  97232. }
  97233. }
  97234. }
  97235. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97236. {
  97237. unsigned i;
  97238. FLAC__double cmax;
  97239. FLAC__int32 qmax, qmin;
  97240. FLAC__ASSERT(precision > 0);
  97241. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97242. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97243. precision--;
  97244. qmax = 1 << precision;
  97245. qmin = -qmax;
  97246. qmax--;
  97247. /* calc cmax = max( |lp_coeff[i]| ) */
  97248. cmax = 0.0;
  97249. for(i = 0; i < order; i++) {
  97250. const FLAC__double d = fabs(lp_coeff[i]);
  97251. if(d > cmax)
  97252. cmax = d;
  97253. }
  97254. if(cmax <= 0.0) {
  97255. /* => coefficients are all 0, which means our constant-detect didn't work */
  97256. return 2;
  97257. }
  97258. else {
  97259. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97260. const int min_shiftlimit = -max_shiftlimit - 1;
  97261. int log2cmax;
  97262. (void)frexp(cmax, &log2cmax);
  97263. log2cmax--;
  97264. *shift = (int)precision - log2cmax - 1;
  97265. if(*shift > max_shiftlimit)
  97266. *shift = max_shiftlimit;
  97267. else if(*shift < min_shiftlimit)
  97268. return 1;
  97269. }
  97270. if(*shift >= 0) {
  97271. FLAC__double error = 0.0;
  97272. FLAC__int32 q;
  97273. for(i = 0; i < order; i++) {
  97274. error += lp_coeff[i] * (1 << *shift);
  97275. #if 1 /* unfortunately lround() is C99 */
  97276. if(error >= 0.0)
  97277. q = (FLAC__int32)(error + 0.5);
  97278. else
  97279. q = (FLAC__int32)(error - 0.5);
  97280. #else
  97281. q = lround(error);
  97282. #endif
  97283. #ifdef FLAC__OVERFLOW_DETECT
  97284. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97285. 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]);
  97286. else if(q < qmin)
  97287. 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]);
  97288. #endif
  97289. if(q > qmax)
  97290. q = qmax;
  97291. else if(q < qmin)
  97292. q = qmin;
  97293. error -= q;
  97294. qlp_coeff[i] = q;
  97295. }
  97296. }
  97297. /* negative shift is very rare but due to design flaw, negative shift is
  97298. * a NOP in the decoder, so it must be handled specially by scaling down
  97299. * coeffs
  97300. */
  97301. else {
  97302. const int nshift = -(*shift);
  97303. FLAC__double error = 0.0;
  97304. FLAC__int32 q;
  97305. #ifdef DEBUG
  97306. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97307. #endif
  97308. for(i = 0; i < order; i++) {
  97309. error += lp_coeff[i] / (1 << nshift);
  97310. #if 1 /* unfortunately lround() is C99 */
  97311. if(error >= 0.0)
  97312. q = (FLAC__int32)(error + 0.5);
  97313. else
  97314. q = (FLAC__int32)(error - 0.5);
  97315. #else
  97316. q = lround(error);
  97317. #endif
  97318. #ifdef FLAC__OVERFLOW_DETECT
  97319. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97320. 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]);
  97321. else if(q < qmin)
  97322. 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]);
  97323. #endif
  97324. if(q > qmax)
  97325. q = qmax;
  97326. else if(q < qmin)
  97327. q = qmin;
  97328. error -= q;
  97329. qlp_coeff[i] = q;
  97330. }
  97331. *shift = 0;
  97332. }
  97333. return 0;
  97334. }
  97335. 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[])
  97336. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97337. {
  97338. FLAC__int64 sumo;
  97339. unsigned i, j;
  97340. FLAC__int32 sum;
  97341. const FLAC__int32 *history;
  97342. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97343. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97344. for(i=0;i<order;i++)
  97345. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97346. fprintf(stderr,"\n");
  97347. #endif
  97348. FLAC__ASSERT(order > 0);
  97349. for(i = 0; i < data_len; i++) {
  97350. sumo = 0;
  97351. sum = 0;
  97352. history = data;
  97353. for(j = 0; j < order; j++) {
  97354. sum += qlp_coeff[j] * (*(--history));
  97355. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97356. #if defined _MSC_VER
  97357. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97358. 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);
  97359. #else
  97360. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97361. 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);
  97362. #endif
  97363. }
  97364. *(residual++) = *(data++) - (sum >> lp_quantization);
  97365. }
  97366. /* Here's a slower but clearer version:
  97367. for(i = 0; i < data_len; i++) {
  97368. sum = 0;
  97369. for(j = 0; j < order; j++)
  97370. sum += qlp_coeff[j] * data[i-j-1];
  97371. residual[i] = data[i] - (sum >> lp_quantization);
  97372. }
  97373. */
  97374. }
  97375. #else /* fully unrolled version for normal use */
  97376. {
  97377. int i;
  97378. FLAC__int32 sum;
  97379. FLAC__ASSERT(order > 0);
  97380. FLAC__ASSERT(order <= 32);
  97381. /*
  97382. * We do unique versions up to 12th order since that's the subset limit.
  97383. * Also they are roughly ordered to match frequency of occurrence to
  97384. * minimize branching.
  97385. */
  97386. if(order <= 12) {
  97387. if(order > 8) {
  97388. if(order > 10) {
  97389. if(order == 12) {
  97390. for(i = 0; i < (int)data_len; i++) {
  97391. sum = 0;
  97392. sum += qlp_coeff[11] * data[i-12];
  97393. sum += qlp_coeff[10] * data[i-11];
  97394. sum += qlp_coeff[9] * data[i-10];
  97395. sum += qlp_coeff[8] * data[i-9];
  97396. sum += qlp_coeff[7] * data[i-8];
  97397. sum += qlp_coeff[6] * data[i-7];
  97398. sum += qlp_coeff[5] * data[i-6];
  97399. sum += qlp_coeff[4] * data[i-5];
  97400. sum += qlp_coeff[3] * data[i-4];
  97401. sum += qlp_coeff[2] * data[i-3];
  97402. sum += qlp_coeff[1] * data[i-2];
  97403. sum += qlp_coeff[0] * data[i-1];
  97404. residual[i] = data[i] - (sum >> lp_quantization);
  97405. }
  97406. }
  97407. else { /* order == 11 */
  97408. for(i = 0; i < (int)data_len; i++) {
  97409. sum = 0;
  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. }
  97425. else {
  97426. if(order == 10) {
  97427. for(i = 0; i < (int)data_len; i++) {
  97428. sum = 0;
  97429. sum += qlp_coeff[9] * data[i-10];
  97430. sum += qlp_coeff[8] * data[i-9];
  97431. sum += qlp_coeff[7] * data[i-8];
  97432. sum += qlp_coeff[6] * data[i-7];
  97433. sum += qlp_coeff[5] * data[i-6];
  97434. sum += qlp_coeff[4] * data[i-5];
  97435. sum += qlp_coeff[3] * data[i-4];
  97436. sum += qlp_coeff[2] * data[i-3];
  97437. sum += qlp_coeff[1] * data[i-2];
  97438. sum += qlp_coeff[0] * data[i-1];
  97439. residual[i] = data[i] - (sum >> lp_quantization);
  97440. }
  97441. }
  97442. else { /* order == 9 */
  97443. for(i = 0; i < (int)data_len; i++) {
  97444. sum = 0;
  97445. sum += qlp_coeff[8] * data[i-9];
  97446. sum += qlp_coeff[7] * data[i-8];
  97447. sum += qlp_coeff[6] * data[i-7];
  97448. sum += qlp_coeff[5] * data[i-6];
  97449. sum += qlp_coeff[4] * data[i-5];
  97450. sum += qlp_coeff[3] * data[i-4];
  97451. sum += qlp_coeff[2] * data[i-3];
  97452. sum += qlp_coeff[1] * data[i-2];
  97453. sum += qlp_coeff[0] * data[i-1];
  97454. residual[i] = data[i] - (sum >> lp_quantization);
  97455. }
  97456. }
  97457. }
  97458. }
  97459. else if(order > 4) {
  97460. if(order > 6) {
  97461. if(order == 8) {
  97462. for(i = 0; i < (int)data_len; i++) {
  97463. sum = 0;
  97464. sum += qlp_coeff[7] * data[i-8];
  97465. sum += qlp_coeff[6] * data[i-7];
  97466. sum += qlp_coeff[5] * data[i-6];
  97467. sum += qlp_coeff[4] * data[i-5];
  97468. sum += qlp_coeff[3] * data[i-4];
  97469. sum += qlp_coeff[2] * data[i-3];
  97470. sum += qlp_coeff[1] * data[i-2];
  97471. sum += qlp_coeff[0] * data[i-1];
  97472. residual[i] = data[i] - (sum >> lp_quantization);
  97473. }
  97474. }
  97475. else { /* order == 7 */
  97476. for(i = 0; i < (int)data_len; i++) {
  97477. sum = 0;
  97478. sum += qlp_coeff[6] * data[i-7];
  97479. sum += qlp_coeff[5] * data[i-6];
  97480. sum += qlp_coeff[4] * data[i-5];
  97481. sum += qlp_coeff[3] * data[i-4];
  97482. sum += qlp_coeff[2] * data[i-3];
  97483. sum += qlp_coeff[1] * data[i-2];
  97484. sum += qlp_coeff[0] * data[i-1];
  97485. residual[i] = data[i] - (sum >> lp_quantization);
  97486. }
  97487. }
  97488. }
  97489. else {
  97490. if(order == 6) {
  97491. for(i = 0; i < (int)data_len; i++) {
  97492. sum = 0;
  97493. sum += qlp_coeff[5] * data[i-6];
  97494. sum += qlp_coeff[4] * data[i-5];
  97495. sum += qlp_coeff[3] * data[i-4];
  97496. sum += qlp_coeff[2] * data[i-3];
  97497. sum += qlp_coeff[1] * data[i-2];
  97498. sum += qlp_coeff[0] * data[i-1];
  97499. residual[i] = data[i] - (sum >> lp_quantization);
  97500. }
  97501. }
  97502. else { /* order == 5 */
  97503. for(i = 0; i < (int)data_len; i++) {
  97504. sum = 0;
  97505. sum += qlp_coeff[4] * data[i-5];
  97506. sum += qlp_coeff[3] * data[i-4];
  97507. sum += qlp_coeff[2] * data[i-3];
  97508. sum += qlp_coeff[1] * data[i-2];
  97509. sum += qlp_coeff[0] * data[i-1];
  97510. residual[i] = data[i] - (sum >> lp_quantization);
  97511. }
  97512. }
  97513. }
  97514. }
  97515. else {
  97516. if(order > 2) {
  97517. if(order == 4) {
  97518. for(i = 0; i < (int)data_len; i++) {
  97519. sum = 0;
  97520. sum += qlp_coeff[3] * data[i-4];
  97521. sum += qlp_coeff[2] * data[i-3];
  97522. sum += qlp_coeff[1] * data[i-2];
  97523. sum += qlp_coeff[0] * data[i-1];
  97524. residual[i] = data[i] - (sum >> lp_quantization);
  97525. }
  97526. }
  97527. else { /* order == 3 */
  97528. for(i = 0; i < (int)data_len; i++) {
  97529. sum = 0;
  97530. sum += qlp_coeff[2] * data[i-3];
  97531. sum += qlp_coeff[1] * data[i-2];
  97532. sum += qlp_coeff[0] * data[i-1];
  97533. residual[i] = data[i] - (sum >> lp_quantization);
  97534. }
  97535. }
  97536. }
  97537. else {
  97538. if(order == 2) {
  97539. for(i = 0; i < (int)data_len; i++) {
  97540. sum = 0;
  97541. sum += qlp_coeff[1] * data[i-2];
  97542. sum += qlp_coeff[0] * data[i-1];
  97543. residual[i] = data[i] - (sum >> lp_quantization);
  97544. }
  97545. }
  97546. else { /* order == 1 */
  97547. for(i = 0; i < (int)data_len; i++)
  97548. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97549. }
  97550. }
  97551. }
  97552. }
  97553. else { /* order > 12 */
  97554. for(i = 0; i < (int)data_len; i++) {
  97555. sum = 0;
  97556. switch(order) {
  97557. case 32: sum += qlp_coeff[31] * data[i-32];
  97558. case 31: sum += qlp_coeff[30] * data[i-31];
  97559. case 30: sum += qlp_coeff[29] * data[i-30];
  97560. case 29: sum += qlp_coeff[28] * data[i-29];
  97561. case 28: sum += qlp_coeff[27] * data[i-28];
  97562. case 27: sum += qlp_coeff[26] * data[i-27];
  97563. case 26: sum += qlp_coeff[25] * data[i-26];
  97564. case 25: sum += qlp_coeff[24] * data[i-25];
  97565. case 24: sum += qlp_coeff[23] * data[i-24];
  97566. case 23: sum += qlp_coeff[22] * data[i-23];
  97567. case 22: sum += qlp_coeff[21] * data[i-22];
  97568. case 21: sum += qlp_coeff[20] * data[i-21];
  97569. case 20: sum += qlp_coeff[19] * data[i-20];
  97570. case 19: sum += qlp_coeff[18] * data[i-19];
  97571. case 18: sum += qlp_coeff[17] * data[i-18];
  97572. case 17: sum += qlp_coeff[16] * data[i-17];
  97573. case 16: sum += qlp_coeff[15] * data[i-16];
  97574. case 15: sum += qlp_coeff[14] * data[i-15];
  97575. case 14: sum += qlp_coeff[13] * data[i-14];
  97576. case 13: sum += qlp_coeff[12] * data[i-13];
  97577. sum += qlp_coeff[11] * data[i-12];
  97578. sum += qlp_coeff[10] * data[i-11];
  97579. sum += qlp_coeff[ 9] * data[i-10];
  97580. sum += qlp_coeff[ 8] * data[i- 9];
  97581. sum += qlp_coeff[ 7] * data[i- 8];
  97582. sum += qlp_coeff[ 6] * data[i- 7];
  97583. sum += qlp_coeff[ 5] * data[i- 6];
  97584. sum += qlp_coeff[ 4] * data[i- 5];
  97585. sum += qlp_coeff[ 3] * data[i- 4];
  97586. sum += qlp_coeff[ 2] * data[i- 3];
  97587. sum += qlp_coeff[ 1] * data[i- 2];
  97588. sum += qlp_coeff[ 0] * data[i- 1];
  97589. }
  97590. residual[i] = data[i] - (sum >> lp_quantization);
  97591. }
  97592. }
  97593. }
  97594. #endif
  97595. 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[])
  97596. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97597. {
  97598. unsigned i, j;
  97599. FLAC__int64 sum;
  97600. const FLAC__int32 *history;
  97601. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97602. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97603. for(i=0;i<order;i++)
  97604. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97605. fprintf(stderr,"\n");
  97606. #endif
  97607. FLAC__ASSERT(order > 0);
  97608. for(i = 0; i < data_len; i++) {
  97609. sum = 0;
  97610. history = data;
  97611. for(j = 0; j < order; j++)
  97612. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97613. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97614. #if defined _MSC_VER
  97615. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97616. #else
  97617. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97618. #endif
  97619. break;
  97620. }
  97621. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97622. #if defined _MSC_VER
  97623. 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));
  97624. #else
  97625. 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)));
  97626. #endif
  97627. break;
  97628. }
  97629. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97630. }
  97631. }
  97632. #else /* fully unrolled version for normal use */
  97633. {
  97634. int i;
  97635. FLAC__int64 sum;
  97636. FLAC__ASSERT(order > 0);
  97637. FLAC__ASSERT(order <= 32);
  97638. /*
  97639. * We do unique versions up to 12th order since that's the subset limit.
  97640. * Also they are roughly ordered to match frequency of occurrence to
  97641. * minimize branching.
  97642. */
  97643. if(order <= 12) {
  97644. if(order > 8) {
  97645. if(order > 10) {
  97646. if(order == 12) {
  97647. for(i = 0; i < (int)data_len; i++) {
  97648. sum = 0;
  97649. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97650. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97651. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97652. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97653. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97654. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97655. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97656. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97657. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97658. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97659. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97660. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97661. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97662. }
  97663. }
  97664. else { /* order == 11 */
  97665. for(i = 0; i < (int)data_len; i++) {
  97666. sum = 0;
  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. }
  97682. else {
  97683. if(order == 10) {
  97684. for(i = 0; i < (int)data_len; i++) {
  97685. sum = 0;
  97686. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97687. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97688. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97689. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97690. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97691. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97692. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97693. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97694. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97695. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97696. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97697. }
  97698. }
  97699. else { /* order == 9 */
  97700. for(i = 0; i < (int)data_len; i++) {
  97701. sum = 0;
  97702. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97703. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97704. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97705. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97706. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97707. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97708. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97709. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97710. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97711. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97712. }
  97713. }
  97714. }
  97715. }
  97716. else if(order > 4) {
  97717. if(order > 6) {
  97718. if(order == 8) {
  97719. for(i = 0; i < (int)data_len; i++) {
  97720. sum = 0;
  97721. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97722. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97723. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97724. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97725. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97726. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97727. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97728. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97729. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97730. }
  97731. }
  97732. else { /* order == 7 */
  97733. for(i = 0; i < (int)data_len; i++) {
  97734. sum = 0;
  97735. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97736. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97737. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97738. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97739. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97740. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97741. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97742. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97743. }
  97744. }
  97745. }
  97746. else {
  97747. if(order == 6) {
  97748. for(i = 0; i < (int)data_len; i++) {
  97749. sum = 0;
  97750. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97751. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97752. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97753. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97754. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97755. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97756. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97757. }
  97758. }
  97759. else { /* order == 5 */
  97760. for(i = 0; i < (int)data_len; i++) {
  97761. sum = 0;
  97762. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97763. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97764. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97765. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97766. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97767. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97768. }
  97769. }
  97770. }
  97771. }
  97772. else {
  97773. if(order > 2) {
  97774. if(order == 4) {
  97775. for(i = 0; i < (int)data_len; i++) {
  97776. sum = 0;
  97777. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97778. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97779. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97780. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97781. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97782. }
  97783. }
  97784. else { /* order == 3 */
  97785. for(i = 0; i < (int)data_len; i++) {
  97786. sum = 0;
  97787. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97788. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97789. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97790. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97791. }
  97792. }
  97793. }
  97794. else {
  97795. if(order == 2) {
  97796. for(i = 0; i < (int)data_len; i++) {
  97797. sum = 0;
  97798. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97799. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97800. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97801. }
  97802. }
  97803. else { /* order == 1 */
  97804. for(i = 0; i < (int)data_len; i++)
  97805. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97806. }
  97807. }
  97808. }
  97809. }
  97810. else { /* order > 12 */
  97811. for(i = 0; i < (int)data_len; i++) {
  97812. sum = 0;
  97813. switch(order) {
  97814. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97815. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97816. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97817. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97818. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97819. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97820. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97821. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97822. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97823. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97824. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97825. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97826. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97827. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97828. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97829. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97830. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97831. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97832. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97833. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97834. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97835. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97836. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97837. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97838. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97839. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97840. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97841. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97842. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97843. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97844. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97845. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97846. }
  97847. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97848. }
  97849. }
  97850. }
  97851. #endif
  97852. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97853. 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[])
  97854. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97855. {
  97856. FLAC__int64 sumo;
  97857. unsigned i, j;
  97858. FLAC__int32 sum;
  97859. const FLAC__int32 *r = residual, *history;
  97860. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97861. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97862. for(i=0;i<order;i++)
  97863. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97864. fprintf(stderr,"\n");
  97865. #endif
  97866. FLAC__ASSERT(order > 0);
  97867. for(i = 0; i < data_len; i++) {
  97868. sumo = 0;
  97869. sum = 0;
  97870. history = data;
  97871. for(j = 0; j < order; j++) {
  97872. sum += qlp_coeff[j] * (*(--history));
  97873. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97874. #if defined _MSC_VER
  97875. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97876. 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);
  97877. #else
  97878. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97879. 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);
  97880. #endif
  97881. }
  97882. *(data++) = *(r++) + (sum >> lp_quantization);
  97883. }
  97884. /* Here's a slower but clearer version:
  97885. for(i = 0; i < data_len; i++) {
  97886. sum = 0;
  97887. for(j = 0; j < order; j++)
  97888. sum += qlp_coeff[j] * data[i-j-1];
  97889. data[i] = residual[i] + (sum >> lp_quantization);
  97890. }
  97891. */
  97892. }
  97893. #else /* fully unrolled version for normal use */
  97894. {
  97895. int i;
  97896. FLAC__int32 sum;
  97897. FLAC__ASSERT(order > 0);
  97898. FLAC__ASSERT(order <= 32);
  97899. /*
  97900. * We do unique versions up to 12th order since that's the subset limit.
  97901. * Also they are roughly ordered to match frequency of occurrence to
  97902. * minimize branching.
  97903. */
  97904. if(order <= 12) {
  97905. if(order > 8) {
  97906. if(order > 10) {
  97907. if(order == 12) {
  97908. for(i = 0; i < (int)data_len; i++) {
  97909. sum = 0;
  97910. sum += qlp_coeff[11] * data[i-12];
  97911. sum += qlp_coeff[10] * data[i-11];
  97912. sum += qlp_coeff[9] * data[i-10];
  97913. sum += qlp_coeff[8] * data[i-9];
  97914. sum += qlp_coeff[7] * data[i-8];
  97915. sum += qlp_coeff[6] * data[i-7];
  97916. sum += qlp_coeff[5] * data[i-6];
  97917. sum += qlp_coeff[4] * data[i-5];
  97918. sum += qlp_coeff[3] * data[i-4];
  97919. sum += qlp_coeff[2] * data[i-3];
  97920. sum += qlp_coeff[1] * data[i-2];
  97921. sum += qlp_coeff[0] * data[i-1];
  97922. data[i] = residual[i] + (sum >> lp_quantization);
  97923. }
  97924. }
  97925. else { /* order == 11 */
  97926. for(i = 0; i < (int)data_len; i++) {
  97927. sum = 0;
  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. }
  97943. else {
  97944. if(order == 10) {
  97945. for(i = 0; i < (int)data_len; i++) {
  97946. sum = 0;
  97947. sum += qlp_coeff[9] * data[i-10];
  97948. sum += qlp_coeff[8] * data[i-9];
  97949. sum += qlp_coeff[7] * data[i-8];
  97950. sum += qlp_coeff[6] * data[i-7];
  97951. sum += qlp_coeff[5] * data[i-6];
  97952. sum += qlp_coeff[4] * data[i-5];
  97953. sum += qlp_coeff[3] * data[i-4];
  97954. sum += qlp_coeff[2] * data[i-3];
  97955. sum += qlp_coeff[1] * data[i-2];
  97956. sum += qlp_coeff[0] * data[i-1];
  97957. data[i] = residual[i] + (sum >> lp_quantization);
  97958. }
  97959. }
  97960. else { /* order == 9 */
  97961. for(i = 0; i < (int)data_len; i++) {
  97962. sum = 0;
  97963. sum += qlp_coeff[8] * data[i-9];
  97964. sum += qlp_coeff[7] * data[i-8];
  97965. sum += qlp_coeff[6] * data[i-7];
  97966. sum += qlp_coeff[5] * data[i-6];
  97967. sum += qlp_coeff[4] * data[i-5];
  97968. sum += qlp_coeff[3] * data[i-4];
  97969. sum += qlp_coeff[2] * data[i-3];
  97970. sum += qlp_coeff[1] * data[i-2];
  97971. sum += qlp_coeff[0] * data[i-1];
  97972. data[i] = residual[i] + (sum >> lp_quantization);
  97973. }
  97974. }
  97975. }
  97976. }
  97977. else if(order > 4) {
  97978. if(order > 6) {
  97979. if(order == 8) {
  97980. for(i = 0; i < (int)data_len; i++) {
  97981. sum = 0;
  97982. sum += qlp_coeff[7] * data[i-8];
  97983. sum += qlp_coeff[6] * data[i-7];
  97984. sum += qlp_coeff[5] * data[i-6];
  97985. sum += qlp_coeff[4] * data[i-5];
  97986. sum += qlp_coeff[3] * data[i-4];
  97987. sum += qlp_coeff[2] * data[i-3];
  97988. sum += qlp_coeff[1] * data[i-2];
  97989. sum += qlp_coeff[0] * data[i-1];
  97990. data[i] = residual[i] + (sum >> lp_quantization);
  97991. }
  97992. }
  97993. else { /* order == 7 */
  97994. for(i = 0; i < (int)data_len; i++) {
  97995. sum = 0;
  97996. sum += qlp_coeff[6] * data[i-7];
  97997. sum += qlp_coeff[5] * data[i-6];
  97998. sum += qlp_coeff[4] * data[i-5];
  97999. sum += qlp_coeff[3] * data[i-4];
  98000. sum += qlp_coeff[2] * data[i-3];
  98001. sum += qlp_coeff[1] * data[i-2];
  98002. sum += qlp_coeff[0] * data[i-1];
  98003. data[i] = residual[i] + (sum >> lp_quantization);
  98004. }
  98005. }
  98006. }
  98007. else {
  98008. if(order == 6) {
  98009. for(i = 0; i < (int)data_len; i++) {
  98010. sum = 0;
  98011. sum += qlp_coeff[5] * data[i-6];
  98012. sum += qlp_coeff[4] * data[i-5];
  98013. sum += qlp_coeff[3] * data[i-4];
  98014. sum += qlp_coeff[2] * data[i-3];
  98015. sum += qlp_coeff[1] * data[i-2];
  98016. sum += qlp_coeff[0] * data[i-1];
  98017. data[i] = residual[i] + (sum >> lp_quantization);
  98018. }
  98019. }
  98020. else { /* order == 5 */
  98021. for(i = 0; i < (int)data_len; i++) {
  98022. sum = 0;
  98023. sum += qlp_coeff[4] * data[i-5];
  98024. sum += qlp_coeff[3] * data[i-4];
  98025. sum += qlp_coeff[2] * data[i-3];
  98026. sum += qlp_coeff[1] * data[i-2];
  98027. sum += qlp_coeff[0] * data[i-1];
  98028. data[i] = residual[i] + (sum >> lp_quantization);
  98029. }
  98030. }
  98031. }
  98032. }
  98033. else {
  98034. if(order > 2) {
  98035. if(order == 4) {
  98036. for(i = 0; i < (int)data_len; i++) {
  98037. sum = 0;
  98038. sum += qlp_coeff[3] * data[i-4];
  98039. sum += qlp_coeff[2] * data[i-3];
  98040. sum += qlp_coeff[1] * data[i-2];
  98041. sum += qlp_coeff[0] * data[i-1];
  98042. data[i] = residual[i] + (sum >> lp_quantization);
  98043. }
  98044. }
  98045. else { /* order == 3 */
  98046. for(i = 0; i < (int)data_len; i++) {
  98047. sum = 0;
  98048. sum += qlp_coeff[2] * data[i-3];
  98049. sum += qlp_coeff[1] * data[i-2];
  98050. sum += qlp_coeff[0] * data[i-1];
  98051. data[i] = residual[i] + (sum >> lp_quantization);
  98052. }
  98053. }
  98054. }
  98055. else {
  98056. if(order == 2) {
  98057. for(i = 0; i < (int)data_len; i++) {
  98058. sum = 0;
  98059. sum += qlp_coeff[1] * data[i-2];
  98060. sum += qlp_coeff[0] * data[i-1];
  98061. data[i] = residual[i] + (sum >> lp_quantization);
  98062. }
  98063. }
  98064. else { /* order == 1 */
  98065. for(i = 0; i < (int)data_len; i++)
  98066. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98067. }
  98068. }
  98069. }
  98070. }
  98071. else { /* order > 12 */
  98072. for(i = 0; i < (int)data_len; i++) {
  98073. sum = 0;
  98074. switch(order) {
  98075. case 32: sum += qlp_coeff[31] * data[i-32];
  98076. case 31: sum += qlp_coeff[30] * data[i-31];
  98077. case 30: sum += qlp_coeff[29] * data[i-30];
  98078. case 29: sum += qlp_coeff[28] * data[i-29];
  98079. case 28: sum += qlp_coeff[27] * data[i-28];
  98080. case 27: sum += qlp_coeff[26] * data[i-27];
  98081. case 26: sum += qlp_coeff[25] * data[i-26];
  98082. case 25: sum += qlp_coeff[24] * data[i-25];
  98083. case 24: sum += qlp_coeff[23] * data[i-24];
  98084. case 23: sum += qlp_coeff[22] * data[i-23];
  98085. case 22: sum += qlp_coeff[21] * data[i-22];
  98086. case 21: sum += qlp_coeff[20] * data[i-21];
  98087. case 20: sum += qlp_coeff[19] * data[i-20];
  98088. case 19: sum += qlp_coeff[18] * data[i-19];
  98089. case 18: sum += qlp_coeff[17] * data[i-18];
  98090. case 17: sum += qlp_coeff[16] * data[i-17];
  98091. case 16: sum += qlp_coeff[15] * data[i-16];
  98092. case 15: sum += qlp_coeff[14] * data[i-15];
  98093. case 14: sum += qlp_coeff[13] * data[i-14];
  98094. case 13: sum += qlp_coeff[12] * data[i-13];
  98095. sum += qlp_coeff[11] * data[i-12];
  98096. sum += qlp_coeff[10] * data[i-11];
  98097. sum += qlp_coeff[ 9] * data[i-10];
  98098. sum += qlp_coeff[ 8] * data[i- 9];
  98099. sum += qlp_coeff[ 7] * data[i- 8];
  98100. sum += qlp_coeff[ 6] * data[i- 7];
  98101. sum += qlp_coeff[ 5] * data[i- 6];
  98102. sum += qlp_coeff[ 4] * data[i- 5];
  98103. sum += qlp_coeff[ 3] * data[i- 4];
  98104. sum += qlp_coeff[ 2] * data[i- 3];
  98105. sum += qlp_coeff[ 1] * data[i- 2];
  98106. sum += qlp_coeff[ 0] * data[i- 1];
  98107. }
  98108. data[i] = residual[i] + (sum >> lp_quantization);
  98109. }
  98110. }
  98111. }
  98112. #endif
  98113. 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[])
  98114. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98115. {
  98116. unsigned i, j;
  98117. FLAC__int64 sum;
  98118. const FLAC__int32 *r = residual, *history;
  98119. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98120. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98121. for(i=0;i<order;i++)
  98122. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98123. fprintf(stderr,"\n");
  98124. #endif
  98125. FLAC__ASSERT(order > 0);
  98126. for(i = 0; i < data_len; i++) {
  98127. sum = 0;
  98128. history = data;
  98129. for(j = 0; j < order; j++)
  98130. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98131. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98132. #ifdef _MSC_VER
  98133. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98134. #else
  98135. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98136. #endif
  98137. break;
  98138. }
  98139. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98140. #ifdef _MSC_VER
  98141. 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));
  98142. #else
  98143. 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)));
  98144. #endif
  98145. break;
  98146. }
  98147. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98148. }
  98149. }
  98150. #else /* fully unrolled version for normal use */
  98151. {
  98152. int i;
  98153. FLAC__int64 sum;
  98154. FLAC__ASSERT(order > 0);
  98155. FLAC__ASSERT(order <= 32);
  98156. /*
  98157. * We do unique versions up to 12th order since that's the subset limit.
  98158. * Also they are roughly ordered to match frequency of occurrence to
  98159. * minimize branching.
  98160. */
  98161. if(order <= 12) {
  98162. if(order > 8) {
  98163. if(order > 10) {
  98164. if(order == 12) {
  98165. for(i = 0; i < (int)data_len; i++) {
  98166. sum = 0;
  98167. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98168. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98169. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98170. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98171. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98172. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98173. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98174. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98175. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98176. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98177. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98178. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98179. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98180. }
  98181. }
  98182. else { /* order == 11 */
  98183. for(i = 0; i < (int)data_len; i++) {
  98184. sum = 0;
  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. }
  98200. else {
  98201. if(order == 10) {
  98202. for(i = 0; i < (int)data_len; i++) {
  98203. sum = 0;
  98204. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98205. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98206. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98207. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98208. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98209. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98210. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98211. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98212. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98213. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98214. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98215. }
  98216. }
  98217. else { /* order == 9 */
  98218. for(i = 0; i < (int)data_len; i++) {
  98219. sum = 0;
  98220. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98221. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98222. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98223. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98224. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98225. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98226. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98227. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98228. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98229. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98230. }
  98231. }
  98232. }
  98233. }
  98234. else if(order > 4) {
  98235. if(order > 6) {
  98236. if(order == 8) {
  98237. for(i = 0; i < (int)data_len; i++) {
  98238. sum = 0;
  98239. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98240. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98241. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98242. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98243. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98244. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98245. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98246. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98247. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98248. }
  98249. }
  98250. else { /* order == 7 */
  98251. for(i = 0; i < (int)data_len; i++) {
  98252. sum = 0;
  98253. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98254. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98255. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98256. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98257. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98258. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98259. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98260. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98261. }
  98262. }
  98263. }
  98264. else {
  98265. if(order == 6) {
  98266. for(i = 0; i < (int)data_len; i++) {
  98267. sum = 0;
  98268. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98269. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98270. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98271. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98272. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98273. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98274. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98275. }
  98276. }
  98277. else { /* order == 5 */
  98278. for(i = 0; i < (int)data_len; i++) {
  98279. sum = 0;
  98280. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98281. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98282. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98283. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98284. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98285. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98286. }
  98287. }
  98288. }
  98289. }
  98290. else {
  98291. if(order > 2) {
  98292. if(order == 4) {
  98293. for(i = 0; i < (int)data_len; i++) {
  98294. sum = 0;
  98295. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98296. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98297. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98298. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98299. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98300. }
  98301. }
  98302. else { /* order == 3 */
  98303. for(i = 0; i < (int)data_len; i++) {
  98304. sum = 0;
  98305. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98306. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98307. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98308. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98309. }
  98310. }
  98311. }
  98312. else {
  98313. if(order == 2) {
  98314. for(i = 0; i < (int)data_len; i++) {
  98315. sum = 0;
  98316. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98317. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98318. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98319. }
  98320. }
  98321. else { /* order == 1 */
  98322. for(i = 0; i < (int)data_len; i++)
  98323. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98324. }
  98325. }
  98326. }
  98327. }
  98328. else { /* order > 12 */
  98329. for(i = 0; i < (int)data_len; i++) {
  98330. sum = 0;
  98331. switch(order) {
  98332. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98333. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98334. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98335. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98336. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98337. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98338. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98339. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98340. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98341. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98342. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98343. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98344. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98345. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98346. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98347. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98348. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98349. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98350. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98351. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98352. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98353. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98354. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98355. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98356. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98357. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98358. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98359. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98360. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98361. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98362. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98363. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98364. }
  98365. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98366. }
  98367. }
  98368. }
  98369. #endif
  98370. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98371. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98372. {
  98373. FLAC__double error_scale;
  98374. FLAC__ASSERT(total_samples > 0);
  98375. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98376. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98377. }
  98378. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98379. {
  98380. if(lpc_error > 0.0) {
  98381. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98382. if(bps >= 0.0)
  98383. return bps;
  98384. else
  98385. return 0.0;
  98386. }
  98387. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98388. return 1e32;
  98389. }
  98390. else {
  98391. return 0.0;
  98392. }
  98393. }
  98394. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98395. {
  98396. 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 */
  98397. FLAC__double bits, best_bits, error_scale;
  98398. FLAC__ASSERT(max_order > 0);
  98399. FLAC__ASSERT(total_samples > 0);
  98400. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98401. best_index = 0;
  98402. best_bits = (unsigned)(-1);
  98403. for(index = 0, order = 1; index < max_order; index++, order++) {
  98404. 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);
  98405. if(bits < best_bits) {
  98406. best_index = index;
  98407. best_bits = bits;
  98408. }
  98409. }
  98410. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98411. }
  98412. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98413. #endif
  98414. /*** End of inlined file: lpc_flac.c ***/
  98415. /*** Start of inlined file: md5.c ***/
  98416. /*** Start of inlined file: juce_FlacHeader.h ***/
  98417. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98418. // tasks..
  98419. #define VERSION "1.2.1"
  98420. #define FLAC__NO_DLL 1
  98421. #if JUCE_MSVC
  98422. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98423. #endif
  98424. #if JUCE_MAC
  98425. #define FLAC__SYS_DARWIN 1
  98426. #endif
  98427. /*** End of inlined file: juce_FlacHeader.h ***/
  98428. #if JUCE_USE_FLAC
  98429. #if HAVE_CONFIG_H
  98430. # include <config.h>
  98431. #endif
  98432. #include <stdlib.h> /* for malloc() */
  98433. #include <string.h> /* for memcpy() */
  98434. /*** Start of inlined file: md5.h ***/
  98435. #ifndef FLAC__PRIVATE__MD5_H
  98436. #define FLAC__PRIVATE__MD5_H
  98437. /*
  98438. * This is the header file for the MD5 message-digest algorithm.
  98439. * The algorithm is due to Ron Rivest. This code was
  98440. * written by Colin Plumb in 1993, no copyright is claimed.
  98441. * This code is in the public domain; do with it what you wish.
  98442. *
  98443. * Equivalent code is available from RSA Data Security, Inc.
  98444. * This code has been tested against that, and is equivalent,
  98445. * except that you don't need to include two pages of legalese
  98446. * with every copy.
  98447. *
  98448. * To compute the message digest of a chunk of bytes, declare an
  98449. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98450. * needed on buffers full of bytes, and then call MD5Final, which
  98451. * will fill a supplied 16-byte array with the digest.
  98452. *
  98453. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98454. * header definitions; now uses stuff from dpkg's config.h
  98455. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98456. * Still in the public domain.
  98457. *
  98458. * Josh Coalson: made some changes to integrate with libFLAC.
  98459. * Still in the public domain, with no warranty.
  98460. */
  98461. typedef struct {
  98462. FLAC__uint32 in[16];
  98463. FLAC__uint32 buf[4];
  98464. FLAC__uint32 bytes[2];
  98465. FLAC__byte *internal_buf;
  98466. size_t capacity;
  98467. } FLAC__MD5Context;
  98468. void FLAC__MD5Init(FLAC__MD5Context *context);
  98469. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98470. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98471. #endif
  98472. /*** End of inlined file: md5.h ***/
  98473. #ifndef FLaC__INLINE
  98474. #define FLaC__INLINE
  98475. #endif
  98476. /*
  98477. * This code implements the MD5 message-digest algorithm.
  98478. * The algorithm is due to Ron Rivest. This code was
  98479. * written by Colin Plumb in 1993, no copyright is claimed.
  98480. * This code is in the public domain; do with it what you wish.
  98481. *
  98482. * Equivalent code is available from RSA Data Security, Inc.
  98483. * This code has been tested against that, and is equivalent,
  98484. * except that you don't need to include two pages of legalese
  98485. * with every copy.
  98486. *
  98487. * To compute the message digest of a chunk of bytes, declare an
  98488. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98489. * needed on buffers full of bytes, and then call MD5Final, which
  98490. * will fill a supplied 16-byte array with the digest.
  98491. *
  98492. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98493. * definitions; now uses stuff from dpkg's config.h.
  98494. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98495. * Still in the public domain.
  98496. *
  98497. * Josh Coalson: made some changes to integrate with libFLAC.
  98498. * Still in the public domain.
  98499. */
  98500. /* The four core functions - F1 is optimized somewhat */
  98501. /* #define F1(x, y, z) (x & y | ~x & z) */
  98502. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98503. #define F2(x, y, z) F1(z, x, y)
  98504. #define F3(x, y, z) (x ^ y ^ z)
  98505. #define F4(x, y, z) (y ^ (x | ~z))
  98506. /* This is the central step in the MD5 algorithm. */
  98507. #define MD5STEP(f,w,x,y,z,in,s) \
  98508. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98509. /*
  98510. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98511. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98512. * the data and converts bytes into longwords for this routine.
  98513. */
  98514. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98515. {
  98516. register FLAC__uint32 a, b, c, d;
  98517. a = buf[0];
  98518. b = buf[1];
  98519. c = buf[2];
  98520. d = buf[3];
  98521. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98522. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98523. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98524. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98525. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98526. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98527. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98528. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98529. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98530. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98531. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98532. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98533. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98534. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98535. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98536. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98537. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98538. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98539. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98540. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98541. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98542. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98543. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98544. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98545. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98546. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98547. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98548. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98549. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98550. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98551. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98552. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98553. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98554. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98555. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98556. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98557. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98558. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98559. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98560. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98561. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98562. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98563. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98564. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98565. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98566. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98567. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98568. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98569. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98570. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98571. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98572. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98573. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98574. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98575. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98576. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98577. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98578. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98579. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98580. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98581. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98582. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98583. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98584. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98585. buf[0] += a;
  98586. buf[1] += b;
  98587. buf[2] += c;
  98588. buf[3] += d;
  98589. }
  98590. #if WORDS_BIGENDIAN
  98591. //@@@@@@ OPT: use bswap/intrinsics
  98592. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98593. {
  98594. register FLAC__uint32 x;
  98595. do {
  98596. x = *buf;
  98597. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98598. *buf++ = (x >> 16) | (x << 16);
  98599. } while (--words);
  98600. }
  98601. static void byteSwapX16(FLAC__uint32 *buf)
  98602. {
  98603. register FLAC__uint32 x;
  98604. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98605. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98606. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98607. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98608. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98609. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98610. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98611. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98612. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98613. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98614. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98615. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98616. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98617. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98618. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98619. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98620. }
  98621. #else
  98622. #define byteSwap(buf, words)
  98623. #define byteSwapX16(buf)
  98624. #endif
  98625. /*
  98626. * Update context to reflect the concatenation of another buffer full
  98627. * of bytes.
  98628. */
  98629. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98630. {
  98631. FLAC__uint32 t;
  98632. /* Update byte count */
  98633. t = ctx->bytes[0];
  98634. if ((ctx->bytes[0] = t + len) < t)
  98635. ctx->bytes[1]++; /* Carry from low to high */
  98636. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98637. if (t > len) {
  98638. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98639. return;
  98640. }
  98641. /* First chunk is an odd size */
  98642. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98643. byteSwapX16(ctx->in);
  98644. FLAC__MD5Transform(ctx->buf, ctx->in);
  98645. buf += t;
  98646. len -= t;
  98647. /* Process data in 64-byte chunks */
  98648. while (len >= 64) {
  98649. memcpy(ctx->in, buf, 64);
  98650. byteSwapX16(ctx->in);
  98651. FLAC__MD5Transform(ctx->buf, ctx->in);
  98652. buf += 64;
  98653. len -= 64;
  98654. }
  98655. /* Handle any remaining bytes of data. */
  98656. memcpy(ctx->in, buf, len);
  98657. }
  98658. /*
  98659. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98660. * initialization constants.
  98661. */
  98662. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98663. {
  98664. ctx->buf[0] = 0x67452301;
  98665. ctx->buf[1] = 0xefcdab89;
  98666. ctx->buf[2] = 0x98badcfe;
  98667. ctx->buf[3] = 0x10325476;
  98668. ctx->bytes[0] = 0;
  98669. ctx->bytes[1] = 0;
  98670. ctx->internal_buf = 0;
  98671. ctx->capacity = 0;
  98672. }
  98673. /*
  98674. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98675. * 1 0* (64-bit count of bits processed, MSB-first)
  98676. */
  98677. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98678. {
  98679. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98680. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98681. /* Set the first char of padding to 0x80. There is always room. */
  98682. *p++ = 0x80;
  98683. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98684. count = 56 - 1 - count;
  98685. if (count < 0) { /* Padding forces an extra block */
  98686. memset(p, 0, count + 8);
  98687. byteSwapX16(ctx->in);
  98688. FLAC__MD5Transform(ctx->buf, ctx->in);
  98689. p = (FLAC__byte *)ctx->in;
  98690. count = 56;
  98691. }
  98692. memset(p, 0, count);
  98693. byteSwap(ctx->in, 14);
  98694. /* Append length in bits and transform */
  98695. ctx->in[14] = ctx->bytes[0] << 3;
  98696. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98697. FLAC__MD5Transform(ctx->buf, ctx->in);
  98698. byteSwap(ctx->buf, 4);
  98699. memcpy(digest, ctx->buf, 16);
  98700. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98701. if(0 != ctx->internal_buf) {
  98702. free(ctx->internal_buf);
  98703. ctx->internal_buf = 0;
  98704. ctx->capacity = 0;
  98705. }
  98706. }
  98707. /*
  98708. * Convert the incoming audio signal to a byte stream
  98709. */
  98710. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98711. {
  98712. unsigned channel, sample;
  98713. register FLAC__int32 a_word;
  98714. register FLAC__byte *buf_ = buf;
  98715. #if WORDS_BIGENDIAN
  98716. #else
  98717. if(channels == 2 && bytes_per_sample == 2) {
  98718. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98719. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98720. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98721. *buf1_ = (FLAC__int16)signal[1][sample];
  98722. }
  98723. else if(channels == 1 && bytes_per_sample == 2) {
  98724. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98725. for(sample = 0; sample < samples; sample++)
  98726. *buf1_++ = (FLAC__int16)signal[0][sample];
  98727. }
  98728. else
  98729. #endif
  98730. if(bytes_per_sample == 2) {
  98731. if(channels == 2) {
  98732. for(sample = 0; sample < samples; sample++) {
  98733. a_word = signal[0][sample];
  98734. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98735. *buf_++ = (FLAC__byte)a_word;
  98736. a_word = signal[1][sample];
  98737. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98738. *buf_++ = (FLAC__byte)a_word;
  98739. }
  98740. }
  98741. else if(channels == 1) {
  98742. for(sample = 0; sample < samples; sample++) {
  98743. a_word = signal[0][sample];
  98744. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98745. *buf_++ = (FLAC__byte)a_word;
  98746. }
  98747. }
  98748. else {
  98749. for(sample = 0; sample < samples; sample++) {
  98750. for(channel = 0; channel < channels; channel++) {
  98751. a_word = signal[channel][sample];
  98752. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98753. *buf_++ = (FLAC__byte)a_word;
  98754. }
  98755. }
  98756. }
  98757. }
  98758. else if(bytes_per_sample == 3) {
  98759. if(channels == 2) {
  98760. for(sample = 0; sample < samples; sample++) {
  98761. a_word = signal[0][sample];
  98762. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98763. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98764. *buf_++ = (FLAC__byte)a_word;
  98765. a_word = signal[1][sample];
  98766. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98767. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98768. *buf_++ = (FLAC__byte)a_word;
  98769. }
  98770. }
  98771. else if(channels == 1) {
  98772. for(sample = 0; sample < samples; sample++) {
  98773. a_word = signal[0][sample];
  98774. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98775. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98776. *buf_++ = (FLAC__byte)a_word;
  98777. }
  98778. }
  98779. else {
  98780. for(sample = 0; sample < samples; sample++) {
  98781. for(channel = 0; channel < channels; channel++) {
  98782. a_word = signal[channel][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. }
  98789. }
  98790. else if(bytes_per_sample == 1) {
  98791. if(channels == 2) {
  98792. for(sample = 0; sample < samples; sample++) {
  98793. a_word = signal[0][sample];
  98794. *buf_++ = (FLAC__byte)a_word;
  98795. a_word = signal[1][sample];
  98796. *buf_++ = (FLAC__byte)a_word;
  98797. }
  98798. }
  98799. else if(channels == 1) {
  98800. for(sample = 0; sample < samples; sample++) {
  98801. a_word = signal[0][sample];
  98802. *buf_++ = (FLAC__byte)a_word;
  98803. }
  98804. }
  98805. else {
  98806. for(sample = 0; sample < samples; sample++) {
  98807. for(channel = 0; channel < channels; channel++) {
  98808. a_word = signal[channel][sample];
  98809. *buf_++ = (FLAC__byte)a_word;
  98810. }
  98811. }
  98812. }
  98813. }
  98814. else { /* bytes_per_sample == 4, maybe optimize more later */
  98815. for(sample = 0; sample < samples; sample++) {
  98816. for(channel = 0; channel < channels; channel++) {
  98817. a_word = signal[channel][sample];
  98818. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98819. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98820. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98821. *buf_++ = (FLAC__byte)a_word;
  98822. }
  98823. }
  98824. }
  98825. }
  98826. /*
  98827. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98828. */
  98829. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98830. {
  98831. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98832. /* overflow check */
  98833. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98834. return false;
  98835. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98836. return false;
  98837. if(ctx->capacity < bytes_needed) {
  98838. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98839. if(0 == tmp) {
  98840. free(ctx->internal_buf);
  98841. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98842. return false;
  98843. }
  98844. ctx->internal_buf = tmp;
  98845. ctx->capacity = bytes_needed;
  98846. }
  98847. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98848. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98849. return true;
  98850. }
  98851. #endif
  98852. /*** End of inlined file: md5.c ***/
  98853. /*** Start of inlined file: memory.c ***/
  98854. /*** Start of inlined file: juce_FlacHeader.h ***/
  98855. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98856. // tasks..
  98857. #define VERSION "1.2.1"
  98858. #define FLAC__NO_DLL 1
  98859. #if JUCE_MSVC
  98860. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98861. #endif
  98862. #if JUCE_MAC
  98863. #define FLAC__SYS_DARWIN 1
  98864. #endif
  98865. /*** End of inlined file: juce_FlacHeader.h ***/
  98866. #if JUCE_USE_FLAC
  98867. #if HAVE_CONFIG_H
  98868. # include <config.h>
  98869. #endif
  98870. /*** Start of inlined file: memory.h ***/
  98871. #ifndef FLAC__PRIVATE__MEMORY_H
  98872. #define FLAC__PRIVATE__MEMORY_H
  98873. #ifdef HAVE_CONFIG_H
  98874. #include <config.h>
  98875. #endif
  98876. #include <stdlib.h> /* for size_t */
  98877. /* Returns the unaligned address returned by malloc.
  98878. * Use free() on this address to deallocate.
  98879. */
  98880. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98881. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98882. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98883. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98884. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98885. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98886. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98887. #endif
  98888. #endif
  98889. /*** End of inlined file: memory.h ***/
  98890. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98891. {
  98892. void *x;
  98893. FLAC__ASSERT(0 != aligned_address);
  98894. #ifdef FLAC__ALIGN_MALLOC_DATA
  98895. /* align on 32-byte (256-bit) boundary */
  98896. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98897. #ifdef SIZEOF_VOIDP
  98898. #if SIZEOF_VOIDP == 4
  98899. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98900. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98901. #elif SIZEOF_VOIDP == 8
  98902. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98903. #else
  98904. # error Unsupported sizeof(void*)
  98905. #endif
  98906. #else
  98907. /* there's got to be a better way to do this right for all archs */
  98908. if(sizeof(void*) == sizeof(unsigned))
  98909. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98910. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98911. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98912. else
  98913. return 0;
  98914. #endif
  98915. #else
  98916. x = safe_malloc_(bytes);
  98917. *aligned_address = x;
  98918. #endif
  98919. return x;
  98920. }
  98921. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98922. {
  98923. FLAC__int32 *pu; /* unaligned pointer */
  98924. union { /* union needed to comply with C99 pointer aliasing rules */
  98925. FLAC__int32 *pa; /* aligned pointer */
  98926. void *pv; /* aligned pointer alias */
  98927. } u;
  98928. FLAC__ASSERT(elements > 0);
  98929. FLAC__ASSERT(0 != unaligned_pointer);
  98930. FLAC__ASSERT(0 != aligned_pointer);
  98931. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98932. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98933. if(0 == pu) {
  98934. return false;
  98935. }
  98936. else {
  98937. if(*unaligned_pointer != 0)
  98938. free(*unaligned_pointer);
  98939. *unaligned_pointer = pu;
  98940. *aligned_pointer = u.pa;
  98941. return true;
  98942. }
  98943. }
  98944. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98945. {
  98946. FLAC__uint32 *pu; /* unaligned pointer */
  98947. union { /* union needed to comply with C99 pointer aliasing rules */
  98948. FLAC__uint32 *pa; /* aligned pointer */
  98949. void *pv; /* aligned pointer alias */
  98950. } u;
  98951. FLAC__ASSERT(elements > 0);
  98952. FLAC__ASSERT(0 != unaligned_pointer);
  98953. FLAC__ASSERT(0 != aligned_pointer);
  98954. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98955. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98956. if(0 == pu) {
  98957. return false;
  98958. }
  98959. else {
  98960. if(*unaligned_pointer != 0)
  98961. free(*unaligned_pointer);
  98962. *unaligned_pointer = pu;
  98963. *aligned_pointer = u.pa;
  98964. return true;
  98965. }
  98966. }
  98967. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98968. {
  98969. FLAC__uint64 *pu; /* unaligned pointer */
  98970. union { /* union needed to comply with C99 pointer aliasing rules */
  98971. FLAC__uint64 *pa; /* aligned pointer */
  98972. void *pv; /* aligned pointer alias */
  98973. } u;
  98974. FLAC__ASSERT(elements > 0);
  98975. FLAC__ASSERT(0 != unaligned_pointer);
  98976. FLAC__ASSERT(0 != aligned_pointer);
  98977. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98978. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98979. if(0 == pu) {
  98980. return false;
  98981. }
  98982. else {
  98983. if(*unaligned_pointer != 0)
  98984. free(*unaligned_pointer);
  98985. *unaligned_pointer = pu;
  98986. *aligned_pointer = u.pa;
  98987. return true;
  98988. }
  98989. }
  98990. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98991. {
  98992. unsigned *pu; /* unaligned pointer */
  98993. union { /* union needed to comply with C99 pointer aliasing rules */
  98994. unsigned *pa; /* aligned pointer */
  98995. void *pv; /* aligned pointer alias */
  98996. } u;
  98997. FLAC__ASSERT(elements > 0);
  98998. FLAC__ASSERT(0 != unaligned_pointer);
  98999. FLAC__ASSERT(0 != aligned_pointer);
  99000. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99001. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99002. if(0 == pu) {
  99003. return false;
  99004. }
  99005. else {
  99006. if(*unaligned_pointer != 0)
  99007. free(*unaligned_pointer);
  99008. *unaligned_pointer = pu;
  99009. *aligned_pointer = u.pa;
  99010. return true;
  99011. }
  99012. }
  99013. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99014. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99015. {
  99016. FLAC__real *pu; /* unaligned pointer */
  99017. union { /* union needed to comply with C99 pointer aliasing rules */
  99018. FLAC__real *pa; /* aligned pointer */
  99019. void *pv; /* aligned pointer alias */
  99020. } u;
  99021. FLAC__ASSERT(elements > 0);
  99022. FLAC__ASSERT(0 != unaligned_pointer);
  99023. FLAC__ASSERT(0 != aligned_pointer);
  99024. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99025. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99026. if(0 == pu) {
  99027. return false;
  99028. }
  99029. else {
  99030. if(*unaligned_pointer != 0)
  99031. free(*unaligned_pointer);
  99032. *unaligned_pointer = pu;
  99033. *aligned_pointer = u.pa;
  99034. return true;
  99035. }
  99036. }
  99037. #endif
  99038. #endif
  99039. /*** End of inlined file: memory.c ***/
  99040. /*** Start of inlined file: stream_decoder.c ***/
  99041. /*** Start of inlined file: juce_FlacHeader.h ***/
  99042. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99043. // tasks..
  99044. #define VERSION "1.2.1"
  99045. #define FLAC__NO_DLL 1
  99046. #if JUCE_MSVC
  99047. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99048. #endif
  99049. #if JUCE_MAC
  99050. #define FLAC__SYS_DARWIN 1
  99051. #endif
  99052. /*** End of inlined file: juce_FlacHeader.h ***/
  99053. #if JUCE_USE_FLAC
  99054. #if HAVE_CONFIG_H
  99055. # include <config.h>
  99056. #endif
  99057. #if defined _MSC_VER || defined __MINGW32__
  99058. #include <io.h> /* for _setmode() */
  99059. #include <fcntl.h> /* for _O_BINARY */
  99060. #endif
  99061. #if defined __CYGWIN__ || defined __EMX__
  99062. #include <io.h> /* for setmode(), O_BINARY */
  99063. #include <fcntl.h> /* for _O_BINARY */
  99064. #endif
  99065. #include <stdio.h>
  99066. #include <stdlib.h> /* for malloc() */
  99067. #include <string.h> /* for memset/memcpy() */
  99068. #include <sys/stat.h> /* for stat() */
  99069. #include <sys/types.h> /* for off_t */
  99070. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99071. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99072. #define fseeko fseek
  99073. #define ftello ftell
  99074. #endif
  99075. #endif
  99076. /*** Start of inlined file: stream_decoder.h ***/
  99077. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99078. #define FLAC__PROTECTED__STREAM_DECODER_H
  99079. #if FLAC__HAS_OGG
  99080. #include "include/private/ogg_decoder_aspect.h"
  99081. #endif
  99082. typedef struct FLAC__StreamDecoderProtected {
  99083. FLAC__StreamDecoderState state;
  99084. unsigned channels;
  99085. FLAC__ChannelAssignment channel_assignment;
  99086. unsigned bits_per_sample;
  99087. unsigned sample_rate; /* in Hz */
  99088. unsigned blocksize; /* in samples (per channel) */
  99089. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99090. #if FLAC__HAS_OGG
  99091. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99092. #endif
  99093. } FLAC__StreamDecoderProtected;
  99094. /*
  99095. * return the number of input bytes consumed
  99096. */
  99097. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99098. #endif
  99099. /*** End of inlined file: stream_decoder.h ***/
  99100. #ifdef max
  99101. #undef max
  99102. #endif
  99103. #define max(a,b) ((a)>(b)?(a):(b))
  99104. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99105. #ifdef _MSC_VER
  99106. #define FLAC__U64L(x) x
  99107. #else
  99108. #define FLAC__U64L(x) x##LLU
  99109. #endif
  99110. /* technically this should be in an "export.c" but this is convenient enough */
  99111. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99112. #if FLAC__HAS_OGG
  99113. 1
  99114. #else
  99115. 0
  99116. #endif
  99117. ;
  99118. /***********************************************************************
  99119. *
  99120. * Private static data
  99121. *
  99122. ***********************************************************************/
  99123. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99124. /***********************************************************************
  99125. *
  99126. * Private class method prototypes
  99127. *
  99128. ***********************************************************************/
  99129. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99130. static FILE *get_binary_stdin_(void);
  99131. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99132. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99133. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99134. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99135. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99136. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99137. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99138. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99139. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99140. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99141. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99142. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99143. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99144. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99145. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99146. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99147. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99148. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99149. 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);
  99150. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99151. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99152. #if FLAC__HAS_OGG
  99153. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99154. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99155. #endif
  99156. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99157. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99158. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99159. #if FLAC__HAS_OGG
  99160. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99161. #endif
  99162. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99163. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99164. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99165. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99166. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99167. /***********************************************************************
  99168. *
  99169. * Private class data
  99170. *
  99171. ***********************************************************************/
  99172. typedef struct FLAC__StreamDecoderPrivate {
  99173. #if FLAC__HAS_OGG
  99174. FLAC__bool is_ogg;
  99175. #endif
  99176. FLAC__StreamDecoderReadCallback read_callback;
  99177. FLAC__StreamDecoderSeekCallback seek_callback;
  99178. FLAC__StreamDecoderTellCallback tell_callback;
  99179. FLAC__StreamDecoderLengthCallback length_callback;
  99180. FLAC__StreamDecoderEofCallback eof_callback;
  99181. FLAC__StreamDecoderWriteCallback write_callback;
  99182. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99183. FLAC__StreamDecoderErrorCallback error_callback;
  99184. /* generic 32-bit datapath: */
  99185. 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[]);
  99186. /* generic 64-bit datapath: */
  99187. 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[]);
  99188. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99189. 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[]);
  99190. /* 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: */
  99191. 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[]);
  99192. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99193. void *client_data;
  99194. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99195. FLAC__BitReader *input;
  99196. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99197. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99198. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99199. unsigned output_capacity, output_channels;
  99200. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99201. FLAC__uint64 samples_decoded;
  99202. FLAC__bool has_stream_info, has_seek_table;
  99203. FLAC__StreamMetadata stream_info;
  99204. FLAC__StreamMetadata seek_table;
  99205. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99206. FLAC__byte *metadata_filter_ids;
  99207. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99208. FLAC__Frame frame;
  99209. FLAC__bool cached; /* true if there is a byte in lookahead */
  99210. FLAC__CPUInfo cpuinfo;
  99211. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99212. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99213. /* unaligned (original) pointers to allocated data */
  99214. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99215. 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 */
  99216. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99217. FLAC__bool is_seeking;
  99218. FLAC__MD5Context md5context;
  99219. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99220. /* (the rest of these are only used for seeking) */
  99221. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99222. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99223. FLAC__uint64 target_sample;
  99224. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99225. #if FLAC__HAS_OGG
  99226. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99227. #endif
  99228. } FLAC__StreamDecoderPrivate;
  99229. /***********************************************************************
  99230. *
  99231. * Public static class data
  99232. *
  99233. ***********************************************************************/
  99234. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99235. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99236. "FLAC__STREAM_DECODER_READ_METADATA",
  99237. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99238. "FLAC__STREAM_DECODER_READ_FRAME",
  99239. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99240. "FLAC__STREAM_DECODER_OGG_ERROR",
  99241. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99242. "FLAC__STREAM_DECODER_ABORTED",
  99243. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99244. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99245. };
  99246. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99247. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99248. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99249. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99250. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99251. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99252. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99253. };
  99254. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99255. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99256. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99257. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99258. };
  99259. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99260. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99261. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99262. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99263. };
  99264. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99265. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99266. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99267. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99268. };
  99269. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99270. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99271. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99272. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99273. };
  99274. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99275. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99276. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99277. };
  99278. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99279. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99280. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99281. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99282. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99283. };
  99284. /***********************************************************************
  99285. *
  99286. * Class constructor/destructor
  99287. *
  99288. ***********************************************************************/
  99289. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99290. {
  99291. FLAC__StreamDecoder *decoder;
  99292. unsigned i;
  99293. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99294. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99295. if(decoder == 0) {
  99296. return 0;
  99297. }
  99298. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99299. if(decoder->protected_ == 0) {
  99300. free(decoder);
  99301. return 0;
  99302. }
  99303. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99304. if(decoder->private_ == 0) {
  99305. free(decoder->protected_);
  99306. free(decoder);
  99307. return 0;
  99308. }
  99309. decoder->private_->input = FLAC__bitreader_new();
  99310. if(decoder->private_->input == 0) {
  99311. free(decoder->private_);
  99312. free(decoder->protected_);
  99313. free(decoder);
  99314. return 0;
  99315. }
  99316. decoder->private_->metadata_filter_ids_capacity = 16;
  99317. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99318. FLAC__bitreader_delete(decoder->private_->input);
  99319. free(decoder->private_);
  99320. free(decoder->protected_);
  99321. free(decoder);
  99322. return 0;
  99323. }
  99324. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99325. decoder->private_->output[i] = 0;
  99326. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99327. }
  99328. decoder->private_->output_capacity = 0;
  99329. decoder->private_->output_channels = 0;
  99330. decoder->private_->has_seek_table = false;
  99331. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99332. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99333. decoder->private_->file = 0;
  99334. set_defaults_dec(decoder);
  99335. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99336. return decoder;
  99337. }
  99338. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99339. {
  99340. unsigned i;
  99341. FLAC__ASSERT(0 != decoder);
  99342. FLAC__ASSERT(0 != decoder->protected_);
  99343. FLAC__ASSERT(0 != decoder->private_);
  99344. FLAC__ASSERT(0 != decoder->private_->input);
  99345. (void)FLAC__stream_decoder_finish(decoder);
  99346. if(0 != decoder->private_->metadata_filter_ids)
  99347. free(decoder->private_->metadata_filter_ids);
  99348. FLAC__bitreader_delete(decoder->private_->input);
  99349. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99350. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99351. free(decoder->private_);
  99352. free(decoder->protected_);
  99353. free(decoder);
  99354. }
  99355. /***********************************************************************
  99356. *
  99357. * Public class methods
  99358. *
  99359. ***********************************************************************/
  99360. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99361. FLAC__StreamDecoder *decoder,
  99362. FLAC__StreamDecoderReadCallback read_callback,
  99363. FLAC__StreamDecoderSeekCallback seek_callback,
  99364. FLAC__StreamDecoderTellCallback tell_callback,
  99365. FLAC__StreamDecoderLengthCallback length_callback,
  99366. FLAC__StreamDecoderEofCallback eof_callback,
  99367. FLAC__StreamDecoderWriteCallback write_callback,
  99368. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99369. FLAC__StreamDecoderErrorCallback error_callback,
  99370. void *client_data,
  99371. FLAC__bool is_ogg
  99372. )
  99373. {
  99374. FLAC__ASSERT(0 != decoder);
  99375. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99376. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99377. #if !FLAC__HAS_OGG
  99378. if(is_ogg)
  99379. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99380. #endif
  99381. if(
  99382. 0 == read_callback ||
  99383. 0 == write_callback ||
  99384. 0 == error_callback ||
  99385. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99386. )
  99387. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99388. #if FLAC__HAS_OGG
  99389. decoder->private_->is_ogg = is_ogg;
  99390. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99391. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99392. #endif
  99393. /*
  99394. * get the CPU info and set the function pointers
  99395. */
  99396. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99397. /* first default to the non-asm routines */
  99398. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99399. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99400. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99401. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99402. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99403. /* now override with asm where appropriate */
  99404. #ifndef FLAC__NO_ASM
  99405. if(decoder->private_->cpuinfo.use_asm) {
  99406. #ifdef FLAC__CPU_IA32
  99407. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99408. #ifdef FLAC__HAS_NASM
  99409. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99410. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99411. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99412. #endif
  99413. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99414. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99415. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99416. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99417. }
  99418. else {
  99419. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99420. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99421. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99422. }
  99423. #endif
  99424. #elif defined FLAC__CPU_PPC
  99425. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99426. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99427. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99428. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99429. }
  99430. #endif
  99431. }
  99432. #endif
  99433. /* from here on, errors are fatal */
  99434. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99435. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99436. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99437. }
  99438. decoder->private_->read_callback = read_callback;
  99439. decoder->private_->seek_callback = seek_callback;
  99440. decoder->private_->tell_callback = tell_callback;
  99441. decoder->private_->length_callback = length_callback;
  99442. decoder->private_->eof_callback = eof_callback;
  99443. decoder->private_->write_callback = write_callback;
  99444. decoder->private_->metadata_callback = metadata_callback;
  99445. decoder->private_->error_callback = error_callback;
  99446. decoder->private_->client_data = client_data;
  99447. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99448. decoder->private_->samples_decoded = 0;
  99449. decoder->private_->has_stream_info = false;
  99450. decoder->private_->cached = false;
  99451. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99452. decoder->private_->is_seeking = false;
  99453. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99454. if(!FLAC__stream_decoder_reset(decoder)) {
  99455. /* above call sets the state for us */
  99456. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99457. }
  99458. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99459. }
  99460. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99461. FLAC__StreamDecoder *decoder,
  99462. FLAC__StreamDecoderReadCallback read_callback,
  99463. FLAC__StreamDecoderSeekCallback seek_callback,
  99464. FLAC__StreamDecoderTellCallback tell_callback,
  99465. FLAC__StreamDecoderLengthCallback length_callback,
  99466. FLAC__StreamDecoderEofCallback eof_callback,
  99467. FLAC__StreamDecoderWriteCallback write_callback,
  99468. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99469. FLAC__StreamDecoderErrorCallback error_callback,
  99470. void *client_data
  99471. )
  99472. {
  99473. return init_stream_internal_dec(
  99474. decoder,
  99475. read_callback,
  99476. seek_callback,
  99477. tell_callback,
  99478. length_callback,
  99479. eof_callback,
  99480. write_callback,
  99481. metadata_callback,
  99482. error_callback,
  99483. client_data,
  99484. /*is_ogg=*/false
  99485. );
  99486. }
  99487. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99488. FLAC__StreamDecoder *decoder,
  99489. FLAC__StreamDecoderReadCallback read_callback,
  99490. FLAC__StreamDecoderSeekCallback seek_callback,
  99491. FLAC__StreamDecoderTellCallback tell_callback,
  99492. FLAC__StreamDecoderLengthCallback length_callback,
  99493. FLAC__StreamDecoderEofCallback eof_callback,
  99494. FLAC__StreamDecoderWriteCallback write_callback,
  99495. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99496. FLAC__StreamDecoderErrorCallback error_callback,
  99497. void *client_data
  99498. )
  99499. {
  99500. return init_stream_internal_dec(
  99501. decoder,
  99502. read_callback,
  99503. seek_callback,
  99504. tell_callback,
  99505. length_callback,
  99506. eof_callback,
  99507. write_callback,
  99508. metadata_callback,
  99509. error_callback,
  99510. client_data,
  99511. /*is_ogg=*/true
  99512. );
  99513. }
  99514. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99515. FLAC__StreamDecoder *decoder,
  99516. FILE *file,
  99517. FLAC__StreamDecoderWriteCallback write_callback,
  99518. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99519. FLAC__StreamDecoderErrorCallback error_callback,
  99520. void *client_data,
  99521. FLAC__bool is_ogg
  99522. )
  99523. {
  99524. FLAC__ASSERT(0 != decoder);
  99525. FLAC__ASSERT(0 != file);
  99526. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99527. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99528. if(0 == write_callback || 0 == error_callback)
  99529. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99530. /*
  99531. * To make sure that our file does not go unclosed after an error, we
  99532. * must assign the FILE pointer before any further error can occur in
  99533. * this routine.
  99534. */
  99535. if(file == stdin)
  99536. file = get_binary_stdin_(); /* just to be safe */
  99537. decoder->private_->file = file;
  99538. return init_stream_internal_dec(
  99539. decoder,
  99540. file_read_callback_dec,
  99541. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99542. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99543. decoder->private_->file == stdin? 0: file_length_callback_,
  99544. file_eof_callback_,
  99545. write_callback,
  99546. metadata_callback,
  99547. error_callback,
  99548. client_data,
  99549. is_ogg
  99550. );
  99551. }
  99552. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99553. FLAC__StreamDecoder *decoder,
  99554. FILE *file,
  99555. FLAC__StreamDecoderWriteCallback write_callback,
  99556. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99557. FLAC__StreamDecoderErrorCallback error_callback,
  99558. void *client_data
  99559. )
  99560. {
  99561. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99562. }
  99563. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99564. FLAC__StreamDecoder *decoder,
  99565. FILE *file,
  99566. FLAC__StreamDecoderWriteCallback write_callback,
  99567. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99568. FLAC__StreamDecoderErrorCallback error_callback,
  99569. void *client_data
  99570. )
  99571. {
  99572. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99573. }
  99574. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99575. FLAC__StreamDecoder *decoder,
  99576. const char *filename,
  99577. FLAC__StreamDecoderWriteCallback write_callback,
  99578. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99579. FLAC__StreamDecoderErrorCallback error_callback,
  99580. void *client_data,
  99581. FLAC__bool is_ogg
  99582. )
  99583. {
  99584. FILE *file;
  99585. FLAC__ASSERT(0 != decoder);
  99586. /*
  99587. * To make sure that our file does not go unclosed after an error, we
  99588. * have to do the same entrance checks here that are later performed
  99589. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99590. */
  99591. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99592. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99593. if(0 == write_callback || 0 == error_callback)
  99594. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99595. file = filename? fopen(filename, "rb") : stdin;
  99596. if(0 == file)
  99597. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99598. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99599. }
  99600. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99601. FLAC__StreamDecoder *decoder,
  99602. const char *filename,
  99603. FLAC__StreamDecoderWriteCallback write_callback,
  99604. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99605. FLAC__StreamDecoderErrorCallback error_callback,
  99606. void *client_data
  99607. )
  99608. {
  99609. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99610. }
  99611. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99612. FLAC__StreamDecoder *decoder,
  99613. const char *filename,
  99614. FLAC__StreamDecoderWriteCallback write_callback,
  99615. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99616. FLAC__StreamDecoderErrorCallback error_callback,
  99617. void *client_data
  99618. )
  99619. {
  99620. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99621. }
  99622. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99623. {
  99624. FLAC__bool md5_failed = false;
  99625. unsigned i;
  99626. FLAC__ASSERT(0 != decoder);
  99627. FLAC__ASSERT(0 != decoder->private_);
  99628. FLAC__ASSERT(0 != decoder->protected_);
  99629. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99630. return true;
  99631. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99632. * always call FLAC__MD5Final()
  99633. */
  99634. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99635. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99636. free(decoder->private_->seek_table.data.seek_table.points);
  99637. decoder->private_->seek_table.data.seek_table.points = 0;
  99638. decoder->private_->has_seek_table = false;
  99639. }
  99640. FLAC__bitreader_free(decoder->private_->input);
  99641. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99642. /* WATCHOUT:
  99643. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99644. * output arrays have a buffer of up to 3 zeroes in front
  99645. * (at negative indices) for alignment purposes; we use 4
  99646. * to keep the data well-aligned.
  99647. */
  99648. if(0 != decoder->private_->output[i]) {
  99649. free(decoder->private_->output[i]-4);
  99650. decoder->private_->output[i] = 0;
  99651. }
  99652. if(0 != decoder->private_->residual_unaligned[i]) {
  99653. free(decoder->private_->residual_unaligned[i]);
  99654. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99655. }
  99656. }
  99657. decoder->private_->output_capacity = 0;
  99658. decoder->private_->output_channels = 0;
  99659. #if FLAC__HAS_OGG
  99660. if(decoder->private_->is_ogg)
  99661. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99662. #endif
  99663. if(0 != decoder->private_->file) {
  99664. if(decoder->private_->file != stdin)
  99665. fclose(decoder->private_->file);
  99666. decoder->private_->file = 0;
  99667. }
  99668. if(decoder->private_->do_md5_checking) {
  99669. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99670. md5_failed = true;
  99671. }
  99672. decoder->private_->is_seeking = false;
  99673. set_defaults_dec(decoder);
  99674. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99675. return !md5_failed;
  99676. }
  99677. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99678. {
  99679. FLAC__ASSERT(0 != decoder);
  99680. FLAC__ASSERT(0 != decoder->private_);
  99681. FLAC__ASSERT(0 != decoder->protected_);
  99682. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99683. return false;
  99684. #if FLAC__HAS_OGG
  99685. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99686. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99687. return true;
  99688. #else
  99689. (void)value;
  99690. return false;
  99691. #endif
  99692. }
  99693. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99694. {
  99695. FLAC__ASSERT(0 != decoder);
  99696. FLAC__ASSERT(0 != decoder->protected_);
  99697. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99698. return false;
  99699. decoder->protected_->md5_checking = value;
  99700. return true;
  99701. }
  99702. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99703. {
  99704. FLAC__ASSERT(0 != decoder);
  99705. FLAC__ASSERT(0 != decoder->private_);
  99706. FLAC__ASSERT(0 != decoder->protected_);
  99707. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99708. /* double protection */
  99709. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99710. return false;
  99711. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99712. return false;
  99713. decoder->private_->metadata_filter[type] = true;
  99714. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99715. decoder->private_->metadata_filter_ids_count = 0;
  99716. return true;
  99717. }
  99718. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99719. {
  99720. FLAC__ASSERT(0 != decoder);
  99721. FLAC__ASSERT(0 != decoder->private_);
  99722. FLAC__ASSERT(0 != decoder->protected_);
  99723. FLAC__ASSERT(0 != id);
  99724. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99725. return false;
  99726. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99727. return true;
  99728. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99729. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99730. 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))) {
  99731. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99732. return false;
  99733. }
  99734. decoder->private_->metadata_filter_ids_capacity *= 2;
  99735. }
  99736. 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));
  99737. decoder->private_->metadata_filter_ids_count++;
  99738. return true;
  99739. }
  99740. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99741. {
  99742. unsigned i;
  99743. FLAC__ASSERT(0 != decoder);
  99744. FLAC__ASSERT(0 != decoder->private_);
  99745. FLAC__ASSERT(0 != decoder->protected_);
  99746. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99747. return false;
  99748. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99749. decoder->private_->metadata_filter[i] = true;
  99750. decoder->private_->metadata_filter_ids_count = 0;
  99751. return true;
  99752. }
  99753. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99754. {
  99755. FLAC__ASSERT(0 != decoder);
  99756. FLAC__ASSERT(0 != decoder->private_);
  99757. FLAC__ASSERT(0 != decoder->protected_);
  99758. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99759. /* double protection */
  99760. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99761. return false;
  99762. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99763. return false;
  99764. decoder->private_->metadata_filter[type] = false;
  99765. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99766. decoder->private_->metadata_filter_ids_count = 0;
  99767. return true;
  99768. }
  99769. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99770. {
  99771. FLAC__ASSERT(0 != decoder);
  99772. FLAC__ASSERT(0 != decoder->private_);
  99773. FLAC__ASSERT(0 != decoder->protected_);
  99774. FLAC__ASSERT(0 != id);
  99775. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99776. return false;
  99777. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99778. return true;
  99779. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99780. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99781. 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))) {
  99782. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99783. return false;
  99784. }
  99785. decoder->private_->metadata_filter_ids_capacity *= 2;
  99786. }
  99787. 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));
  99788. decoder->private_->metadata_filter_ids_count++;
  99789. return true;
  99790. }
  99791. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99792. {
  99793. FLAC__ASSERT(0 != decoder);
  99794. FLAC__ASSERT(0 != decoder->private_);
  99795. FLAC__ASSERT(0 != decoder->protected_);
  99796. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99797. return false;
  99798. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99799. decoder->private_->metadata_filter_ids_count = 0;
  99800. return true;
  99801. }
  99802. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99803. {
  99804. FLAC__ASSERT(0 != decoder);
  99805. FLAC__ASSERT(0 != decoder->protected_);
  99806. return decoder->protected_->state;
  99807. }
  99808. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99809. {
  99810. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99811. }
  99812. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99813. {
  99814. FLAC__ASSERT(0 != decoder);
  99815. FLAC__ASSERT(0 != decoder->protected_);
  99816. return decoder->protected_->md5_checking;
  99817. }
  99818. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99819. {
  99820. FLAC__ASSERT(0 != decoder);
  99821. FLAC__ASSERT(0 != decoder->protected_);
  99822. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99823. }
  99824. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99825. {
  99826. FLAC__ASSERT(0 != decoder);
  99827. FLAC__ASSERT(0 != decoder->protected_);
  99828. return decoder->protected_->channels;
  99829. }
  99830. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99831. {
  99832. FLAC__ASSERT(0 != decoder);
  99833. FLAC__ASSERT(0 != decoder->protected_);
  99834. return decoder->protected_->channel_assignment;
  99835. }
  99836. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99837. {
  99838. FLAC__ASSERT(0 != decoder);
  99839. FLAC__ASSERT(0 != decoder->protected_);
  99840. return decoder->protected_->bits_per_sample;
  99841. }
  99842. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99843. {
  99844. FLAC__ASSERT(0 != decoder);
  99845. FLAC__ASSERT(0 != decoder->protected_);
  99846. return decoder->protected_->sample_rate;
  99847. }
  99848. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99849. {
  99850. FLAC__ASSERT(0 != decoder);
  99851. FLAC__ASSERT(0 != decoder->protected_);
  99852. return decoder->protected_->blocksize;
  99853. }
  99854. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99855. {
  99856. FLAC__ASSERT(0 != decoder);
  99857. FLAC__ASSERT(0 != decoder->private_);
  99858. FLAC__ASSERT(0 != position);
  99859. #if FLAC__HAS_OGG
  99860. if(decoder->private_->is_ogg)
  99861. return false;
  99862. #endif
  99863. if(0 == decoder->private_->tell_callback)
  99864. return false;
  99865. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99866. return false;
  99867. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99868. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99869. return false;
  99870. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99871. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99872. return true;
  99873. }
  99874. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99875. {
  99876. FLAC__ASSERT(0 != decoder);
  99877. FLAC__ASSERT(0 != decoder->private_);
  99878. FLAC__ASSERT(0 != decoder->protected_);
  99879. decoder->private_->samples_decoded = 0;
  99880. decoder->private_->do_md5_checking = false;
  99881. #if FLAC__HAS_OGG
  99882. if(decoder->private_->is_ogg)
  99883. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99884. #endif
  99885. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99886. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99887. return false;
  99888. }
  99889. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99890. return true;
  99891. }
  99892. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99893. {
  99894. FLAC__ASSERT(0 != decoder);
  99895. FLAC__ASSERT(0 != decoder->private_);
  99896. FLAC__ASSERT(0 != decoder->protected_);
  99897. if(!FLAC__stream_decoder_flush(decoder)) {
  99898. /* above call sets the state for us */
  99899. return false;
  99900. }
  99901. #if FLAC__HAS_OGG
  99902. /*@@@ could go in !internal_reset_hack block below */
  99903. if(decoder->private_->is_ogg)
  99904. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99905. #endif
  99906. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99907. * (internal_reset_hack) don't try to rewind since we are already at
  99908. * the beginning of the stream and don't want to fail if the input is
  99909. * not seekable.
  99910. */
  99911. if(!decoder->private_->internal_reset_hack) {
  99912. if(decoder->private_->file == stdin)
  99913. return false; /* can't rewind stdin, reset fails */
  99914. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99915. return false; /* seekable and seek fails, reset fails */
  99916. }
  99917. else
  99918. decoder->private_->internal_reset_hack = false;
  99919. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99920. decoder->private_->has_stream_info = false;
  99921. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99922. free(decoder->private_->seek_table.data.seek_table.points);
  99923. decoder->private_->seek_table.data.seek_table.points = 0;
  99924. decoder->private_->has_seek_table = false;
  99925. }
  99926. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99927. /*
  99928. * This goes in reset() and not flush() because according to the spec, a
  99929. * fixed-blocksize stream must stay that way through the whole stream.
  99930. */
  99931. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99932. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99933. * is because md5 checking may be turned on to start and then turned off if
  99934. * a seek occurs. So we init the context here and finalize it in
  99935. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99936. * properly.
  99937. */
  99938. FLAC__MD5Init(&decoder->private_->md5context);
  99939. decoder->private_->first_frame_offset = 0;
  99940. decoder->private_->unparseable_frame_count = 0;
  99941. return true;
  99942. }
  99943. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99944. {
  99945. FLAC__bool got_a_frame;
  99946. FLAC__ASSERT(0 != decoder);
  99947. FLAC__ASSERT(0 != decoder->protected_);
  99948. while(1) {
  99949. switch(decoder->protected_->state) {
  99950. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99951. if(!find_metadata_(decoder))
  99952. return false; /* above function sets the status for us */
  99953. break;
  99954. case FLAC__STREAM_DECODER_READ_METADATA:
  99955. if(!read_metadata_(decoder))
  99956. return false; /* above function sets the status for us */
  99957. else
  99958. return true;
  99959. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99960. if(!frame_sync_(decoder))
  99961. return true; /* above function sets the status for us */
  99962. break;
  99963. case FLAC__STREAM_DECODER_READ_FRAME:
  99964. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99965. return false; /* above function sets the status for us */
  99966. if(got_a_frame)
  99967. return true; /* above function sets the status for us */
  99968. break;
  99969. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99970. case FLAC__STREAM_DECODER_ABORTED:
  99971. return true;
  99972. default:
  99973. FLAC__ASSERT(0);
  99974. return false;
  99975. }
  99976. }
  99977. }
  99978. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99979. {
  99980. FLAC__ASSERT(0 != decoder);
  99981. FLAC__ASSERT(0 != decoder->protected_);
  99982. while(1) {
  99983. switch(decoder->protected_->state) {
  99984. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99985. if(!find_metadata_(decoder))
  99986. return false; /* above function sets the status for us */
  99987. break;
  99988. case FLAC__STREAM_DECODER_READ_METADATA:
  99989. if(!read_metadata_(decoder))
  99990. return false; /* above function sets the status for us */
  99991. break;
  99992. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99993. case FLAC__STREAM_DECODER_READ_FRAME:
  99994. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99995. case FLAC__STREAM_DECODER_ABORTED:
  99996. return true;
  99997. default:
  99998. FLAC__ASSERT(0);
  99999. return false;
  100000. }
  100001. }
  100002. }
  100003. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100004. {
  100005. FLAC__bool dummy;
  100006. FLAC__ASSERT(0 != decoder);
  100007. FLAC__ASSERT(0 != decoder->protected_);
  100008. while(1) {
  100009. switch(decoder->protected_->state) {
  100010. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100011. if(!find_metadata_(decoder))
  100012. return false; /* above function sets the status for us */
  100013. break;
  100014. case FLAC__STREAM_DECODER_READ_METADATA:
  100015. if(!read_metadata_(decoder))
  100016. return false; /* above function sets the status for us */
  100017. break;
  100018. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100019. if(!frame_sync_(decoder))
  100020. return true; /* above function sets the status for us */
  100021. break;
  100022. case FLAC__STREAM_DECODER_READ_FRAME:
  100023. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100024. return false; /* above function sets the status for us */
  100025. break;
  100026. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100027. case FLAC__STREAM_DECODER_ABORTED:
  100028. return true;
  100029. default:
  100030. FLAC__ASSERT(0);
  100031. return false;
  100032. }
  100033. }
  100034. }
  100035. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100036. {
  100037. FLAC__bool got_a_frame;
  100038. FLAC__ASSERT(0 != decoder);
  100039. FLAC__ASSERT(0 != decoder->protected_);
  100040. while(1) {
  100041. switch(decoder->protected_->state) {
  100042. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100043. case FLAC__STREAM_DECODER_READ_METADATA:
  100044. return false; /* above function sets the status for us */
  100045. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100046. if(!frame_sync_(decoder))
  100047. return true; /* above function sets the status for us */
  100048. break;
  100049. case FLAC__STREAM_DECODER_READ_FRAME:
  100050. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100051. return false; /* above function sets the status for us */
  100052. if(got_a_frame)
  100053. return true; /* above function sets the status for us */
  100054. break;
  100055. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100056. case FLAC__STREAM_DECODER_ABORTED:
  100057. return true;
  100058. default:
  100059. FLAC__ASSERT(0);
  100060. return false;
  100061. }
  100062. }
  100063. }
  100064. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100065. {
  100066. FLAC__uint64 length;
  100067. FLAC__ASSERT(0 != decoder);
  100068. if(
  100069. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100070. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100071. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100072. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100073. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100074. )
  100075. return false;
  100076. if(0 == decoder->private_->seek_callback)
  100077. return false;
  100078. FLAC__ASSERT(decoder->private_->seek_callback);
  100079. FLAC__ASSERT(decoder->private_->tell_callback);
  100080. FLAC__ASSERT(decoder->private_->length_callback);
  100081. FLAC__ASSERT(decoder->private_->eof_callback);
  100082. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100083. return false;
  100084. decoder->private_->is_seeking = true;
  100085. /* turn off md5 checking if a seek is attempted */
  100086. decoder->private_->do_md5_checking = false;
  100087. /* 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) */
  100088. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100089. decoder->private_->is_seeking = false;
  100090. return false;
  100091. }
  100092. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100093. if(
  100094. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100095. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100096. ) {
  100097. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100098. /* above call sets the state for us */
  100099. decoder->private_->is_seeking = false;
  100100. return false;
  100101. }
  100102. /* check this again in case we didn't know total_samples the first time */
  100103. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100104. decoder->private_->is_seeking = false;
  100105. return false;
  100106. }
  100107. }
  100108. {
  100109. const FLAC__bool ok =
  100110. #if FLAC__HAS_OGG
  100111. decoder->private_->is_ogg?
  100112. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100113. #endif
  100114. seek_to_absolute_sample_(decoder, length, sample)
  100115. ;
  100116. decoder->private_->is_seeking = false;
  100117. return ok;
  100118. }
  100119. }
  100120. /***********************************************************************
  100121. *
  100122. * Protected class methods
  100123. *
  100124. ***********************************************************************/
  100125. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100126. {
  100127. FLAC__ASSERT(0 != decoder);
  100128. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100129. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100130. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100131. }
  100132. /***********************************************************************
  100133. *
  100134. * Private class methods
  100135. *
  100136. ***********************************************************************/
  100137. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100138. {
  100139. #if FLAC__HAS_OGG
  100140. decoder->private_->is_ogg = false;
  100141. #endif
  100142. decoder->private_->read_callback = 0;
  100143. decoder->private_->seek_callback = 0;
  100144. decoder->private_->tell_callback = 0;
  100145. decoder->private_->length_callback = 0;
  100146. decoder->private_->eof_callback = 0;
  100147. decoder->private_->write_callback = 0;
  100148. decoder->private_->metadata_callback = 0;
  100149. decoder->private_->error_callback = 0;
  100150. decoder->private_->client_data = 0;
  100151. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100152. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100153. decoder->private_->metadata_filter_ids_count = 0;
  100154. decoder->protected_->md5_checking = false;
  100155. #if FLAC__HAS_OGG
  100156. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100157. #endif
  100158. }
  100159. /*
  100160. * This will forcibly set stdin to binary mode (for OSes that require it)
  100161. */
  100162. FILE *get_binary_stdin_(void)
  100163. {
  100164. /* if something breaks here it is probably due to the presence or
  100165. * absence of an underscore before the identifiers 'setmode',
  100166. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100167. */
  100168. #if defined _MSC_VER || defined __MINGW32__
  100169. _setmode(_fileno(stdin), _O_BINARY);
  100170. #elif defined __CYGWIN__
  100171. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100172. setmode(_fileno(stdin), _O_BINARY);
  100173. #elif defined __EMX__
  100174. setmode(fileno(stdin), O_BINARY);
  100175. #endif
  100176. return stdin;
  100177. }
  100178. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100179. {
  100180. unsigned i;
  100181. FLAC__int32 *tmp;
  100182. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100183. return true;
  100184. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100185. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100186. if(0 != decoder->private_->output[i]) {
  100187. free(decoder->private_->output[i]-4);
  100188. decoder->private_->output[i] = 0;
  100189. }
  100190. if(0 != decoder->private_->residual_unaligned[i]) {
  100191. free(decoder->private_->residual_unaligned[i]);
  100192. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100193. }
  100194. }
  100195. for(i = 0; i < channels; i++) {
  100196. /* WATCHOUT:
  100197. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100198. * output arrays have a buffer of up to 3 zeroes in front
  100199. * (at negative indices) for alignment purposes; we use 4
  100200. * to keep the data well-aligned.
  100201. */
  100202. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100203. if(tmp == 0) {
  100204. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100205. return false;
  100206. }
  100207. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100208. decoder->private_->output[i] = tmp + 4;
  100209. /* WATCHOUT:
  100210. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100211. */
  100212. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100213. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100214. return false;
  100215. }
  100216. }
  100217. decoder->private_->output_capacity = size;
  100218. decoder->private_->output_channels = channels;
  100219. return true;
  100220. }
  100221. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100222. {
  100223. size_t i;
  100224. FLAC__ASSERT(0 != decoder);
  100225. FLAC__ASSERT(0 != decoder->private_);
  100226. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100227. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100228. return true;
  100229. return false;
  100230. }
  100231. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100232. {
  100233. FLAC__uint32 x;
  100234. unsigned i, id_;
  100235. FLAC__bool first = true;
  100236. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100237. for(i = id_ = 0; i < 4; ) {
  100238. if(decoder->private_->cached) {
  100239. x = (FLAC__uint32)decoder->private_->lookahead;
  100240. decoder->private_->cached = false;
  100241. }
  100242. else {
  100243. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100244. return false; /* read_callback_ sets the state for us */
  100245. }
  100246. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100247. first = true;
  100248. i++;
  100249. id_ = 0;
  100250. continue;
  100251. }
  100252. if(x == ID3V2_TAG_[id_]) {
  100253. id_++;
  100254. i = 0;
  100255. if(id_ == 3) {
  100256. if(!skip_id3v2_tag_(decoder))
  100257. return false; /* skip_id3v2_tag_ sets the state for us */
  100258. }
  100259. continue;
  100260. }
  100261. id_ = 0;
  100262. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100263. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100264. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100265. return false; /* read_callback_ sets the state for us */
  100266. /* 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 */
  100267. /* else we have to check if the second byte is the end of a sync code */
  100268. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100269. decoder->private_->lookahead = (FLAC__byte)x;
  100270. decoder->private_->cached = true;
  100271. }
  100272. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100273. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100274. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100275. return true;
  100276. }
  100277. }
  100278. i = 0;
  100279. if(first) {
  100280. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100281. first = false;
  100282. }
  100283. }
  100284. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100285. return true;
  100286. }
  100287. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100288. {
  100289. FLAC__bool is_last;
  100290. FLAC__uint32 i, x, type, length;
  100291. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100292. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100293. return false; /* read_callback_ sets the state for us */
  100294. is_last = x? true : false;
  100295. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100296. return false; /* read_callback_ sets the state for us */
  100297. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100298. return false; /* read_callback_ sets the state for us */
  100299. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100300. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100301. return false;
  100302. decoder->private_->has_stream_info = true;
  100303. 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))
  100304. decoder->private_->do_md5_checking = false;
  100305. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100306. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100307. }
  100308. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100309. if(!read_metadata_seektable_(decoder, is_last, length))
  100310. return false;
  100311. decoder->private_->has_seek_table = true;
  100312. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100313. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100314. }
  100315. else {
  100316. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100317. unsigned real_length = length;
  100318. FLAC__StreamMetadata block;
  100319. block.is_last = is_last;
  100320. block.type = (FLAC__MetadataType)type;
  100321. block.length = length;
  100322. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100323. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100324. return false; /* read_callback_ sets the state for us */
  100325. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100326. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100327. return false;
  100328. }
  100329. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100330. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100331. skip_it = !skip_it;
  100332. }
  100333. if(skip_it) {
  100334. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100335. return false; /* read_callback_ sets the state for us */
  100336. }
  100337. else {
  100338. switch(type) {
  100339. case FLAC__METADATA_TYPE_PADDING:
  100340. /* skip the padding bytes */
  100341. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100342. return false; /* read_callback_ sets the state for us */
  100343. break;
  100344. case FLAC__METADATA_TYPE_APPLICATION:
  100345. /* remember, we read the ID already */
  100346. if(real_length > 0) {
  100347. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100348. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100349. return false;
  100350. }
  100351. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100352. return false; /* read_callback_ sets the state for us */
  100353. }
  100354. else
  100355. block.data.application.data = 0;
  100356. break;
  100357. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100358. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100359. return false;
  100360. break;
  100361. case FLAC__METADATA_TYPE_CUESHEET:
  100362. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100363. return false;
  100364. break;
  100365. case FLAC__METADATA_TYPE_PICTURE:
  100366. if(!read_metadata_picture_(decoder, &block.data.picture))
  100367. return false;
  100368. break;
  100369. case FLAC__METADATA_TYPE_STREAMINFO:
  100370. case FLAC__METADATA_TYPE_SEEKTABLE:
  100371. FLAC__ASSERT(0);
  100372. break;
  100373. default:
  100374. if(real_length > 0) {
  100375. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100376. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100377. return false;
  100378. }
  100379. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100380. return false; /* read_callback_ sets the state for us */
  100381. }
  100382. else
  100383. block.data.unknown.data = 0;
  100384. break;
  100385. }
  100386. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100387. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100388. /* now we have to free any malloc()ed data in the block */
  100389. switch(type) {
  100390. case FLAC__METADATA_TYPE_PADDING:
  100391. break;
  100392. case FLAC__METADATA_TYPE_APPLICATION:
  100393. if(0 != block.data.application.data)
  100394. free(block.data.application.data);
  100395. break;
  100396. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100397. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100398. free(block.data.vorbis_comment.vendor_string.entry);
  100399. if(block.data.vorbis_comment.num_comments > 0)
  100400. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100401. if(0 != block.data.vorbis_comment.comments[i].entry)
  100402. free(block.data.vorbis_comment.comments[i].entry);
  100403. if(0 != block.data.vorbis_comment.comments)
  100404. free(block.data.vorbis_comment.comments);
  100405. break;
  100406. case FLAC__METADATA_TYPE_CUESHEET:
  100407. if(block.data.cue_sheet.num_tracks > 0)
  100408. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100409. if(0 != block.data.cue_sheet.tracks[i].indices)
  100410. free(block.data.cue_sheet.tracks[i].indices);
  100411. if(0 != block.data.cue_sheet.tracks)
  100412. free(block.data.cue_sheet.tracks);
  100413. break;
  100414. case FLAC__METADATA_TYPE_PICTURE:
  100415. if(0 != block.data.picture.mime_type)
  100416. free(block.data.picture.mime_type);
  100417. if(0 != block.data.picture.description)
  100418. free(block.data.picture.description);
  100419. if(0 != block.data.picture.data)
  100420. free(block.data.picture.data);
  100421. break;
  100422. case FLAC__METADATA_TYPE_STREAMINFO:
  100423. case FLAC__METADATA_TYPE_SEEKTABLE:
  100424. FLAC__ASSERT(0);
  100425. default:
  100426. if(0 != block.data.unknown.data)
  100427. free(block.data.unknown.data);
  100428. break;
  100429. }
  100430. }
  100431. }
  100432. if(is_last) {
  100433. /* if this fails, it's OK, it's just a hint for the seek routine */
  100434. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100435. decoder->private_->first_frame_offset = 0;
  100436. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100437. }
  100438. return true;
  100439. }
  100440. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100441. {
  100442. FLAC__uint32 x;
  100443. unsigned bits, used_bits = 0;
  100444. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100445. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100446. decoder->private_->stream_info.is_last = is_last;
  100447. decoder->private_->stream_info.length = length;
  100448. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100449. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100450. return false; /* read_callback_ sets the state for us */
  100451. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100452. used_bits += bits;
  100453. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100454. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100455. return false; /* read_callback_ sets the state for us */
  100456. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100457. used_bits += bits;
  100458. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100459. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100460. return false; /* read_callback_ sets the state for us */
  100461. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100462. used_bits += bits;
  100463. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100464. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100465. return false; /* read_callback_ sets the state for us */
  100466. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100467. used_bits += bits;
  100468. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100469. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100470. return false; /* read_callback_ sets the state for us */
  100471. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100472. used_bits += bits;
  100473. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100474. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100475. return false; /* read_callback_ sets the state for us */
  100476. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100477. used_bits += bits;
  100478. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100479. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100480. return false; /* read_callback_ sets the state for us */
  100481. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100482. used_bits += bits;
  100483. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100484. 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))
  100485. return false; /* read_callback_ sets the state for us */
  100486. used_bits += bits;
  100487. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100488. return false; /* read_callback_ sets the state for us */
  100489. used_bits += 16*8;
  100490. /* skip the rest of the block */
  100491. FLAC__ASSERT(used_bits % 8 == 0);
  100492. length -= (used_bits / 8);
  100493. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100494. return false; /* read_callback_ sets the state for us */
  100495. return true;
  100496. }
  100497. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100498. {
  100499. FLAC__uint32 i, x;
  100500. FLAC__uint64 xx;
  100501. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100502. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100503. decoder->private_->seek_table.is_last = is_last;
  100504. decoder->private_->seek_table.length = length;
  100505. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100506. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100507. 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)))) {
  100508. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100509. return false;
  100510. }
  100511. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100512. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100513. return false; /* read_callback_ sets the state for us */
  100514. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100515. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100516. return false; /* read_callback_ sets the state for us */
  100517. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100519. return false; /* read_callback_ sets the state for us */
  100520. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100521. }
  100522. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100523. /* if there is a partial point left, skip over it */
  100524. if(length > 0) {
  100525. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100526. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100527. return false; /* read_callback_ sets the state for us */
  100528. }
  100529. return true;
  100530. }
  100531. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100532. {
  100533. FLAC__uint32 i;
  100534. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100535. /* read vendor string */
  100536. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100537. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100538. return false; /* read_callback_ sets the state for us */
  100539. if(obj->vendor_string.length > 0) {
  100540. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100541. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100542. return false;
  100543. }
  100544. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100545. return false; /* read_callback_ sets the state for us */
  100546. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100547. }
  100548. else
  100549. obj->vendor_string.entry = 0;
  100550. /* read num comments */
  100551. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100552. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100553. return false; /* read_callback_ sets the state for us */
  100554. /* read comments */
  100555. if(obj->num_comments > 0) {
  100556. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100557. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100558. return false;
  100559. }
  100560. for(i = 0; i < obj->num_comments; i++) {
  100561. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100562. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100563. return false; /* read_callback_ sets the state for us */
  100564. if(obj->comments[i].length > 0) {
  100565. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100566. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100567. return false;
  100568. }
  100569. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100570. return false; /* read_callback_ sets the state for us */
  100571. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100572. }
  100573. else
  100574. obj->comments[i].entry = 0;
  100575. }
  100576. }
  100577. else {
  100578. obj->comments = 0;
  100579. }
  100580. return true;
  100581. }
  100582. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100583. {
  100584. FLAC__uint32 i, j, x;
  100585. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100586. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100587. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100588. 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))
  100589. return false; /* read_callback_ sets the state for us */
  100590. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100591. return false; /* read_callback_ sets the state for us */
  100592. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100593. return false; /* read_callback_ sets the state for us */
  100594. obj->is_cd = x? true : false;
  100595. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100596. return false; /* read_callback_ sets the state for us */
  100597. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100598. return false; /* read_callback_ sets the state for us */
  100599. obj->num_tracks = x;
  100600. if(obj->num_tracks > 0) {
  100601. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100602. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100603. return false;
  100604. }
  100605. for(i = 0; i < obj->num_tracks; i++) {
  100606. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100607. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_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_TRACK_NUMBER_LEN))
  100610. return false; /* read_callback_ sets the state for us */
  100611. track->number = (FLAC__byte)x;
  100612. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100613. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100614. return false; /* read_callback_ sets the state for us */
  100615. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100616. return false; /* read_callback_ sets the state for us */
  100617. track->type = x;
  100618. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100619. return false; /* read_callback_ sets the state for us */
  100620. track->pre_emphasis = x;
  100621. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100622. return false; /* read_callback_ sets the state for us */
  100623. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100624. return false; /* read_callback_ sets the state for us */
  100625. track->num_indices = (FLAC__byte)x;
  100626. if(track->num_indices > 0) {
  100627. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100628. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100629. return false;
  100630. }
  100631. for(j = 0; j < track->num_indices; j++) {
  100632. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100633. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100634. return false; /* read_callback_ sets the state for us */
  100635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100636. return false; /* read_callback_ sets the state for us */
  100637. index->number = (FLAC__byte)x;
  100638. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100639. return false; /* read_callback_ sets the state for us */
  100640. }
  100641. }
  100642. }
  100643. }
  100644. return true;
  100645. }
  100646. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100647. {
  100648. FLAC__uint32 x;
  100649. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100650. /* read type */
  100651. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100652. return false; /* read_callback_ sets the state for us */
  100653. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100654. /* read MIME type */
  100655. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100656. return false; /* read_callback_ sets the state for us */
  100657. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100658. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100659. return false;
  100660. }
  100661. if(x > 0) {
  100662. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100663. return false; /* read_callback_ sets the state for us */
  100664. }
  100665. obj->mime_type[x] = '\0';
  100666. /* read description */
  100667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100668. return false; /* read_callback_ sets the state for us */
  100669. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100670. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100671. return false;
  100672. }
  100673. if(x > 0) {
  100674. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100675. return false; /* read_callback_ sets the state for us */
  100676. }
  100677. obj->description[x] = '\0';
  100678. /* read width */
  100679. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100680. return false; /* read_callback_ sets the state for us */
  100681. /* read height */
  100682. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100683. return false; /* read_callback_ sets the state for us */
  100684. /* read depth */
  100685. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100686. return false; /* read_callback_ sets the state for us */
  100687. /* read colors */
  100688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100689. return false; /* read_callback_ sets the state for us */
  100690. /* read data */
  100691. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100692. return false; /* read_callback_ sets the state for us */
  100693. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100694. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100695. return false;
  100696. }
  100697. if(obj->data_length > 0) {
  100698. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100699. return false; /* read_callback_ sets the state for us */
  100700. }
  100701. return true;
  100702. }
  100703. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100704. {
  100705. FLAC__uint32 x;
  100706. unsigned i, skip;
  100707. /* skip the version and flags bytes */
  100708. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100709. return false; /* read_callback_ sets the state for us */
  100710. /* get the size (in bytes) to skip */
  100711. skip = 0;
  100712. for(i = 0; i < 4; i++) {
  100713. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100714. return false; /* read_callback_ sets the state for us */
  100715. skip <<= 7;
  100716. skip |= (x & 0x7f);
  100717. }
  100718. /* skip the rest of the tag */
  100719. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100720. return false; /* read_callback_ sets the state for us */
  100721. return true;
  100722. }
  100723. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100724. {
  100725. FLAC__uint32 x;
  100726. FLAC__bool first = true;
  100727. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100728. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100729. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100730. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100731. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100732. return true;
  100733. }
  100734. }
  100735. /* make sure we're byte aligned */
  100736. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100737. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100738. return false; /* read_callback_ sets the state for us */
  100739. }
  100740. while(1) {
  100741. if(decoder->private_->cached) {
  100742. x = (FLAC__uint32)decoder->private_->lookahead;
  100743. decoder->private_->cached = false;
  100744. }
  100745. else {
  100746. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100747. return false; /* read_callback_ sets the state for us */
  100748. }
  100749. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100750. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100751. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100752. return false; /* read_callback_ sets the state for us */
  100753. /* 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 */
  100754. /* else we have to check if the second byte is the end of a sync code */
  100755. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100756. decoder->private_->lookahead = (FLAC__byte)x;
  100757. decoder->private_->cached = true;
  100758. }
  100759. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100760. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100761. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100762. return true;
  100763. }
  100764. }
  100765. if(first) {
  100766. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100767. first = false;
  100768. }
  100769. }
  100770. return true;
  100771. }
  100772. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100773. {
  100774. unsigned channel;
  100775. unsigned i;
  100776. FLAC__int32 mid, side;
  100777. unsigned frame_crc; /* the one we calculate from the input stream */
  100778. FLAC__uint32 x;
  100779. *got_a_frame = false;
  100780. /* init the CRC */
  100781. frame_crc = 0;
  100782. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100783. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100784. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100785. if(!read_frame_header_(decoder))
  100786. return false;
  100787. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100788. return true;
  100789. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100790. return false;
  100791. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100792. /*
  100793. * first figure the correct bits-per-sample of the subframe
  100794. */
  100795. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100796. switch(decoder->private_->frame.header.channel_assignment) {
  100797. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100798. /* no adjustment needed */
  100799. break;
  100800. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100801. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100802. if(channel == 1)
  100803. bps++;
  100804. break;
  100805. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100806. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100807. if(channel == 0)
  100808. bps++;
  100809. break;
  100810. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100811. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100812. if(channel == 1)
  100813. bps++;
  100814. break;
  100815. default:
  100816. FLAC__ASSERT(0);
  100817. }
  100818. /*
  100819. * now read it
  100820. */
  100821. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100822. return false;
  100823. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100824. return true;
  100825. }
  100826. if(!read_zero_padding_(decoder))
  100827. return false;
  100828. 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) */
  100829. return true;
  100830. /*
  100831. * Read the frame CRC-16 from the footer and check
  100832. */
  100833. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100834. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100835. return false; /* read_callback_ sets the state for us */
  100836. if(frame_crc == x) {
  100837. if(do_full_decode) {
  100838. /* Undo any special channel coding */
  100839. switch(decoder->private_->frame.header.channel_assignment) {
  100840. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100841. /* do nothing */
  100842. break;
  100843. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100844. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100845. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100846. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100847. break;
  100848. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100849. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100850. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100851. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100852. break;
  100853. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100854. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100855. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100856. #if 1
  100857. mid = decoder->private_->output[0][i];
  100858. side = decoder->private_->output[1][i];
  100859. mid <<= 1;
  100860. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100861. decoder->private_->output[0][i] = (mid + side) >> 1;
  100862. decoder->private_->output[1][i] = (mid - side) >> 1;
  100863. #else
  100864. /* OPT: without 'side' temp variable */
  100865. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100866. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100867. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100868. #endif
  100869. }
  100870. break;
  100871. default:
  100872. FLAC__ASSERT(0);
  100873. break;
  100874. }
  100875. }
  100876. }
  100877. else {
  100878. /* Bad frame, emit error and zero the output signal */
  100879. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100880. if(do_full_decode) {
  100881. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100882. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100883. }
  100884. }
  100885. }
  100886. *got_a_frame = true;
  100887. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100888. if(decoder->private_->next_fixed_block_size)
  100889. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100890. /* put the latest values into the public section of the decoder instance */
  100891. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100892. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100893. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100894. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100895. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100896. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100897. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100898. /* write it */
  100899. if(do_full_decode) {
  100900. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100901. return false;
  100902. }
  100903. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100904. return true;
  100905. }
  100906. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100907. {
  100908. FLAC__uint32 x;
  100909. FLAC__uint64 xx;
  100910. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100911. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100912. unsigned raw_header_len;
  100913. FLAC__bool is_unparseable = false;
  100914. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100915. /* init the raw header with the saved bits from synchronization */
  100916. raw_header[0] = decoder->private_->header_warmup[0];
  100917. raw_header[1] = decoder->private_->header_warmup[1];
  100918. raw_header_len = 2;
  100919. /* check to make sure that reserved bit is 0 */
  100920. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100921. is_unparseable = true;
  100922. /*
  100923. * Note that along the way as we read the header, we look for a sync
  100924. * code inside. If we find one it would indicate that our original
  100925. * sync was bad since there cannot be a sync code in a valid header.
  100926. *
  100927. * Three kinds of things can go wrong when reading the frame header:
  100928. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100929. * If we don't find a sync code, it can end up looking like we read
  100930. * a valid but unparseable header, until getting to the frame header
  100931. * CRC. Even then we could get a false positive on the CRC.
  100932. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100933. * future encoder).
  100934. * 3) We may be on a damaged frame which appears valid but unparseable.
  100935. *
  100936. * For all these reasons, we try and read a complete frame header as
  100937. * long as it seems valid, even if unparseable, up until the frame
  100938. * header CRC.
  100939. */
  100940. /*
  100941. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100942. */
  100943. for(i = 0; i < 2; i++) {
  100944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100945. return false; /* read_callback_ sets the state for us */
  100946. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100947. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100948. decoder->private_->lookahead = (FLAC__byte)x;
  100949. decoder->private_->cached = true;
  100950. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100951. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100952. return true;
  100953. }
  100954. raw_header[raw_header_len++] = (FLAC__byte)x;
  100955. }
  100956. switch(x = raw_header[2] >> 4) {
  100957. case 0:
  100958. is_unparseable = true;
  100959. break;
  100960. case 1:
  100961. decoder->private_->frame.header.blocksize = 192;
  100962. break;
  100963. case 2:
  100964. case 3:
  100965. case 4:
  100966. case 5:
  100967. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100968. break;
  100969. case 6:
  100970. case 7:
  100971. blocksize_hint = x;
  100972. break;
  100973. case 8:
  100974. case 9:
  100975. case 10:
  100976. case 11:
  100977. case 12:
  100978. case 13:
  100979. case 14:
  100980. case 15:
  100981. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100982. break;
  100983. default:
  100984. FLAC__ASSERT(0);
  100985. break;
  100986. }
  100987. switch(x = raw_header[2] & 0x0f) {
  100988. case 0:
  100989. if(decoder->private_->has_stream_info)
  100990. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100991. else
  100992. is_unparseable = true;
  100993. break;
  100994. case 1:
  100995. decoder->private_->frame.header.sample_rate = 88200;
  100996. break;
  100997. case 2:
  100998. decoder->private_->frame.header.sample_rate = 176400;
  100999. break;
  101000. case 3:
  101001. decoder->private_->frame.header.sample_rate = 192000;
  101002. break;
  101003. case 4:
  101004. decoder->private_->frame.header.sample_rate = 8000;
  101005. break;
  101006. case 5:
  101007. decoder->private_->frame.header.sample_rate = 16000;
  101008. break;
  101009. case 6:
  101010. decoder->private_->frame.header.sample_rate = 22050;
  101011. break;
  101012. case 7:
  101013. decoder->private_->frame.header.sample_rate = 24000;
  101014. break;
  101015. case 8:
  101016. decoder->private_->frame.header.sample_rate = 32000;
  101017. break;
  101018. case 9:
  101019. decoder->private_->frame.header.sample_rate = 44100;
  101020. break;
  101021. case 10:
  101022. decoder->private_->frame.header.sample_rate = 48000;
  101023. break;
  101024. case 11:
  101025. decoder->private_->frame.header.sample_rate = 96000;
  101026. break;
  101027. case 12:
  101028. case 13:
  101029. case 14:
  101030. sample_rate_hint = x;
  101031. break;
  101032. case 15:
  101033. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101034. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101035. return true;
  101036. default:
  101037. FLAC__ASSERT(0);
  101038. }
  101039. x = (unsigned)(raw_header[3] >> 4);
  101040. if(x & 8) {
  101041. decoder->private_->frame.header.channels = 2;
  101042. switch(x & 7) {
  101043. case 0:
  101044. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101045. break;
  101046. case 1:
  101047. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101048. break;
  101049. case 2:
  101050. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101051. break;
  101052. default:
  101053. is_unparseable = true;
  101054. break;
  101055. }
  101056. }
  101057. else {
  101058. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101059. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101060. }
  101061. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101062. case 0:
  101063. if(decoder->private_->has_stream_info)
  101064. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101065. else
  101066. is_unparseable = true;
  101067. break;
  101068. case 1:
  101069. decoder->private_->frame.header.bits_per_sample = 8;
  101070. break;
  101071. case 2:
  101072. decoder->private_->frame.header.bits_per_sample = 12;
  101073. break;
  101074. case 4:
  101075. decoder->private_->frame.header.bits_per_sample = 16;
  101076. break;
  101077. case 5:
  101078. decoder->private_->frame.header.bits_per_sample = 20;
  101079. break;
  101080. case 6:
  101081. decoder->private_->frame.header.bits_per_sample = 24;
  101082. break;
  101083. case 3:
  101084. case 7:
  101085. is_unparseable = true;
  101086. break;
  101087. default:
  101088. FLAC__ASSERT(0);
  101089. break;
  101090. }
  101091. /* check to make sure that reserved bit is 0 */
  101092. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101093. is_unparseable = true;
  101094. /* read the frame's starting sample number (or frame number as the case may be) */
  101095. if(
  101096. raw_header[1] & 0x01 ||
  101097. /*@@@ 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 */
  101098. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101099. ) { /* variable blocksize */
  101100. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101101. return false; /* read_callback_ sets the state for us */
  101102. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101103. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101104. decoder->private_->cached = true;
  101105. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101106. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101107. return true;
  101108. }
  101109. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101110. decoder->private_->frame.header.number.sample_number = xx;
  101111. }
  101112. else { /* fixed blocksize */
  101113. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101114. return false; /* read_callback_ sets the state for us */
  101115. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101116. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101117. decoder->private_->cached = true;
  101118. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101119. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101120. return true;
  101121. }
  101122. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101123. decoder->private_->frame.header.number.frame_number = x;
  101124. }
  101125. if(blocksize_hint) {
  101126. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101127. return false; /* read_callback_ sets the state for us */
  101128. raw_header[raw_header_len++] = (FLAC__byte)x;
  101129. if(blocksize_hint == 7) {
  101130. FLAC__uint32 _x;
  101131. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101132. return false; /* read_callback_ sets the state for us */
  101133. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101134. x = (x << 8) | _x;
  101135. }
  101136. decoder->private_->frame.header.blocksize = x+1;
  101137. }
  101138. if(sample_rate_hint) {
  101139. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101140. return false; /* read_callback_ sets the state for us */
  101141. raw_header[raw_header_len++] = (FLAC__byte)x;
  101142. if(sample_rate_hint != 12) {
  101143. FLAC__uint32 _x;
  101144. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101145. return false; /* read_callback_ sets the state for us */
  101146. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101147. x = (x << 8) | _x;
  101148. }
  101149. if(sample_rate_hint == 12)
  101150. decoder->private_->frame.header.sample_rate = x*1000;
  101151. else if(sample_rate_hint == 13)
  101152. decoder->private_->frame.header.sample_rate = x;
  101153. else
  101154. decoder->private_->frame.header.sample_rate = x*10;
  101155. }
  101156. /* read the CRC-8 byte */
  101157. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101158. return false; /* read_callback_ sets the state for us */
  101159. crc8 = (FLAC__byte)x;
  101160. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101161. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101162. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101163. return true;
  101164. }
  101165. /* calculate the sample number from the frame number if needed */
  101166. decoder->private_->next_fixed_block_size = 0;
  101167. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101168. x = decoder->private_->frame.header.number.frame_number;
  101169. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101170. if(decoder->private_->fixed_block_size)
  101171. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101172. else if(decoder->private_->has_stream_info) {
  101173. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101174. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101175. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101176. }
  101177. else
  101178. is_unparseable = true;
  101179. }
  101180. else if(x == 0) {
  101181. decoder->private_->frame.header.number.sample_number = 0;
  101182. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101183. }
  101184. else {
  101185. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101186. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101187. }
  101188. }
  101189. if(is_unparseable) {
  101190. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101191. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101192. return true;
  101193. }
  101194. return true;
  101195. }
  101196. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101197. {
  101198. FLAC__uint32 x;
  101199. FLAC__bool wasted_bits;
  101200. unsigned i;
  101201. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101202. return false; /* read_callback_ sets the state for us */
  101203. wasted_bits = (x & 1);
  101204. x &= 0xfe;
  101205. if(wasted_bits) {
  101206. unsigned u;
  101207. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101208. return false; /* read_callback_ sets the state for us */
  101209. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101210. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101211. }
  101212. else
  101213. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101214. /*
  101215. * Lots of magic numbers here
  101216. */
  101217. if(x & 0x80) {
  101218. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101219. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101220. return true;
  101221. }
  101222. else if(x == 0) {
  101223. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101224. return false;
  101225. }
  101226. else if(x == 2) {
  101227. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101228. return false;
  101229. }
  101230. else if(x < 16) {
  101231. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101232. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101233. return true;
  101234. }
  101235. else if(x <= 24) {
  101236. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101237. return false;
  101238. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101239. return true;
  101240. }
  101241. else if(x < 64) {
  101242. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101243. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101244. return true;
  101245. }
  101246. else {
  101247. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101248. return false;
  101249. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101250. return true;
  101251. }
  101252. if(wasted_bits && do_full_decode) {
  101253. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101254. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101255. decoder->private_->output[channel][i] <<= x;
  101256. }
  101257. return true;
  101258. }
  101259. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101260. {
  101261. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101262. FLAC__int32 x;
  101263. unsigned i;
  101264. FLAC__int32 *output = decoder->private_->output[channel];
  101265. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101266. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101267. return false; /* read_callback_ sets the state for us */
  101268. subframe->value = x;
  101269. /* decode the subframe */
  101270. if(do_full_decode) {
  101271. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101272. output[i] = x;
  101273. }
  101274. return true;
  101275. }
  101276. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101277. {
  101278. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101279. FLAC__int32 i32;
  101280. FLAC__uint32 u32;
  101281. unsigned u;
  101282. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101283. subframe->residual = decoder->private_->residual[channel];
  101284. subframe->order = order;
  101285. /* read warm-up samples */
  101286. for(u = 0; u < order; u++) {
  101287. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101288. return false; /* read_callback_ sets the state for us */
  101289. subframe->warmup[u] = i32;
  101290. }
  101291. /* read entropy coding method info */
  101292. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101293. return false; /* read_callback_ sets the state for us */
  101294. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101295. switch(subframe->entropy_coding_method.type) {
  101296. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101297. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101298. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101299. return false; /* read_callback_ sets the state for us */
  101300. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101301. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101302. break;
  101303. default:
  101304. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101305. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101306. return true;
  101307. }
  101308. /* read residual */
  101309. switch(subframe->entropy_coding_method.type) {
  101310. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101311. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101312. 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))
  101313. return false;
  101314. break;
  101315. default:
  101316. FLAC__ASSERT(0);
  101317. }
  101318. /* decode the subframe */
  101319. if(do_full_decode) {
  101320. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101321. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101322. }
  101323. return true;
  101324. }
  101325. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101326. {
  101327. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101328. FLAC__int32 i32;
  101329. FLAC__uint32 u32;
  101330. unsigned u;
  101331. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101332. subframe->residual = decoder->private_->residual[channel];
  101333. subframe->order = order;
  101334. /* read warm-up samples */
  101335. for(u = 0; u < order; u++) {
  101336. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101337. return false; /* read_callback_ sets the state for us */
  101338. subframe->warmup[u] = i32;
  101339. }
  101340. /* read qlp coeff precision */
  101341. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101342. return false; /* read_callback_ sets the state for us */
  101343. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101344. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101345. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101346. return true;
  101347. }
  101348. subframe->qlp_coeff_precision = u32+1;
  101349. /* read qlp shift */
  101350. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101351. return false; /* read_callback_ sets the state for us */
  101352. subframe->quantization_level = i32;
  101353. /* read quantized lp coefficiencts */
  101354. for(u = 0; u < order; u++) {
  101355. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101356. return false; /* read_callback_ sets the state for us */
  101357. subframe->qlp_coeff[u] = i32;
  101358. }
  101359. /* read entropy coding method info */
  101360. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101361. return false; /* read_callback_ sets the state for us */
  101362. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101363. switch(subframe->entropy_coding_method.type) {
  101364. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101365. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101366. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101367. return false; /* read_callback_ sets the state for us */
  101368. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101369. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101370. break;
  101371. default:
  101372. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101373. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101374. return true;
  101375. }
  101376. /* read residual */
  101377. switch(subframe->entropy_coding_method.type) {
  101378. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101379. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101380. 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))
  101381. return false;
  101382. break;
  101383. default:
  101384. FLAC__ASSERT(0);
  101385. }
  101386. /* decode the subframe */
  101387. if(do_full_decode) {
  101388. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101389. /*@@@@@@ technically not pessimistic enough, should be more like
  101390. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101391. */
  101392. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101393. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101394. if(order <= 8)
  101395. 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);
  101396. else
  101397. 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);
  101398. }
  101399. else
  101400. 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);
  101401. else
  101402. 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);
  101403. }
  101404. return true;
  101405. }
  101406. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101407. {
  101408. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101409. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101410. unsigned i;
  101411. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101412. subframe->data = residual;
  101413. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101414. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101415. return false; /* read_callback_ sets the state for us */
  101416. residual[i] = x;
  101417. }
  101418. /* decode the subframe */
  101419. if(do_full_decode)
  101420. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101421. return true;
  101422. }
  101423. 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)
  101424. {
  101425. FLAC__uint32 rice_parameter;
  101426. int i;
  101427. unsigned partition, sample, u;
  101428. const unsigned partitions = 1u << partition_order;
  101429. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101430. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101431. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101432. /* sanity checks */
  101433. if(partition_order == 0) {
  101434. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101435. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101436. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101437. return true;
  101438. }
  101439. }
  101440. else {
  101441. if(partition_samples < predictor_order) {
  101442. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101443. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101444. return true;
  101445. }
  101446. }
  101447. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101448. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101449. return false;
  101450. }
  101451. sample = 0;
  101452. for(partition = 0; partition < partitions; partition++) {
  101453. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101454. return false; /* read_callback_ sets the state for us */
  101455. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101456. if(rice_parameter < pesc) {
  101457. partitioned_rice_contents->raw_bits[partition] = 0;
  101458. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101459. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101460. return false; /* read_callback_ sets the state for us */
  101461. sample += u;
  101462. }
  101463. else {
  101464. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101465. return false; /* read_callback_ sets the state for us */
  101466. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101467. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101468. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101469. return false; /* read_callback_ sets the state for us */
  101470. residual[sample] = i;
  101471. }
  101472. }
  101473. }
  101474. return true;
  101475. }
  101476. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101477. {
  101478. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101479. FLAC__uint32 zero = 0;
  101480. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101481. return false; /* read_callback_ sets the state for us */
  101482. if(zero != 0) {
  101483. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101484. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101485. }
  101486. }
  101487. return true;
  101488. }
  101489. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101490. {
  101491. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101492. if(
  101493. #if FLAC__HAS_OGG
  101494. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101495. !decoder->private_->is_ogg &&
  101496. #endif
  101497. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101498. ) {
  101499. *bytes = 0;
  101500. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101501. return false;
  101502. }
  101503. else if(*bytes > 0) {
  101504. /* While seeking, it is possible for our seek to land in the
  101505. * middle of audio data that looks exactly like a frame header
  101506. * from a future version of an encoder. When that happens, our
  101507. * error callback will get an
  101508. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101509. * unparseable_frame_count. But there is a remote possibility
  101510. * that it is properly synced at such a "future-codec frame",
  101511. * so to make sure, we wait to see many "unparseable" errors in
  101512. * a row before bailing out.
  101513. */
  101514. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101515. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101516. return false;
  101517. }
  101518. else {
  101519. const FLAC__StreamDecoderReadStatus status =
  101520. #if FLAC__HAS_OGG
  101521. decoder->private_->is_ogg?
  101522. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101523. #endif
  101524. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101525. ;
  101526. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101527. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101528. return false;
  101529. }
  101530. else if(*bytes == 0) {
  101531. if(
  101532. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101533. (
  101534. #if FLAC__HAS_OGG
  101535. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101536. !decoder->private_->is_ogg &&
  101537. #endif
  101538. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101539. )
  101540. ) {
  101541. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101542. return false;
  101543. }
  101544. else
  101545. return true;
  101546. }
  101547. else
  101548. return true;
  101549. }
  101550. }
  101551. else {
  101552. /* abort to avoid a deadlock */
  101553. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101554. return false;
  101555. }
  101556. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101557. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101558. * and at the same time hit the end of the stream (for example, seeking
  101559. * to a point that is after the beginning of the last Ogg page). There
  101560. * is no way to report an Ogg sync loss through the callbacks (see note
  101561. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101562. * So to keep the decoder from stopping at this point we gate the call
  101563. * to the eof_callback and let the Ogg decoder aspect set the
  101564. * end-of-stream state when it is needed.
  101565. */
  101566. }
  101567. #if FLAC__HAS_OGG
  101568. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101569. {
  101570. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101571. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101572. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101573. /* we don't really have a way to handle lost sync via read
  101574. * callback so we'll let it pass and let the underlying
  101575. * FLAC decoder catch the error
  101576. */
  101577. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101578. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101579. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101580. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101581. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101582. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101583. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101584. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101585. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101586. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101587. default:
  101588. FLAC__ASSERT(0);
  101589. /* double protection */
  101590. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101591. }
  101592. }
  101593. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101594. {
  101595. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101596. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101597. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101598. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101599. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101600. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101601. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101602. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101603. default:
  101604. /* double protection: */
  101605. FLAC__ASSERT(0);
  101606. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101607. }
  101608. }
  101609. #endif
  101610. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101611. {
  101612. if(decoder->private_->is_seeking) {
  101613. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101614. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101615. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101616. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101617. #if FLAC__HAS_OGG
  101618. decoder->private_->got_a_frame = true;
  101619. #endif
  101620. decoder->private_->last_frame = *frame; /* save the frame */
  101621. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101622. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101623. /* kick out of seek mode */
  101624. decoder->private_->is_seeking = false;
  101625. /* shift out the samples before target_sample */
  101626. if(delta > 0) {
  101627. unsigned channel;
  101628. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101629. for(channel = 0; channel < frame->header.channels; channel++)
  101630. newbuffer[channel] = buffer[channel] + delta;
  101631. decoder->private_->last_frame.header.blocksize -= delta;
  101632. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101633. /* write the relevant samples */
  101634. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101635. }
  101636. else {
  101637. /* write the relevant samples */
  101638. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101639. }
  101640. }
  101641. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101642. }
  101643. /*
  101644. * If we never got STREAMINFO, turn off MD5 checking to save
  101645. * cycles since we don't have a sum to compare to anyway
  101646. */
  101647. if(!decoder->private_->has_stream_info)
  101648. decoder->private_->do_md5_checking = false;
  101649. if(decoder->private_->do_md5_checking) {
  101650. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101651. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101652. }
  101653. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101654. }
  101655. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101656. {
  101657. if(!decoder->private_->is_seeking)
  101658. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101659. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101660. decoder->private_->unparseable_frame_count++;
  101661. }
  101662. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101663. {
  101664. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101665. FLAC__int64 pos = -1;
  101666. int i;
  101667. unsigned approx_bytes_per_frame;
  101668. FLAC__bool first_seek = true;
  101669. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101670. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101671. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101672. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101673. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101674. /* take these from the current frame in case they've changed mid-stream */
  101675. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101676. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101677. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101678. /* use values from stream info if we didn't decode a frame */
  101679. if(channels == 0)
  101680. channels = decoder->private_->stream_info.data.stream_info.channels;
  101681. if(bps == 0)
  101682. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101683. /* we are just guessing here */
  101684. if(max_framesize > 0)
  101685. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101686. /*
  101687. * Check if it's a known fixed-blocksize stream. Note that though
  101688. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101689. * never get a STREAMINFO block when decoding so the value of
  101690. * min_blocksize might be zero.
  101691. */
  101692. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101693. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101694. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101695. }
  101696. else
  101697. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101698. /*
  101699. * First, we set an upper and lower bound on where in the
  101700. * stream we will search. For now we assume the worst case
  101701. * scenario, which is our best guess at the beginning of
  101702. * the first frame and end of the stream.
  101703. */
  101704. lower_bound = first_frame_offset;
  101705. lower_bound_sample = 0;
  101706. upper_bound = stream_length;
  101707. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101708. /*
  101709. * Now we refine the bounds if we have a seektable with
  101710. * suitable points. Note that according to the spec they
  101711. * must be ordered by ascending sample number.
  101712. *
  101713. * Note: to protect against invalid seek tables we will ignore points
  101714. * that have frame_samples==0 or sample_number>=total_samples
  101715. */
  101716. if(seek_table) {
  101717. FLAC__uint64 new_lower_bound = lower_bound;
  101718. FLAC__uint64 new_upper_bound = upper_bound;
  101719. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101720. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101721. /* find the closest seek point <= target_sample, if it exists */
  101722. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101723. if(
  101724. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101725. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101726. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101727. seek_table->points[i].sample_number <= target_sample
  101728. )
  101729. break;
  101730. }
  101731. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101732. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101733. new_lower_bound_sample = seek_table->points[i].sample_number;
  101734. }
  101735. /* find the closest seek point > target_sample, if it exists */
  101736. for(i = 0; i < (int)seek_table->num_points; i++) {
  101737. if(
  101738. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101739. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101740. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101741. seek_table->points[i].sample_number > target_sample
  101742. )
  101743. break;
  101744. }
  101745. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101746. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101747. new_upper_bound_sample = seek_table->points[i].sample_number;
  101748. }
  101749. /* final protection against unsorted seek tables; keep original values if bogus */
  101750. if(new_upper_bound >= new_lower_bound) {
  101751. lower_bound = new_lower_bound;
  101752. upper_bound = new_upper_bound;
  101753. lower_bound_sample = new_lower_bound_sample;
  101754. upper_bound_sample = new_upper_bound_sample;
  101755. }
  101756. }
  101757. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101758. /* there are 2 insidious ways that the following equality occurs, which
  101759. * we need to fix:
  101760. * 1) total_samples is 0 (unknown) and target_sample is 0
  101761. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101762. * exactly equal to the last seek point in the seek table; this
  101763. * means there is no seek point above it, and upper_bound_samples
  101764. * remains equal to the estimate (of target_samples) we made above
  101765. * in either case it does not hurt to move upper_bound_sample up by 1
  101766. */
  101767. if(upper_bound_sample == lower_bound_sample)
  101768. upper_bound_sample++;
  101769. decoder->private_->target_sample = target_sample;
  101770. while(1) {
  101771. /* check if the bounds are still ok */
  101772. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101773. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101774. return false;
  101775. }
  101776. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101777. #if defined _MSC_VER || defined __MINGW32__
  101778. /* with VC++ you have to spoon feed it the casting */
  101779. 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;
  101780. #else
  101781. 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;
  101782. #endif
  101783. #else
  101784. /* a little less accurate: */
  101785. if(upper_bound - lower_bound < 0xffffffff)
  101786. 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;
  101787. else /* @@@ WATCHOUT, ~2TB limit */
  101788. 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;
  101789. #endif
  101790. if(pos >= (FLAC__int64)upper_bound)
  101791. pos = (FLAC__int64)upper_bound - 1;
  101792. if(pos < (FLAC__int64)lower_bound)
  101793. pos = (FLAC__int64)lower_bound;
  101794. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101795. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101796. return false;
  101797. }
  101798. if(!FLAC__stream_decoder_flush(decoder)) {
  101799. /* above call sets the state for us */
  101800. return false;
  101801. }
  101802. /* Now we need to get a frame. First we need to reset our
  101803. * unparseable_frame_count; if we get too many unparseable
  101804. * frames in a row, the read callback will return
  101805. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101806. * FLAC__stream_decoder_process_single() to return false.
  101807. */
  101808. decoder->private_->unparseable_frame_count = 0;
  101809. if(!FLAC__stream_decoder_process_single(decoder)) {
  101810. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101811. return false;
  101812. }
  101813. /* our write callback will change the state when it gets to the target frame */
  101814. /* 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 */
  101815. #if 0
  101816. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101817. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101818. break;
  101819. #endif
  101820. if(!decoder->private_->is_seeking)
  101821. break;
  101822. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101823. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101824. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101825. if (pos == (FLAC__int64)lower_bound) {
  101826. /* can't move back any more than the first frame, something is fatally wrong */
  101827. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101828. return false;
  101829. }
  101830. /* our last move backwards wasn't big enough, try again */
  101831. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101832. continue;
  101833. }
  101834. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101835. first_seek = false;
  101836. /* make sure we are not seeking in corrupted stream */
  101837. if (this_frame_sample < lower_bound_sample) {
  101838. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101839. return false;
  101840. }
  101841. /* we need to narrow the search */
  101842. if(target_sample < this_frame_sample) {
  101843. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101844. /*@@@@@@ what will decode position be if at end of stream? */
  101845. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101846. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101847. return false;
  101848. }
  101849. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101850. }
  101851. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101852. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101853. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101854. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101855. return false;
  101856. }
  101857. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101858. }
  101859. }
  101860. return true;
  101861. }
  101862. #if FLAC__HAS_OGG
  101863. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101864. {
  101865. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101866. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101867. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101868. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101869. FLAC__bool did_a_seek;
  101870. unsigned iteration = 0;
  101871. /* In the first iterations, we will calculate the target byte position
  101872. * by the distance from the target sample to left_sample and
  101873. * right_sample (let's call it "proportional search"). After that, we
  101874. * will switch to binary search.
  101875. */
  101876. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101877. /* We will switch to a linear search once our current sample is less
  101878. * than this number of samples ahead of the target sample
  101879. */
  101880. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101881. /* If the total number of samples is unknown, use a large value, and
  101882. * force binary search immediately.
  101883. */
  101884. if(right_sample == 0) {
  101885. right_sample = (FLAC__uint64)(-1);
  101886. BINARY_SEARCH_AFTER_ITERATION = 0;
  101887. }
  101888. decoder->private_->target_sample = target_sample;
  101889. for( ; ; iteration++) {
  101890. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101891. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101892. pos = (right_pos + left_pos) / 2;
  101893. }
  101894. else {
  101895. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101896. #if defined _MSC_VER || defined __MINGW32__
  101897. /* with MSVC you have to spoon feed it the casting */
  101898. 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));
  101899. #else
  101900. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101901. #endif
  101902. #else
  101903. /* a little less accurate: */
  101904. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101905. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101906. else /* @@@ WATCHOUT, ~2TB limit */
  101907. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101908. #endif
  101909. /* @@@ TODO: might want to limit pos to some distance
  101910. * before EOF, to make sure we land before the last frame,
  101911. * thereby getting a this_frame_sample and so having a better
  101912. * estimate.
  101913. */
  101914. }
  101915. /* physical seek */
  101916. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101917. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101918. return false;
  101919. }
  101920. if(!FLAC__stream_decoder_flush(decoder)) {
  101921. /* above call sets the state for us */
  101922. return false;
  101923. }
  101924. did_a_seek = true;
  101925. }
  101926. else
  101927. did_a_seek = false;
  101928. decoder->private_->got_a_frame = false;
  101929. if(!FLAC__stream_decoder_process_single(decoder)) {
  101930. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101931. return false;
  101932. }
  101933. if(!decoder->private_->got_a_frame) {
  101934. if(did_a_seek) {
  101935. /* this can happen if we seek to a point after the last frame; we drop
  101936. * to binary search right away in this case to avoid any wasted
  101937. * iterations of proportional search.
  101938. */
  101939. right_pos = pos;
  101940. BINARY_SEARCH_AFTER_ITERATION = 0;
  101941. }
  101942. else {
  101943. /* this can probably only happen if total_samples is unknown and the
  101944. * target_sample is past the end of the stream
  101945. */
  101946. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101947. return false;
  101948. }
  101949. }
  101950. /* our write callback will change the state when it gets to the target frame */
  101951. else if(!decoder->private_->is_seeking) {
  101952. break;
  101953. }
  101954. else {
  101955. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101956. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101957. if (did_a_seek) {
  101958. if (this_frame_sample <= target_sample) {
  101959. /* The 'equal' case should not happen, since
  101960. * FLAC__stream_decoder_process_single()
  101961. * should recognize that it has hit the
  101962. * target sample and we would exit through
  101963. * the 'break' above.
  101964. */
  101965. FLAC__ASSERT(this_frame_sample != target_sample);
  101966. left_sample = this_frame_sample;
  101967. /* sanity check to avoid infinite loop */
  101968. if (left_pos == pos) {
  101969. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101970. return false;
  101971. }
  101972. left_pos = pos;
  101973. }
  101974. else if(this_frame_sample > target_sample) {
  101975. right_sample = this_frame_sample;
  101976. /* sanity check to avoid infinite loop */
  101977. if (right_pos == pos) {
  101978. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101979. return false;
  101980. }
  101981. right_pos = pos;
  101982. }
  101983. }
  101984. }
  101985. }
  101986. return true;
  101987. }
  101988. #endif
  101989. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101990. {
  101991. (void)client_data;
  101992. if(*bytes > 0) {
  101993. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101994. if(ferror(decoder->private_->file))
  101995. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101996. else if(*bytes == 0)
  101997. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101998. else
  101999. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102000. }
  102001. else
  102002. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102003. }
  102004. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102005. {
  102006. (void)client_data;
  102007. if(decoder->private_->file == stdin)
  102008. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102009. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102010. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102011. else
  102012. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102013. }
  102014. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102015. {
  102016. off_t pos;
  102017. (void)client_data;
  102018. if(decoder->private_->file == stdin)
  102019. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102020. else if((pos = ftello(decoder->private_->file)) < 0)
  102021. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102022. else {
  102023. *absolute_byte_offset = (FLAC__uint64)pos;
  102024. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102025. }
  102026. }
  102027. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102028. {
  102029. struct stat filestats;
  102030. (void)client_data;
  102031. if(decoder->private_->file == stdin)
  102032. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102033. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102034. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102035. else {
  102036. *stream_length = (FLAC__uint64)filestats.st_size;
  102037. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102038. }
  102039. }
  102040. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102041. {
  102042. (void)client_data;
  102043. return feof(decoder->private_->file)? true : false;
  102044. }
  102045. #endif
  102046. /*** End of inlined file: stream_decoder.c ***/
  102047. /*** Start of inlined file: stream_encoder.c ***/
  102048. /*** Start of inlined file: juce_FlacHeader.h ***/
  102049. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102050. // tasks..
  102051. #define VERSION "1.2.1"
  102052. #define FLAC__NO_DLL 1
  102053. #if JUCE_MSVC
  102054. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102055. #endif
  102056. #if JUCE_MAC
  102057. #define FLAC__SYS_DARWIN 1
  102058. #endif
  102059. /*** End of inlined file: juce_FlacHeader.h ***/
  102060. #if JUCE_USE_FLAC
  102061. #if HAVE_CONFIG_H
  102062. # include <config.h>
  102063. #endif
  102064. #if defined _MSC_VER || defined __MINGW32__
  102065. #include <io.h> /* for _setmode() */
  102066. #include <fcntl.h> /* for _O_BINARY */
  102067. #endif
  102068. #if defined __CYGWIN__ || defined __EMX__
  102069. #include <io.h> /* for setmode(), O_BINARY */
  102070. #include <fcntl.h> /* for _O_BINARY */
  102071. #endif
  102072. #include <limits.h>
  102073. #include <stdio.h>
  102074. #include <stdlib.h> /* for malloc() */
  102075. #include <string.h> /* for memcpy() */
  102076. #include <sys/types.h> /* for off_t */
  102077. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102078. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102079. #define fseeko fseek
  102080. #define ftello ftell
  102081. #endif
  102082. #endif
  102083. /*** Start of inlined file: stream_encoder.h ***/
  102084. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102085. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102086. #if FLAC__HAS_OGG
  102087. #include "private/ogg_encoder_aspect.h"
  102088. #endif
  102089. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102090. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102091. typedef enum {
  102092. FLAC__APODIZATION_BARTLETT,
  102093. FLAC__APODIZATION_BARTLETT_HANN,
  102094. FLAC__APODIZATION_BLACKMAN,
  102095. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102096. FLAC__APODIZATION_CONNES,
  102097. FLAC__APODIZATION_FLATTOP,
  102098. FLAC__APODIZATION_GAUSS,
  102099. FLAC__APODIZATION_HAMMING,
  102100. FLAC__APODIZATION_HANN,
  102101. FLAC__APODIZATION_KAISER_BESSEL,
  102102. FLAC__APODIZATION_NUTTALL,
  102103. FLAC__APODIZATION_RECTANGLE,
  102104. FLAC__APODIZATION_TRIANGLE,
  102105. FLAC__APODIZATION_TUKEY,
  102106. FLAC__APODIZATION_WELCH
  102107. } FLAC__ApodizationFunction;
  102108. typedef struct {
  102109. FLAC__ApodizationFunction type;
  102110. union {
  102111. struct {
  102112. FLAC__real stddev;
  102113. } gauss;
  102114. struct {
  102115. FLAC__real p;
  102116. } tukey;
  102117. } parameters;
  102118. } FLAC__ApodizationSpecification;
  102119. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102120. typedef struct FLAC__StreamEncoderProtected {
  102121. FLAC__StreamEncoderState state;
  102122. FLAC__bool verify;
  102123. FLAC__bool streamable_subset;
  102124. FLAC__bool do_md5;
  102125. FLAC__bool do_mid_side_stereo;
  102126. FLAC__bool loose_mid_side_stereo;
  102127. unsigned channels;
  102128. unsigned bits_per_sample;
  102129. unsigned sample_rate;
  102130. unsigned blocksize;
  102131. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102132. unsigned num_apodizations;
  102133. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102134. #endif
  102135. unsigned max_lpc_order;
  102136. unsigned qlp_coeff_precision;
  102137. FLAC__bool do_qlp_coeff_prec_search;
  102138. FLAC__bool do_exhaustive_model_search;
  102139. FLAC__bool do_escape_coding;
  102140. unsigned min_residual_partition_order;
  102141. unsigned max_residual_partition_order;
  102142. unsigned rice_parameter_search_dist;
  102143. FLAC__uint64 total_samples_estimate;
  102144. FLAC__StreamMetadata **metadata;
  102145. unsigned num_metadata_blocks;
  102146. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102147. #if FLAC__HAS_OGG
  102148. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102149. #endif
  102150. } FLAC__StreamEncoderProtected;
  102151. #endif
  102152. /*** End of inlined file: stream_encoder.h ***/
  102153. #if FLAC__HAS_OGG
  102154. #include "include/private/ogg_helper.h"
  102155. #include "include/private/ogg_mapping.h"
  102156. #endif
  102157. /*** Start of inlined file: stream_encoder_framing.h ***/
  102158. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102159. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102160. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102161. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102162. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102163. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102164. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102165. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102166. #endif
  102167. /*** End of inlined file: stream_encoder_framing.h ***/
  102168. /*** Start of inlined file: window.h ***/
  102169. #ifndef FLAC__PRIVATE__WINDOW_H
  102170. #define FLAC__PRIVATE__WINDOW_H
  102171. #ifdef HAVE_CONFIG_H
  102172. #include <config.h>
  102173. #endif
  102174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102175. /*
  102176. * FLAC__window_*()
  102177. * --------------------------------------------------------------------
  102178. * Calculates window coefficients according to different apodization
  102179. * functions.
  102180. *
  102181. * OUT window[0,L-1]
  102182. * IN L (number of points in window)
  102183. */
  102184. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102185. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102186. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102187. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102188. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102189. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102190. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102191. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102192. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102193. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102194. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102195. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102196. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102197. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102198. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102199. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102200. #endif
  102201. /*** End of inlined file: window.h ***/
  102202. #ifndef FLaC__INLINE
  102203. #define FLaC__INLINE
  102204. #endif
  102205. #ifdef min
  102206. #undef min
  102207. #endif
  102208. #define min(x,y) ((x)<(y)?(x):(y))
  102209. #ifdef max
  102210. #undef max
  102211. #endif
  102212. #define max(x,y) ((x)>(y)?(x):(y))
  102213. /* Exact Rice codeword length calculation is off by default. The simple
  102214. * (and fast) estimation (of how many bits a residual value will be
  102215. * encoded with) in this encoder is very good, almost always yielding
  102216. * compression within 0.1% of exact calculation.
  102217. */
  102218. #undef EXACT_RICE_BITS_CALCULATION
  102219. /* Rice parameter searching is off by default. The simple (and fast)
  102220. * parameter estimation in this encoder is very good, almost always
  102221. * yielding compression within 0.1% of the optimal parameters.
  102222. */
  102223. #undef ENABLE_RICE_PARAMETER_SEARCH
  102224. typedef struct {
  102225. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102226. unsigned size; /* of each data[] in samples */
  102227. unsigned tail;
  102228. } verify_input_fifo;
  102229. typedef struct {
  102230. const FLAC__byte *data;
  102231. unsigned capacity;
  102232. unsigned bytes;
  102233. } verify_output;
  102234. typedef enum {
  102235. ENCODER_IN_MAGIC = 0,
  102236. ENCODER_IN_METADATA = 1,
  102237. ENCODER_IN_AUDIO = 2
  102238. } EncoderStateHint;
  102239. static struct CompressionLevels {
  102240. FLAC__bool do_mid_side_stereo;
  102241. FLAC__bool loose_mid_side_stereo;
  102242. unsigned max_lpc_order;
  102243. unsigned qlp_coeff_precision;
  102244. FLAC__bool do_qlp_coeff_prec_search;
  102245. FLAC__bool do_escape_coding;
  102246. FLAC__bool do_exhaustive_model_search;
  102247. unsigned min_residual_partition_order;
  102248. unsigned max_residual_partition_order;
  102249. unsigned rice_parameter_search_dist;
  102250. } compression_levels_[] = {
  102251. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102252. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102253. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102254. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102255. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102256. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102257. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102258. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102259. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102260. };
  102261. /***********************************************************************
  102262. *
  102263. * Private class method prototypes
  102264. *
  102265. ***********************************************************************/
  102266. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102267. static void free_(FLAC__StreamEncoder *encoder);
  102268. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102269. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102270. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102271. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102272. #if FLAC__HAS_OGG
  102273. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102274. #endif
  102275. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102276. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102277. static FLAC__bool process_subframe_(
  102278. FLAC__StreamEncoder *encoder,
  102279. unsigned min_partition_order,
  102280. unsigned max_partition_order,
  102281. const FLAC__FrameHeader *frame_header,
  102282. unsigned subframe_bps,
  102283. const FLAC__int32 integer_signal[],
  102284. FLAC__Subframe *subframe[2],
  102285. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102286. FLAC__int32 *residual[2],
  102287. unsigned *best_subframe,
  102288. unsigned *best_bits
  102289. );
  102290. static FLAC__bool add_subframe_(
  102291. FLAC__StreamEncoder *encoder,
  102292. unsigned blocksize,
  102293. unsigned subframe_bps,
  102294. const FLAC__Subframe *subframe,
  102295. FLAC__BitWriter *frame
  102296. );
  102297. static unsigned evaluate_constant_subframe_(
  102298. FLAC__StreamEncoder *encoder,
  102299. const FLAC__int32 signal,
  102300. unsigned blocksize,
  102301. unsigned subframe_bps,
  102302. FLAC__Subframe *subframe
  102303. );
  102304. static unsigned evaluate_fixed_subframe_(
  102305. FLAC__StreamEncoder *encoder,
  102306. const FLAC__int32 signal[],
  102307. FLAC__int32 residual[],
  102308. FLAC__uint64 abs_residual_partition_sums[],
  102309. unsigned raw_bits_per_partition[],
  102310. unsigned blocksize,
  102311. unsigned subframe_bps,
  102312. unsigned order,
  102313. unsigned rice_parameter,
  102314. unsigned rice_parameter_limit,
  102315. unsigned min_partition_order,
  102316. unsigned max_partition_order,
  102317. FLAC__bool do_escape_coding,
  102318. unsigned rice_parameter_search_dist,
  102319. FLAC__Subframe *subframe,
  102320. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102321. );
  102322. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102323. static unsigned evaluate_lpc_subframe_(
  102324. FLAC__StreamEncoder *encoder,
  102325. const FLAC__int32 signal[],
  102326. FLAC__int32 residual[],
  102327. FLAC__uint64 abs_residual_partition_sums[],
  102328. unsigned raw_bits_per_partition[],
  102329. const FLAC__real lp_coeff[],
  102330. unsigned blocksize,
  102331. unsigned subframe_bps,
  102332. unsigned order,
  102333. unsigned qlp_coeff_precision,
  102334. unsigned rice_parameter,
  102335. unsigned rice_parameter_limit,
  102336. unsigned min_partition_order,
  102337. unsigned max_partition_order,
  102338. FLAC__bool do_escape_coding,
  102339. unsigned rice_parameter_search_dist,
  102340. FLAC__Subframe *subframe,
  102341. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102342. );
  102343. #endif
  102344. static unsigned evaluate_verbatim_subframe_(
  102345. FLAC__StreamEncoder *encoder,
  102346. const FLAC__int32 signal[],
  102347. unsigned blocksize,
  102348. unsigned subframe_bps,
  102349. FLAC__Subframe *subframe
  102350. );
  102351. static unsigned find_best_partition_order_(
  102352. struct FLAC__StreamEncoderPrivate *private_,
  102353. const FLAC__int32 residual[],
  102354. FLAC__uint64 abs_residual_partition_sums[],
  102355. unsigned raw_bits_per_partition[],
  102356. unsigned residual_samples,
  102357. unsigned predictor_order,
  102358. unsigned rice_parameter,
  102359. unsigned rice_parameter_limit,
  102360. unsigned min_partition_order,
  102361. unsigned max_partition_order,
  102362. unsigned bps,
  102363. FLAC__bool do_escape_coding,
  102364. unsigned rice_parameter_search_dist,
  102365. FLAC__EntropyCodingMethod *best_ecm
  102366. );
  102367. static void precompute_partition_info_sums_(
  102368. const FLAC__int32 residual[],
  102369. FLAC__uint64 abs_residual_partition_sums[],
  102370. unsigned residual_samples,
  102371. unsigned predictor_order,
  102372. unsigned min_partition_order,
  102373. unsigned max_partition_order,
  102374. unsigned bps
  102375. );
  102376. static void precompute_partition_info_escapes_(
  102377. const FLAC__int32 residual[],
  102378. unsigned raw_bits_per_partition[],
  102379. unsigned residual_samples,
  102380. unsigned predictor_order,
  102381. unsigned min_partition_order,
  102382. unsigned max_partition_order
  102383. );
  102384. static FLAC__bool set_partitioned_rice_(
  102385. #ifdef EXACT_RICE_BITS_CALCULATION
  102386. const FLAC__int32 residual[],
  102387. #endif
  102388. const FLAC__uint64 abs_residual_partition_sums[],
  102389. const unsigned raw_bits_per_partition[],
  102390. const unsigned residual_samples,
  102391. const unsigned predictor_order,
  102392. const unsigned suggested_rice_parameter,
  102393. const unsigned rice_parameter_limit,
  102394. const unsigned rice_parameter_search_dist,
  102395. const unsigned partition_order,
  102396. const FLAC__bool search_for_escapes,
  102397. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102398. unsigned *bits
  102399. );
  102400. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102401. /* verify-related routines: */
  102402. static void append_to_verify_fifo_(
  102403. verify_input_fifo *fifo,
  102404. const FLAC__int32 * const input[],
  102405. unsigned input_offset,
  102406. unsigned channels,
  102407. unsigned wide_samples
  102408. );
  102409. static void append_to_verify_fifo_interleaved_(
  102410. verify_input_fifo *fifo,
  102411. const FLAC__int32 input[],
  102412. unsigned input_offset,
  102413. unsigned channels,
  102414. unsigned wide_samples
  102415. );
  102416. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102417. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102418. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102419. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102420. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102421. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102422. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102423. 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);
  102424. static FILE *get_binary_stdout_(void);
  102425. /***********************************************************************
  102426. *
  102427. * Private class data
  102428. *
  102429. ***********************************************************************/
  102430. typedef struct FLAC__StreamEncoderPrivate {
  102431. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102432. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102433. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102434. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102435. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102436. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102437. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102438. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102439. #endif
  102440. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102441. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102442. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102443. FLAC__int32 *residual_workspace_mid_side[2][2];
  102444. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102445. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102446. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102447. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102448. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102449. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102450. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102451. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102452. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102453. unsigned best_subframe_mid_side[2];
  102454. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102455. unsigned best_subframe_bits_mid_side[2];
  102456. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102457. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102458. FLAC__BitWriter *frame; /* the current frame being worked on */
  102459. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102460. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102461. FLAC__ChannelAssignment last_channel_assignment;
  102462. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102463. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102464. unsigned current_sample_number;
  102465. unsigned current_frame_number;
  102466. FLAC__MD5Context md5context;
  102467. FLAC__CPUInfo cpuinfo;
  102468. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102469. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102470. #else
  102471. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102472. #endif
  102473. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102474. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102475. 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[]);
  102476. 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[]);
  102477. 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[]);
  102478. #endif
  102479. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102480. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102481. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102482. FLAC__bool disable_constant_subframes;
  102483. FLAC__bool disable_fixed_subframes;
  102484. FLAC__bool disable_verbatim_subframes;
  102485. #if FLAC__HAS_OGG
  102486. FLAC__bool is_ogg;
  102487. #endif
  102488. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102489. FLAC__StreamEncoderSeekCallback seek_callback;
  102490. FLAC__StreamEncoderTellCallback tell_callback;
  102491. FLAC__StreamEncoderWriteCallback write_callback;
  102492. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102493. FLAC__StreamEncoderProgressCallback progress_callback;
  102494. void *client_data;
  102495. unsigned first_seekpoint_to_check;
  102496. FILE *file; /* only used when encoding to a file */
  102497. FLAC__uint64 bytes_written;
  102498. FLAC__uint64 samples_written;
  102499. unsigned frames_written;
  102500. unsigned total_frames_estimate;
  102501. /* unaligned (original) pointers to allocated data */
  102502. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102503. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102504. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102505. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102506. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102507. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102508. FLAC__real *windowed_signal_unaligned;
  102509. #endif
  102510. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102511. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102512. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102513. unsigned *raw_bits_per_partition_unaligned;
  102514. /*
  102515. * These fields have been moved here from private function local
  102516. * declarations merely to save stack space during encoding.
  102517. */
  102518. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102519. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102520. #endif
  102521. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102522. /*
  102523. * The data for the verify section
  102524. */
  102525. struct {
  102526. FLAC__StreamDecoder *decoder;
  102527. EncoderStateHint state_hint;
  102528. FLAC__bool needs_magic_hack;
  102529. verify_input_fifo input_fifo;
  102530. verify_output output;
  102531. struct {
  102532. FLAC__uint64 absolute_sample;
  102533. unsigned frame_number;
  102534. unsigned channel;
  102535. unsigned sample;
  102536. FLAC__int32 expected;
  102537. FLAC__int32 got;
  102538. } error_stats;
  102539. } verify;
  102540. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102541. } FLAC__StreamEncoderPrivate;
  102542. /***********************************************************************
  102543. *
  102544. * Public static class data
  102545. *
  102546. ***********************************************************************/
  102547. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102548. "FLAC__STREAM_ENCODER_OK",
  102549. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102550. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102551. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102552. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102553. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102554. "FLAC__STREAM_ENCODER_IO_ERROR",
  102555. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102556. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102557. };
  102558. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102559. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102560. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102561. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102562. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102563. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102564. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102565. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102566. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102567. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102568. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102569. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102570. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102571. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102572. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102573. };
  102574. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102575. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102576. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102577. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102578. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102579. };
  102580. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102581. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102582. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102583. };
  102584. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102585. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102586. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102587. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102588. };
  102589. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102590. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102591. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102592. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102593. };
  102594. /* Number of samples that will be overread to watch for end of stream. By
  102595. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102596. * always try to read blocksize+1 samples before encoding a block, so that
  102597. * even if the stream has a total sample count that is an integral multiple
  102598. * of the blocksize, we will still notice when we are encoding the last
  102599. * block. This is needed, for example, to correctly set the end-of-stream
  102600. * marker in Ogg FLAC.
  102601. *
  102602. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102603. * not really any reason to change it.
  102604. */
  102605. static const unsigned OVERREAD_ = 1;
  102606. /***********************************************************************
  102607. *
  102608. * Class constructor/destructor
  102609. *
  102610. */
  102611. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102612. {
  102613. FLAC__StreamEncoder *encoder;
  102614. unsigned i;
  102615. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102616. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102617. if(encoder == 0) {
  102618. return 0;
  102619. }
  102620. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102621. if(encoder->protected_ == 0) {
  102622. free(encoder);
  102623. return 0;
  102624. }
  102625. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102626. if(encoder->private_ == 0) {
  102627. free(encoder->protected_);
  102628. free(encoder);
  102629. return 0;
  102630. }
  102631. encoder->private_->frame = FLAC__bitwriter_new();
  102632. if(encoder->private_->frame == 0) {
  102633. free(encoder->private_);
  102634. free(encoder->protected_);
  102635. free(encoder);
  102636. return 0;
  102637. }
  102638. encoder->private_->file = 0;
  102639. set_defaults_enc(encoder);
  102640. encoder->private_->is_being_deleted = false;
  102641. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102642. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102643. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102644. }
  102645. for(i = 0; i < 2; i++) {
  102646. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102647. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102648. }
  102649. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102650. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102651. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102652. }
  102653. for(i = 0; i < 2; i++) {
  102654. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102655. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102656. }
  102657. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102658. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102659. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102660. }
  102661. for(i = 0; i < 2; i++) {
  102662. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102663. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102664. }
  102665. for(i = 0; i < 2; i++)
  102666. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102667. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102668. return encoder;
  102669. }
  102670. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102671. {
  102672. unsigned i;
  102673. FLAC__ASSERT(0 != encoder);
  102674. FLAC__ASSERT(0 != encoder->protected_);
  102675. FLAC__ASSERT(0 != encoder->private_);
  102676. FLAC__ASSERT(0 != encoder->private_->frame);
  102677. encoder->private_->is_being_deleted = true;
  102678. (void)FLAC__stream_encoder_finish(encoder);
  102679. if(0 != encoder->private_->verify.decoder)
  102680. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102681. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102682. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102683. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102684. }
  102685. for(i = 0; i < 2; i++) {
  102686. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102687. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102688. }
  102689. for(i = 0; i < 2; i++)
  102690. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102691. FLAC__bitwriter_delete(encoder->private_->frame);
  102692. free(encoder->private_);
  102693. free(encoder->protected_);
  102694. free(encoder);
  102695. }
  102696. /***********************************************************************
  102697. *
  102698. * Public class methods
  102699. *
  102700. ***********************************************************************/
  102701. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102702. FLAC__StreamEncoder *encoder,
  102703. FLAC__StreamEncoderReadCallback read_callback,
  102704. FLAC__StreamEncoderWriteCallback write_callback,
  102705. FLAC__StreamEncoderSeekCallback seek_callback,
  102706. FLAC__StreamEncoderTellCallback tell_callback,
  102707. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102708. void *client_data,
  102709. FLAC__bool is_ogg
  102710. )
  102711. {
  102712. unsigned i;
  102713. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102714. FLAC__ASSERT(0 != encoder);
  102715. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102716. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102717. #if !FLAC__HAS_OGG
  102718. if(is_ogg)
  102719. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102720. #endif
  102721. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102722. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102723. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102724. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102725. if(encoder->protected_->channels != 2) {
  102726. encoder->protected_->do_mid_side_stereo = false;
  102727. encoder->protected_->loose_mid_side_stereo = false;
  102728. }
  102729. else if(!encoder->protected_->do_mid_side_stereo)
  102730. encoder->protected_->loose_mid_side_stereo = false;
  102731. if(encoder->protected_->bits_per_sample >= 32)
  102732. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102733. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102734. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102735. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102736. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102737. if(encoder->protected_->blocksize == 0) {
  102738. if(encoder->protected_->max_lpc_order == 0)
  102739. encoder->protected_->blocksize = 1152;
  102740. else
  102741. encoder->protected_->blocksize = 4096;
  102742. }
  102743. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102744. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102745. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102746. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102747. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102748. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102749. if(encoder->protected_->qlp_coeff_precision == 0) {
  102750. if(encoder->protected_->bits_per_sample < 16) {
  102751. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102752. /* @@@ until then we'll make a guess */
  102753. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102754. }
  102755. else if(encoder->protected_->bits_per_sample == 16) {
  102756. if(encoder->protected_->blocksize <= 192)
  102757. encoder->protected_->qlp_coeff_precision = 7;
  102758. else if(encoder->protected_->blocksize <= 384)
  102759. encoder->protected_->qlp_coeff_precision = 8;
  102760. else if(encoder->protected_->blocksize <= 576)
  102761. encoder->protected_->qlp_coeff_precision = 9;
  102762. else if(encoder->protected_->blocksize <= 1152)
  102763. encoder->protected_->qlp_coeff_precision = 10;
  102764. else if(encoder->protected_->blocksize <= 2304)
  102765. encoder->protected_->qlp_coeff_precision = 11;
  102766. else if(encoder->protected_->blocksize <= 4608)
  102767. encoder->protected_->qlp_coeff_precision = 12;
  102768. else
  102769. encoder->protected_->qlp_coeff_precision = 13;
  102770. }
  102771. else {
  102772. if(encoder->protected_->blocksize <= 384)
  102773. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102774. else if(encoder->protected_->blocksize <= 1152)
  102775. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102776. else
  102777. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102778. }
  102779. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102780. }
  102781. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102782. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102783. if(encoder->protected_->streamable_subset) {
  102784. if(
  102785. encoder->protected_->blocksize != 192 &&
  102786. encoder->protected_->blocksize != 576 &&
  102787. encoder->protected_->blocksize != 1152 &&
  102788. encoder->protected_->blocksize != 2304 &&
  102789. encoder->protected_->blocksize != 4608 &&
  102790. encoder->protected_->blocksize != 256 &&
  102791. encoder->protected_->blocksize != 512 &&
  102792. encoder->protected_->blocksize != 1024 &&
  102793. encoder->protected_->blocksize != 2048 &&
  102794. encoder->protected_->blocksize != 4096 &&
  102795. encoder->protected_->blocksize != 8192 &&
  102796. encoder->protected_->blocksize != 16384
  102797. )
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102799. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102800. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102801. if(
  102802. encoder->protected_->bits_per_sample != 8 &&
  102803. encoder->protected_->bits_per_sample != 12 &&
  102804. encoder->protected_->bits_per_sample != 16 &&
  102805. encoder->protected_->bits_per_sample != 20 &&
  102806. encoder->protected_->bits_per_sample != 24
  102807. )
  102808. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102809. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102810. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102811. if(
  102812. encoder->protected_->sample_rate <= 48000 &&
  102813. (
  102814. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102815. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102816. )
  102817. ) {
  102818. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102819. }
  102820. }
  102821. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102822. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102823. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102824. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102825. #if FLAC__HAS_OGG
  102826. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102827. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102828. unsigned i;
  102829. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102830. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102831. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102832. for( ; i > 0; i--)
  102833. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102834. encoder->protected_->metadata[0] = vc;
  102835. break;
  102836. }
  102837. }
  102838. }
  102839. #endif
  102840. /* keep track of any SEEKTABLE block */
  102841. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102842. unsigned i;
  102843. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102844. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102845. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102846. break; /* take only the first one */
  102847. }
  102848. }
  102849. }
  102850. /* validate metadata */
  102851. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102852. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102853. metadata_has_seektable = false;
  102854. metadata_has_vorbis_comment = false;
  102855. metadata_picture_has_type1 = false;
  102856. metadata_picture_has_type2 = false;
  102857. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102858. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102859. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102860. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102861. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102862. if(metadata_has_seektable) /* only one is allowed */
  102863. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102864. metadata_has_seektable = true;
  102865. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102866. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102867. }
  102868. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102869. if(metadata_has_vorbis_comment) /* only one is allowed */
  102870. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102871. metadata_has_vorbis_comment = true;
  102872. }
  102873. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102874. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102875. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102876. }
  102877. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102878. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102879. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102880. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102881. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102882. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102883. metadata_picture_has_type1 = true;
  102884. /* standard icon must be 32x32 pixel PNG */
  102885. if(
  102886. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102887. (
  102888. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102889. m->data.picture.width != 32 ||
  102890. m->data.picture.height != 32
  102891. )
  102892. )
  102893. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102894. }
  102895. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102896. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102897. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102898. metadata_picture_has_type2 = true;
  102899. }
  102900. }
  102901. }
  102902. encoder->private_->input_capacity = 0;
  102903. for(i = 0; i < encoder->protected_->channels; i++) {
  102904. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102905. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102906. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102907. #endif
  102908. }
  102909. for(i = 0; i < 2; i++) {
  102910. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102911. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102912. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102913. #endif
  102914. }
  102915. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102916. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102917. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102918. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102919. #endif
  102920. for(i = 0; i < encoder->protected_->channels; i++) {
  102921. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102922. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102923. encoder->private_->best_subframe[i] = 0;
  102924. }
  102925. for(i = 0; i < 2; i++) {
  102926. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102927. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102928. encoder->private_->best_subframe_mid_side[i] = 0;
  102929. }
  102930. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102931. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102932. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102933. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102934. #else
  102935. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102936. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102937. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102938. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102939. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102940. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102941. 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);
  102942. #endif
  102943. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102944. encoder->private_->loose_mid_side_stereo_frames = 1;
  102945. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102946. encoder->private_->current_sample_number = 0;
  102947. encoder->private_->current_frame_number = 0;
  102948. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102949. 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? */
  102950. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102951. /*
  102952. * get the CPU info and set the function pointers
  102953. */
  102954. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102955. /* first default to the non-asm routines */
  102956. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102957. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102958. #endif
  102959. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102960. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102961. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102962. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102963. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102964. #endif
  102965. /* now override with asm where appropriate */
  102966. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102967. # ifndef FLAC__NO_ASM
  102968. if(encoder->private_->cpuinfo.use_asm) {
  102969. # ifdef FLAC__CPU_IA32
  102970. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102971. # ifdef FLAC__HAS_NASM
  102972. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102973. if(encoder->protected_->max_lpc_order < 4)
  102974. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102975. else if(encoder->protected_->max_lpc_order < 8)
  102976. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102977. else if(encoder->protected_->max_lpc_order < 12)
  102978. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102979. else
  102980. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102981. }
  102982. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102983. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102984. else
  102985. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102986. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102987. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102988. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102989. }
  102990. else {
  102991. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102992. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102993. }
  102994. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102995. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102996. # endif /* FLAC__HAS_NASM */
  102997. # endif /* FLAC__CPU_IA32 */
  102998. }
  102999. # endif /* !FLAC__NO_ASM */
  103000. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103001. /* finally override based on wide-ness if necessary */
  103002. if(encoder->private_->use_wide_by_block) {
  103003. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103004. }
  103005. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103006. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103007. #if FLAC__HAS_OGG
  103008. encoder->private_->is_ogg = is_ogg;
  103009. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103010. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103011. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103012. }
  103013. #endif
  103014. encoder->private_->read_callback = read_callback;
  103015. encoder->private_->write_callback = write_callback;
  103016. encoder->private_->seek_callback = seek_callback;
  103017. encoder->private_->tell_callback = tell_callback;
  103018. encoder->private_->metadata_callback = metadata_callback;
  103019. encoder->private_->client_data = client_data;
  103020. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103021. /* the above function sets the state for us in case of an error */
  103022. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103023. }
  103024. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103025. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103026. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103027. }
  103028. /*
  103029. * Set up the verify stuff if necessary
  103030. */
  103031. if(encoder->protected_->verify) {
  103032. /*
  103033. * First, set up the fifo which will hold the
  103034. * original signal to compare against
  103035. */
  103036. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103037. for(i = 0; i < encoder->protected_->channels; i++) {
  103038. 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))) {
  103039. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103040. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103041. }
  103042. }
  103043. encoder->private_->verify.input_fifo.tail = 0;
  103044. /*
  103045. * Now set up a stream decoder for verification
  103046. */
  103047. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103048. if(0 == encoder->private_->verify.decoder) {
  103049. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103050. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103051. }
  103052. 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) {
  103053. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103054. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103055. }
  103056. }
  103057. encoder->private_->verify.error_stats.absolute_sample = 0;
  103058. encoder->private_->verify.error_stats.frame_number = 0;
  103059. encoder->private_->verify.error_stats.channel = 0;
  103060. encoder->private_->verify.error_stats.sample = 0;
  103061. encoder->private_->verify.error_stats.expected = 0;
  103062. encoder->private_->verify.error_stats.got = 0;
  103063. /*
  103064. * These must be done before we write any metadata, because that
  103065. * calls the write_callback, which uses these values.
  103066. */
  103067. encoder->private_->first_seekpoint_to_check = 0;
  103068. encoder->private_->samples_written = 0;
  103069. encoder->protected_->streaminfo_offset = 0;
  103070. encoder->protected_->seektable_offset = 0;
  103071. encoder->protected_->audio_offset = 0;
  103072. /*
  103073. * write the stream header
  103074. */
  103075. if(encoder->protected_->verify)
  103076. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103077. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103078. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103079. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103080. }
  103081. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103082. /* the above function sets the state for us in case of an error */
  103083. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103084. }
  103085. /*
  103086. * write the STREAMINFO metadata block
  103087. */
  103088. if(encoder->protected_->verify)
  103089. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103090. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103091. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103092. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103093. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103094. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103095. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103096. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103097. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103098. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103099. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103100. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103101. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103102. if(encoder->protected_->do_md5)
  103103. FLAC__MD5Init(&encoder->private_->md5context);
  103104. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103105. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103106. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103107. }
  103108. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103109. /* the above function sets the state for us in case of an error */
  103110. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103111. }
  103112. /*
  103113. * Now that the STREAMINFO block is written, we can init this to an
  103114. * absurdly-high value...
  103115. */
  103116. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103117. /* ... and clear this to 0 */
  103118. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103119. /*
  103120. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103121. * if not, we will write an empty one (FLAC__add_metadata_block()
  103122. * automatically supplies the vendor string).
  103123. *
  103124. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103125. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103126. * true it will have already insured that the metadata list is properly
  103127. * ordered.)
  103128. */
  103129. if(!metadata_has_vorbis_comment) {
  103130. FLAC__StreamMetadata vorbis_comment;
  103131. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103132. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103133. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103134. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103135. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103136. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103137. vorbis_comment.data.vorbis_comment.comments = 0;
  103138. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103139. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103140. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103141. }
  103142. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103143. /* the above function sets the state for us in case of an error */
  103144. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103145. }
  103146. }
  103147. /*
  103148. * write the user's metadata blocks
  103149. */
  103150. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103151. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103152. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103153. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103154. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103155. }
  103156. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103157. /* the above function sets the state for us in case of an error */
  103158. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103159. }
  103160. }
  103161. /* now that all the metadata is written, we save the stream offset */
  103162. 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 */
  103163. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103164. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103165. }
  103166. if(encoder->protected_->verify)
  103167. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103168. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103169. }
  103170. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103171. FLAC__StreamEncoder *encoder,
  103172. FLAC__StreamEncoderWriteCallback write_callback,
  103173. FLAC__StreamEncoderSeekCallback seek_callback,
  103174. FLAC__StreamEncoderTellCallback tell_callback,
  103175. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103176. void *client_data
  103177. )
  103178. {
  103179. return init_stream_internal_enc(
  103180. encoder,
  103181. /*read_callback=*/0,
  103182. write_callback,
  103183. seek_callback,
  103184. tell_callback,
  103185. metadata_callback,
  103186. client_data,
  103187. /*is_ogg=*/false
  103188. );
  103189. }
  103190. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103191. FLAC__StreamEncoder *encoder,
  103192. FLAC__StreamEncoderReadCallback read_callback,
  103193. FLAC__StreamEncoderWriteCallback write_callback,
  103194. FLAC__StreamEncoderSeekCallback seek_callback,
  103195. FLAC__StreamEncoderTellCallback tell_callback,
  103196. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103197. void *client_data
  103198. )
  103199. {
  103200. return init_stream_internal_enc(
  103201. encoder,
  103202. read_callback,
  103203. write_callback,
  103204. seek_callback,
  103205. tell_callback,
  103206. metadata_callback,
  103207. client_data,
  103208. /*is_ogg=*/true
  103209. );
  103210. }
  103211. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103212. FLAC__StreamEncoder *encoder,
  103213. FILE *file,
  103214. FLAC__StreamEncoderProgressCallback progress_callback,
  103215. void *client_data,
  103216. FLAC__bool is_ogg
  103217. )
  103218. {
  103219. FLAC__StreamEncoderInitStatus init_status;
  103220. FLAC__ASSERT(0 != encoder);
  103221. FLAC__ASSERT(0 != file);
  103222. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103223. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103224. /* double protection */
  103225. if(file == 0) {
  103226. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103227. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103228. }
  103229. /*
  103230. * To make sure that our file does not go unclosed after an error, we
  103231. * must assign the FILE pointer before any further error can occur in
  103232. * this routine.
  103233. */
  103234. if(file == stdout)
  103235. file = get_binary_stdout_(); /* just to be safe */
  103236. encoder->private_->file = file;
  103237. encoder->private_->progress_callback = progress_callback;
  103238. encoder->private_->bytes_written = 0;
  103239. encoder->private_->samples_written = 0;
  103240. encoder->private_->frames_written = 0;
  103241. init_status = init_stream_internal_enc(
  103242. encoder,
  103243. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103244. file_write_callback_,
  103245. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103246. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103247. /*metadata_callback=*/0,
  103248. client_data,
  103249. is_ogg
  103250. );
  103251. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103252. /* the above function sets the state for us in case of an error */
  103253. return init_status;
  103254. }
  103255. {
  103256. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103257. FLAC__ASSERT(blocksize != 0);
  103258. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103259. }
  103260. return init_status;
  103261. }
  103262. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103263. FLAC__StreamEncoder *encoder,
  103264. FILE *file,
  103265. FLAC__StreamEncoderProgressCallback progress_callback,
  103266. void *client_data
  103267. )
  103268. {
  103269. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103270. }
  103271. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103272. FLAC__StreamEncoder *encoder,
  103273. FILE *file,
  103274. FLAC__StreamEncoderProgressCallback progress_callback,
  103275. void *client_data
  103276. )
  103277. {
  103278. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103279. }
  103280. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103281. FLAC__StreamEncoder *encoder,
  103282. const char *filename,
  103283. FLAC__StreamEncoderProgressCallback progress_callback,
  103284. void *client_data,
  103285. FLAC__bool is_ogg
  103286. )
  103287. {
  103288. FILE *file;
  103289. FLAC__ASSERT(0 != encoder);
  103290. /*
  103291. * To make sure that our file does not go unclosed after an error, we
  103292. * have to do the same entrance checks here that are later performed
  103293. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103294. */
  103295. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103296. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103297. file = filename? fopen(filename, "w+b") : stdout;
  103298. if(file == 0) {
  103299. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103300. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103301. }
  103302. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103303. }
  103304. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103305. FLAC__StreamEncoder *encoder,
  103306. const char *filename,
  103307. FLAC__StreamEncoderProgressCallback progress_callback,
  103308. void *client_data
  103309. )
  103310. {
  103311. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103312. }
  103313. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103314. FLAC__StreamEncoder *encoder,
  103315. const char *filename,
  103316. FLAC__StreamEncoderProgressCallback progress_callback,
  103317. void *client_data
  103318. )
  103319. {
  103320. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103321. }
  103322. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103323. {
  103324. FLAC__bool error = false;
  103325. FLAC__ASSERT(0 != encoder);
  103326. FLAC__ASSERT(0 != encoder->private_);
  103327. FLAC__ASSERT(0 != encoder->protected_);
  103328. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103329. return true;
  103330. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103331. if(encoder->private_->current_sample_number != 0) {
  103332. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103333. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103334. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103335. error = true;
  103336. }
  103337. }
  103338. if(encoder->protected_->do_md5)
  103339. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103340. if(!encoder->private_->is_being_deleted) {
  103341. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103342. if(encoder->private_->seek_callback) {
  103343. #if FLAC__HAS_OGG
  103344. if(encoder->private_->is_ogg)
  103345. update_ogg_metadata_(encoder);
  103346. else
  103347. #endif
  103348. update_metadata_(encoder);
  103349. /* check if an error occurred while updating metadata */
  103350. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103351. error = true;
  103352. }
  103353. if(encoder->private_->metadata_callback)
  103354. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103355. }
  103356. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103357. if(!error)
  103358. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103359. error = true;
  103360. }
  103361. }
  103362. if(0 != encoder->private_->file) {
  103363. if(encoder->private_->file != stdout)
  103364. fclose(encoder->private_->file);
  103365. encoder->private_->file = 0;
  103366. }
  103367. #if FLAC__HAS_OGG
  103368. if(encoder->private_->is_ogg)
  103369. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103370. #endif
  103371. free_(encoder);
  103372. set_defaults_enc(encoder);
  103373. if(!error)
  103374. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103375. return !error;
  103376. }
  103377. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103378. {
  103379. FLAC__ASSERT(0 != encoder);
  103380. FLAC__ASSERT(0 != encoder->private_);
  103381. FLAC__ASSERT(0 != encoder->protected_);
  103382. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103383. return false;
  103384. #if FLAC__HAS_OGG
  103385. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103386. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103387. return true;
  103388. #else
  103389. (void)value;
  103390. return false;
  103391. #endif
  103392. }
  103393. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103394. {
  103395. FLAC__ASSERT(0 != encoder);
  103396. FLAC__ASSERT(0 != encoder->private_);
  103397. FLAC__ASSERT(0 != encoder->protected_);
  103398. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103399. return false;
  103400. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103401. encoder->protected_->verify = value;
  103402. #endif
  103403. return true;
  103404. }
  103405. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103406. {
  103407. FLAC__ASSERT(0 != encoder);
  103408. FLAC__ASSERT(0 != encoder->private_);
  103409. FLAC__ASSERT(0 != encoder->protected_);
  103410. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103411. return false;
  103412. encoder->protected_->streamable_subset = value;
  103413. return true;
  103414. }
  103415. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103416. {
  103417. FLAC__ASSERT(0 != encoder);
  103418. FLAC__ASSERT(0 != encoder->private_);
  103419. FLAC__ASSERT(0 != encoder->protected_);
  103420. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103421. return false;
  103422. encoder->protected_->do_md5 = value;
  103423. return true;
  103424. }
  103425. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103426. {
  103427. FLAC__ASSERT(0 != encoder);
  103428. FLAC__ASSERT(0 != encoder->private_);
  103429. FLAC__ASSERT(0 != encoder->protected_);
  103430. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103431. return false;
  103432. encoder->protected_->channels = value;
  103433. return true;
  103434. }
  103435. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103436. {
  103437. FLAC__ASSERT(0 != encoder);
  103438. FLAC__ASSERT(0 != encoder->private_);
  103439. FLAC__ASSERT(0 != encoder->protected_);
  103440. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103441. return false;
  103442. encoder->protected_->bits_per_sample = value;
  103443. return true;
  103444. }
  103445. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103446. {
  103447. FLAC__ASSERT(0 != encoder);
  103448. FLAC__ASSERT(0 != encoder->private_);
  103449. FLAC__ASSERT(0 != encoder->protected_);
  103450. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103451. return false;
  103452. encoder->protected_->sample_rate = value;
  103453. return true;
  103454. }
  103455. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103456. {
  103457. FLAC__bool ok = true;
  103458. FLAC__ASSERT(0 != encoder);
  103459. FLAC__ASSERT(0 != encoder->private_);
  103460. FLAC__ASSERT(0 != encoder->protected_);
  103461. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103462. return false;
  103463. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103464. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103465. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103466. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103467. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103468. #if 0
  103469. /* was: */
  103470. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103471. /* but it's too hard to specify the string in a locale-specific way */
  103472. #else
  103473. encoder->protected_->num_apodizations = 1;
  103474. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103475. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103476. #endif
  103477. #endif
  103478. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103479. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103480. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103481. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103482. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103483. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103484. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103485. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103486. return ok;
  103487. }
  103488. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103489. {
  103490. FLAC__ASSERT(0 != encoder);
  103491. FLAC__ASSERT(0 != encoder->private_);
  103492. FLAC__ASSERT(0 != encoder->protected_);
  103493. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103494. return false;
  103495. encoder->protected_->blocksize = value;
  103496. return true;
  103497. }
  103498. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103499. {
  103500. FLAC__ASSERT(0 != encoder);
  103501. FLAC__ASSERT(0 != encoder->private_);
  103502. FLAC__ASSERT(0 != encoder->protected_);
  103503. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103504. return false;
  103505. encoder->protected_->do_mid_side_stereo = value;
  103506. return true;
  103507. }
  103508. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103509. {
  103510. FLAC__ASSERT(0 != encoder);
  103511. FLAC__ASSERT(0 != encoder->private_);
  103512. FLAC__ASSERT(0 != encoder->protected_);
  103513. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103514. return false;
  103515. encoder->protected_->loose_mid_side_stereo = value;
  103516. return true;
  103517. }
  103518. /*@@@@add to tests*/
  103519. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103520. {
  103521. FLAC__ASSERT(0 != encoder);
  103522. FLAC__ASSERT(0 != encoder->private_);
  103523. FLAC__ASSERT(0 != encoder->protected_);
  103524. FLAC__ASSERT(0 != specification);
  103525. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103526. return false;
  103527. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103528. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103529. #else
  103530. encoder->protected_->num_apodizations = 0;
  103531. while(1) {
  103532. const char *s = strchr(specification, ';');
  103533. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103534. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103535. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103536. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103537. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103538. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103539. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103540. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103541. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103542. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103543. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103544. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103545. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103546. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103547. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103548. if (stddev > 0.0 && stddev <= 0.5) {
  103549. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103550. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103551. }
  103552. }
  103553. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103554. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103555. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103556. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103557. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103558. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103559. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103560. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103561. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103562. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103563. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103564. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103565. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103566. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103567. if (p >= 0.0 && p <= 1.0) {
  103568. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103569. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103570. }
  103571. }
  103572. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103573. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103574. if (encoder->protected_->num_apodizations == 32)
  103575. break;
  103576. if (s)
  103577. specification = s+1;
  103578. else
  103579. break;
  103580. }
  103581. if(encoder->protected_->num_apodizations == 0) {
  103582. encoder->protected_->num_apodizations = 1;
  103583. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103584. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103585. }
  103586. #endif
  103587. return true;
  103588. }
  103589. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103590. {
  103591. FLAC__ASSERT(0 != encoder);
  103592. FLAC__ASSERT(0 != encoder->private_);
  103593. FLAC__ASSERT(0 != encoder->protected_);
  103594. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103595. return false;
  103596. encoder->protected_->max_lpc_order = value;
  103597. return true;
  103598. }
  103599. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103600. {
  103601. FLAC__ASSERT(0 != encoder);
  103602. FLAC__ASSERT(0 != encoder->private_);
  103603. FLAC__ASSERT(0 != encoder->protected_);
  103604. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103605. return false;
  103606. encoder->protected_->qlp_coeff_precision = value;
  103607. return true;
  103608. }
  103609. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103610. {
  103611. FLAC__ASSERT(0 != encoder);
  103612. FLAC__ASSERT(0 != encoder->private_);
  103613. FLAC__ASSERT(0 != encoder->protected_);
  103614. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103615. return false;
  103616. encoder->protected_->do_qlp_coeff_prec_search = value;
  103617. return true;
  103618. }
  103619. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103620. {
  103621. FLAC__ASSERT(0 != encoder);
  103622. FLAC__ASSERT(0 != encoder->private_);
  103623. FLAC__ASSERT(0 != encoder->protected_);
  103624. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103625. return false;
  103626. #if 0
  103627. /*@@@ deprecated: */
  103628. encoder->protected_->do_escape_coding = value;
  103629. #else
  103630. (void)value;
  103631. #endif
  103632. return true;
  103633. }
  103634. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103635. {
  103636. FLAC__ASSERT(0 != encoder);
  103637. FLAC__ASSERT(0 != encoder->private_);
  103638. FLAC__ASSERT(0 != encoder->protected_);
  103639. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103640. return false;
  103641. encoder->protected_->do_exhaustive_model_search = value;
  103642. return true;
  103643. }
  103644. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103645. {
  103646. FLAC__ASSERT(0 != encoder);
  103647. FLAC__ASSERT(0 != encoder->private_);
  103648. FLAC__ASSERT(0 != encoder->protected_);
  103649. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103650. return false;
  103651. encoder->protected_->min_residual_partition_order = value;
  103652. return true;
  103653. }
  103654. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103655. {
  103656. FLAC__ASSERT(0 != encoder);
  103657. FLAC__ASSERT(0 != encoder->private_);
  103658. FLAC__ASSERT(0 != encoder->protected_);
  103659. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103660. return false;
  103661. encoder->protected_->max_residual_partition_order = value;
  103662. return true;
  103663. }
  103664. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103665. {
  103666. FLAC__ASSERT(0 != encoder);
  103667. FLAC__ASSERT(0 != encoder->private_);
  103668. FLAC__ASSERT(0 != encoder->protected_);
  103669. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103670. return false;
  103671. #if 0
  103672. /*@@@ deprecated: */
  103673. encoder->protected_->rice_parameter_search_dist = value;
  103674. #else
  103675. (void)value;
  103676. #endif
  103677. return true;
  103678. }
  103679. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103680. {
  103681. FLAC__ASSERT(0 != encoder);
  103682. FLAC__ASSERT(0 != encoder->private_);
  103683. FLAC__ASSERT(0 != encoder->protected_);
  103684. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103685. return false;
  103686. encoder->protected_->total_samples_estimate = value;
  103687. return true;
  103688. }
  103689. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103690. {
  103691. FLAC__ASSERT(0 != encoder);
  103692. FLAC__ASSERT(0 != encoder->private_);
  103693. FLAC__ASSERT(0 != encoder->protected_);
  103694. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103695. return false;
  103696. if(0 == metadata)
  103697. num_blocks = 0;
  103698. if(0 == num_blocks)
  103699. metadata = 0;
  103700. /* realloc() does not do exactly what we want so... */
  103701. if(encoder->protected_->metadata) {
  103702. free(encoder->protected_->metadata);
  103703. encoder->protected_->metadata = 0;
  103704. encoder->protected_->num_metadata_blocks = 0;
  103705. }
  103706. if(num_blocks) {
  103707. FLAC__StreamMetadata **m;
  103708. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103709. return false;
  103710. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103711. encoder->protected_->metadata = m;
  103712. encoder->protected_->num_metadata_blocks = num_blocks;
  103713. }
  103714. #if FLAC__HAS_OGG
  103715. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103716. return false;
  103717. #endif
  103718. return true;
  103719. }
  103720. /*
  103721. * These three functions are not static, but not publically exposed in
  103722. * include/FLAC/ either. They are used by the test suite.
  103723. */
  103724. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103725. {
  103726. FLAC__ASSERT(0 != encoder);
  103727. FLAC__ASSERT(0 != encoder->private_);
  103728. FLAC__ASSERT(0 != encoder->protected_);
  103729. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103730. return false;
  103731. encoder->private_->disable_constant_subframes = value;
  103732. return true;
  103733. }
  103734. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103735. {
  103736. FLAC__ASSERT(0 != encoder);
  103737. FLAC__ASSERT(0 != encoder->private_);
  103738. FLAC__ASSERT(0 != encoder->protected_);
  103739. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103740. return false;
  103741. encoder->private_->disable_fixed_subframes = value;
  103742. return true;
  103743. }
  103744. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103745. {
  103746. FLAC__ASSERT(0 != encoder);
  103747. FLAC__ASSERT(0 != encoder->private_);
  103748. FLAC__ASSERT(0 != encoder->protected_);
  103749. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103750. return false;
  103751. encoder->private_->disable_verbatim_subframes = value;
  103752. return true;
  103753. }
  103754. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103755. {
  103756. FLAC__ASSERT(0 != encoder);
  103757. FLAC__ASSERT(0 != encoder->private_);
  103758. FLAC__ASSERT(0 != encoder->protected_);
  103759. return encoder->protected_->state;
  103760. }
  103761. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103762. {
  103763. FLAC__ASSERT(0 != encoder);
  103764. FLAC__ASSERT(0 != encoder->private_);
  103765. FLAC__ASSERT(0 != encoder->protected_);
  103766. if(encoder->protected_->verify)
  103767. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103768. else
  103769. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103770. }
  103771. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103772. {
  103773. FLAC__ASSERT(0 != encoder);
  103774. FLAC__ASSERT(0 != encoder->private_);
  103775. FLAC__ASSERT(0 != encoder->protected_);
  103776. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103777. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103778. else
  103779. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103780. }
  103781. 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)
  103782. {
  103783. FLAC__ASSERT(0 != encoder);
  103784. FLAC__ASSERT(0 != encoder->private_);
  103785. FLAC__ASSERT(0 != encoder->protected_);
  103786. if(0 != absolute_sample)
  103787. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103788. if(0 != frame_number)
  103789. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103790. if(0 != channel)
  103791. *channel = encoder->private_->verify.error_stats.channel;
  103792. if(0 != sample)
  103793. *sample = encoder->private_->verify.error_stats.sample;
  103794. if(0 != expected)
  103795. *expected = encoder->private_->verify.error_stats.expected;
  103796. if(0 != got)
  103797. *got = encoder->private_->verify.error_stats.got;
  103798. }
  103799. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103800. {
  103801. FLAC__ASSERT(0 != encoder);
  103802. FLAC__ASSERT(0 != encoder->private_);
  103803. FLAC__ASSERT(0 != encoder->protected_);
  103804. return encoder->protected_->verify;
  103805. }
  103806. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103807. {
  103808. FLAC__ASSERT(0 != encoder);
  103809. FLAC__ASSERT(0 != encoder->private_);
  103810. FLAC__ASSERT(0 != encoder->protected_);
  103811. return encoder->protected_->streamable_subset;
  103812. }
  103813. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103814. {
  103815. FLAC__ASSERT(0 != encoder);
  103816. FLAC__ASSERT(0 != encoder->private_);
  103817. FLAC__ASSERT(0 != encoder->protected_);
  103818. return encoder->protected_->do_md5;
  103819. }
  103820. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103821. {
  103822. FLAC__ASSERT(0 != encoder);
  103823. FLAC__ASSERT(0 != encoder->private_);
  103824. FLAC__ASSERT(0 != encoder->protected_);
  103825. return encoder->protected_->channels;
  103826. }
  103827. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103828. {
  103829. FLAC__ASSERT(0 != encoder);
  103830. FLAC__ASSERT(0 != encoder->private_);
  103831. FLAC__ASSERT(0 != encoder->protected_);
  103832. return encoder->protected_->bits_per_sample;
  103833. }
  103834. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103835. {
  103836. FLAC__ASSERT(0 != encoder);
  103837. FLAC__ASSERT(0 != encoder->private_);
  103838. FLAC__ASSERT(0 != encoder->protected_);
  103839. return encoder->protected_->sample_rate;
  103840. }
  103841. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103842. {
  103843. FLAC__ASSERT(0 != encoder);
  103844. FLAC__ASSERT(0 != encoder->private_);
  103845. FLAC__ASSERT(0 != encoder->protected_);
  103846. return encoder->protected_->blocksize;
  103847. }
  103848. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103849. {
  103850. FLAC__ASSERT(0 != encoder);
  103851. FLAC__ASSERT(0 != encoder->private_);
  103852. FLAC__ASSERT(0 != encoder->protected_);
  103853. return encoder->protected_->do_mid_side_stereo;
  103854. }
  103855. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103856. {
  103857. FLAC__ASSERT(0 != encoder);
  103858. FLAC__ASSERT(0 != encoder->private_);
  103859. FLAC__ASSERT(0 != encoder->protected_);
  103860. return encoder->protected_->loose_mid_side_stereo;
  103861. }
  103862. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103863. {
  103864. FLAC__ASSERT(0 != encoder);
  103865. FLAC__ASSERT(0 != encoder->private_);
  103866. FLAC__ASSERT(0 != encoder->protected_);
  103867. return encoder->protected_->max_lpc_order;
  103868. }
  103869. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103870. {
  103871. FLAC__ASSERT(0 != encoder);
  103872. FLAC__ASSERT(0 != encoder->private_);
  103873. FLAC__ASSERT(0 != encoder->protected_);
  103874. return encoder->protected_->qlp_coeff_precision;
  103875. }
  103876. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103877. {
  103878. FLAC__ASSERT(0 != encoder);
  103879. FLAC__ASSERT(0 != encoder->private_);
  103880. FLAC__ASSERT(0 != encoder->protected_);
  103881. return encoder->protected_->do_qlp_coeff_prec_search;
  103882. }
  103883. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103884. {
  103885. FLAC__ASSERT(0 != encoder);
  103886. FLAC__ASSERT(0 != encoder->private_);
  103887. FLAC__ASSERT(0 != encoder->protected_);
  103888. return encoder->protected_->do_escape_coding;
  103889. }
  103890. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103891. {
  103892. FLAC__ASSERT(0 != encoder);
  103893. FLAC__ASSERT(0 != encoder->private_);
  103894. FLAC__ASSERT(0 != encoder->protected_);
  103895. return encoder->protected_->do_exhaustive_model_search;
  103896. }
  103897. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103898. {
  103899. FLAC__ASSERT(0 != encoder);
  103900. FLAC__ASSERT(0 != encoder->private_);
  103901. FLAC__ASSERT(0 != encoder->protected_);
  103902. return encoder->protected_->min_residual_partition_order;
  103903. }
  103904. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103905. {
  103906. FLAC__ASSERT(0 != encoder);
  103907. FLAC__ASSERT(0 != encoder->private_);
  103908. FLAC__ASSERT(0 != encoder->protected_);
  103909. return encoder->protected_->max_residual_partition_order;
  103910. }
  103911. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103912. {
  103913. FLAC__ASSERT(0 != encoder);
  103914. FLAC__ASSERT(0 != encoder->private_);
  103915. FLAC__ASSERT(0 != encoder->protected_);
  103916. return encoder->protected_->rice_parameter_search_dist;
  103917. }
  103918. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103919. {
  103920. FLAC__ASSERT(0 != encoder);
  103921. FLAC__ASSERT(0 != encoder->private_);
  103922. FLAC__ASSERT(0 != encoder->protected_);
  103923. return encoder->protected_->total_samples_estimate;
  103924. }
  103925. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103926. {
  103927. unsigned i, j = 0, channel;
  103928. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103929. FLAC__ASSERT(0 != encoder);
  103930. FLAC__ASSERT(0 != encoder->private_);
  103931. FLAC__ASSERT(0 != encoder->protected_);
  103932. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103933. do {
  103934. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103935. if(encoder->protected_->verify)
  103936. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103937. for(channel = 0; channel < channels; channel++)
  103938. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103939. if(encoder->protected_->do_mid_side_stereo) {
  103940. FLAC__ASSERT(channels == 2);
  103941. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103942. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103943. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103944. 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' ! */
  103945. }
  103946. }
  103947. else
  103948. j += n;
  103949. encoder->private_->current_sample_number += n;
  103950. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103951. if(encoder->private_->current_sample_number > blocksize) {
  103952. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103953. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103954. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103955. return false;
  103956. /* move unprocessed overread samples to beginnings of arrays */
  103957. for(channel = 0; channel < channels; channel++)
  103958. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103959. if(encoder->protected_->do_mid_side_stereo) {
  103960. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103961. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103962. }
  103963. encoder->private_->current_sample_number = 1;
  103964. }
  103965. } while(j < samples);
  103966. return true;
  103967. }
  103968. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103969. {
  103970. unsigned i, j, k, channel;
  103971. FLAC__int32 x, mid, side;
  103972. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103973. FLAC__ASSERT(0 != encoder);
  103974. FLAC__ASSERT(0 != encoder->private_);
  103975. FLAC__ASSERT(0 != encoder->protected_);
  103976. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103977. j = k = 0;
  103978. /*
  103979. * we have several flavors of the same basic loop, optimized for
  103980. * different conditions:
  103981. */
  103982. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103983. /*
  103984. * stereo coding: unroll channel loop
  103985. */
  103986. do {
  103987. if(encoder->protected_->verify)
  103988. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103989. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103990. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103991. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103992. x = buffer[k++];
  103993. encoder->private_->integer_signal[1][i] = x;
  103994. mid += x;
  103995. side -= x;
  103996. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103997. encoder->private_->integer_signal_mid_side[1][i] = side;
  103998. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103999. }
  104000. encoder->private_->current_sample_number = i;
  104001. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104002. if(i > blocksize) {
  104003. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104004. return false;
  104005. /* move unprocessed overread samples to beginnings of arrays */
  104006. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104007. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104008. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104009. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104010. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104011. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104012. encoder->private_->current_sample_number = 1;
  104013. }
  104014. } while(j < samples);
  104015. }
  104016. else {
  104017. /*
  104018. * independent channel coding: buffer each channel in inner loop
  104019. */
  104020. do {
  104021. if(encoder->protected_->verify)
  104022. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104023. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104024. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104025. for(channel = 0; channel < channels; channel++)
  104026. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104027. }
  104028. encoder->private_->current_sample_number = i;
  104029. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104030. if(i > blocksize) {
  104031. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104032. return false;
  104033. /* move unprocessed overread samples to beginnings of arrays */
  104034. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104035. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104036. for(channel = 0; channel < channels; channel++)
  104037. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104038. encoder->private_->current_sample_number = 1;
  104039. }
  104040. } while(j < samples);
  104041. }
  104042. return true;
  104043. }
  104044. /***********************************************************************
  104045. *
  104046. * Private class methods
  104047. *
  104048. ***********************************************************************/
  104049. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104050. {
  104051. FLAC__ASSERT(0 != encoder);
  104052. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104053. encoder->protected_->verify = true;
  104054. #else
  104055. encoder->protected_->verify = false;
  104056. #endif
  104057. encoder->protected_->streamable_subset = true;
  104058. encoder->protected_->do_md5 = true;
  104059. encoder->protected_->do_mid_side_stereo = false;
  104060. encoder->protected_->loose_mid_side_stereo = false;
  104061. encoder->protected_->channels = 2;
  104062. encoder->protected_->bits_per_sample = 16;
  104063. encoder->protected_->sample_rate = 44100;
  104064. encoder->protected_->blocksize = 0;
  104065. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104066. encoder->protected_->num_apodizations = 1;
  104067. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104068. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104069. #endif
  104070. encoder->protected_->max_lpc_order = 0;
  104071. encoder->protected_->qlp_coeff_precision = 0;
  104072. encoder->protected_->do_qlp_coeff_prec_search = false;
  104073. encoder->protected_->do_exhaustive_model_search = false;
  104074. encoder->protected_->do_escape_coding = false;
  104075. encoder->protected_->min_residual_partition_order = 0;
  104076. encoder->protected_->max_residual_partition_order = 0;
  104077. encoder->protected_->rice_parameter_search_dist = 0;
  104078. encoder->protected_->total_samples_estimate = 0;
  104079. encoder->protected_->metadata = 0;
  104080. encoder->protected_->num_metadata_blocks = 0;
  104081. encoder->private_->seek_table = 0;
  104082. encoder->private_->disable_constant_subframes = false;
  104083. encoder->private_->disable_fixed_subframes = false;
  104084. encoder->private_->disable_verbatim_subframes = false;
  104085. #if FLAC__HAS_OGG
  104086. encoder->private_->is_ogg = false;
  104087. #endif
  104088. encoder->private_->read_callback = 0;
  104089. encoder->private_->write_callback = 0;
  104090. encoder->private_->seek_callback = 0;
  104091. encoder->private_->tell_callback = 0;
  104092. encoder->private_->metadata_callback = 0;
  104093. encoder->private_->progress_callback = 0;
  104094. encoder->private_->client_data = 0;
  104095. #if FLAC__HAS_OGG
  104096. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104097. #endif
  104098. }
  104099. void free_(FLAC__StreamEncoder *encoder)
  104100. {
  104101. unsigned i, channel;
  104102. FLAC__ASSERT(0 != encoder);
  104103. if(encoder->protected_->metadata) {
  104104. free(encoder->protected_->metadata);
  104105. encoder->protected_->metadata = 0;
  104106. encoder->protected_->num_metadata_blocks = 0;
  104107. }
  104108. for(i = 0; i < encoder->protected_->channels; i++) {
  104109. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104110. free(encoder->private_->integer_signal_unaligned[i]);
  104111. encoder->private_->integer_signal_unaligned[i] = 0;
  104112. }
  104113. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104114. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104115. free(encoder->private_->real_signal_unaligned[i]);
  104116. encoder->private_->real_signal_unaligned[i] = 0;
  104117. }
  104118. #endif
  104119. }
  104120. for(i = 0; i < 2; i++) {
  104121. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104122. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104123. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104124. }
  104125. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104126. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104127. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104128. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104129. }
  104130. #endif
  104131. }
  104132. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104133. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104134. if(0 != encoder->private_->window_unaligned[i]) {
  104135. free(encoder->private_->window_unaligned[i]);
  104136. encoder->private_->window_unaligned[i] = 0;
  104137. }
  104138. }
  104139. if(0 != encoder->private_->windowed_signal_unaligned) {
  104140. free(encoder->private_->windowed_signal_unaligned);
  104141. encoder->private_->windowed_signal_unaligned = 0;
  104142. }
  104143. #endif
  104144. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104145. for(i = 0; i < 2; i++) {
  104146. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104147. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104148. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104149. }
  104150. }
  104151. }
  104152. for(channel = 0; channel < 2; channel++) {
  104153. for(i = 0; i < 2; i++) {
  104154. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104155. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104156. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104157. }
  104158. }
  104159. }
  104160. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104161. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104162. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104163. }
  104164. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104165. free(encoder->private_->raw_bits_per_partition_unaligned);
  104166. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104167. }
  104168. if(encoder->protected_->verify) {
  104169. for(i = 0; i < encoder->protected_->channels; i++) {
  104170. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104171. free(encoder->private_->verify.input_fifo.data[i]);
  104172. encoder->private_->verify.input_fifo.data[i] = 0;
  104173. }
  104174. }
  104175. }
  104176. FLAC__bitwriter_free(encoder->private_->frame);
  104177. }
  104178. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104179. {
  104180. FLAC__bool ok;
  104181. unsigned i, channel;
  104182. FLAC__ASSERT(new_blocksize > 0);
  104183. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104184. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104185. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104186. if(new_blocksize <= encoder->private_->input_capacity)
  104187. return true;
  104188. ok = true;
  104189. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104190. * requires that the input arrays (in our case the integer signals)
  104191. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104192. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104193. */
  104194. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104195. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104196. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104197. encoder->private_->integer_signal[i] += 4;
  104198. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104199. #if 0 /* @@@ currently unused */
  104200. if(encoder->protected_->max_lpc_order > 0)
  104201. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104202. #endif
  104203. #endif
  104204. }
  104205. for(i = 0; ok && i < 2; i++) {
  104206. 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]);
  104207. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104208. encoder->private_->integer_signal_mid_side[i] += 4;
  104209. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104210. #if 0 /* @@@ currently unused */
  104211. if(encoder->protected_->max_lpc_order > 0)
  104212. 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]);
  104213. #endif
  104214. #endif
  104215. }
  104216. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104217. if(ok && encoder->protected_->max_lpc_order > 0) {
  104218. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104219. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104220. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104221. }
  104222. #endif
  104223. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104224. for(i = 0; ok && i < 2; i++) {
  104225. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104226. }
  104227. }
  104228. for(channel = 0; ok && channel < 2; channel++) {
  104229. for(i = 0; ok && i < 2; i++) {
  104230. 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]);
  104231. }
  104232. }
  104233. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104234. /*@@@ 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) */
  104235. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104236. if(encoder->protected_->do_escape_coding)
  104237. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104238. /* now adjust the windows if the blocksize has changed */
  104239. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104240. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104241. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104242. switch(encoder->protected_->apodizations[i].type) {
  104243. case FLAC__APODIZATION_BARTLETT:
  104244. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104245. break;
  104246. case FLAC__APODIZATION_BARTLETT_HANN:
  104247. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104248. break;
  104249. case FLAC__APODIZATION_BLACKMAN:
  104250. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104251. break;
  104252. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104253. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104254. break;
  104255. case FLAC__APODIZATION_CONNES:
  104256. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104257. break;
  104258. case FLAC__APODIZATION_FLATTOP:
  104259. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104260. break;
  104261. case FLAC__APODIZATION_GAUSS:
  104262. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104263. break;
  104264. case FLAC__APODIZATION_HAMMING:
  104265. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104266. break;
  104267. case FLAC__APODIZATION_HANN:
  104268. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104269. break;
  104270. case FLAC__APODIZATION_KAISER_BESSEL:
  104271. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104272. break;
  104273. case FLAC__APODIZATION_NUTTALL:
  104274. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104275. break;
  104276. case FLAC__APODIZATION_RECTANGLE:
  104277. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104278. break;
  104279. case FLAC__APODIZATION_TRIANGLE:
  104280. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104281. break;
  104282. case FLAC__APODIZATION_TUKEY:
  104283. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104284. break;
  104285. case FLAC__APODIZATION_WELCH:
  104286. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104287. break;
  104288. default:
  104289. FLAC__ASSERT(0);
  104290. /* double protection */
  104291. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104292. break;
  104293. }
  104294. }
  104295. }
  104296. #endif
  104297. if(ok)
  104298. encoder->private_->input_capacity = new_blocksize;
  104299. else
  104300. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104301. return ok;
  104302. }
  104303. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104304. {
  104305. const FLAC__byte *buffer;
  104306. size_t bytes;
  104307. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104308. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104309. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104310. return false;
  104311. }
  104312. if(encoder->protected_->verify) {
  104313. encoder->private_->verify.output.data = buffer;
  104314. encoder->private_->verify.output.bytes = bytes;
  104315. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104316. encoder->private_->verify.needs_magic_hack = true;
  104317. }
  104318. else {
  104319. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104320. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104321. FLAC__bitwriter_clear(encoder->private_->frame);
  104322. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104323. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104324. return false;
  104325. }
  104326. }
  104327. }
  104328. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104329. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104330. FLAC__bitwriter_clear(encoder->private_->frame);
  104331. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104332. return false;
  104333. }
  104334. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104335. FLAC__bitwriter_clear(encoder->private_->frame);
  104336. if(samples > 0) {
  104337. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104338. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104339. }
  104340. return true;
  104341. }
  104342. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104343. {
  104344. FLAC__StreamEncoderWriteStatus status;
  104345. FLAC__uint64 output_position = 0;
  104346. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104347. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104348. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104349. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104350. }
  104351. /*
  104352. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104353. */
  104354. if(samples == 0) {
  104355. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104356. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104357. encoder->protected_->streaminfo_offset = output_position;
  104358. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104359. encoder->protected_->seektable_offset = output_position;
  104360. }
  104361. /*
  104362. * Mark the current seek point if hit (if audio_offset == 0 that
  104363. * means we're still writing metadata and haven't hit the first
  104364. * frame yet)
  104365. */
  104366. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104367. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104368. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104369. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104370. FLAC__uint64 test_sample;
  104371. unsigned i;
  104372. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104373. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104374. if(test_sample > frame_last_sample) {
  104375. break;
  104376. }
  104377. else if(test_sample >= frame_first_sample) {
  104378. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104379. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104380. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104381. encoder->private_->first_seekpoint_to_check++;
  104382. /* DO NOT: "break;" and here's why:
  104383. * The seektable template may contain more than one target
  104384. * sample for any given frame; we will keep looping, generating
  104385. * duplicate seekpoints for them, and we'll clean it up later,
  104386. * just before writing the seektable back to the metadata.
  104387. */
  104388. }
  104389. else {
  104390. encoder->private_->first_seekpoint_to_check++;
  104391. }
  104392. }
  104393. }
  104394. #if FLAC__HAS_OGG
  104395. if(encoder->private_->is_ogg) {
  104396. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104397. &encoder->protected_->ogg_encoder_aspect,
  104398. buffer,
  104399. bytes,
  104400. samples,
  104401. encoder->private_->current_frame_number,
  104402. is_last_block,
  104403. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104404. encoder,
  104405. encoder->private_->client_data
  104406. );
  104407. }
  104408. else
  104409. #endif
  104410. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104411. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104412. encoder->private_->bytes_written += bytes;
  104413. encoder->private_->samples_written += samples;
  104414. /* we keep a high watermark on the number of frames written because
  104415. * when the encoder goes back to write metadata, 'current_frame'
  104416. * will drop back to 0.
  104417. */
  104418. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104419. }
  104420. else
  104421. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104422. return status;
  104423. }
  104424. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104425. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104426. {
  104427. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104428. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104429. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104430. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104431. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104432. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104433. FLAC__StreamEncoderSeekStatus seek_status;
  104434. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104435. /* All this is based on intimate knowledge of the stream header
  104436. * layout, but a change to the header format that would break this
  104437. * would also break all streams encoded in the previous format.
  104438. */
  104439. /*
  104440. * Write MD5 signature
  104441. */
  104442. {
  104443. const unsigned md5_offset =
  104444. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104445. (
  104446. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104447. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104448. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104449. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104450. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104451. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104452. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104453. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104454. ) / 8;
  104455. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104456. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104457. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104458. return;
  104459. }
  104460. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104461. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104462. return;
  104463. }
  104464. }
  104465. /*
  104466. * Write total samples
  104467. */
  104468. {
  104469. const unsigned total_samples_byte_offset =
  104470. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104471. (
  104472. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104473. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104474. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104475. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104476. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104477. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104478. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104479. - 4
  104480. ) / 8;
  104481. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104482. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104483. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104484. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104485. b[4] = (FLAC__byte)(samples & 0xFF);
  104486. 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) {
  104487. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104488. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104489. return;
  104490. }
  104491. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104492. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104493. return;
  104494. }
  104495. }
  104496. /*
  104497. * Write min/max framesize
  104498. */
  104499. {
  104500. const unsigned min_framesize_offset =
  104501. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104502. (
  104503. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104504. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104505. ) / 8;
  104506. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104507. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104508. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104509. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104510. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104511. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104512. 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) {
  104513. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104514. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104515. return;
  104516. }
  104517. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104518. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104519. return;
  104520. }
  104521. }
  104522. /*
  104523. * Write seektable
  104524. */
  104525. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104526. unsigned i;
  104527. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104528. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104529. 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) {
  104530. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104531. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104532. return;
  104533. }
  104534. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104535. FLAC__uint64 xx;
  104536. unsigned x;
  104537. xx = encoder->private_->seek_table->points[i].sample_number;
  104538. b[7] = (FLAC__byte)xx; xx >>= 8;
  104539. b[6] = (FLAC__byte)xx; xx >>= 8;
  104540. b[5] = (FLAC__byte)xx; xx >>= 8;
  104541. b[4] = (FLAC__byte)xx; xx >>= 8;
  104542. b[3] = (FLAC__byte)xx; xx >>= 8;
  104543. b[2] = (FLAC__byte)xx; xx >>= 8;
  104544. b[1] = (FLAC__byte)xx; xx >>= 8;
  104545. b[0] = (FLAC__byte)xx; xx >>= 8;
  104546. xx = encoder->private_->seek_table->points[i].stream_offset;
  104547. b[15] = (FLAC__byte)xx; xx >>= 8;
  104548. b[14] = (FLAC__byte)xx; xx >>= 8;
  104549. b[13] = (FLAC__byte)xx; xx >>= 8;
  104550. b[12] = (FLAC__byte)xx; xx >>= 8;
  104551. b[11] = (FLAC__byte)xx; xx >>= 8;
  104552. b[10] = (FLAC__byte)xx; xx >>= 8;
  104553. b[9] = (FLAC__byte)xx; xx >>= 8;
  104554. b[8] = (FLAC__byte)xx; xx >>= 8;
  104555. x = encoder->private_->seek_table->points[i].frame_samples;
  104556. b[17] = (FLAC__byte)x; x >>= 8;
  104557. b[16] = (FLAC__byte)x; x >>= 8;
  104558. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104559. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104560. return;
  104561. }
  104562. }
  104563. }
  104564. }
  104565. #if FLAC__HAS_OGG
  104566. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104567. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104568. {
  104569. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104570. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104571. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104572. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104573. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104574. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104575. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104576. FLAC__STREAM_SYNC_LENGTH
  104577. ;
  104578. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104579. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104580. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104581. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104582. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104583. ogg_page page;
  104584. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104585. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104586. /* Pre-check that client supports seeking, since we don't want the
  104587. * ogg_helper code to ever have to deal with this condition.
  104588. */
  104589. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104590. return;
  104591. /* All this is based on intimate knowledge of the stream header
  104592. * layout, but a change to the header format that would break this
  104593. * would also break all streams encoded in the previous format.
  104594. */
  104595. /**
  104596. ** Write STREAMINFO stats
  104597. **/
  104598. simple_ogg_page__init(&page);
  104599. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104600. simple_ogg_page__clear(&page);
  104601. return; /* state already set */
  104602. }
  104603. /*
  104604. * Write MD5 signature
  104605. */
  104606. {
  104607. const unsigned md5_offset =
  104608. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104609. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104610. (
  104611. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104612. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104613. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104614. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104615. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104616. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104617. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104618. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104619. ) / 8;
  104620. if(md5_offset + 16 > (unsigned)page.body_len) {
  104621. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104622. simple_ogg_page__clear(&page);
  104623. return;
  104624. }
  104625. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104626. }
  104627. /*
  104628. * Write total samples
  104629. */
  104630. {
  104631. const unsigned total_samples_byte_offset =
  104632. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104633. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104634. (
  104635. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104636. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104637. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104638. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104639. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104640. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104641. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104642. - 4
  104643. ) / 8;
  104644. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104645. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104646. simple_ogg_page__clear(&page);
  104647. return;
  104648. }
  104649. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104650. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104651. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104652. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104653. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104654. b[4] = (FLAC__byte)(samples & 0xFF);
  104655. memcpy(page.body + total_samples_byte_offset, b, 5);
  104656. }
  104657. /*
  104658. * Write min/max framesize
  104659. */
  104660. {
  104661. const unsigned min_framesize_offset =
  104662. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104663. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104664. (
  104665. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104666. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104667. ) / 8;
  104668. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104669. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104670. simple_ogg_page__clear(&page);
  104671. return;
  104672. }
  104673. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104674. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104675. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104676. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104677. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104678. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104679. memcpy(page.body + min_framesize_offset, b, 6);
  104680. }
  104681. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104682. simple_ogg_page__clear(&page);
  104683. return; /* state already set */
  104684. }
  104685. simple_ogg_page__clear(&page);
  104686. /*
  104687. * Write seektable
  104688. */
  104689. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104690. unsigned i;
  104691. FLAC__byte *p;
  104692. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104693. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104694. simple_ogg_page__init(&page);
  104695. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104696. simple_ogg_page__clear(&page);
  104697. return; /* state already set */
  104698. }
  104699. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104700. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104701. simple_ogg_page__clear(&page);
  104702. return;
  104703. }
  104704. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104705. FLAC__uint64 xx;
  104706. unsigned x;
  104707. xx = encoder->private_->seek_table->points[i].sample_number;
  104708. b[7] = (FLAC__byte)xx; xx >>= 8;
  104709. b[6] = (FLAC__byte)xx; xx >>= 8;
  104710. b[5] = (FLAC__byte)xx; xx >>= 8;
  104711. b[4] = (FLAC__byte)xx; xx >>= 8;
  104712. b[3] = (FLAC__byte)xx; xx >>= 8;
  104713. b[2] = (FLAC__byte)xx; xx >>= 8;
  104714. b[1] = (FLAC__byte)xx; xx >>= 8;
  104715. b[0] = (FLAC__byte)xx; xx >>= 8;
  104716. xx = encoder->private_->seek_table->points[i].stream_offset;
  104717. b[15] = (FLAC__byte)xx; xx >>= 8;
  104718. b[14] = (FLAC__byte)xx; xx >>= 8;
  104719. b[13] = (FLAC__byte)xx; xx >>= 8;
  104720. b[12] = (FLAC__byte)xx; xx >>= 8;
  104721. b[11] = (FLAC__byte)xx; xx >>= 8;
  104722. b[10] = (FLAC__byte)xx; xx >>= 8;
  104723. b[9] = (FLAC__byte)xx; xx >>= 8;
  104724. b[8] = (FLAC__byte)xx; xx >>= 8;
  104725. x = encoder->private_->seek_table->points[i].frame_samples;
  104726. b[17] = (FLAC__byte)x; x >>= 8;
  104727. b[16] = (FLAC__byte)x; x >>= 8;
  104728. memcpy(p, b, 18);
  104729. }
  104730. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104731. simple_ogg_page__clear(&page);
  104732. return; /* state already set */
  104733. }
  104734. simple_ogg_page__clear(&page);
  104735. }
  104736. }
  104737. #endif
  104738. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104739. {
  104740. FLAC__uint16 crc;
  104741. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104742. /*
  104743. * Accumulate raw signal to the MD5 signature
  104744. */
  104745. 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)) {
  104746. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104747. return false;
  104748. }
  104749. /*
  104750. * Process the frame header and subframes into the frame bitbuffer
  104751. */
  104752. if(!process_subframes_(encoder, is_fractional_block)) {
  104753. /* the above function sets the state for us in case of an error */
  104754. return false;
  104755. }
  104756. /*
  104757. * Zero-pad the frame to a byte_boundary
  104758. */
  104759. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104760. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104761. return false;
  104762. }
  104763. /*
  104764. * CRC-16 the whole thing
  104765. */
  104766. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104767. if(
  104768. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104769. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104770. ) {
  104771. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104772. return false;
  104773. }
  104774. /*
  104775. * Write it
  104776. */
  104777. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104778. /* the above function sets the state for us in case of an error */
  104779. return false;
  104780. }
  104781. /*
  104782. * Get ready for the next frame
  104783. */
  104784. encoder->private_->current_sample_number = 0;
  104785. encoder->private_->current_frame_number++;
  104786. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104787. return true;
  104788. }
  104789. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104790. {
  104791. FLAC__FrameHeader frame_header;
  104792. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104793. FLAC__bool do_independent, do_mid_side;
  104794. /*
  104795. * Calculate the min,max Rice partition orders
  104796. */
  104797. if(is_fractional_block) {
  104798. max_partition_order = 0;
  104799. }
  104800. else {
  104801. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104802. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104803. }
  104804. min_partition_order = min(min_partition_order, max_partition_order);
  104805. /*
  104806. * Setup the frame
  104807. */
  104808. frame_header.blocksize = encoder->protected_->blocksize;
  104809. frame_header.sample_rate = encoder->protected_->sample_rate;
  104810. frame_header.channels = encoder->protected_->channels;
  104811. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104812. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104813. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104814. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104815. /*
  104816. * Figure out what channel assignments to try
  104817. */
  104818. if(encoder->protected_->do_mid_side_stereo) {
  104819. if(encoder->protected_->loose_mid_side_stereo) {
  104820. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104821. do_independent = true;
  104822. do_mid_side = true;
  104823. }
  104824. else {
  104825. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104826. do_mid_side = !do_independent;
  104827. }
  104828. }
  104829. else {
  104830. do_independent = true;
  104831. do_mid_side = true;
  104832. }
  104833. }
  104834. else {
  104835. do_independent = true;
  104836. do_mid_side = false;
  104837. }
  104838. FLAC__ASSERT(do_independent || do_mid_side);
  104839. /*
  104840. * Check for wasted bits; set effective bps for each subframe
  104841. */
  104842. if(do_independent) {
  104843. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104844. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104845. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104846. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104847. }
  104848. }
  104849. if(do_mid_side) {
  104850. FLAC__ASSERT(encoder->protected_->channels == 2);
  104851. for(channel = 0; channel < 2; channel++) {
  104852. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104853. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104854. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104855. }
  104856. }
  104857. /*
  104858. * First do a normal encoding pass of each independent channel
  104859. */
  104860. if(do_independent) {
  104861. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104862. if(!
  104863. process_subframe_(
  104864. encoder,
  104865. min_partition_order,
  104866. max_partition_order,
  104867. &frame_header,
  104868. encoder->private_->subframe_bps[channel],
  104869. encoder->private_->integer_signal[channel],
  104870. encoder->private_->subframe_workspace_ptr[channel],
  104871. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104872. encoder->private_->residual_workspace[channel],
  104873. encoder->private_->best_subframe+channel,
  104874. encoder->private_->best_subframe_bits+channel
  104875. )
  104876. )
  104877. return false;
  104878. }
  104879. }
  104880. /*
  104881. * Now do mid and side channels if requested
  104882. */
  104883. if(do_mid_side) {
  104884. FLAC__ASSERT(encoder->protected_->channels == 2);
  104885. for(channel = 0; channel < 2; channel++) {
  104886. if(!
  104887. process_subframe_(
  104888. encoder,
  104889. min_partition_order,
  104890. max_partition_order,
  104891. &frame_header,
  104892. encoder->private_->subframe_bps_mid_side[channel],
  104893. encoder->private_->integer_signal_mid_side[channel],
  104894. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104895. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104896. encoder->private_->residual_workspace_mid_side[channel],
  104897. encoder->private_->best_subframe_mid_side+channel,
  104898. encoder->private_->best_subframe_bits_mid_side+channel
  104899. )
  104900. )
  104901. return false;
  104902. }
  104903. }
  104904. /*
  104905. * Compose the frame bitbuffer
  104906. */
  104907. if(do_mid_side) {
  104908. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104909. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104910. FLAC__ChannelAssignment channel_assignment;
  104911. FLAC__ASSERT(encoder->protected_->channels == 2);
  104912. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104913. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104914. }
  104915. else {
  104916. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104917. unsigned min_bits;
  104918. int ca;
  104919. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104920. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104921. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104922. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104923. FLAC__ASSERT(do_independent && do_mid_side);
  104924. /* We have to figure out which channel assignent results in the smallest frame */
  104925. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104926. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104927. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104928. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104929. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104930. min_bits = bits[channel_assignment];
  104931. for(ca = 1; ca <= 3; ca++) {
  104932. if(bits[ca] < min_bits) {
  104933. min_bits = bits[ca];
  104934. channel_assignment = (FLAC__ChannelAssignment)ca;
  104935. }
  104936. }
  104937. }
  104938. frame_header.channel_assignment = channel_assignment;
  104939. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104940. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104941. return false;
  104942. }
  104943. switch(channel_assignment) {
  104944. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104945. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104946. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104947. break;
  104948. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104949. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104950. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104951. break;
  104952. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104953. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104954. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104955. break;
  104956. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104957. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104958. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104959. break;
  104960. default:
  104961. FLAC__ASSERT(0);
  104962. }
  104963. switch(channel_assignment) {
  104964. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104965. left_bps = encoder->private_->subframe_bps [0];
  104966. right_bps = encoder->private_->subframe_bps [1];
  104967. break;
  104968. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104969. left_bps = encoder->private_->subframe_bps [0];
  104970. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104971. break;
  104972. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104973. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104974. right_bps = encoder->private_->subframe_bps [1];
  104975. break;
  104976. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104977. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104978. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104979. break;
  104980. default:
  104981. FLAC__ASSERT(0);
  104982. }
  104983. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104984. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104985. return false;
  104986. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104987. return false;
  104988. }
  104989. else {
  104990. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104991. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104992. return false;
  104993. }
  104994. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104995. 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)) {
  104996. /* the above function sets the state for us in case of an error */
  104997. return false;
  104998. }
  104999. }
  105000. }
  105001. if(encoder->protected_->loose_mid_side_stereo) {
  105002. encoder->private_->loose_mid_side_stereo_frame_count++;
  105003. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105004. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105005. }
  105006. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105007. return true;
  105008. }
  105009. FLAC__bool process_subframe_(
  105010. FLAC__StreamEncoder *encoder,
  105011. unsigned min_partition_order,
  105012. unsigned max_partition_order,
  105013. const FLAC__FrameHeader *frame_header,
  105014. unsigned subframe_bps,
  105015. const FLAC__int32 integer_signal[],
  105016. FLAC__Subframe *subframe[2],
  105017. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105018. FLAC__int32 *residual[2],
  105019. unsigned *best_subframe,
  105020. unsigned *best_bits
  105021. )
  105022. {
  105023. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105024. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105025. #else
  105026. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105027. #endif
  105028. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105029. FLAC__double lpc_residual_bits_per_sample;
  105030. 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 */
  105031. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105032. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105033. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105034. #endif
  105035. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105036. unsigned rice_parameter;
  105037. unsigned _candidate_bits, _best_bits;
  105038. unsigned _best_subframe;
  105039. /* only use RICE2 partitions if stream bps > 16 */
  105040. 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;
  105041. FLAC__ASSERT(frame_header->blocksize > 0);
  105042. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105043. _best_subframe = 0;
  105044. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105045. _best_bits = UINT_MAX;
  105046. else
  105047. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105048. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105049. unsigned signal_is_constant = false;
  105050. 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);
  105051. /* check for constant subframe */
  105052. if(
  105053. !encoder->private_->disable_constant_subframes &&
  105054. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105055. fixed_residual_bits_per_sample[1] == 0.0
  105056. #else
  105057. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105058. #endif
  105059. ) {
  105060. /* the above means it's possible all samples are the same value; now double-check it: */
  105061. unsigned i;
  105062. signal_is_constant = true;
  105063. for(i = 1; i < frame_header->blocksize; i++) {
  105064. if(integer_signal[0] != integer_signal[i]) {
  105065. signal_is_constant = false;
  105066. break;
  105067. }
  105068. }
  105069. }
  105070. if(signal_is_constant) {
  105071. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105072. if(_candidate_bits < _best_bits) {
  105073. _best_subframe = !_best_subframe;
  105074. _best_bits = _candidate_bits;
  105075. }
  105076. }
  105077. else {
  105078. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105079. /* encode fixed */
  105080. if(encoder->protected_->do_exhaustive_model_search) {
  105081. min_fixed_order = 0;
  105082. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105083. }
  105084. else {
  105085. min_fixed_order = max_fixed_order = guess_fixed_order;
  105086. }
  105087. if(max_fixed_order >= frame_header->blocksize)
  105088. max_fixed_order = frame_header->blocksize - 1;
  105089. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105090. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105091. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105092. continue; /* don't even try */
  105093. 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 */
  105094. #else
  105095. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105096. continue; /* don't even try */
  105097. 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 */
  105098. #endif
  105099. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105100. if(rice_parameter >= rice_parameter_limit) {
  105101. #ifdef DEBUG_VERBOSE
  105102. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105103. #endif
  105104. rice_parameter = rice_parameter_limit - 1;
  105105. }
  105106. _candidate_bits =
  105107. evaluate_fixed_subframe_(
  105108. encoder,
  105109. integer_signal,
  105110. residual[!_best_subframe],
  105111. encoder->private_->abs_residual_partition_sums,
  105112. encoder->private_->raw_bits_per_partition,
  105113. frame_header->blocksize,
  105114. subframe_bps,
  105115. fixed_order,
  105116. rice_parameter,
  105117. rice_parameter_limit,
  105118. min_partition_order,
  105119. max_partition_order,
  105120. encoder->protected_->do_escape_coding,
  105121. encoder->protected_->rice_parameter_search_dist,
  105122. subframe[!_best_subframe],
  105123. partitioned_rice_contents[!_best_subframe]
  105124. );
  105125. if(_candidate_bits < _best_bits) {
  105126. _best_subframe = !_best_subframe;
  105127. _best_bits = _candidate_bits;
  105128. }
  105129. }
  105130. }
  105131. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105132. /* encode lpc */
  105133. if(encoder->protected_->max_lpc_order > 0) {
  105134. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105135. max_lpc_order = frame_header->blocksize-1;
  105136. else
  105137. max_lpc_order = encoder->protected_->max_lpc_order;
  105138. if(max_lpc_order > 0) {
  105139. unsigned a;
  105140. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105141. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105142. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105143. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105144. if(autoc[0] != 0.0) {
  105145. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105146. if(encoder->protected_->do_exhaustive_model_search) {
  105147. min_lpc_order = 1;
  105148. }
  105149. else {
  105150. const unsigned guess_lpc_order =
  105151. FLAC__lpc_compute_best_order(
  105152. lpc_error,
  105153. max_lpc_order,
  105154. frame_header->blocksize,
  105155. subframe_bps + (
  105156. encoder->protected_->do_qlp_coeff_prec_search?
  105157. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105158. encoder->protected_->qlp_coeff_precision
  105159. )
  105160. );
  105161. min_lpc_order = max_lpc_order = guess_lpc_order;
  105162. }
  105163. if(max_lpc_order >= frame_header->blocksize)
  105164. max_lpc_order = frame_header->blocksize - 1;
  105165. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105166. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105167. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105168. continue; /* don't even try */
  105169. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105170. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105171. if(rice_parameter >= rice_parameter_limit) {
  105172. #ifdef DEBUG_VERBOSE
  105173. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105174. #endif
  105175. rice_parameter = rice_parameter_limit - 1;
  105176. }
  105177. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105178. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105179. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105180. if(subframe_bps <= 17) {
  105181. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105182. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105183. }
  105184. else
  105185. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105186. }
  105187. else {
  105188. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105189. }
  105190. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105191. _candidate_bits =
  105192. evaluate_lpc_subframe_(
  105193. encoder,
  105194. integer_signal,
  105195. residual[!_best_subframe],
  105196. encoder->private_->abs_residual_partition_sums,
  105197. encoder->private_->raw_bits_per_partition,
  105198. encoder->private_->lp_coeff[lpc_order-1],
  105199. frame_header->blocksize,
  105200. subframe_bps,
  105201. lpc_order,
  105202. qlp_coeff_precision,
  105203. rice_parameter,
  105204. rice_parameter_limit,
  105205. min_partition_order,
  105206. max_partition_order,
  105207. encoder->protected_->do_escape_coding,
  105208. encoder->protected_->rice_parameter_search_dist,
  105209. subframe[!_best_subframe],
  105210. partitioned_rice_contents[!_best_subframe]
  105211. );
  105212. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105213. if(_candidate_bits < _best_bits) {
  105214. _best_subframe = !_best_subframe;
  105215. _best_bits = _candidate_bits;
  105216. }
  105217. }
  105218. }
  105219. }
  105220. }
  105221. }
  105222. }
  105223. }
  105224. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105225. }
  105226. }
  105227. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105228. if(_best_bits == UINT_MAX) {
  105229. FLAC__ASSERT(_best_subframe == 0);
  105230. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105231. }
  105232. *best_subframe = _best_subframe;
  105233. *best_bits = _best_bits;
  105234. return true;
  105235. }
  105236. FLAC__bool add_subframe_(
  105237. FLAC__StreamEncoder *encoder,
  105238. unsigned blocksize,
  105239. unsigned subframe_bps,
  105240. const FLAC__Subframe *subframe,
  105241. FLAC__BitWriter *frame
  105242. )
  105243. {
  105244. switch(subframe->type) {
  105245. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105246. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105247. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105248. return false;
  105249. }
  105250. break;
  105251. case FLAC__SUBFRAME_TYPE_FIXED:
  105252. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105253. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105254. return false;
  105255. }
  105256. break;
  105257. case FLAC__SUBFRAME_TYPE_LPC:
  105258. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105259. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105260. return false;
  105261. }
  105262. break;
  105263. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105264. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105265. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105266. return false;
  105267. }
  105268. break;
  105269. default:
  105270. FLAC__ASSERT(0);
  105271. }
  105272. return true;
  105273. }
  105274. #define SPOTCHECK_ESTIMATE 0
  105275. #if SPOTCHECK_ESTIMATE
  105276. static void spotcheck_subframe_estimate_(
  105277. FLAC__StreamEncoder *encoder,
  105278. unsigned blocksize,
  105279. unsigned subframe_bps,
  105280. const FLAC__Subframe *subframe,
  105281. unsigned estimate
  105282. )
  105283. {
  105284. FLAC__bool ret;
  105285. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105286. if(frame == 0) {
  105287. fprintf(stderr, "EST: can't allocate frame\n");
  105288. return;
  105289. }
  105290. if(!FLAC__bitwriter_init(frame)) {
  105291. fprintf(stderr, "EST: can't init frame\n");
  105292. return;
  105293. }
  105294. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105295. FLAC__ASSERT(ret);
  105296. {
  105297. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105298. if(estimate != actual)
  105299. 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);
  105300. }
  105301. FLAC__bitwriter_delete(frame);
  105302. }
  105303. #endif
  105304. unsigned evaluate_constant_subframe_(
  105305. FLAC__StreamEncoder *encoder,
  105306. const FLAC__int32 signal,
  105307. unsigned blocksize,
  105308. unsigned subframe_bps,
  105309. FLAC__Subframe *subframe
  105310. )
  105311. {
  105312. unsigned estimate;
  105313. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105314. subframe->data.constant.value = signal;
  105315. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105316. #if SPOTCHECK_ESTIMATE
  105317. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105318. #else
  105319. (void)encoder, (void)blocksize;
  105320. #endif
  105321. return estimate;
  105322. }
  105323. unsigned evaluate_fixed_subframe_(
  105324. FLAC__StreamEncoder *encoder,
  105325. const FLAC__int32 signal[],
  105326. FLAC__int32 residual[],
  105327. FLAC__uint64 abs_residual_partition_sums[],
  105328. unsigned raw_bits_per_partition[],
  105329. unsigned blocksize,
  105330. unsigned subframe_bps,
  105331. unsigned order,
  105332. unsigned rice_parameter,
  105333. unsigned rice_parameter_limit,
  105334. unsigned min_partition_order,
  105335. unsigned max_partition_order,
  105336. FLAC__bool do_escape_coding,
  105337. unsigned rice_parameter_search_dist,
  105338. FLAC__Subframe *subframe,
  105339. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105340. )
  105341. {
  105342. unsigned i, residual_bits, estimate;
  105343. const unsigned residual_samples = blocksize - order;
  105344. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105345. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105346. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105347. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105348. subframe->data.fixed.residual = residual;
  105349. residual_bits =
  105350. find_best_partition_order_(
  105351. encoder->private_,
  105352. residual,
  105353. abs_residual_partition_sums,
  105354. raw_bits_per_partition,
  105355. residual_samples,
  105356. order,
  105357. rice_parameter,
  105358. rice_parameter_limit,
  105359. min_partition_order,
  105360. max_partition_order,
  105361. subframe_bps,
  105362. do_escape_coding,
  105363. rice_parameter_search_dist,
  105364. &subframe->data.fixed.entropy_coding_method
  105365. );
  105366. subframe->data.fixed.order = order;
  105367. for(i = 0; i < order; i++)
  105368. subframe->data.fixed.warmup[i] = signal[i];
  105369. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105370. #if SPOTCHECK_ESTIMATE
  105371. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105372. #endif
  105373. return estimate;
  105374. }
  105375. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105376. unsigned evaluate_lpc_subframe_(
  105377. FLAC__StreamEncoder *encoder,
  105378. const FLAC__int32 signal[],
  105379. FLAC__int32 residual[],
  105380. FLAC__uint64 abs_residual_partition_sums[],
  105381. unsigned raw_bits_per_partition[],
  105382. const FLAC__real lp_coeff[],
  105383. unsigned blocksize,
  105384. unsigned subframe_bps,
  105385. unsigned order,
  105386. unsigned qlp_coeff_precision,
  105387. unsigned rice_parameter,
  105388. unsigned rice_parameter_limit,
  105389. unsigned min_partition_order,
  105390. unsigned max_partition_order,
  105391. FLAC__bool do_escape_coding,
  105392. unsigned rice_parameter_search_dist,
  105393. FLAC__Subframe *subframe,
  105394. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105395. )
  105396. {
  105397. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105398. unsigned i, residual_bits, estimate;
  105399. int quantization, ret;
  105400. const unsigned residual_samples = blocksize - order;
  105401. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105402. if(subframe_bps <= 16) {
  105403. FLAC__ASSERT(order > 0);
  105404. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105405. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105406. }
  105407. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105408. if(ret != 0)
  105409. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105410. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105411. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105412. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105413. else
  105414. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105415. else
  105416. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105417. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105418. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105419. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105420. subframe->data.lpc.residual = residual;
  105421. residual_bits =
  105422. find_best_partition_order_(
  105423. encoder->private_,
  105424. residual,
  105425. abs_residual_partition_sums,
  105426. raw_bits_per_partition,
  105427. residual_samples,
  105428. order,
  105429. rice_parameter,
  105430. rice_parameter_limit,
  105431. min_partition_order,
  105432. max_partition_order,
  105433. subframe_bps,
  105434. do_escape_coding,
  105435. rice_parameter_search_dist,
  105436. &subframe->data.lpc.entropy_coding_method
  105437. );
  105438. subframe->data.lpc.order = order;
  105439. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105440. subframe->data.lpc.quantization_level = quantization;
  105441. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105442. for(i = 0; i < order; i++)
  105443. subframe->data.lpc.warmup[i] = signal[i];
  105444. 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;
  105445. #if SPOTCHECK_ESTIMATE
  105446. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105447. #endif
  105448. return estimate;
  105449. }
  105450. #endif
  105451. unsigned evaluate_verbatim_subframe_(
  105452. FLAC__StreamEncoder *encoder,
  105453. const FLAC__int32 signal[],
  105454. unsigned blocksize,
  105455. unsigned subframe_bps,
  105456. FLAC__Subframe *subframe
  105457. )
  105458. {
  105459. unsigned estimate;
  105460. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105461. subframe->data.verbatim.data = signal;
  105462. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105463. #if SPOTCHECK_ESTIMATE
  105464. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105465. #else
  105466. (void)encoder;
  105467. #endif
  105468. return estimate;
  105469. }
  105470. unsigned find_best_partition_order_(
  105471. FLAC__StreamEncoderPrivate *private_,
  105472. const FLAC__int32 residual[],
  105473. FLAC__uint64 abs_residual_partition_sums[],
  105474. unsigned raw_bits_per_partition[],
  105475. unsigned residual_samples,
  105476. unsigned predictor_order,
  105477. unsigned rice_parameter,
  105478. unsigned rice_parameter_limit,
  105479. unsigned min_partition_order,
  105480. unsigned max_partition_order,
  105481. unsigned bps,
  105482. FLAC__bool do_escape_coding,
  105483. unsigned rice_parameter_search_dist,
  105484. FLAC__EntropyCodingMethod *best_ecm
  105485. )
  105486. {
  105487. unsigned residual_bits, best_residual_bits = 0;
  105488. unsigned best_parameters_index = 0;
  105489. unsigned best_partition_order = 0;
  105490. const unsigned blocksize = residual_samples + predictor_order;
  105491. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105492. min_partition_order = min(min_partition_order, max_partition_order);
  105493. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105494. if(do_escape_coding)
  105495. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105496. {
  105497. int partition_order;
  105498. unsigned sum;
  105499. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105500. if(!
  105501. set_partitioned_rice_(
  105502. #ifdef EXACT_RICE_BITS_CALCULATION
  105503. residual,
  105504. #endif
  105505. abs_residual_partition_sums+sum,
  105506. raw_bits_per_partition+sum,
  105507. residual_samples,
  105508. predictor_order,
  105509. rice_parameter,
  105510. rice_parameter_limit,
  105511. rice_parameter_search_dist,
  105512. (unsigned)partition_order,
  105513. do_escape_coding,
  105514. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105515. &residual_bits
  105516. )
  105517. )
  105518. {
  105519. FLAC__ASSERT(best_residual_bits != 0);
  105520. break;
  105521. }
  105522. sum += 1u << partition_order;
  105523. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105524. best_residual_bits = residual_bits;
  105525. best_parameters_index = !best_parameters_index;
  105526. best_partition_order = partition_order;
  105527. }
  105528. }
  105529. }
  105530. best_ecm->data.partitioned_rice.order = best_partition_order;
  105531. {
  105532. /*
  105533. * We are allowed to de-const the pointer based on our special
  105534. * knowledge; it is const to the outside world.
  105535. */
  105536. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105537. unsigned partition;
  105538. /* save best parameters and raw_bits */
  105539. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105540. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105541. if(do_escape_coding)
  105542. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105543. /*
  105544. * Now need to check if the type should be changed to
  105545. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105546. * size of the rice parameters.
  105547. */
  105548. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105549. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105550. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105551. break;
  105552. }
  105553. }
  105554. }
  105555. return best_residual_bits;
  105556. }
  105557. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105558. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105559. const FLAC__int32 residual[],
  105560. FLAC__uint64 abs_residual_partition_sums[],
  105561. unsigned blocksize,
  105562. unsigned predictor_order,
  105563. unsigned min_partition_order,
  105564. unsigned max_partition_order
  105565. );
  105566. #endif
  105567. void precompute_partition_info_sums_(
  105568. const FLAC__int32 residual[],
  105569. FLAC__uint64 abs_residual_partition_sums[],
  105570. unsigned residual_samples,
  105571. unsigned predictor_order,
  105572. unsigned min_partition_order,
  105573. unsigned max_partition_order,
  105574. unsigned bps
  105575. )
  105576. {
  105577. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105578. unsigned partitions = 1u << max_partition_order;
  105579. FLAC__ASSERT(default_partition_samples > predictor_order);
  105580. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105581. /* slightly pessimistic but still catches all common cases */
  105582. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105583. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105584. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105585. return;
  105586. }
  105587. #endif
  105588. /* first do max_partition_order */
  105589. {
  105590. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105591. /* slightly pessimistic but still catches all common cases */
  105592. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105593. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105594. FLAC__uint32 abs_residual_partition_sum;
  105595. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105596. end += default_partition_samples;
  105597. abs_residual_partition_sum = 0;
  105598. for( ; residual_sample < end; residual_sample++)
  105599. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105600. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105601. }
  105602. }
  105603. else { /* have to pessimistically use 64 bits for accumulator */
  105604. FLAC__uint64 abs_residual_partition_sum;
  105605. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105606. end += default_partition_samples;
  105607. abs_residual_partition_sum = 0;
  105608. for( ; residual_sample < end; residual_sample++)
  105609. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105610. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105611. }
  105612. }
  105613. }
  105614. /* now merge partitions for lower orders */
  105615. {
  105616. unsigned from_partition = 0, to_partition = partitions;
  105617. int partition_order;
  105618. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105619. unsigned i;
  105620. partitions >>= 1;
  105621. for(i = 0; i < partitions; i++) {
  105622. abs_residual_partition_sums[to_partition++] =
  105623. abs_residual_partition_sums[from_partition ] +
  105624. abs_residual_partition_sums[from_partition+1];
  105625. from_partition += 2;
  105626. }
  105627. }
  105628. }
  105629. }
  105630. void precompute_partition_info_escapes_(
  105631. const FLAC__int32 residual[],
  105632. unsigned raw_bits_per_partition[],
  105633. unsigned residual_samples,
  105634. unsigned predictor_order,
  105635. unsigned min_partition_order,
  105636. unsigned max_partition_order
  105637. )
  105638. {
  105639. int partition_order;
  105640. unsigned from_partition, to_partition = 0;
  105641. const unsigned blocksize = residual_samples + predictor_order;
  105642. /* first do max_partition_order */
  105643. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105644. FLAC__int32 r;
  105645. FLAC__uint32 rmax;
  105646. unsigned partition, partition_sample, partition_samples, residual_sample;
  105647. const unsigned partitions = 1u << partition_order;
  105648. const unsigned default_partition_samples = blocksize >> partition_order;
  105649. FLAC__ASSERT(default_partition_samples > predictor_order);
  105650. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105651. partition_samples = default_partition_samples;
  105652. if(partition == 0)
  105653. partition_samples -= predictor_order;
  105654. rmax = 0;
  105655. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105656. r = residual[residual_sample++];
  105657. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105658. if(r < 0)
  105659. rmax |= ~r;
  105660. else
  105661. rmax |= r;
  105662. }
  105663. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105664. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105665. }
  105666. to_partition = partitions;
  105667. break; /*@@@ yuck, should remove the 'for' loop instead */
  105668. }
  105669. /* now merge partitions for lower orders */
  105670. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105671. unsigned m;
  105672. unsigned i;
  105673. const unsigned partitions = 1u << partition_order;
  105674. for(i = 0; i < partitions; i++) {
  105675. m = raw_bits_per_partition[from_partition];
  105676. from_partition++;
  105677. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105678. from_partition++;
  105679. to_partition++;
  105680. }
  105681. }
  105682. }
  105683. #ifdef EXACT_RICE_BITS_CALCULATION
  105684. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105685. const unsigned rice_parameter,
  105686. const unsigned partition_samples,
  105687. const FLAC__int32 *residual
  105688. )
  105689. {
  105690. unsigned i, partition_bits =
  105691. 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 */
  105692. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105693. ;
  105694. for(i = 0; i < partition_samples; i++)
  105695. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105696. return partition_bits;
  105697. }
  105698. #else
  105699. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105700. const unsigned rice_parameter,
  105701. const unsigned partition_samples,
  105702. const FLAC__uint64 abs_residual_partition_sum
  105703. )
  105704. {
  105705. return
  105706. 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 */
  105707. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105708. (
  105709. rice_parameter?
  105710. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105711. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105712. )
  105713. - (partition_samples >> 1)
  105714. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105715. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105716. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105717. * So the subtraction term tries to guess how many extra bits were contributed.
  105718. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105719. */
  105720. ;
  105721. }
  105722. #endif
  105723. FLAC__bool set_partitioned_rice_(
  105724. #ifdef EXACT_RICE_BITS_CALCULATION
  105725. const FLAC__int32 residual[],
  105726. #endif
  105727. const FLAC__uint64 abs_residual_partition_sums[],
  105728. const unsigned raw_bits_per_partition[],
  105729. const unsigned residual_samples,
  105730. const unsigned predictor_order,
  105731. const unsigned suggested_rice_parameter,
  105732. const unsigned rice_parameter_limit,
  105733. const unsigned rice_parameter_search_dist,
  105734. const unsigned partition_order,
  105735. const FLAC__bool search_for_escapes,
  105736. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105737. unsigned *bits
  105738. )
  105739. {
  105740. unsigned rice_parameter, partition_bits;
  105741. unsigned best_partition_bits, best_rice_parameter = 0;
  105742. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105743. unsigned *parameters, *raw_bits;
  105744. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105745. unsigned min_rice_parameter, max_rice_parameter;
  105746. #else
  105747. (void)rice_parameter_search_dist;
  105748. #endif
  105749. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105750. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105751. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105752. parameters = partitioned_rice_contents->parameters;
  105753. raw_bits = partitioned_rice_contents->raw_bits;
  105754. if(partition_order == 0) {
  105755. best_partition_bits = (unsigned)(-1);
  105756. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105757. if(rice_parameter_search_dist) {
  105758. if(suggested_rice_parameter < rice_parameter_search_dist)
  105759. min_rice_parameter = 0;
  105760. else
  105761. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105762. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105763. if(max_rice_parameter >= rice_parameter_limit) {
  105764. #ifdef DEBUG_VERBOSE
  105765. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105766. #endif
  105767. max_rice_parameter = rice_parameter_limit - 1;
  105768. }
  105769. }
  105770. else
  105771. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105772. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105773. #else
  105774. rice_parameter = suggested_rice_parameter;
  105775. #endif
  105776. #ifdef EXACT_RICE_BITS_CALCULATION
  105777. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105778. #else
  105779. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105780. #endif
  105781. if(partition_bits < best_partition_bits) {
  105782. best_rice_parameter = rice_parameter;
  105783. best_partition_bits = partition_bits;
  105784. }
  105785. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105786. }
  105787. #endif
  105788. if(search_for_escapes) {
  105789. 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;
  105790. if(partition_bits <= best_partition_bits) {
  105791. raw_bits[0] = raw_bits_per_partition[0];
  105792. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105793. best_partition_bits = partition_bits;
  105794. }
  105795. else
  105796. raw_bits[0] = 0;
  105797. }
  105798. parameters[0] = best_rice_parameter;
  105799. bits_ += best_partition_bits;
  105800. }
  105801. else {
  105802. unsigned partition, residual_sample;
  105803. unsigned partition_samples;
  105804. FLAC__uint64 mean, k;
  105805. const unsigned partitions = 1u << partition_order;
  105806. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105807. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105808. if(partition == 0) {
  105809. if(partition_samples <= predictor_order)
  105810. return false;
  105811. else
  105812. partition_samples -= predictor_order;
  105813. }
  105814. mean = abs_residual_partition_sums[partition];
  105815. /* we are basically calculating the size in bits of the
  105816. * average residual magnitude in the partition:
  105817. * rice_parameter = floor(log2(mean/partition_samples))
  105818. * 'mean' is not a good name for the variable, it is
  105819. * actually the sum of magnitudes of all residual values
  105820. * in the partition, so the actual mean is
  105821. * mean/partition_samples
  105822. */
  105823. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105824. ;
  105825. if(rice_parameter >= rice_parameter_limit) {
  105826. #ifdef DEBUG_VERBOSE
  105827. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105828. #endif
  105829. rice_parameter = rice_parameter_limit - 1;
  105830. }
  105831. best_partition_bits = (unsigned)(-1);
  105832. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105833. if(rice_parameter_search_dist) {
  105834. if(rice_parameter < rice_parameter_search_dist)
  105835. min_rice_parameter = 0;
  105836. else
  105837. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105838. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105839. if(max_rice_parameter >= rice_parameter_limit) {
  105840. #ifdef DEBUG_VERBOSE
  105841. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105842. #endif
  105843. max_rice_parameter = rice_parameter_limit - 1;
  105844. }
  105845. }
  105846. else
  105847. min_rice_parameter = max_rice_parameter = rice_parameter;
  105848. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105849. #endif
  105850. #ifdef EXACT_RICE_BITS_CALCULATION
  105851. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105852. #else
  105853. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105854. #endif
  105855. if(partition_bits < best_partition_bits) {
  105856. best_rice_parameter = rice_parameter;
  105857. best_partition_bits = partition_bits;
  105858. }
  105859. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105860. }
  105861. #endif
  105862. if(search_for_escapes) {
  105863. 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;
  105864. if(partition_bits <= best_partition_bits) {
  105865. raw_bits[partition] = raw_bits_per_partition[partition];
  105866. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105867. best_partition_bits = partition_bits;
  105868. }
  105869. else
  105870. raw_bits[partition] = 0;
  105871. }
  105872. parameters[partition] = best_rice_parameter;
  105873. bits_ += best_partition_bits;
  105874. residual_sample += partition_samples;
  105875. }
  105876. }
  105877. *bits = bits_;
  105878. return true;
  105879. }
  105880. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105881. {
  105882. unsigned i, shift;
  105883. FLAC__int32 x = 0;
  105884. for(i = 0; i < samples && !(x&1); i++)
  105885. x |= signal[i];
  105886. if(x == 0) {
  105887. shift = 0;
  105888. }
  105889. else {
  105890. for(shift = 0; !(x&1); shift++)
  105891. x >>= 1;
  105892. }
  105893. if(shift > 0) {
  105894. for(i = 0; i < samples; i++)
  105895. signal[i] >>= shift;
  105896. }
  105897. return shift;
  105898. }
  105899. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105900. {
  105901. unsigned channel;
  105902. for(channel = 0; channel < channels; channel++)
  105903. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105904. fifo->tail += wide_samples;
  105905. FLAC__ASSERT(fifo->tail <= fifo->size);
  105906. }
  105907. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105908. {
  105909. unsigned channel;
  105910. unsigned sample, wide_sample;
  105911. unsigned tail = fifo->tail;
  105912. sample = input_offset * channels;
  105913. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105914. for(channel = 0; channel < channels; channel++)
  105915. fifo->data[channel][tail] = input[sample++];
  105916. tail++;
  105917. }
  105918. fifo->tail = tail;
  105919. FLAC__ASSERT(fifo->tail <= fifo->size);
  105920. }
  105921. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105922. {
  105923. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105924. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105925. (void)decoder;
  105926. if(encoder->private_->verify.needs_magic_hack) {
  105927. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105928. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105929. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105930. encoder->private_->verify.needs_magic_hack = false;
  105931. }
  105932. else {
  105933. if(encoded_bytes == 0) {
  105934. /*
  105935. * If we get here, a FIFO underflow has occurred,
  105936. * which means there is a bug somewhere.
  105937. */
  105938. FLAC__ASSERT(0);
  105939. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105940. }
  105941. else if(encoded_bytes < *bytes)
  105942. *bytes = encoded_bytes;
  105943. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105944. encoder->private_->verify.output.data += *bytes;
  105945. encoder->private_->verify.output.bytes -= *bytes;
  105946. }
  105947. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105948. }
  105949. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105950. {
  105951. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105952. unsigned channel;
  105953. const unsigned channels = frame->header.channels;
  105954. const unsigned blocksize = frame->header.blocksize;
  105955. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105956. (void)decoder;
  105957. for(channel = 0; channel < channels; channel++) {
  105958. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105959. unsigned i, sample = 0;
  105960. FLAC__int32 expect = 0, got = 0;
  105961. for(i = 0; i < blocksize; i++) {
  105962. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105963. sample = i;
  105964. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105965. got = (FLAC__int32)buffer[channel][i];
  105966. break;
  105967. }
  105968. }
  105969. FLAC__ASSERT(i < blocksize);
  105970. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105971. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105972. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105973. encoder->private_->verify.error_stats.channel = channel;
  105974. encoder->private_->verify.error_stats.sample = sample;
  105975. encoder->private_->verify.error_stats.expected = expect;
  105976. encoder->private_->verify.error_stats.got = got;
  105977. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105978. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105979. }
  105980. }
  105981. /* dequeue the frame from the fifo */
  105982. encoder->private_->verify.input_fifo.tail -= blocksize;
  105983. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105984. for(channel = 0; channel < channels; channel++)
  105985. 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]));
  105986. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105987. }
  105988. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105989. {
  105990. (void)decoder, (void)metadata, (void)client_data;
  105991. }
  105992. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105993. {
  105994. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105995. (void)decoder, (void)status;
  105996. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105997. }
  105998. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105999. {
  106000. (void)client_data;
  106001. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106002. if (*bytes == 0) {
  106003. if (feof(encoder->private_->file))
  106004. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106005. else if (ferror(encoder->private_->file))
  106006. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106007. }
  106008. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106009. }
  106010. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106011. {
  106012. (void)client_data;
  106013. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106014. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106015. else
  106016. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106017. }
  106018. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106019. {
  106020. off_t offset;
  106021. (void)client_data;
  106022. offset = ftello(encoder->private_->file);
  106023. if(offset < 0) {
  106024. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106025. }
  106026. else {
  106027. *absolute_byte_offset = (FLAC__uint64)offset;
  106028. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106029. }
  106030. }
  106031. #ifdef FLAC__VALGRIND_TESTING
  106032. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106033. {
  106034. size_t ret = fwrite(ptr, size, nmemb, stream);
  106035. if(!ferror(stream))
  106036. fflush(stream);
  106037. return ret;
  106038. }
  106039. #else
  106040. #define local__fwrite fwrite
  106041. #endif
  106042. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106043. {
  106044. (void)client_data, (void)current_frame;
  106045. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106046. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106047. #if FLAC__HAS_OGG
  106048. /* We would like to be able to use 'samples > 0' in the
  106049. * clause here but currently because of the nature of our
  106050. * Ogg writing implementation, 'samples' is always 0 (see
  106051. * ogg_encoder_aspect.c). The downside is extra progress
  106052. * callbacks.
  106053. */
  106054. encoder->private_->is_ogg? true :
  106055. #endif
  106056. samples > 0
  106057. );
  106058. if(call_it) {
  106059. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106060. * because at this point in the callback chain, the stats
  106061. * have not been updated. Only after we return and control
  106062. * gets back to write_frame_() are the stats updated
  106063. */
  106064. 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);
  106065. }
  106066. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106067. }
  106068. else
  106069. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106070. }
  106071. /*
  106072. * This will forcibly set stdout to binary mode (for OSes that require it)
  106073. */
  106074. FILE *get_binary_stdout_(void)
  106075. {
  106076. /* if something breaks here it is probably due to the presence or
  106077. * absence of an underscore before the identifiers 'setmode',
  106078. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106079. */
  106080. #if defined _MSC_VER || defined __MINGW32__
  106081. _setmode(_fileno(stdout), _O_BINARY);
  106082. #elif defined __CYGWIN__
  106083. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106084. setmode(_fileno(stdout), _O_BINARY);
  106085. #elif defined __EMX__
  106086. setmode(fileno(stdout), O_BINARY);
  106087. #endif
  106088. return stdout;
  106089. }
  106090. #endif
  106091. /*** End of inlined file: stream_encoder.c ***/
  106092. /*** Start of inlined file: stream_encoder_framing.c ***/
  106093. /*** Start of inlined file: juce_FlacHeader.h ***/
  106094. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106095. // tasks..
  106096. #define VERSION "1.2.1"
  106097. #define FLAC__NO_DLL 1
  106098. #if JUCE_MSVC
  106099. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106100. #endif
  106101. #if JUCE_MAC
  106102. #define FLAC__SYS_DARWIN 1
  106103. #endif
  106104. /*** End of inlined file: juce_FlacHeader.h ***/
  106105. #if JUCE_USE_FLAC
  106106. #if HAVE_CONFIG_H
  106107. # include <config.h>
  106108. #endif
  106109. #include <stdio.h>
  106110. #include <string.h> /* for strlen() */
  106111. #ifdef max
  106112. #undef max
  106113. #endif
  106114. #define max(x,y) ((x)>(y)?(x):(y))
  106115. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106116. 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);
  106117. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106118. {
  106119. unsigned i, j;
  106120. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106121. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106122. return false;
  106123. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106124. return false;
  106125. /*
  106126. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106127. */
  106128. i = metadata->length;
  106129. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106130. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106131. i -= metadata->data.vorbis_comment.vendor_string.length;
  106132. i += vendor_string_length;
  106133. }
  106134. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106135. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106136. return false;
  106137. switch(metadata->type) {
  106138. case FLAC__METADATA_TYPE_STREAMINFO:
  106139. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106140. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106141. return false;
  106142. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106143. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106144. return false;
  106145. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106146. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106147. return false;
  106148. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106149. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106150. return false;
  106151. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106152. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106153. return false;
  106154. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106155. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106156. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106157. return false;
  106158. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106159. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106160. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106161. return false;
  106162. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106163. return false;
  106164. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106165. return false;
  106166. break;
  106167. case FLAC__METADATA_TYPE_PADDING:
  106168. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106169. return false;
  106170. break;
  106171. case FLAC__METADATA_TYPE_APPLICATION:
  106172. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106173. return false;
  106174. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106175. return false;
  106176. break;
  106177. case FLAC__METADATA_TYPE_SEEKTABLE:
  106178. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106179. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106180. return false;
  106181. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106182. return false;
  106183. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106184. return false;
  106185. }
  106186. break;
  106187. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106188. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106189. return false;
  106190. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106191. return false;
  106192. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106193. return false;
  106194. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106195. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106196. return false;
  106197. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106198. return false;
  106199. }
  106200. break;
  106201. case FLAC__METADATA_TYPE_CUESHEET:
  106202. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106203. 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))
  106204. return false;
  106205. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106206. return false;
  106207. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106208. return false;
  106209. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106210. return false;
  106211. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106212. return false;
  106213. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106214. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106215. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106216. return false;
  106217. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106218. return false;
  106219. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106220. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106221. return false;
  106222. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106223. return false;
  106224. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106225. return false;
  106226. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106227. return false;
  106228. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106229. return false;
  106230. for(j = 0; j < track->num_indices; j++) {
  106231. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106232. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106233. return false;
  106234. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106235. return false;
  106236. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106237. return false;
  106238. }
  106239. }
  106240. break;
  106241. case FLAC__METADATA_TYPE_PICTURE:
  106242. {
  106243. size_t len;
  106244. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106245. return false;
  106246. len = strlen(metadata->data.picture.mime_type);
  106247. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106248. return false;
  106249. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106250. return false;
  106251. len = strlen((const char *)metadata->data.picture.description);
  106252. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106253. return false;
  106254. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106255. return false;
  106256. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106257. return false;
  106258. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106259. return false;
  106260. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106261. return false;
  106262. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106263. return false;
  106264. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106265. return false;
  106266. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106267. return false;
  106268. }
  106269. break;
  106270. default:
  106271. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106272. return false;
  106273. break;
  106274. }
  106275. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106276. return true;
  106277. }
  106278. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106279. {
  106280. unsigned u, blocksize_hint, sample_rate_hint;
  106281. FLAC__byte crc;
  106282. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106283. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106284. return false;
  106285. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106286. return false;
  106287. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106288. return false;
  106289. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106290. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106291. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106292. blocksize_hint = 0;
  106293. switch(header->blocksize) {
  106294. case 192: u = 1; break;
  106295. case 576: u = 2; break;
  106296. case 1152: u = 3; break;
  106297. case 2304: u = 4; break;
  106298. case 4608: u = 5; break;
  106299. case 256: u = 8; break;
  106300. case 512: u = 9; break;
  106301. case 1024: u = 10; break;
  106302. case 2048: u = 11; break;
  106303. case 4096: u = 12; break;
  106304. case 8192: u = 13; break;
  106305. case 16384: u = 14; break;
  106306. case 32768: u = 15; break;
  106307. default:
  106308. if(header->blocksize <= 0x100)
  106309. blocksize_hint = u = 6;
  106310. else
  106311. blocksize_hint = u = 7;
  106312. break;
  106313. }
  106314. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106315. return false;
  106316. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106317. sample_rate_hint = 0;
  106318. switch(header->sample_rate) {
  106319. case 88200: u = 1; break;
  106320. case 176400: u = 2; break;
  106321. case 192000: u = 3; break;
  106322. case 8000: u = 4; break;
  106323. case 16000: u = 5; break;
  106324. case 22050: u = 6; break;
  106325. case 24000: u = 7; break;
  106326. case 32000: u = 8; break;
  106327. case 44100: u = 9; break;
  106328. case 48000: u = 10; break;
  106329. case 96000: u = 11; break;
  106330. default:
  106331. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106332. sample_rate_hint = u = 12;
  106333. else if(header->sample_rate % 10 == 0)
  106334. sample_rate_hint = u = 14;
  106335. else if(header->sample_rate <= 0xffff)
  106336. sample_rate_hint = u = 13;
  106337. else
  106338. u = 0;
  106339. break;
  106340. }
  106341. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106342. return false;
  106343. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106344. switch(header->channel_assignment) {
  106345. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106346. u = header->channels - 1;
  106347. break;
  106348. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106349. FLAC__ASSERT(header->channels == 2);
  106350. u = 8;
  106351. break;
  106352. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106353. FLAC__ASSERT(header->channels == 2);
  106354. u = 9;
  106355. break;
  106356. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106357. FLAC__ASSERT(header->channels == 2);
  106358. u = 10;
  106359. break;
  106360. default:
  106361. FLAC__ASSERT(0);
  106362. }
  106363. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106364. return false;
  106365. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106366. switch(header->bits_per_sample) {
  106367. case 8 : u = 1; break;
  106368. case 12: u = 2; break;
  106369. case 16: u = 4; break;
  106370. case 20: u = 5; break;
  106371. case 24: u = 6; break;
  106372. default: u = 0; break;
  106373. }
  106374. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106375. return false;
  106376. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106377. return false;
  106378. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106379. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106380. return false;
  106381. }
  106382. else {
  106383. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106384. return false;
  106385. }
  106386. if(blocksize_hint)
  106387. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106388. return false;
  106389. switch(sample_rate_hint) {
  106390. case 12:
  106391. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106392. return false;
  106393. break;
  106394. case 13:
  106395. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106396. return false;
  106397. break;
  106398. case 14:
  106399. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106400. return false;
  106401. break;
  106402. }
  106403. /* write the CRC */
  106404. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106405. return false;
  106406. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106407. return false;
  106408. return true;
  106409. }
  106410. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106411. {
  106412. FLAC__bool ok;
  106413. ok =
  106414. 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) &&
  106415. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106416. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106417. ;
  106418. return ok;
  106419. }
  106420. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106421. {
  106422. unsigned i;
  106423. 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))
  106424. return false;
  106425. if(wasted_bits)
  106426. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106427. return false;
  106428. for(i = 0; i < subframe->order; i++)
  106429. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106430. return false;
  106431. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106432. return false;
  106433. switch(subframe->entropy_coding_method.type) {
  106434. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106435. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106436. if(!add_residual_partitioned_rice_(
  106437. bw,
  106438. subframe->residual,
  106439. residual_samples,
  106440. subframe->order,
  106441. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106442. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106443. subframe->entropy_coding_method.data.partitioned_rice.order,
  106444. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106445. ))
  106446. return false;
  106447. break;
  106448. default:
  106449. FLAC__ASSERT(0);
  106450. }
  106451. return true;
  106452. }
  106453. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106454. {
  106455. unsigned i;
  106456. 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))
  106457. return false;
  106458. if(wasted_bits)
  106459. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106460. return false;
  106461. for(i = 0; i < subframe->order; i++)
  106462. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106463. return false;
  106464. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106465. return false;
  106466. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106467. return false;
  106468. for(i = 0; i < subframe->order; i++)
  106469. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106470. return false;
  106471. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106472. return false;
  106473. switch(subframe->entropy_coding_method.type) {
  106474. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106475. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106476. if(!add_residual_partitioned_rice_(
  106477. bw,
  106478. subframe->residual,
  106479. residual_samples,
  106480. subframe->order,
  106481. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106482. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106483. subframe->entropy_coding_method.data.partitioned_rice.order,
  106484. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106485. ))
  106486. return false;
  106487. break;
  106488. default:
  106489. FLAC__ASSERT(0);
  106490. }
  106491. return true;
  106492. }
  106493. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106494. {
  106495. unsigned i;
  106496. const FLAC__int32 *signal = subframe->data;
  106497. 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))
  106498. return false;
  106499. if(wasted_bits)
  106500. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106501. return false;
  106502. for(i = 0; i < samples; i++)
  106503. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106504. return false;
  106505. return true;
  106506. }
  106507. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106508. {
  106509. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106510. return false;
  106511. switch(method->type) {
  106512. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106513. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106514. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106515. return false;
  106516. break;
  106517. default:
  106518. FLAC__ASSERT(0);
  106519. }
  106520. return true;
  106521. }
  106522. 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)
  106523. {
  106524. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106525. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106526. if(partition_order == 0) {
  106527. unsigned i;
  106528. if(raw_bits[0] == 0) {
  106529. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106530. return false;
  106531. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106532. return false;
  106533. }
  106534. else {
  106535. FLAC__ASSERT(rice_parameters[0] == 0);
  106536. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106537. return false;
  106538. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106539. return false;
  106540. for(i = 0; i < residual_samples; i++) {
  106541. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106542. return false;
  106543. }
  106544. }
  106545. return true;
  106546. }
  106547. else {
  106548. unsigned i, j, k = 0, k_last = 0;
  106549. unsigned partition_samples;
  106550. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106551. for(i = 0; i < (1u<<partition_order); i++) {
  106552. partition_samples = default_partition_samples;
  106553. if(i == 0)
  106554. partition_samples -= predictor_order;
  106555. k += partition_samples;
  106556. if(raw_bits[i] == 0) {
  106557. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106558. return false;
  106559. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106560. return false;
  106561. }
  106562. else {
  106563. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106564. return false;
  106565. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106566. return false;
  106567. for(j = k_last; j < k; j++) {
  106568. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106569. return false;
  106570. }
  106571. }
  106572. k_last = k;
  106573. }
  106574. return true;
  106575. }
  106576. }
  106577. #endif
  106578. /*** End of inlined file: stream_encoder_framing.c ***/
  106579. /*** Start of inlined file: window_flac.c ***/
  106580. /*** Start of inlined file: juce_FlacHeader.h ***/
  106581. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106582. // tasks..
  106583. #define VERSION "1.2.1"
  106584. #define FLAC__NO_DLL 1
  106585. #if JUCE_MSVC
  106586. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106587. #endif
  106588. #if JUCE_MAC
  106589. #define FLAC__SYS_DARWIN 1
  106590. #endif
  106591. /*** End of inlined file: juce_FlacHeader.h ***/
  106592. #if JUCE_USE_FLAC
  106593. #if HAVE_CONFIG_H
  106594. # include <config.h>
  106595. #endif
  106596. #include <math.h>
  106597. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106598. #ifndef M_PI
  106599. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106600. #define M_PI 3.14159265358979323846
  106601. #endif
  106602. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106603. {
  106604. const FLAC__int32 N = L - 1;
  106605. FLAC__int32 n;
  106606. if (L & 1) {
  106607. for (n = 0; n <= N/2; n++)
  106608. window[n] = 2.0f * n / (float)N;
  106609. for (; n <= N; n++)
  106610. window[n] = 2.0f - 2.0f * n / (float)N;
  106611. }
  106612. else {
  106613. for (n = 0; n <= L/2-1; n++)
  106614. window[n] = 2.0f * n / (float)N;
  106615. for (; n <= N; n++)
  106616. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106617. }
  106618. }
  106619. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106620. {
  106621. const FLAC__int32 N = L - 1;
  106622. FLAC__int32 n;
  106623. for (n = 0; n < L; n++)
  106624. 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)));
  106625. }
  106626. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106627. {
  106628. const FLAC__int32 N = L - 1;
  106629. FLAC__int32 n;
  106630. for (n = 0; n < L; n++)
  106631. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106632. }
  106633. /* 4-term -92dB side-lobe */
  106634. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106635. {
  106636. const FLAC__int32 N = L - 1;
  106637. FLAC__int32 n;
  106638. for (n = 0; n <= N; n++)
  106639. 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));
  106640. }
  106641. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106642. {
  106643. const FLAC__int32 N = L - 1;
  106644. const double N2 = (double)N / 2.;
  106645. FLAC__int32 n;
  106646. for (n = 0; n <= N; n++) {
  106647. double k = ((double)n - N2) / N2;
  106648. k = 1.0f - k * k;
  106649. window[n] = (FLAC__real)(k * k);
  106650. }
  106651. }
  106652. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106653. {
  106654. const FLAC__int32 N = L - 1;
  106655. FLAC__int32 n;
  106656. for (n = 0; n < L; n++)
  106657. 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));
  106658. }
  106659. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106660. {
  106661. const FLAC__int32 N = L - 1;
  106662. const double N2 = (double)N / 2.;
  106663. FLAC__int32 n;
  106664. for (n = 0; n <= N; n++) {
  106665. const double k = ((double)n - N2) / (stddev * N2);
  106666. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106667. }
  106668. }
  106669. void FLAC__window_hamming(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)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106675. }
  106676. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106677. {
  106678. const FLAC__int32 N = L - 1;
  106679. FLAC__int32 n;
  106680. for (n = 0; n < L; n++)
  106681. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106682. }
  106683. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106684. {
  106685. const FLAC__int32 N = L - 1;
  106686. FLAC__int32 n;
  106687. for (n = 0; n < L; n++)
  106688. 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));
  106689. }
  106690. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106691. {
  106692. const FLAC__int32 N = L - 1;
  106693. FLAC__int32 n;
  106694. for (n = 0; n < L; n++)
  106695. 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));
  106696. }
  106697. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106698. {
  106699. FLAC__int32 n;
  106700. for (n = 0; n < L; n++)
  106701. window[n] = 1.0f;
  106702. }
  106703. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106704. {
  106705. FLAC__int32 n;
  106706. if (L & 1) {
  106707. for (n = 1; n <= L+1/2; n++)
  106708. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106709. for (; n <= L; n++)
  106710. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106711. }
  106712. else {
  106713. for (n = 1; n <= L/2; n++)
  106714. window[n-1] = 2.0f * n / (float)L;
  106715. for (; n <= L; n++)
  106716. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106717. }
  106718. }
  106719. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106720. {
  106721. if (p <= 0.0)
  106722. FLAC__window_rectangle(window, L);
  106723. else if (p >= 1.0)
  106724. FLAC__window_hann(window, L);
  106725. else {
  106726. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106727. FLAC__int32 n;
  106728. /* start with rectangle... */
  106729. FLAC__window_rectangle(window, L);
  106730. /* ...replace ends with hann */
  106731. if (Np > 0) {
  106732. for (n = 0; n <= Np; n++) {
  106733. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106734. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106735. }
  106736. }
  106737. }
  106738. }
  106739. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106740. {
  106741. const FLAC__int32 N = L - 1;
  106742. const double N2 = (double)N / 2.;
  106743. FLAC__int32 n;
  106744. for (n = 0; n <= N; n++) {
  106745. const double k = ((double)n - N2) / N2;
  106746. window[n] = (FLAC__real)(1.0f - k * k);
  106747. }
  106748. }
  106749. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106750. #endif
  106751. /*** End of inlined file: window_flac.c ***/
  106752. #else
  106753. #include <FLAC/all.h>
  106754. #endif
  106755. }
  106756. #undef max
  106757. #undef min
  106758. BEGIN_JUCE_NAMESPACE
  106759. static const char* const flacFormatName = "FLAC file";
  106760. static const char* const flacExtensions[] = { ".flac", 0 };
  106761. class FlacReader : public AudioFormatReader
  106762. {
  106763. public:
  106764. FlacReader (InputStream* const in)
  106765. : AudioFormatReader (in, TRANS (flacFormatName)),
  106766. reservoir (2, 0),
  106767. reservoirStart (0),
  106768. samplesInReservoir (0),
  106769. scanningForLength (false)
  106770. {
  106771. using namespace FlacNamespace;
  106772. lengthInSamples = 0;
  106773. decoder = FLAC__stream_decoder_new();
  106774. ok = FLAC__stream_decoder_init_stream (decoder,
  106775. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106776. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106777. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106778. if (ok)
  106779. {
  106780. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106781. if (lengthInSamples == 0 && sampleRate > 0)
  106782. {
  106783. // the length hasn't been stored in the metadata, so we'll need to
  106784. // work it out the length the hard way, by scanning the whole file..
  106785. scanningForLength = true;
  106786. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106787. scanningForLength = false;
  106788. const int64 tempLength = lengthInSamples;
  106789. FLAC__stream_decoder_reset (decoder);
  106790. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106791. lengthInSamples = tempLength;
  106792. }
  106793. }
  106794. }
  106795. ~FlacReader()
  106796. {
  106797. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106798. }
  106799. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106800. {
  106801. sampleRate = info.sample_rate;
  106802. bitsPerSample = info.bits_per_sample;
  106803. lengthInSamples = (unsigned int) info.total_samples;
  106804. numChannels = info.channels;
  106805. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106806. }
  106807. // returns the number of samples read
  106808. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106809. int64 startSampleInFile, int numSamples)
  106810. {
  106811. using namespace FlacNamespace;
  106812. if (! ok)
  106813. return false;
  106814. while (numSamples > 0)
  106815. {
  106816. if (startSampleInFile >= reservoirStart
  106817. && startSampleInFile < reservoirStart + samplesInReservoir)
  106818. {
  106819. const int num = (int) jmin ((int64) numSamples,
  106820. reservoirStart + samplesInReservoir - startSampleInFile);
  106821. jassert (num > 0);
  106822. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106823. if (destSamples[i] != 0)
  106824. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106825. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106826. sizeof (int) * num);
  106827. startOffsetInDestBuffer += num;
  106828. startSampleInFile += num;
  106829. numSamples -= num;
  106830. }
  106831. else
  106832. {
  106833. if (startSampleInFile >= (int) lengthInSamples)
  106834. {
  106835. samplesInReservoir = 0;
  106836. }
  106837. else if (startSampleInFile < reservoirStart
  106838. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106839. {
  106840. // had some problems with flac crashing if the read pos is aligned more
  106841. // accurately than this. Probably fixed in newer versions of the library, though.
  106842. reservoirStart = (int) (startSampleInFile & ~511);
  106843. samplesInReservoir = 0;
  106844. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106845. }
  106846. else
  106847. {
  106848. reservoirStart += samplesInReservoir;
  106849. samplesInReservoir = 0;
  106850. FLAC__stream_decoder_process_single (decoder);
  106851. }
  106852. if (samplesInReservoir == 0)
  106853. break;
  106854. }
  106855. }
  106856. if (numSamples > 0)
  106857. {
  106858. for (int i = numDestChannels; --i >= 0;)
  106859. if (destSamples[i] != 0)
  106860. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106861. sizeof (int) * numSamples);
  106862. }
  106863. return true;
  106864. }
  106865. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106866. {
  106867. if (scanningForLength)
  106868. {
  106869. lengthInSamples += numSamples;
  106870. }
  106871. else
  106872. {
  106873. if (numSamples > reservoir.getNumSamples())
  106874. reservoir.setSize (numChannels, numSamples, false, false, true);
  106875. const int bitsToShift = 32 - bitsPerSample;
  106876. for (int i = 0; i < (int) numChannels; ++i)
  106877. {
  106878. const FlacNamespace::FLAC__int32* src = buffer[i];
  106879. int n = i;
  106880. while (src == 0 && n > 0)
  106881. src = buffer [--n];
  106882. if (src != 0)
  106883. {
  106884. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106885. for (int j = 0; j < numSamples; ++j)
  106886. dest[j] = src[j] << bitsToShift;
  106887. }
  106888. }
  106889. samplesInReservoir = numSamples;
  106890. }
  106891. }
  106892. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106893. {
  106894. using namespace FlacNamespace;
  106895. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106896. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106897. }
  106898. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106899. {
  106900. using namespace FlacNamespace;
  106901. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106902. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106903. }
  106904. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106905. {
  106906. using namespace FlacNamespace;
  106907. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106908. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106909. }
  106910. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106911. {
  106912. using namespace FlacNamespace;
  106913. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106914. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106915. }
  106916. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106917. {
  106918. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106919. }
  106920. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106921. const FlacNamespace::FLAC__Frame* frame,
  106922. const FlacNamespace::FLAC__int32* const buffer[],
  106923. void* client_data)
  106924. {
  106925. using namespace FlacNamespace;
  106926. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106927. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106928. }
  106929. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106930. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106931. void* client_data)
  106932. {
  106933. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106934. }
  106935. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106936. {
  106937. }
  106938. juce_UseDebuggingNewOperator
  106939. private:
  106940. FlacNamespace::FLAC__StreamDecoder* decoder;
  106941. AudioSampleBuffer reservoir;
  106942. int reservoirStart, samplesInReservoir;
  106943. bool ok, scanningForLength;
  106944. FlacReader (const FlacReader&);
  106945. FlacReader& operator= (const FlacReader&);
  106946. };
  106947. class FlacWriter : public AudioFormatWriter
  106948. {
  106949. public:
  106950. FlacWriter (OutputStream* const out, double sampleRate_,
  106951. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106952. : AudioFormatWriter (out, TRANS (flacFormatName),
  106953. sampleRate_, numChannels_, bitsPerSample_)
  106954. {
  106955. using namespace FlacNamespace;
  106956. encoder = FLAC__stream_encoder_new();
  106957. if (qualityOptionIndex > 0)
  106958. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106959. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106960. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106961. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106962. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106963. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106964. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106965. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106966. ok = FLAC__stream_encoder_init_stream (encoder,
  106967. encodeWriteCallback, encodeSeekCallback,
  106968. encodeTellCallback, encodeMetadataCallback,
  106969. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106970. }
  106971. ~FlacWriter()
  106972. {
  106973. if (ok)
  106974. {
  106975. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106976. output->flush();
  106977. }
  106978. else
  106979. {
  106980. output = 0; // to stop the base class deleting this, as it needs to be returned
  106981. // to the caller of createWriter()
  106982. }
  106983. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106984. }
  106985. bool write (const int** samplesToWrite, int numSamples)
  106986. {
  106987. using namespace FlacNamespace;
  106988. if (! ok)
  106989. return false;
  106990. int* buf[3];
  106991. const int bitsToShift = 32 - bitsPerSample;
  106992. if (bitsToShift > 0)
  106993. {
  106994. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106995. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  106996. buf[0] = temp.getData();
  106997. buf[1] = temp.getData() + numSamples;
  106998. buf[2] = 0;
  106999. for (int i = numChannelsToWrite; --i >= 0;)
  107000. {
  107001. if (samplesToWrite[i] != 0)
  107002. {
  107003. for (int j = 0; j < numSamples; ++j)
  107004. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107005. }
  107006. }
  107007. samplesToWrite = const_cast<const int**> (buf);
  107008. }
  107009. return FLAC__stream_encoder_process (encoder,
  107010. (const FLAC__int32**) samplesToWrite,
  107011. numSamples) != 0;
  107012. }
  107013. bool writeData (const void* const data, const int size) const
  107014. {
  107015. return output->write (data, size);
  107016. }
  107017. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107018. {
  107019. using namespace FlacNamespace;
  107020. b += bytes;
  107021. for (int i = 0; i < bytes; ++i)
  107022. {
  107023. *(--b) = (FLAC__byte) (val & 0xff);
  107024. val >>= 8;
  107025. }
  107026. }
  107027. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107028. {
  107029. using namespace FlacNamespace;
  107030. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107031. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107032. const unsigned int channelsMinus1 = info.channels - 1;
  107033. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107034. packUint32 (info.min_blocksize, buffer, 2);
  107035. packUint32 (info.max_blocksize, buffer + 2, 2);
  107036. packUint32 (info.min_framesize, buffer + 4, 3);
  107037. packUint32 (info.max_framesize, buffer + 7, 3);
  107038. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107039. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107040. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107041. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107042. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107043. memcpy (buffer + 18, info.md5sum, 16);
  107044. const bool seekOk = output->setPosition (4);
  107045. (void) seekOk;
  107046. // if this fails, you've given it an output stream that can't seek! It needs
  107047. // to be able to seek back to write the header
  107048. jassert (seekOk);
  107049. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107050. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107051. }
  107052. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107053. const FlacNamespace::FLAC__byte buffer[],
  107054. size_t bytes,
  107055. unsigned int /*samples*/,
  107056. unsigned int /*current_frame*/,
  107057. void* client_data)
  107058. {
  107059. using namespace FlacNamespace;
  107060. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107061. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107062. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107063. }
  107064. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107065. {
  107066. using namespace FlacNamespace;
  107067. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107068. }
  107069. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107070. {
  107071. using namespace FlacNamespace;
  107072. if (client_data == 0)
  107073. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107074. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107075. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107076. }
  107077. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107078. {
  107079. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107080. }
  107081. juce_UseDebuggingNewOperator
  107082. bool ok;
  107083. private:
  107084. FlacNamespace::FLAC__StreamEncoder* encoder;
  107085. FlacWriter (const FlacWriter&);
  107086. FlacWriter& operator= (const FlacWriter&);
  107087. };
  107088. FlacAudioFormat::FlacAudioFormat()
  107089. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107090. {
  107091. }
  107092. FlacAudioFormat::~FlacAudioFormat()
  107093. {
  107094. }
  107095. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107096. {
  107097. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107098. return Array <int> (rates);
  107099. }
  107100. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107101. {
  107102. const int depths[] = { 16, 24, 0 };
  107103. return Array <int> (depths);
  107104. }
  107105. bool FlacAudioFormat::canDoStereo() { return true; }
  107106. bool FlacAudioFormat::canDoMono() { return true; }
  107107. bool FlacAudioFormat::isCompressed() { return true; }
  107108. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107109. const bool deleteStreamIfOpeningFails)
  107110. {
  107111. ScopedPointer<FlacReader> r (new FlacReader (in));
  107112. if (r->sampleRate != 0)
  107113. return r.release();
  107114. if (! deleteStreamIfOpeningFails)
  107115. r->input = 0;
  107116. return 0;
  107117. }
  107118. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107119. double sampleRate,
  107120. unsigned int numberOfChannels,
  107121. int bitsPerSample,
  107122. const StringPairArray& /*metadataValues*/,
  107123. int qualityOptionIndex)
  107124. {
  107125. if (getPossibleBitDepths().contains (bitsPerSample))
  107126. {
  107127. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107128. if (w->ok)
  107129. return w.release();
  107130. }
  107131. return 0;
  107132. }
  107133. END_JUCE_NAMESPACE
  107134. #endif
  107135. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107136. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107137. #if JUCE_USE_OGGVORBIS
  107138. #if JUCE_MAC
  107139. #define __MACOSX__ 1
  107140. #endif
  107141. namespace OggVorbisNamespace
  107142. {
  107143. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107144. /*** Start of inlined file: vorbisenc.h ***/
  107145. #ifndef _OV_ENC_H_
  107146. #define _OV_ENC_H_
  107147. #ifdef __cplusplus
  107148. extern "C"
  107149. {
  107150. #endif /* __cplusplus */
  107151. /*** Start of inlined file: codec.h ***/
  107152. #ifndef _vorbis_codec_h_
  107153. #define _vorbis_codec_h_
  107154. #ifdef __cplusplus
  107155. extern "C"
  107156. {
  107157. #endif /* __cplusplus */
  107158. /*** Start of inlined file: ogg.h ***/
  107159. #ifndef _OGG_H
  107160. #define _OGG_H
  107161. #ifdef __cplusplus
  107162. extern "C" {
  107163. #endif
  107164. /*** Start of inlined file: os_types.h ***/
  107165. #ifndef _OS_TYPES_H
  107166. #define _OS_TYPES_H
  107167. /* make it easy on the folks that want to compile the libs with a
  107168. different malloc than stdlib */
  107169. #define _ogg_malloc malloc
  107170. #define _ogg_calloc calloc
  107171. #define _ogg_realloc realloc
  107172. #define _ogg_free free
  107173. #if defined(_WIN32)
  107174. # if defined(__CYGWIN__)
  107175. # include <_G_config.h>
  107176. typedef _G_int64_t ogg_int64_t;
  107177. typedef _G_int32_t ogg_int32_t;
  107178. typedef _G_uint32_t ogg_uint32_t;
  107179. typedef _G_int16_t ogg_int16_t;
  107180. typedef _G_uint16_t ogg_uint16_t;
  107181. # elif defined(__MINGW32__)
  107182. typedef short ogg_int16_t;
  107183. typedef unsigned short ogg_uint16_t;
  107184. typedef int ogg_int32_t;
  107185. typedef unsigned int ogg_uint32_t;
  107186. typedef long long ogg_int64_t;
  107187. typedef unsigned long long ogg_uint64_t;
  107188. # elif defined(__MWERKS__)
  107189. typedef long long ogg_int64_t;
  107190. typedef int ogg_int32_t;
  107191. typedef unsigned int ogg_uint32_t;
  107192. typedef short ogg_int16_t;
  107193. typedef unsigned short ogg_uint16_t;
  107194. # else
  107195. /* MSVC/Borland */
  107196. typedef __int64 ogg_int64_t;
  107197. typedef __int32 ogg_int32_t;
  107198. typedef unsigned __int32 ogg_uint32_t;
  107199. typedef __int16 ogg_int16_t;
  107200. typedef unsigned __int16 ogg_uint16_t;
  107201. # endif
  107202. #elif defined(__MACOS__)
  107203. # include <sys/types.h>
  107204. typedef SInt16 ogg_int16_t;
  107205. typedef UInt16 ogg_uint16_t;
  107206. typedef SInt32 ogg_int32_t;
  107207. typedef UInt32 ogg_uint32_t;
  107208. typedef SInt64 ogg_int64_t;
  107209. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107210. # include <sys/types.h>
  107211. typedef int16_t ogg_int16_t;
  107212. typedef u_int16_t ogg_uint16_t;
  107213. typedef int32_t ogg_int32_t;
  107214. typedef u_int32_t ogg_uint32_t;
  107215. typedef int64_t ogg_int64_t;
  107216. #elif defined(__BEOS__)
  107217. /* Be */
  107218. # include <inttypes.h>
  107219. typedef int16_t ogg_int16_t;
  107220. typedef u_int16_t ogg_uint16_t;
  107221. typedef int32_t ogg_int32_t;
  107222. typedef u_int32_t ogg_uint32_t;
  107223. typedef int64_t ogg_int64_t;
  107224. #elif defined (__EMX__)
  107225. /* OS/2 GCC */
  107226. typedef short ogg_int16_t;
  107227. typedef unsigned short ogg_uint16_t;
  107228. typedef int ogg_int32_t;
  107229. typedef unsigned int ogg_uint32_t;
  107230. typedef long long ogg_int64_t;
  107231. #elif defined (DJGPP)
  107232. /* DJGPP */
  107233. typedef short ogg_int16_t;
  107234. typedef int ogg_int32_t;
  107235. typedef unsigned int ogg_uint32_t;
  107236. typedef long long ogg_int64_t;
  107237. #elif defined(R5900)
  107238. /* PS2 EE */
  107239. typedef long ogg_int64_t;
  107240. typedef int ogg_int32_t;
  107241. typedef unsigned ogg_uint32_t;
  107242. typedef short ogg_int16_t;
  107243. #elif defined(__SYMBIAN32__)
  107244. /* Symbian GCC */
  107245. typedef signed short ogg_int16_t;
  107246. typedef unsigned short ogg_uint16_t;
  107247. typedef signed int ogg_int32_t;
  107248. typedef unsigned int ogg_uint32_t;
  107249. typedef long long int ogg_int64_t;
  107250. #else
  107251. # include <sys/types.h>
  107252. /*** Start of inlined file: config_types.h ***/
  107253. #ifndef __CONFIG_TYPES_H__
  107254. #define __CONFIG_TYPES_H__
  107255. typedef int16_t ogg_int16_t;
  107256. typedef unsigned short ogg_uint16_t;
  107257. typedef int32_t ogg_int32_t;
  107258. typedef unsigned int ogg_uint32_t;
  107259. typedef int64_t ogg_int64_t;
  107260. #endif
  107261. /*** End of inlined file: config_types.h ***/
  107262. #endif
  107263. #endif /* _OS_TYPES_H */
  107264. /*** End of inlined file: os_types.h ***/
  107265. typedef struct {
  107266. long endbyte;
  107267. int endbit;
  107268. unsigned char *buffer;
  107269. unsigned char *ptr;
  107270. long storage;
  107271. } oggpack_buffer;
  107272. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107273. typedef struct {
  107274. unsigned char *header;
  107275. long header_len;
  107276. unsigned char *body;
  107277. long body_len;
  107278. } ogg_page;
  107279. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107280. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107281. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107282. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107283. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107284. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107285. }
  107286. /* ogg_stream_state contains the current encode/decode state of a logical
  107287. Ogg bitstream **********************************************************/
  107288. typedef struct {
  107289. unsigned char *body_data; /* bytes from packet bodies */
  107290. long body_storage; /* storage elements allocated */
  107291. long body_fill; /* elements stored; fill mark */
  107292. long body_returned; /* elements of fill returned */
  107293. int *lacing_vals; /* The values that will go to the segment table */
  107294. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107295. this way, but it is simple coupled to the
  107296. lacing fifo */
  107297. long lacing_storage;
  107298. long lacing_fill;
  107299. long lacing_packet;
  107300. long lacing_returned;
  107301. unsigned char header[282]; /* working space for header encode */
  107302. int header_fill;
  107303. int e_o_s; /* set when we have buffered the last packet in the
  107304. logical bitstream */
  107305. int b_o_s; /* set after we've written the initial page
  107306. of a logical bitstream */
  107307. long serialno;
  107308. long pageno;
  107309. ogg_int64_t packetno; /* sequence number for decode; the framing
  107310. knows where there's a hole in the data,
  107311. but we need coupling so that the codec
  107312. (which is in a seperate abstraction
  107313. layer) also knows about the gap */
  107314. ogg_int64_t granulepos;
  107315. } ogg_stream_state;
  107316. /* ogg_packet is used to encapsulate the data and metadata belonging
  107317. to a single raw Ogg/Vorbis packet *************************************/
  107318. typedef struct {
  107319. unsigned char *packet;
  107320. long bytes;
  107321. long b_o_s;
  107322. long e_o_s;
  107323. ogg_int64_t granulepos;
  107324. ogg_int64_t packetno; /* sequence number for decode; the framing
  107325. knows where there's a hole in the data,
  107326. but we need coupling so that the codec
  107327. (which is in a seperate abstraction
  107328. layer) also knows about the gap */
  107329. } ogg_packet;
  107330. typedef struct {
  107331. unsigned char *data;
  107332. int storage;
  107333. int fill;
  107334. int returned;
  107335. int unsynced;
  107336. int headerbytes;
  107337. int bodybytes;
  107338. } ogg_sync_state;
  107339. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107340. extern void oggpack_writeinit(oggpack_buffer *b);
  107341. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107342. extern void oggpack_writealign(oggpack_buffer *b);
  107343. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107344. extern void oggpack_reset(oggpack_buffer *b);
  107345. extern void oggpack_writeclear(oggpack_buffer *b);
  107346. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107347. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107348. extern long oggpack_look(oggpack_buffer *b,int bits);
  107349. extern long oggpack_look1(oggpack_buffer *b);
  107350. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107351. extern void oggpack_adv1(oggpack_buffer *b);
  107352. extern long oggpack_read(oggpack_buffer *b,int bits);
  107353. extern long oggpack_read1(oggpack_buffer *b);
  107354. extern long oggpack_bytes(oggpack_buffer *b);
  107355. extern long oggpack_bits(oggpack_buffer *b);
  107356. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107357. extern void oggpackB_writeinit(oggpack_buffer *b);
  107358. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107359. extern void oggpackB_writealign(oggpack_buffer *b);
  107360. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107361. extern void oggpackB_reset(oggpack_buffer *b);
  107362. extern void oggpackB_writeclear(oggpack_buffer *b);
  107363. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107364. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107365. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107366. extern long oggpackB_look1(oggpack_buffer *b);
  107367. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107368. extern void oggpackB_adv1(oggpack_buffer *b);
  107369. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107370. extern long oggpackB_read1(oggpack_buffer *b);
  107371. extern long oggpackB_bytes(oggpack_buffer *b);
  107372. extern long oggpackB_bits(oggpack_buffer *b);
  107373. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107374. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107375. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107376. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107377. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107378. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107379. extern int ogg_sync_init(ogg_sync_state *oy);
  107380. extern int ogg_sync_clear(ogg_sync_state *oy);
  107381. extern int ogg_sync_reset(ogg_sync_state *oy);
  107382. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107383. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107384. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107385. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107386. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107387. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107388. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107389. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107390. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107391. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107392. extern int ogg_stream_clear(ogg_stream_state *os);
  107393. extern int ogg_stream_reset(ogg_stream_state *os);
  107394. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107395. extern int ogg_stream_destroy(ogg_stream_state *os);
  107396. extern int ogg_stream_eos(ogg_stream_state *os);
  107397. extern void ogg_page_checksum_set(ogg_page *og);
  107398. extern int ogg_page_version(ogg_page *og);
  107399. extern int ogg_page_continued(ogg_page *og);
  107400. extern int ogg_page_bos(ogg_page *og);
  107401. extern int ogg_page_eos(ogg_page *og);
  107402. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107403. extern int ogg_page_serialno(ogg_page *og);
  107404. extern long ogg_page_pageno(ogg_page *og);
  107405. extern int ogg_page_packets(ogg_page *og);
  107406. extern void ogg_packet_clear(ogg_packet *op);
  107407. #ifdef __cplusplus
  107408. }
  107409. #endif
  107410. #endif /* _OGG_H */
  107411. /*** End of inlined file: ogg.h ***/
  107412. typedef struct vorbis_info{
  107413. int version;
  107414. int channels;
  107415. long rate;
  107416. /* The below bitrate declarations are *hints*.
  107417. Combinations of the three values carry the following implications:
  107418. all three set to the same value:
  107419. implies a fixed rate bitstream
  107420. only nominal set:
  107421. implies a VBR stream that averages the nominal bitrate. No hard
  107422. upper/lower limit
  107423. upper and or lower set:
  107424. implies a VBR bitstream that obeys the bitrate limits. nominal
  107425. may also be set to give a nominal rate.
  107426. none set:
  107427. the coder does not care to speculate.
  107428. */
  107429. long bitrate_upper;
  107430. long bitrate_nominal;
  107431. long bitrate_lower;
  107432. long bitrate_window;
  107433. void *codec_setup;
  107434. } vorbis_info;
  107435. /* vorbis_dsp_state buffers the current vorbis audio
  107436. analysis/synthesis state. The DSP state belongs to a specific
  107437. logical bitstream ****************************************************/
  107438. typedef struct vorbis_dsp_state{
  107439. int analysisp;
  107440. vorbis_info *vi;
  107441. float **pcm;
  107442. float **pcmret;
  107443. int pcm_storage;
  107444. int pcm_current;
  107445. int pcm_returned;
  107446. int preextrapolate;
  107447. int eofflag;
  107448. long lW;
  107449. long W;
  107450. long nW;
  107451. long centerW;
  107452. ogg_int64_t granulepos;
  107453. ogg_int64_t sequence;
  107454. ogg_int64_t glue_bits;
  107455. ogg_int64_t time_bits;
  107456. ogg_int64_t floor_bits;
  107457. ogg_int64_t res_bits;
  107458. void *backend_state;
  107459. } vorbis_dsp_state;
  107460. typedef struct vorbis_block{
  107461. /* necessary stream state for linking to the framing abstraction */
  107462. float **pcm; /* this is a pointer into local storage */
  107463. oggpack_buffer opb;
  107464. long lW;
  107465. long W;
  107466. long nW;
  107467. int pcmend;
  107468. int mode;
  107469. int eofflag;
  107470. ogg_int64_t granulepos;
  107471. ogg_int64_t sequence;
  107472. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107473. /* local storage to avoid remallocing; it's up to the mapping to
  107474. structure it */
  107475. void *localstore;
  107476. long localtop;
  107477. long localalloc;
  107478. long totaluse;
  107479. struct alloc_chain *reap;
  107480. /* bitmetrics for the frame */
  107481. long glue_bits;
  107482. long time_bits;
  107483. long floor_bits;
  107484. long res_bits;
  107485. void *internal;
  107486. } vorbis_block;
  107487. /* vorbis_block is a single block of data to be processed as part of
  107488. the analysis/synthesis stream; it belongs to a specific logical
  107489. bitstream, but is independant from other vorbis_blocks belonging to
  107490. that logical bitstream. *************************************************/
  107491. struct alloc_chain{
  107492. void *ptr;
  107493. struct alloc_chain *next;
  107494. };
  107495. /* vorbis_info contains all the setup information specific to the
  107496. specific compression/decompression mode in progress (eg,
  107497. psychoacoustic settings, channel setup, options, codebook
  107498. etc). vorbis_info and substructures are in backends.h.
  107499. *********************************************************************/
  107500. /* the comments are not part of vorbis_info so that vorbis_info can be
  107501. static storage */
  107502. typedef struct vorbis_comment{
  107503. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107504. whatever vendor is set to in encode */
  107505. char **user_comments;
  107506. int *comment_lengths;
  107507. int comments;
  107508. char *vendor;
  107509. } vorbis_comment;
  107510. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107511. and produce a packet (see docs/analysis.txt). The packet is then
  107512. coded into a framed OggSquish bitstream by the second layer (see
  107513. docs/framing.txt). Decode is the reverse process; we sync/frame
  107514. the bitstream and extract individual packets, then decode the
  107515. packet back into PCM audio.
  107516. The extra framing/packetizing is used in streaming formats, such as
  107517. files. Over the net (such as with UDP), the framing and
  107518. packetization aren't necessary as they're provided by the transport
  107519. and the streaming layer is not used */
  107520. /* Vorbis PRIMITIVES: general ***************************************/
  107521. extern void vorbis_info_init(vorbis_info *vi);
  107522. extern void vorbis_info_clear(vorbis_info *vi);
  107523. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107524. extern void vorbis_comment_init(vorbis_comment *vc);
  107525. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107526. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107527. const char *tag, char *contents);
  107528. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107529. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107530. extern void vorbis_comment_clear(vorbis_comment *vc);
  107531. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107532. extern int vorbis_block_clear(vorbis_block *vb);
  107533. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107534. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107535. ogg_int64_t granulepos);
  107536. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107537. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107538. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107539. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107540. vorbis_comment *vc,
  107541. ogg_packet *op,
  107542. ogg_packet *op_comm,
  107543. ogg_packet *op_code);
  107544. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107545. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107546. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107547. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107548. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107549. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107550. ogg_packet *op);
  107551. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107552. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107553. ogg_packet *op);
  107554. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107555. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107556. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107557. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107558. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107559. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107560. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107561. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107562. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107563. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107564. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107565. /* Vorbis ERRORS and return codes ***********************************/
  107566. #define OV_FALSE -1
  107567. #define OV_EOF -2
  107568. #define OV_HOLE -3
  107569. #define OV_EREAD -128
  107570. #define OV_EFAULT -129
  107571. #define OV_EIMPL -130
  107572. #define OV_EINVAL -131
  107573. #define OV_ENOTVORBIS -132
  107574. #define OV_EBADHEADER -133
  107575. #define OV_EVERSION -134
  107576. #define OV_ENOTAUDIO -135
  107577. #define OV_EBADPACKET -136
  107578. #define OV_EBADLINK -137
  107579. #define OV_ENOSEEK -138
  107580. #ifdef __cplusplus
  107581. }
  107582. #endif /* __cplusplus */
  107583. #endif
  107584. /*** End of inlined file: codec.h ***/
  107585. extern int vorbis_encode_init(vorbis_info *vi,
  107586. long channels,
  107587. long rate,
  107588. long max_bitrate,
  107589. long nominal_bitrate,
  107590. long min_bitrate);
  107591. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107592. long channels,
  107593. long rate,
  107594. long max_bitrate,
  107595. long nominal_bitrate,
  107596. long min_bitrate);
  107597. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107598. long channels,
  107599. long rate,
  107600. float quality /* quality level from 0. (lo) to 1. (hi) */
  107601. );
  107602. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107603. long channels,
  107604. long rate,
  107605. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107606. );
  107607. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107608. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107609. /* deprecated rate management supported only for compatability */
  107610. #define OV_ECTL_RATEMANAGE_GET 0x10
  107611. #define OV_ECTL_RATEMANAGE_SET 0x11
  107612. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107613. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107614. struct ovectl_ratemanage_arg {
  107615. int management_active;
  107616. long bitrate_hard_min;
  107617. long bitrate_hard_max;
  107618. double bitrate_hard_window;
  107619. long bitrate_av_lo;
  107620. long bitrate_av_hi;
  107621. double bitrate_av_window;
  107622. double bitrate_av_window_center;
  107623. };
  107624. /* new rate setup */
  107625. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107626. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107627. struct ovectl_ratemanage2_arg {
  107628. int management_active;
  107629. long bitrate_limit_min_kbps;
  107630. long bitrate_limit_max_kbps;
  107631. long bitrate_limit_reservoir_bits;
  107632. double bitrate_limit_reservoir_bias;
  107633. long bitrate_average_kbps;
  107634. double bitrate_average_damping;
  107635. };
  107636. #define OV_ECTL_LOWPASS_GET 0x20
  107637. #define OV_ECTL_LOWPASS_SET 0x21
  107638. #define OV_ECTL_IBLOCK_GET 0x30
  107639. #define OV_ECTL_IBLOCK_SET 0x31
  107640. #ifdef __cplusplus
  107641. }
  107642. #endif /* __cplusplus */
  107643. #endif
  107644. /*** End of inlined file: vorbisenc.h ***/
  107645. /*** Start of inlined file: vorbisfile.h ***/
  107646. #ifndef _OV_FILE_H_
  107647. #define _OV_FILE_H_
  107648. #ifdef __cplusplus
  107649. extern "C"
  107650. {
  107651. #endif /* __cplusplus */
  107652. #include <stdio.h>
  107653. /* The function prototypes for the callbacks are basically the same as for
  107654. * the stdio functions fread, fseek, fclose, ftell.
  107655. * The one difference is that the FILE * arguments have been replaced with
  107656. * a void * - this is to be used as a pointer to whatever internal data these
  107657. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107658. *
  107659. * If you use other functions, check the docs for these functions and return
  107660. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107661. * unseekable
  107662. */
  107663. typedef struct {
  107664. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107665. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107666. int (*close_func) (void *datasource);
  107667. long (*tell_func) (void *datasource);
  107668. } ov_callbacks;
  107669. #define NOTOPEN 0
  107670. #define PARTOPEN 1
  107671. #define OPENED 2
  107672. #define STREAMSET 3
  107673. #define INITSET 4
  107674. typedef struct OggVorbis_File {
  107675. void *datasource; /* Pointer to a FILE *, etc. */
  107676. int seekable;
  107677. ogg_int64_t offset;
  107678. ogg_int64_t end;
  107679. ogg_sync_state oy;
  107680. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107681. stream appears */
  107682. int links;
  107683. ogg_int64_t *offsets;
  107684. ogg_int64_t *dataoffsets;
  107685. long *serialnos;
  107686. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107687. compatability; x2 size, stores both
  107688. beginning and end values */
  107689. vorbis_info *vi;
  107690. vorbis_comment *vc;
  107691. /* Decoding working state local storage */
  107692. ogg_int64_t pcm_offset;
  107693. int ready_state;
  107694. long current_serialno;
  107695. int current_link;
  107696. double bittrack;
  107697. double samptrack;
  107698. ogg_stream_state os; /* take physical pages, weld into a logical
  107699. stream of packets */
  107700. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107701. vorbis_block vb; /* local working space for packet->PCM decode */
  107702. ov_callbacks callbacks;
  107703. } OggVorbis_File;
  107704. extern int ov_clear(OggVorbis_File *vf);
  107705. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107706. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107707. char *initial, long ibytes, ov_callbacks callbacks);
  107708. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107709. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107710. char *initial, long ibytes, ov_callbacks callbacks);
  107711. extern int ov_test_open(OggVorbis_File *vf);
  107712. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107713. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107714. extern long ov_streams(OggVorbis_File *vf);
  107715. extern long ov_seekable(OggVorbis_File *vf);
  107716. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107717. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107718. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107719. extern double ov_time_total(OggVorbis_File *vf,int i);
  107720. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107721. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107722. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107723. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107724. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107725. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107726. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107727. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107728. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107729. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107730. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107731. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107732. extern double ov_time_tell(OggVorbis_File *vf);
  107733. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107734. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107735. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107736. int *bitstream);
  107737. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107738. int bigendianp,int word,int sgned,int *bitstream);
  107739. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107740. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107741. extern int ov_halfrate_p(OggVorbis_File *vf);
  107742. #ifdef __cplusplus
  107743. }
  107744. #endif /* __cplusplus */
  107745. #endif
  107746. /*** End of inlined file: vorbisfile.h ***/
  107747. /*** Start of inlined file: bitwise.c ***/
  107748. /* We're 'LSb' endian; if we write a word but read individual bits,
  107749. then we'll read the lsb first */
  107750. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107751. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107752. // tasks..
  107753. #if JUCE_MSVC
  107754. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107755. #endif
  107756. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107757. #if JUCE_USE_OGGVORBIS
  107758. #include <string.h>
  107759. #include <stdlib.h>
  107760. #define BUFFER_INCREMENT 256
  107761. static const unsigned long mask[]=
  107762. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107763. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107764. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107765. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107766. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107767. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107768. 0x3fffffff,0x7fffffff,0xffffffff };
  107769. static const unsigned int mask8B[]=
  107770. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107771. void oggpack_writeinit(oggpack_buffer *b){
  107772. memset(b,0,sizeof(*b));
  107773. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107774. b->buffer[0]='\0';
  107775. b->storage=BUFFER_INCREMENT;
  107776. }
  107777. void oggpackB_writeinit(oggpack_buffer *b){
  107778. oggpack_writeinit(b);
  107779. }
  107780. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107781. long bytes=bits>>3;
  107782. bits-=bytes*8;
  107783. b->ptr=b->buffer+bytes;
  107784. b->endbit=bits;
  107785. b->endbyte=bytes;
  107786. *b->ptr&=mask[bits];
  107787. }
  107788. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107789. long bytes=bits>>3;
  107790. bits-=bytes*8;
  107791. b->ptr=b->buffer+bytes;
  107792. b->endbit=bits;
  107793. b->endbyte=bytes;
  107794. *b->ptr&=mask8B[bits];
  107795. }
  107796. /* Takes only up to 32 bits. */
  107797. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107798. if(b->endbyte+4>=b->storage){
  107799. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107800. b->storage+=BUFFER_INCREMENT;
  107801. b->ptr=b->buffer+b->endbyte;
  107802. }
  107803. value&=mask[bits];
  107804. bits+=b->endbit;
  107805. b->ptr[0]|=value<<b->endbit;
  107806. if(bits>=8){
  107807. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107808. if(bits>=16){
  107809. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107810. if(bits>=24){
  107811. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107812. if(bits>=32){
  107813. if(b->endbit)
  107814. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107815. else
  107816. b->ptr[4]=0;
  107817. }
  107818. }
  107819. }
  107820. }
  107821. b->endbyte+=bits/8;
  107822. b->ptr+=bits/8;
  107823. b->endbit=bits&7;
  107824. }
  107825. /* Takes only up to 32 bits. */
  107826. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107827. if(b->endbyte+4>=b->storage){
  107828. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107829. b->storage+=BUFFER_INCREMENT;
  107830. b->ptr=b->buffer+b->endbyte;
  107831. }
  107832. value=(value&mask[bits])<<(32-bits);
  107833. bits+=b->endbit;
  107834. b->ptr[0]|=value>>(24+b->endbit);
  107835. if(bits>=8){
  107836. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107837. if(bits>=16){
  107838. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107839. if(bits>=24){
  107840. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107841. if(bits>=32){
  107842. if(b->endbit)
  107843. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107844. else
  107845. b->ptr[4]=0;
  107846. }
  107847. }
  107848. }
  107849. }
  107850. b->endbyte+=bits/8;
  107851. b->ptr+=bits/8;
  107852. b->endbit=bits&7;
  107853. }
  107854. void oggpack_writealign(oggpack_buffer *b){
  107855. int bits=8-b->endbit;
  107856. if(bits<8)
  107857. oggpack_write(b,0,bits);
  107858. }
  107859. void oggpackB_writealign(oggpack_buffer *b){
  107860. int bits=8-b->endbit;
  107861. if(bits<8)
  107862. oggpackB_write(b,0,bits);
  107863. }
  107864. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107865. void *source,
  107866. long bits,
  107867. void (*w)(oggpack_buffer *,
  107868. unsigned long,
  107869. int),
  107870. int msb){
  107871. unsigned char *ptr=(unsigned char *)source;
  107872. long bytes=bits/8;
  107873. bits-=bytes*8;
  107874. if(b->endbit){
  107875. int i;
  107876. /* unaligned copy. Do it the hard way. */
  107877. for(i=0;i<bytes;i++)
  107878. w(b,(unsigned long)(ptr[i]),8);
  107879. }else{
  107880. /* aligned block copy */
  107881. if(b->endbyte+bytes+1>=b->storage){
  107882. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107883. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107884. b->ptr=b->buffer+b->endbyte;
  107885. }
  107886. memmove(b->ptr,source,bytes);
  107887. b->ptr+=bytes;
  107888. b->endbyte+=bytes;
  107889. *b->ptr=0;
  107890. }
  107891. if(bits){
  107892. if(msb)
  107893. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107894. else
  107895. w(b,(unsigned long)(ptr[bytes]),bits);
  107896. }
  107897. }
  107898. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107899. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107900. }
  107901. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107902. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107903. }
  107904. void oggpack_reset(oggpack_buffer *b){
  107905. b->ptr=b->buffer;
  107906. b->buffer[0]=0;
  107907. b->endbit=b->endbyte=0;
  107908. }
  107909. void oggpackB_reset(oggpack_buffer *b){
  107910. oggpack_reset(b);
  107911. }
  107912. void oggpack_writeclear(oggpack_buffer *b){
  107913. _ogg_free(b->buffer);
  107914. memset(b,0,sizeof(*b));
  107915. }
  107916. void oggpackB_writeclear(oggpack_buffer *b){
  107917. oggpack_writeclear(b);
  107918. }
  107919. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107920. memset(b,0,sizeof(*b));
  107921. b->buffer=b->ptr=buf;
  107922. b->storage=bytes;
  107923. }
  107924. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107925. oggpack_readinit(b,buf,bytes);
  107926. }
  107927. /* Read in bits without advancing the bitptr; bits <= 32 */
  107928. long oggpack_look(oggpack_buffer *b,int bits){
  107929. unsigned long ret;
  107930. unsigned long m=mask[bits];
  107931. bits+=b->endbit;
  107932. if(b->endbyte+4>=b->storage){
  107933. /* not the main path */
  107934. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107935. }
  107936. ret=b->ptr[0]>>b->endbit;
  107937. if(bits>8){
  107938. ret|=b->ptr[1]<<(8-b->endbit);
  107939. if(bits>16){
  107940. ret|=b->ptr[2]<<(16-b->endbit);
  107941. if(bits>24){
  107942. ret|=b->ptr[3]<<(24-b->endbit);
  107943. if(bits>32 && b->endbit)
  107944. ret|=b->ptr[4]<<(32-b->endbit);
  107945. }
  107946. }
  107947. }
  107948. return(m&ret);
  107949. }
  107950. /* Read in bits without advancing the bitptr; bits <= 32 */
  107951. long oggpackB_look(oggpack_buffer *b,int bits){
  107952. unsigned long ret;
  107953. int m=32-bits;
  107954. bits+=b->endbit;
  107955. if(b->endbyte+4>=b->storage){
  107956. /* not the main path */
  107957. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107958. }
  107959. ret=b->ptr[0]<<(24+b->endbit);
  107960. if(bits>8){
  107961. ret|=b->ptr[1]<<(16+b->endbit);
  107962. if(bits>16){
  107963. ret|=b->ptr[2]<<(8+b->endbit);
  107964. if(bits>24){
  107965. ret|=b->ptr[3]<<(b->endbit);
  107966. if(bits>32 && b->endbit)
  107967. ret|=b->ptr[4]>>(8-b->endbit);
  107968. }
  107969. }
  107970. }
  107971. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107972. }
  107973. long oggpack_look1(oggpack_buffer *b){
  107974. if(b->endbyte>=b->storage)return(-1);
  107975. return((b->ptr[0]>>b->endbit)&1);
  107976. }
  107977. long oggpackB_look1(oggpack_buffer *b){
  107978. if(b->endbyte>=b->storage)return(-1);
  107979. return((b->ptr[0]>>(7-b->endbit))&1);
  107980. }
  107981. void oggpack_adv(oggpack_buffer *b,int bits){
  107982. bits+=b->endbit;
  107983. b->ptr+=bits/8;
  107984. b->endbyte+=bits/8;
  107985. b->endbit=bits&7;
  107986. }
  107987. void oggpackB_adv(oggpack_buffer *b,int bits){
  107988. oggpack_adv(b,bits);
  107989. }
  107990. void oggpack_adv1(oggpack_buffer *b){
  107991. if(++(b->endbit)>7){
  107992. b->endbit=0;
  107993. b->ptr++;
  107994. b->endbyte++;
  107995. }
  107996. }
  107997. void oggpackB_adv1(oggpack_buffer *b){
  107998. oggpack_adv1(b);
  107999. }
  108000. /* bits <= 32 */
  108001. long oggpack_read(oggpack_buffer *b,int bits){
  108002. long ret;
  108003. unsigned long m=mask[bits];
  108004. bits+=b->endbit;
  108005. if(b->endbyte+4>=b->storage){
  108006. /* not the main path */
  108007. ret=-1L;
  108008. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108009. }
  108010. ret=b->ptr[0]>>b->endbit;
  108011. if(bits>8){
  108012. ret|=b->ptr[1]<<(8-b->endbit);
  108013. if(bits>16){
  108014. ret|=b->ptr[2]<<(16-b->endbit);
  108015. if(bits>24){
  108016. ret|=b->ptr[3]<<(24-b->endbit);
  108017. if(bits>32 && b->endbit){
  108018. ret|=b->ptr[4]<<(32-b->endbit);
  108019. }
  108020. }
  108021. }
  108022. }
  108023. ret&=m;
  108024. overflow:
  108025. b->ptr+=bits/8;
  108026. b->endbyte+=bits/8;
  108027. b->endbit=bits&7;
  108028. return(ret);
  108029. }
  108030. /* bits <= 32 */
  108031. long oggpackB_read(oggpack_buffer *b,int bits){
  108032. long ret;
  108033. long m=32-bits;
  108034. bits+=b->endbit;
  108035. if(b->endbyte+4>=b->storage){
  108036. /* not the main path */
  108037. ret=-1L;
  108038. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108039. }
  108040. ret=b->ptr[0]<<(24+b->endbit);
  108041. if(bits>8){
  108042. ret|=b->ptr[1]<<(16+b->endbit);
  108043. if(bits>16){
  108044. ret|=b->ptr[2]<<(8+b->endbit);
  108045. if(bits>24){
  108046. ret|=b->ptr[3]<<(b->endbit);
  108047. if(bits>32 && b->endbit)
  108048. ret|=b->ptr[4]>>(8-b->endbit);
  108049. }
  108050. }
  108051. }
  108052. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108053. overflow:
  108054. b->ptr+=bits/8;
  108055. b->endbyte+=bits/8;
  108056. b->endbit=bits&7;
  108057. return(ret);
  108058. }
  108059. long oggpack_read1(oggpack_buffer *b){
  108060. long ret;
  108061. if(b->endbyte>=b->storage){
  108062. /* not the main path */
  108063. ret=-1L;
  108064. goto overflow;
  108065. }
  108066. ret=(b->ptr[0]>>b->endbit)&1;
  108067. overflow:
  108068. b->endbit++;
  108069. if(b->endbit>7){
  108070. b->endbit=0;
  108071. b->ptr++;
  108072. b->endbyte++;
  108073. }
  108074. return(ret);
  108075. }
  108076. long oggpackB_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]>>(7-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 oggpack_bytes(oggpack_buffer *b){
  108094. return(b->endbyte+(b->endbit+7)/8);
  108095. }
  108096. long oggpack_bits(oggpack_buffer *b){
  108097. return(b->endbyte*8+b->endbit);
  108098. }
  108099. long oggpackB_bytes(oggpack_buffer *b){
  108100. return oggpack_bytes(b);
  108101. }
  108102. long oggpackB_bits(oggpack_buffer *b){
  108103. return oggpack_bits(b);
  108104. }
  108105. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108106. return(b->buffer);
  108107. }
  108108. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108109. return oggpack_get_buffer(b);
  108110. }
  108111. /* Self test of the bitwise routines; everything else is based on
  108112. them, so they damned well better be solid. */
  108113. #ifdef _V_SELFTEST
  108114. #include <stdio.h>
  108115. static int ilog(unsigned int v){
  108116. int ret=0;
  108117. while(v){
  108118. ret++;
  108119. v>>=1;
  108120. }
  108121. return(ret);
  108122. }
  108123. oggpack_buffer o;
  108124. oggpack_buffer r;
  108125. void report(char *in){
  108126. fprintf(stderr,"%s",in);
  108127. exit(1);
  108128. }
  108129. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108130. long bytes,i;
  108131. unsigned char *buffer;
  108132. oggpack_reset(&o);
  108133. for(i=0;i<vals;i++)
  108134. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108135. buffer=oggpack_get_buffer(&o);
  108136. bytes=oggpack_bytes(&o);
  108137. if(bytes!=compsize)report("wrong number of bytes!\n");
  108138. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108139. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108140. report("wrote incorrect value!\n");
  108141. }
  108142. oggpack_readinit(&r,buffer,bytes);
  108143. for(i=0;i<vals;i++){
  108144. int tbit=bits?bits:ilog(b[i]);
  108145. if(oggpack_look(&r,tbit)==-1)
  108146. report("out of data!\n");
  108147. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108148. report("looked at incorrect value!\n");
  108149. if(tbit==1)
  108150. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108151. report("looked at single bit incorrect value!\n");
  108152. if(tbit==1){
  108153. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108154. report("read incorrect single bit value!\n");
  108155. }else{
  108156. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108157. report("read incorrect value!\n");
  108158. }
  108159. }
  108160. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108161. }
  108162. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108163. long bytes,i;
  108164. unsigned char *buffer;
  108165. oggpackB_reset(&o);
  108166. for(i=0;i<vals;i++)
  108167. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108168. buffer=oggpackB_get_buffer(&o);
  108169. bytes=oggpackB_bytes(&o);
  108170. if(bytes!=compsize)report("wrong number of bytes!\n");
  108171. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108172. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108173. report("wrote incorrect value!\n");
  108174. }
  108175. oggpackB_readinit(&r,buffer,bytes);
  108176. for(i=0;i<vals;i++){
  108177. int tbit=bits?bits:ilog(b[i]);
  108178. if(oggpackB_look(&r,tbit)==-1)
  108179. report("out of data!\n");
  108180. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108181. report("looked at incorrect value!\n");
  108182. if(tbit==1)
  108183. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108184. report("looked at single bit incorrect value!\n");
  108185. if(tbit==1){
  108186. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108187. report("read incorrect single bit value!\n");
  108188. }else{
  108189. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108190. report("read incorrect value!\n");
  108191. }
  108192. }
  108193. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108194. }
  108195. int main(void){
  108196. unsigned char *buffer;
  108197. long bytes,i;
  108198. static unsigned long testbuffer1[]=
  108199. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108200. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108201. int test1size=43;
  108202. static unsigned long testbuffer2[]=
  108203. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108204. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108205. 85525151,0,12321,1,349528352};
  108206. int test2size=21;
  108207. static unsigned long testbuffer3[]=
  108208. {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,
  108209. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108210. int test3size=56;
  108211. static unsigned long large[]=
  108212. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108213. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108214. 85525151,0,12321,1,2146528352};
  108215. int onesize=33;
  108216. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108217. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108218. 223,4};
  108219. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108220. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108221. 245,251,128};
  108222. int twosize=6;
  108223. static int two[6]={61,255,255,251,231,29};
  108224. static int twoB[6]={247,63,255,253,249,120};
  108225. int threesize=54;
  108226. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108227. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108228. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108229. 100,52,4,14,18,86,77,1};
  108230. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108231. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108232. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108233. 200,20,254,4,58,106,176,144,0};
  108234. int foursize=38;
  108235. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108236. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108237. 28,2,133,0,1};
  108238. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108239. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108240. 129,10,4,32};
  108241. int fivesize=45;
  108242. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108243. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108244. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108245. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108246. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108247. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108248. int sixsize=7;
  108249. static int six[7]={17,177,170,242,169,19,148};
  108250. static int sixB[7]={136,141,85,79,149,200,41};
  108251. /* Test read/write together */
  108252. /* Later we test against pregenerated bitstreams */
  108253. oggpack_writeinit(&o);
  108254. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108255. cliptest(testbuffer1,test1size,0,one,onesize);
  108256. fprintf(stderr,"ok.");
  108257. fprintf(stderr,"\nNull bit call (LSb): ");
  108258. cliptest(testbuffer3,test3size,0,two,twosize);
  108259. fprintf(stderr,"ok.");
  108260. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108261. cliptest(testbuffer2,test2size,0,three,threesize);
  108262. fprintf(stderr,"ok.");
  108263. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108264. oggpack_reset(&o);
  108265. for(i=0;i<test2size;i++)
  108266. oggpack_write(&o,large[i],32);
  108267. buffer=oggpack_get_buffer(&o);
  108268. bytes=oggpack_bytes(&o);
  108269. oggpack_readinit(&r,buffer,bytes);
  108270. for(i=0;i<test2size;i++){
  108271. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108272. if(oggpack_look(&r,32)!=large[i]){
  108273. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108274. oggpack_look(&r,32),large[i]);
  108275. report("read incorrect value!\n");
  108276. }
  108277. oggpack_adv(&r,32);
  108278. }
  108279. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108280. fprintf(stderr,"ok.");
  108281. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108282. cliptest(testbuffer1,test1size,7,four,foursize);
  108283. fprintf(stderr,"ok.");
  108284. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108285. cliptest(testbuffer2,test2size,17,five,fivesize);
  108286. fprintf(stderr,"ok.");
  108287. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108288. cliptest(testbuffer3,test3size,1,six,sixsize);
  108289. fprintf(stderr,"ok.");
  108290. fprintf(stderr,"\nTesting read past end (LSb): ");
  108291. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108292. for(i=0;i<64;i++){
  108293. if(oggpack_read(&r,1)!=0){
  108294. fprintf(stderr,"failed; got -1 prematurely.\n");
  108295. exit(1);
  108296. }
  108297. }
  108298. if(oggpack_look(&r,1)!=-1 ||
  108299. oggpack_read(&r,1)!=-1){
  108300. fprintf(stderr,"failed; read past end without -1.\n");
  108301. exit(1);
  108302. }
  108303. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108304. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108305. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108306. exit(1);
  108307. }
  108308. if(oggpack_look(&r,18)!=0 ||
  108309. oggpack_look(&r,18)!=0){
  108310. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108311. exit(1);
  108312. }
  108313. if(oggpack_look(&r,19)!=-1 ||
  108314. oggpack_look(&r,19)!=-1){
  108315. fprintf(stderr,"failed; read past end without -1.\n");
  108316. exit(1);
  108317. }
  108318. if(oggpack_look(&r,32)!=-1 ||
  108319. oggpack_look(&r,32)!=-1){
  108320. fprintf(stderr,"failed; read past end without -1.\n");
  108321. exit(1);
  108322. }
  108323. oggpack_writeclear(&o);
  108324. fprintf(stderr,"ok.\n");
  108325. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108326. /* Test read/write together */
  108327. /* Later we test against pregenerated bitstreams */
  108328. oggpackB_writeinit(&o);
  108329. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108330. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108331. fprintf(stderr,"ok.");
  108332. fprintf(stderr,"\nNull bit call (MSb): ");
  108333. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108334. fprintf(stderr,"ok.");
  108335. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108336. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108337. fprintf(stderr,"ok.");
  108338. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108339. oggpackB_reset(&o);
  108340. for(i=0;i<test2size;i++)
  108341. oggpackB_write(&o,large[i],32);
  108342. buffer=oggpackB_get_buffer(&o);
  108343. bytes=oggpackB_bytes(&o);
  108344. oggpackB_readinit(&r,buffer,bytes);
  108345. for(i=0;i<test2size;i++){
  108346. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108347. if(oggpackB_look(&r,32)!=large[i]){
  108348. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108349. oggpackB_look(&r,32),large[i]);
  108350. report("read incorrect value!\n");
  108351. }
  108352. oggpackB_adv(&r,32);
  108353. }
  108354. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108355. fprintf(stderr,"ok.");
  108356. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108357. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108358. fprintf(stderr,"ok.");
  108359. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108360. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108361. fprintf(stderr,"ok.");
  108362. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108363. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108364. fprintf(stderr,"ok.");
  108365. fprintf(stderr,"\nTesting read past end (MSb): ");
  108366. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108367. for(i=0;i<64;i++){
  108368. if(oggpackB_read(&r,1)!=0){
  108369. fprintf(stderr,"failed; got -1 prematurely.\n");
  108370. exit(1);
  108371. }
  108372. }
  108373. if(oggpackB_look(&r,1)!=-1 ||
  108374. oggpackB_read(&r,1)!=-1){
  108375. fprintf(stderr,"failed; read past end without -1.\n");
  108376. exit(1);
  108377. }
  108378. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108379. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108380. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108381. exit(1);
  108382. }
  108383. if(oggpackB_look(&r,18)!=0 ||
  108384. oggpackB_look(&r,18)!=0){
  108385. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108386. exit(1);
  108387. }
  108388. if(oggpackB_look(&r,19)!=-1 ||
  108389. oggpackB_look(&r,19)!=-1){
  108390. fprintf(stderr,"failed; read past end without -1.\n");
  108391. exit(1);
  108392. }
  108393. if(oggpackB_look(&r,32)!=-1 ||
  108394. oggpackB_look(&r,32)!=-1){
  108395. fprintf(stderr,"failed; read past end without -1.\n");
  108396. exit(1);
  108397. }
  108398. oggpackB_writeclear(&o);
  108399. fprintf(stderr,"ok.\n\n");
  108400. return(0);
  108401. }
  108402. #endif /* _V_SELFTEST */
  108403. #undef BUFFER_INCREMENT
  108404. #endif
  108405. /*** End of inlined file: bitwise.c ***/
  108406. /*** Start of inlined file: framing.c ***/
  108407. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108408. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108409. // tasks..
  108410. #if JUCE_MSVC
  108411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108412. #endif
  108413. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108414. #if JUCE_USE_OGGVORBIS
  108415. #include <stdlib.h>
  108416. #include <string.h>
  108417. /* A complete description of Ogg framing exists in docs/framing.html */
  108418. int ogg_page_version(ogg_page *og){
  108419. return((int)(og->header[4]));
  108420. }
  108421. int ogg_page_continued(ogg_page *og){
  108422. return((int)(og->header[5]&0x01));
  108423. }
  108424. int ogg_page_bos(ogg_page *og){
  108425. return((int)(og->header[5]&0x02));
  108426. }
  108427. int ogg_page_eos(ogg_page *og){
  108428. return((int)(og->header[5]&0x04));
  108429. }
  108430. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108431. unsigned char *page=og->header;
  108432. ogg_int64_t granulepos=page[13]&(0xff);
  108433. granulepos= (granulepos<<8)|(page[12]&0xff);
  108434. granulepos= (granulepos<<8)|(page[11]&0xff);
  108435. granulepos= (granulepos<<8)|(page[10]&0xff);
  108436. granulepos= (granulepos<<8)|(page[9]&0xff);
  108437. granulepos= (granulepos<<8)|(page[8]&0xff);
  108438. granulepos= (granulepos<<8)|(page[7]&0xff);
  108439. granulepos= (granulepos<<8)|(page[6]&0xff);
  108440. return(granulepos);
  108441. }
  108442. int ogg_page_serialno(ogg_page *og){
  108443. return(og->header[14] |
  108444. (og->header[15]<<8) |
  108445. (og->header[16]<<16) |
  108446. (og->header[17]<<24));
  108447. }
  108448. long ogg_page_pageno(ogg_page *og){
  108449. return(og->header[18] |
  108450. (og->header[19]<<8) |
  108451. (og->header[20]<<16) |
  108452. (og->header[21]<<24));
  108453. }
  108454. /* returns the number of packets that are completed on this page (if
  108455. the leading packet is begun on a previous page, but ends on this
  108456. page, it's counted */
  108457. /* NOTE:
  108458. If a page consists of a packet begun on a previous page, and a new
  108459. packet begun (but not completed) on this page, the return will be:
  108460. ogg_page_packets(page) ==1,
  108461. ogg_page_continued(page) !=0
  108462. If a page happens to be a single packet that was begun on a
  108463. previous page, and spans to the next page (in the case of a three or
  108464. more page packet), the return will be:
  108465. ogg_page_packets(page) ==0,
  108466. ogg_page_continued(page) !=0
  108467. */
  108468. int ogg_page_packets(ogg_page *og){
  108469. int i,n=og->header[26],count=0;
  108470. for(i=0;i<n;i++)
  108471. if(og->header[27+i]<255)count++;
  108472. return(count);
  108473. }
  108474. #if 0
  108475. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108476. use the static init below) */
  108477. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108478. int i;
  108479. unsigned long r;
  108480. r = index << 24;
  108481. for (i=0; i<8; i++)
  108482. if (r & 0x80000000UL)
  108483. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108484. polynomial, although we use an
  108485. unreflected alg and an init/final
  108486. of 0, not 0xffffffff */
  108487. else
  108488. r<<=1;
  108489. return (r & 0xffffffffUL);
  108490. }
  108491. #endif
  108492. static const ogg_uint32_t crc_lookup[256]={
  108493. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108494. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108495. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108496. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108497. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108498. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108499. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108500. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108501. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108502. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108503. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108504. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108505. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108506. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108507. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108508. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108509. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108510. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108511. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108512. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108513. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108514. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108515. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108516. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108517. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108518. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108519. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108520. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108521. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108522. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108523. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108524. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108525. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108526. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108527. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108528. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108529. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108530. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108531. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108532. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108533. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108534. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108535. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108536. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108537. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108538. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108539. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108540. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108541. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108542. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108543. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108544. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108545. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108546. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108547. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108548. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108549. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108550. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108551. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108552. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108553. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108554. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108555. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108556. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108557. /* init the encode/decode logical stream state */
  108558. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108559. if(os){
  108560. memset(os,0,sizeof(*os));
  108561. os->body_storage=16*1024;
  108562. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108563. os->lacing_storage=1024;
  108564. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108565. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108566. os->serialno=serialno;
  108567. return(0);
  108568. }
  108569. return(-1);
  108570. }
  108571. /* _clear does not free os, only the non-flat storage within */
  108572. int ogg_stream_clear(ogg_stream_state *os){
  108573. if(os){
  108574. if(os->body_data)_ogg_free(os->body_data);
  108575. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108576. if(os->granule_vals)_ogg_free(os->granule_vals);
  108577. memset(os,0,sizeof(*os));
  108578. }
  108579. return(0);
  108580. }
  108581. int ogg_stream_destroy(ogg_stream_state *os){
  108582. if(os){
  108583. ogg_stream_clear(os);
  108584. _ogg_free(os);
  108585. }
  108586. return(0);
  108587. }
  108588. /* Helpers for ogg_stream_encode; this keeps the structure and
  108589. what's happening fairly clear */
  108590. static void _os_body_expand(ogg_stream_state *os,int needed){
  108591. if(os->body_storage<=os->body_fill+needed){
  108592. os->body_storage+=(needed+1024);
  108593. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108594. }
  108595. }
  108596. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108597. if(os->lacing_storage<=os->lacing_fill+needed){
  108598. os->lacing_storage+=(needed+32);
  108599. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108600. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108601. }
  108602. }
  108603. /* checksum the page */
  108604. /* Direct table CRC; note that this will be faster in the future if we
  108605. perform the checksum silmultaneously with other copies */
  108606. void ogg_page_checksum_set(ogg_page *og){
  108607. if(og){
  108608. ogg_uint32_t crc_reg=0;
  108609. int i;
  108610. /* safety; needed for API behavior, but not framing code */
  108611. og->header[22]=0;
  108612. og->header[23]=0;
  108613. og->header[24]=0;
  108614. og->header[25]=0;
  108615. for(i=0;i<og->header_len;i++)
  108616. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108617. for(i=0;i<og->body_len;i++)
  108618. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108619. og->header[22]=(unsigned char)(crc_reg&0xff);
  108620. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108621. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108622. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108623. }
  108624. }
  108625. /* submit data to the internal buffer of the framing engine */
  108626. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108627. int lacing_vals=op->bytes/255+1,i;
  108628. if(os->body_returned){
  108629. /* advance packet data according to the body_returned pointer. We
  108630. had to keep it around to return a pointer into the buffer last
  108631. call */
  108632. os->body_fill-=os->body_returned;
  108633. if(os->body_fill)
  108634. memmove(os->body_data,os->body_data+os->body_returned,
  108635. os->body_fill);
  108636. os->body_returned=0;
  108637. }
  108638. /* make sure we have the buffer storage */
  108639. _os_body_expand(os,op->bytes);
  108640. _os_lacing_expand(os,lacing_vals);
  108641. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108642. the liability of overly clean abstraction for the time being. It
  108643. will actually be fairly easy to eliminate the extra copy in the
  108644. future */
  108645. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108646. os->body_fill+=op->bytes;
  108647. /* Store lacing vals for this packet */
  108648. for(i=0;i<lacing_vals-1;i++){
  108649. os->lacing_vals[os->lacing_fill+i]=255;
  108650. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108651. }
  108652. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108653. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108654. /* flag the first segment as the beginning of the packet */
  108655. os->lacing_vals[os->lacing_fill]|= 0x100;
  108656. os->lacing_fill+=lacing_vals;
  108657. /* for the sake of completeness */
  108658. os->packetno++;
  108659. if(op->e_o_s)os->e_o_s=1;
  108660. return(0);
  108661. }
  108662. /* This will flush remaining packets into a page (returning nonzero),
  108663. even if there is not enough data to trigger a flush normally
  108664. (undersized page). If there are no packets or partial packets to
  108665. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108666. try to flush a normal sized page like ogg_stream_pageout; a call to
  108667. ogg_stream_flush does not guarantee that all packets have flushed.
  108668. Only a return value of 0 from ogg_stream_flush indicates all packet
  108669. data is flushed into pages.
  108670. since ogg_stream_flush will flush the last page in a stream even if
  108671. it's undersized, you almost certainly want to use ogg_stream_pageout
  108672. (and *not* ogg_stream_flush) unless you specifically need to flush
  108673. an page regardless of size in the middle of a stream. */
  108674. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108675. int i;
  108676. int vals=0;
  108677. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108678. int bytes=0;
  108679. long acc=0;
  108680. ogg_int64_t granule_pos=-1;
  108681. if(maxvals==0)return(0);
  108682. /* construct a page */
  108683. /* decide how many segments to include */
  108684. /* If this is the initial header case, the first page must only include
  108685. the initial header packet */
  108686. if(os->b_o_s==0){ /* 'initial header page' case */
  108687. granule_pos=0;
  108688. for(vals=0;vals<maxvals;vals++){
  108689. if((os->lacing_vals[vals]&0x0ff)<255){
  108690. vals++;
  108691. break;
  108692. }
  108693. }
  108694. }else{
  108695. for(vals=0;vals<maxvals;vals++){
  108696. if(acc>4096)break;
  108697. acc+=os->lacing_vals[vals]&0x0ff;
  108698. if((os->lacing_vals[vals]&0xff)<255)
  108699. granule_pos=os->granule_vals[vals];
  108700. }
  108701. }
  108702. /* construct the header in temp storage */
  108703. memcpy(os->header,"OggS",4);
  108704. /* stream structure version */
  108705. os->header[4]=0x00;
  108706. /* continued packet flag? */
  108707. os->header[5]=0x00;
  108708. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108709. /* first page flag? */
  108710. if(os->b_o_s==0)os->header[5]|=0x02;
  108711. /* last page flag? */
  108712. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108713. os->b_o_s=1;
  108714. /* 64 bits of PCM position */
  108715. for(i=6;i<14;i++){
  108716. os->header[i]=(unsigned char)(granule_pos&0xff);
  108717. granule_pos>>=8;
  108718. }
  108719. /* 32 bits of stream serial number */
  108720. {
  108721. long serialno=os->serialno;
  108722. for(i=14;i<18;i++){
  108723. os->header[i]=(unsigned char)(serialno&0xff);
  108724. serialno>>=8;
  108725. }
  108726. }
  108727. /* 32 bits of page counter (we have both counter and page header
  108728. because this val can roll over) */
  108729. if(os->pageno==-1)os->pageno=0; /* because someone called
  108730. stream_reset; this would be a
  108731. strange thing to do in an
  108732. encode stream, but it has
  108733. plausible uses */
  108734. {
  108735. long pageno=os->pageno++;
  108736. for(i=18;i<22;i++){
  108737. os->header[i]=(unsigned char)(pageno&0xff);
  108738. pageno>>=8;
  108739. }
  108740. }
  108741. /* zero for computation; filled in later */
  108742. os->header[22]=0;
  108743. os->header[23]=0;
  108744. os->header[24]=0;
  108745. os->header[25]=0;
  108746. /* segment table */
  108747. os->header[26]=(unsigned char)(vals&0xff);
  108748. for(i=0;i<vals;i++)
  108749. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108750. /* set pointers in the ogg_page struct */
  108751. og->header=os->header;
  108752. og->header_len=os->header_fill=vals+27;
  108753. og->body=os->body_data+os->body_returned;
  108754. og->body_len=bytes;
  108755. /* advance the lacing data and set the body_returned pointer */
  108756. os->lacing_fill-=vals;
  108757. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108758. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108759. os->body_returned+=bytes;
  108760. /* calculate the checksum */
  108761. ogg_page_checksum_set(og);
  108762. /* done */
  108763. return(1);
  108764. }
  108765. /* This constructs pages from buffered packet segments. The pointers
  108766. returned are to static buffers; do not free. The returned buffers are
  108767. good only until the next call (using the same ogg_stream_state) */
  108768. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108769. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108770. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108771. os->lacing_fill>=255 || /* 'segment table full' case */
  108772. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108773. return(ogg_stream_flush(os,og));
  108774. }
  108775. /* not enough data to construct a page and not end of stream */
  108776. return(0);
  108777. }
  108778. int ogg_stream_eos(ogg_stream_state *os){
  108779. return os->e_o_s;
  108780. }
  108781. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108782. /* This has two layers to place more of the multi-serialno and paging
  108783. control in the application's hands. First, we expose a data buffer
  108784. using ogg_sync_buffer(). The app either copies into the
  108785. buffer, or passes it directly to read(), etc. We then call
  108786. ogg_sync_wrote() to tell how many bytes we just added.
  108787. Pages are returned (pointers into the buffer in ogg_sync_state)
  108788. by ogg_sync_pageout(). The page is then submitted to
  108789. ogg_stream_pagein() along with the appropriate
  108790. ogg_stream_state* (ie, matching serialno). We then get raw
  108791. packets out calling ogg_stream_packetout() with a
  108792. ogg_stream_state. */
  108793. /* initialize the struct to a known state */
  108794. int ogg_sync_init(ogg_sync_state *oy){
  108795. if(oy){
  108796. memset(oy,0,sizeof(*oy));
  108797. }
  108798. return(0);
  108799. }
  108800. /* clear non-flat storage within */
  108801. int ogg_sync_clear(ogg_sync_state *oy){
  108802. if(oy){
  108803. if(oy->data)_ogg_free(oy->data);
  108804. ogg_sync_init(oy);
  108805. }
  108806. return(0);
  108807. }
  108808. int ogg_sync_destroy(ogg_sync_state *oy){
  108809. if(oy){
  108810. ogg_sync_clear(oy);
  108811. _ogg_free(oy);
  108812. }
  108813. return(0);
  108814. }
  108815. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108816. /* first, clear out any space that has been previously returned */
  108817. if(oy->returned){
  108818. oy->fill-=oy->returned;
  108819. if(oy->fill>0)
  108820. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108821. oy->returned=0;
  108822. }
  108823. if(size>oy->storage-oy->fill){
  108824. /* We need to extend the internal buffer */
  108825. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108826. if(oy->data)
  108827. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108828. else
  108829. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108830. oy->storage=newsize;
  108831. }
  108832. /* expose a segment at least as large as requested at the fill mark */
  108833. return((char *)oy->data+oy->fill);
  108834. }
  108835. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108836. if(oy->fill+bytes>oy->storage)return(-1);
  108837. oy->fill+=bytes;
  108838. return(0);
  108839. }
  108840. /* sync the stream. This is meant to be useful for finding page
  108841. boundaries.
  108842. return values for this:
  108843. -n) skipped n bytes
  108844. 0) page not ready; more data (no bytes skipped)
  108845. n) page synced at current location; page length n bytes
  108846. */
  108847. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108848. unsigned char *page=oy->data+oy->returned;
  108849. unsigned char *next;
  108850. long bytes=oy->fill-oy->returned;
  108851. if(oy->headerbytes==0){
  108852. int headerbytes,i;
  108853. if(bytes<27)return(0); /* not enough for a header */
  108854. /* verify capture pattern */
  108855. if(memcmp(page,"OggS",4))goto sync_fail;
  108856. headerbytes=page[26]+27;
  108857. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108858. /* count up body length in the segment table */
  108859. for(i=0;i<page[26];i++)
  108860. oy->bodybytes+=page[27+i];
  108861. oy->headerbytes=headerbytes;
  108862. }
  108863. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108864. /* The whole test page is buffered. Verify the checksum */
  108865. {
  108866. /* Grab the checksum bytes, set the header field to zero */
  108867. char chksum[4];
  108868. ogg_page log;
  108869. memcpy(chksum,page+22,4);
  108870. memset(page+22,0,4);
  108871. /* set up a temp page struct and recompute the checksum */
  108872. log.header=page;
  108873. log.header_len=oy->headerbytes;
  108874. log.body=page+oy->headerbytes;
  108875. log.body_len=oy->bodybytes;
  108876. ogg_page_checksum_set(&log);
  108877. /* Compare */
  108878. if(memcmp(chksum,page+22,4)){
  108879. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108880. at all) */
  108881. /* replace the computed checksum with the one actually read in */
  108882. memcpy(page+22,chksum,4);
  108883. /* Bad checksum. Lose sync */
  108884. goto sync_fail;
  108885. }
  108886. }
  108887. /* yes, have a whole page all ready to go */
  108888. {
  108889. unsigned char *page=oy->data+oy->returned;
  108890. long bytes;
  108891. if(og){
  108892. og->header=page;
  108893. og->header_len=oy->headerbytes;
  108894. og->body=page+oy->headerbytes;
  108895. og->body_len=oy->bodybytes;
  108896. }
  108897. oy->unsynced=0;
  108898. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108899. oy->headerbytes=0;
  108900. oy->bodybytes=0;
  108901. return(bytes);
  108902. }
  108903. sync_fail:
  108904. oy->headerbytes=0;
  108905. oy->bodybytes=0;
  108906. /* search for possible capture */
  108907. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108908. if(!next)
  108909. next=oy->data+oy->fill;
  108910. oy->returned=next-oy->data;
  108911. return(-(next-page));
  108912. }
  108913. /* sync the stream and get a page. Keep trying until we find a page.
  108914. Supress 'sync errors' after reporting the first.
  108915. return values:
  108916. -1) recapture (hole in data)
  108917. 0) need more data
  108918. 1) page returned
  108919. Returns pointers into buffered data; invalidated by next call to
  108920. _stream, _clear, _init, or _buffer */
  108921. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108922. /* all we need to do is verify a page at the head of the stream
  108923. buffer. If it doesn't verify, we look for the next potential
  108924. frame */
  108925. for(;;){
  108926. long ret=ogg_sync_pageseek(oy,og);
  108927. if(ret>0){
  108928. /* have a page */
  108929. return(1);
  108930. }
  108931. if(ret==0){
  108932. /* need more data */
  108933. return(0);
  108934. }
  108935. /* head did not start a synced page... skipped some bytes */
  108936. if(!oy->unsynced){
  108937. oy->unsynced=1;
  108938. return(-1);
  108939. }
  108940. /* loop. keep looking */
  108941. }
  108942. }
  108943. /* add the incoming page to the stream state; we decompose the page
  108944. into packet segments here as well. */
  108945. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108946. unsigned char *header=og->header;
  108947. unsigned char *body=og->body;
  108948. long bodysize=og->body_len;
  108949. int segptr=0;
  108950. int version=ogg_page_version(og);
  108951. int continued=ogg_page_continued(og);
  108952. int bos=ogg_page_bos(og);
  108953. int eos=ogg_page_eos(og);
  108954. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108955. int serialno=ogg_page_serialno(og);
  108956. long pageno=ogg_page_pageno(og);
  108957. int segments=header[26];
  108958. /* clean up 'returned data' */
  108959. {
  108960. long lr=os->lacing_returned;
  108961. long br=os->body_returned;
  108962. /* body data */
  108963. if(br){
  108964. os->body_fill-=br;
  108965. if(os->body_fill)
  108966. memmove(os->body_data,os->body_data+br,os->body_fill);
  108967. os->body_returned=0;
  108968. }
  108969. if(lr){
  108970. /* segment table */
  108971. if(os->lacing_fill-lr){
  108972. memmove(os->lacing_vals,os->lacing_vals+lr,
  108973. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108974. memmove(os->granule_vals,os->granule_vals+lr,
  108975. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108976. }
  108977. os->lacing_fill-=lr;
  108978. os->lacing_packet-=lr;
  108979. os->lacing_returned=0;
  108980. }
  108981. }
  108982. /* check the serial number */
  108983. if(serialno!=os->serialno)return(-1);
  108984. if(version>0)return(-1);
  108985. _os_lacing_expand(os,segments+1);
  108986. /* are we in sequence? */
  108987. if(pageno!=os->pageno){
  108988. int i;
  108989. /* unroll previous partial packet (if any) */
  108990. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108991. os->body_fill-=os->lacing_vals[i]&0xff;
  108992. os->lacing_fill=os->lacing_packet;
  108993. /* make a note of dropped data in segment table */
  108994. if(os->pageno!=-1){
  108995. os->lacing_vals[os->lacing_fill++]=0x400;
  108996. os->lacing_packet++;
  108997. }
  108998. }
  108999. /* are we a 'continued packet' page? If so, we may need to skip
  109000. some segments */
  109001. if(continued){
  109002. if(os->lacing_fill<1 ||
  109003. os->lacing_vals[os->lacing_fill-1]==0x400){
  109004. bos=0;
  109005. for(;segptr<segments;segptr++){
  109006. int val=header[27+segptr];
  109007. body+=val;
  109008. bodysize-=val;
  109009. if(val<255){
  109010. segptr++;
  109011. break;
  109012. }
  109013. }
  109014. }
  109015. }
  109016. if(bodysize){
  109017. _os_body_expand(os,bodysize);
  109018. memcpy(os->body_data+os->body_fill,body,bodysize);
  109019. os->body_fill+=bodysize;
  109020. }
  109021. {
  109022. int saved=-1;
  109023. while(segptr<segments){
  109024. int val=header[27+segptr];
  109025. os->lacing_vals[os->lacing_fill]=val;
  109026. os->granule_vals[os->lacing_fill]=-1;
  109027. if(bos){
  109028. os->lacing_vals[os->lacing_fill]|=0x100;
  109029. bos=0;
  109030. }
  109031. if(val<255)saved=os->lacing_fill;
  109032. os->lacing_fill++;
  109033. segptr++;
  109034. if(val<255)os->lacing_packet=os->lacing_fill;
  109035. }
  109036. /* set the granulepos on the last granuleval of the last full packet */
  109037. if(saved!=-1){
  109038. os->granule_vals[saved]=granulepos;
  109039. }
  109040. }
  109041. if(eos){
  109042. os->e_o_s=1;
  109043. if(os->lacing_fill>0)
  109044. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109045. }
  109046. os->pageno=pageno+1;
  109047. return(0);
  109048. }
  109049. /* clear things to an initial state. Good to call, eg, before seeking */
  109050. int ogg_sync_reset(ogg_sync_state *oy){
  109051. oy->fill=0;
  109052. oy->returned=0;
  109053. oy->unsynced=0;
  109054. oy->headerbytes=0;
  109055. oy->bodybytes=0;
  109056. return(0);
  109057. }
  109058. int ogg_stream_reset(ogg_stream_state *os){
  109059. os->body_fill=0;
  109060. os->body_returned=0;
  109061. os->lacing_fill=0;
  109062. os->lacing_packet=0;
  109063. os->lacing_returned=0;
  109064. os->header_fill=0;
  109065. os->e_o_s=0;
  109066. os->b_o_s=0;
  109067. os->pageno=-1;
  109068. os->packetno=0;
  109069. os->granulepos=0;
  109070. return(0);
  109071. }
  109072. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109073. ogg_stream_reset(os);
  109074. os->serialno=serialno;
  109075. return(0);
  109076. }
  109077. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109078. /* The last part of decode. We have the stream broken into packet
  109079. segments. Now we need to group them into packets (or return the
  109080. out of sync markers) */
  109081. int ptr=os->lacing_returned;
  109082. if(os->lacing_packet<=ptr)return(0);
  109083. if(os->lacing_vals[ptr]&0x400){
  109084. /* we need to tell the codec there's a gap; it might need to
  109085. handle previous packet dependencies. */
  109086. os->lacing_returned++;
  109087. os->packetno++;
  109088. return(-1);
  109089. }
  109090. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109091. to ask if there's a whole packet
  109092. waiting */
  109093. /* Gather the whole packet. We'll have no holes or a partial packet */
  109094. {
  109095. int size=os->lacing_vals[ptr]&0xff;
  109096. int bytes=size;
  109097. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109098. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109099. while(size==255){
  109100. int val=os->lacing_vals[++ptr];
  109101. size=val&0xff;
  109102. if(val&0x200)eos=0x200;
  109103. bytes+=size;
  109104. }
  109105. if(op){
  109106. op->e_o_s=eos;
  109107. op->b_o_s=bos;
  109108. op->packet=os->body_data+os->body_returned;
  109109. op->packetno=os->packetno;
  109110. op->granulepos=os->granule_vals[ptr];
  109111. op->bytes=bytes;
  109112. }
  109113. if(adv){
  109114. os->body_returned+=bytes;
  109115. os->lacing_returned=ptr+1;
  109116. os->packetno++;
  109117. }
  109118. }
  109119. return(1);
  109120. }
  109121. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109122. return _packetout(os,op,1);
  109123. }
  109124. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109125. return _packetout(os,op,0);
  109126. }
  109127. void ogg_packet_clear(ogg_packet *op) {
  109128. _ogg_free(op->packet);
  109129. memset(op, 0, sizeof(*op));
  109130. }
  109131. #ifdef _V_SELFTEST
  109132. #include <stdio.h>
  109133. ogg_stream_state os_en, os_de;
  109134. ogg_sync_state oy;
  109135. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109136. long j;
  109137. static int sequence=0;
  109138. static int lastno=0;
  109139. if(op->bytes!=len){
  109140. fprintf(stderr,"incorrect packet length!\n");
  109141. exit(1);
  109142. }
  109143. if(op->granulepos!=pos){
  109144. fprintf(stderr,"incorrect packet position!\n");
  109145. exit(1);
  109146. }
  109147. /* packet number just follows sequence/gap; adjust the input number
  109148. for that */
  109149. if(no==0){
  109150. sequence=0;
  109151. }else{
  109152. sequence++;
  109153. if(no>lastno+1)
  109154. sequence++;
  109155. }
  109156. lastno=no;
  109157. if(op->packetno!=sequence){
  109158. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109159. (long)(op->packetno),sequence);
  109160. exit(1);
  109161. }
  109162. /* Test data */
  109163. for(j=0;j<op->bytes;j++)
  109164. if(op->packet[j]!=((j+no)&0xff)){
  109165. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109166. j,op->packet[j],(j+no)&0xff);
  109167. exit(1);
  109168. }
  109169. }
  109170. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109171. long j;
  109172. /* Test data */
  109173. for(j=0;j<og->body_len;j++)
  109174. if(og->body[j]!=data[j]){
  109175. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109176. j,data[j],og->body[j]);
  109177. exit(1);
  109178. }
  109179. /* Test header */
  109180. for(j=0;j<og->header_len;j++){
  109181. if(og->header[j]!=header[j]){
  109182. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109183. for(j=0;j<header[26]+27;j++)
  109184. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109185. fprintf(stderr,"\n");
  109186. exit(1);
  109187. }
  109188. }
  109189. if(og->header_len!=header[26]+27){
  109190. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109191. og->header_len,header[26]+27);
  109192. exit(1);
  109193. }
  109194. }
  109195. void print_header(ogg_page *og){
  109196. int j;
  109197. fprintf(stderr,"\nHEADER:\n");
  109198. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109199. og->header[0],og->header[1],og->header[2],og->header[3],
  109200. (int)og->header[4],(int)og->header[5]);
  109201. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109202. (og->header[9]<<24)|(og->header[8]<<16)|
  109203. (og->header[7]<<8)|og->header[6],
  109204. (og->header[17]<<24)|(og->header[16]<<16)|
  109205. (og->header[15]<<8)|og->header[14],
  109206. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109207. (og->header[19]<<8)|og->header[18]);
  109208. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109209. (int)og->header[22],(int)og->header[23],
  109210. (int)og->header[24],(int)og->header[25],
  109211. (int)og->header[26]);
  109212. for(j=27;j<og->header_len;j++)
  109213. fprintf(stderr,"%d ",(int)og->header[j]);
  109214. fprintf(stderr,")\n\n");
  109215. }
  109216. void copy_page(ogg_page *og){
  109217. unsigned char *temp=_ogg_malloc(og->header_len);
  109218. memcpy(temp,og->header,og->header_len);
  109219. og->header=temp;
  109220. temp=_ogg_malloc(og->body_len);
  109221. memcpy(temp,og->body,og->body_len);
  109222. og->body=temp;
  109223. }
  109224. void free_page(ogg_page *og){
  109225. _ogg_free (og->header);
  109226. _ogg_free (og->body);
  109227. }
  109228. void error(void){
  109229. fprintf(stderr,"error!\n");
  109230. exit(1);
  109231. }
  109232. /* 17 only */
  109233. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109234. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109235. 0x01,0x02,0x03,0x04,0,0,0,0,
  109236. 0x15,0xed,0xec,0x91,
  109237. 1,
  109238. 17};
  109239. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109240. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109241. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109242. 0x01,0x02,0x03,0x04,0,0,0,0,
  109243. 0x59,0x10,0x6c,0x2c,
  109244. 1,
  109245. 17};
  109246. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109247. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109248. 0x01,0x02,0x03,0x04,1,0,0,0,
  109249. 0x89,0x33,0x85,0xce,
  109250. 13,
  109251. 254,255,0,255,1,255,245,255,255,0,
  109252. 255,255,90};
  109253. /* nil packets; beginning,middle,end */
  109254. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109255. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109256. 0x01,0x02,0x03,0x04,0,0,0,0,
  109257. 0xff,0x7b,0x23,0x17,
  109258. 1,
  109259. 0};
  109260. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109261. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109262. 0x01,0x02,0x03,0x04,1,0,0,0,
  109263. 0x5c,0x3f,0x66,0xcb,
  109264. 17,
  109265. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109266. 255,255,90,0};
  109267. /* large initial packet */
  109268. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109269. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109270. 0x01,0x02,0x03,0x04,0,0,0,0,
  109271. 0x01,0x27,0x31,0xaa,
  109272. 18,
  109273. 255,255,255,255,255,255,255,255,
  109274. 255,255,255,255,255,255,255,255,255,10};
  109275. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109276. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109277. 0x01,0x02,0x03,0x04,1,0,0,0,
  109278. 0x7f,0x4e,0x8a,0xd2,
  109279. 4,
  109280. 255,4,255,0};
  109281. /* continuing packet test */
  109282. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109283. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109284. 0x01,0x02,0x03,0x04,0,0,0,0,
  109285. 0xff,0x7b,0x23,0x17,
  109286. 1,
  109287. 0};
  109288. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109289. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109290. 0x01,0x02,0x03,0x04,1,0,0,0,
  109291. 0x54,0x05,0x51,0xc8,
  109292. 17,
  109293. 255,255,255,255,255,255,255,255,
  109294. 255,255,255,255,255,255,255,255,255};
  109295. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109296. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109297. 0x01,0x02,0x03,0x04,2,0,0,0,
  109298. 0xc8,0xc3,0xcb,0xed,
  109299. 5,
  109300. 10,255,4,255,0};
  109301. /* page with the 255 segment limit */
  109302. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109303. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109304. 0x01,0x02,0x03,0x04,0,0,0,0,
  109305. 0xff,0x7b,0x23,0x17,
  109306. 1,
  109307. 0};
  109308. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109309. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109310. 0x01,0x02,0x03,0x04,1,0,0,0,
  109311. 0xed,0x2a,0x2e,0xa7,
  109312. 255,
  109313. 10,10,10,10,10,10,10,10,
  109314. 10,10,10,10,10,10,10,10,
  109315. 10,10,10,10,10,10,10,10,
  109316. 10,10,10,10,10,10,10,10,
  109317. 10,10,10,10,10,10,10,10,
  109318. 10,10,10,10,10,10,10,10,
  109319. 10,10,10,10,10,10,10,10,
  109320. 10,10,10,10,10,10,10,10,
  109321. 10,10,10,10,10,10,10,10,
  109322. 10,10,10,10,10,10,10,10,
  109323. 10,10,10,10,10,10,10,10,
  109324. 10,10,10,10,10,10,10,10,
  109325. 10,10,10,10,10,10,10,10,
  109326. 10,10,10,10,10,10,10,10,
  109327. 10,10,10,10,10,10,10,10,
  109328. 10,10,10,10,10,10,10,10,
  109329. 10,10,10,10,10,10,10,10,
  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};
  109345. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109346. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109347. 0x01,0x02,0x03,0x04,2,0,0,0,
  109348. 0x6c,0x3b,0x82,0x3d,
  109349. 1,
  109350. 50};
  109351. /* packet that overspans over an entire page */
  109352. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109353. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109354. 0x01,0x02,0x03,0x04,0,0,0,0,
  109355. 0xff,0x7b,0x23,0x17,
  109356. 1,
  109357. 0};
  109358. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109359. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109360. 0x01,0x02,0x03,0x04,1,0,0,0,
  109361. 0x3c,0xd9,0x4d,0x3f,
  109362. 17,
  109363. 100,255,255,255,255,255,255,255,255,
  109364. 255,255,255,255,255,255,255,255};
  109365. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109366. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109367. 0x01,0x02,0x03,0x04,2,0,0,0,
  109368. 0x01,0xd2,0xe5,0xe5,
  109369. 17,
  109370. 255,255,255,255,255,255,255,255,
  109371. 255,255,255,255,255,255,255,255,255};
  109372. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109373. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109374. 0x01,0x02,0x03,0x04,3,0,0,0,
  109375. 0xef,0xdd,0x88,0xde,
  109376. 7,
  109377. 255,255,75,255,4,255,0};
  109378. /* packet that overspans over an entire page */
  109379. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109380. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109381. 0x01,0x02,0x03,0x04,0,0,0,0,
  109382. 0xff,0x7b,0x23,0x17,
  109383. 1,
  109384. 0};
  109385. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109386. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109387. 0x01,0x02,0x03,0x04,1,0,0,0,
  109388. 0x3c,0xd9,0x4d,0x3f,
  109389. 17,
  109390. 100,255,255,255,255,255,255,255,255,
  109391. 255,255,255,255,255,255,255,255};
  109392. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109393. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109394. 0x01,0x02,0x03,0x04,2,0,0,0,
  109395. 0xd4,0xe0,0x60,0xe5,
  109396. 1,0};
  109397. void test_pack(const int *pl, const int **headers, int byteskip,
  109398. int pageskip, int packetskip){
  109399. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109400. long inptr=0;
  109401. long outptr=0;
  109402. long deptr=0;
  109403. long depacket=0;
  109404. long granule_pos=7,pageno=0;
  109405. int i,j,packets,pageout=pageskip;
  109406. int eosflag=0;
  109407. int bosflag=0;
  109408. int byteskipcount=0;
  109409. ogg_stream_reset(&os_en);
  109410. ogg_stream_reset(&os_de);
  109411. ogg_sync_reset(&oy);
  109412. for(packets=0;packets<packetskip;packets++)
  109413. depacket+=pl[packets];
  109414. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109415. for(i=0;i<packets;i++){
  109416. /* construct a test packet */
  109417. ogg_packet op;
  109418. int len=pl[i];
  109419. op.packet=data+inptr;
  109420. op.bytes=len;
  109421. op.e_o_s=(pl[i+1]<0?1:0);
  109422. op.granulepos=granule_pos;
  109423. granule_pos+=1024;
  109424. for(j=0;j<len;j++)data[inptr++]=i+j;
  109425. /* submit the test packet */
  109426. ogg_stream_packetin(&os_en,&op);
  109427. /* retrieve any finished pages */
  109428. {
  109429. ogg_page og;
  109430. while(ogg_stream_pageout(&os_en,&og)){
  109431. /* We have a page. Check it carefully */
  109432. fprintf(stderr,"%ld, ",pageno);
  109433. if(headers[pageno]==NULL){
  109434. fprintf(stderr,"coded too many pages!\n");
  109435. exit(1);
  109436. }
  109437. check_page(data+outptr,headers[pageno],&og);
  109438. outptr+=og.body_len;
  109439. pageno++;
  109440. if(pageskip){
  109441. bosflag=1;
  109442. pageskip--;
  109443. deptr+=og.body_len;
  109444. }
  109445. /* have a complete page; submit it to sync/decode */
  109446. {
  109447. ogg_page og_de;
  109448. ogg_packet op_de,op_de2;
  109449. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109450. char *next=buf;
  109451. byteskipcount+=og.header_len;
  109452. if(byteskipcount>byteskip){
  109453. memcpy(next,og.header,byteskipcount-byteskip);
  109454. next+=byteskipcount-byteskip;
  109455. byteskipcount=byteskip;
  109456. }
  109457. byteskipcount+=og.body_len;
  109458. if(byteskipcount>byteskip){
  109459. memcpy(next,og.body,byteskipcount-byteskip);
  109460. next+=byteskipcount-byteskip;
  109461. byteskipcount=byteskip;
  109462. }
  109463. ogg_sync_wrote(&oy,next-buf);
  109464. while(1){
  109465. int ret=ogg_sync_pageout(&oy,&og_de);
  109466. if(ret==0)break;
  109467. if(ret<0)continue;
  109468. /* got a page. Happy happy. Verify that it's good. */
  109469. fprintf(stderr,"(%ld), ",pageout);
  109470. check_page(data+deptr,headers[pageout],&og_de);
  109471. deptr+=og_de.body_len;
  109472. pageout++;
  109473. /* submit it to deconstitution */
  109474. ogg_stream_pagein(&os_de,&og_de);
  109475. /* packets out? */
  109476. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109477. ogg_stream_packetpeek(&os_de,NULL);
  109478. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109479. /* verify peek and out match */
  109480. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109481. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109482. depacket);
  109483. exit(1);
  109484. }
  109485. /* verify the packet! */
  109486. /* check data */
  109487. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109488. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109489. depacket);
  109490. exit(1);
  109491. }
  109492. /* check bos flag */
  109493. if(bosflag==0 && op_de.b_o_s==0){
  109494. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109495. exit(1);
  109496. }
  109497. if(bosflag && op_de.b_o_s){
  109498. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109499. exit(1);
  109500. }
  109501. bosflag=1;
  109502. depacket+=op_de.bytes;
  109503. /* check eos flag */
  109504. if(eosflag){
  109505. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109506. exit(1);
  109507. }
  109508. if(op_de.e_o_s)eosflag=1;
  109509. /* check granulepos flag */
  109510. if(op_de.granulepos!=-1){
  109511. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109512. }
  109513. }
  109514. }
  109515. }
  109516. }
  109517. }
  109518. }
  109519. _ogg_free(data);
  109520. if(headers[pageno]!=NULL){
  109521. fprintf(stderr,"did not write last page!\n");
  109522. exit(1);
  109523. }
  109524. if(headers[pageout]!=NULL){
  109525. fprintf(stderr,"did not decode last page!\n");
  109526. exit(1);
  109527. }
  109528. if(inptr!=outptr){
  109529. fprintf(stderr,"encoded page data incomplete!\n");
  109530. exit(1);
  109531. }
  109532. if(inptr!=deptr){
  109533. fprintf(stderr,"decoded page data incomplete!\n");
  109534. exit(1);
  109535. }
  109536. if(inptr!=depacket){
  109537. fprintf(stderr,"decoded packet data incomplete!\n");
  109538. exit(1);
  109539. }
  109540. if(!eosflag){
  109541. fprintf(stderr,"Never got a packet with EOS set!\n");
  109542. exit(1);
  109543. }
  109544. fprintf(stderr,"ok.\n");
  109545. }
  109546. int main(void){
  109547. ogg_stream_init(&os_en,0x04030201);
  109548. ogg_stream_init(&os_de,0x04030201);
  109549. ogg_sync_init(&oy);
  109550. /* Exercise each code path in the framing code. Also verify that
  109551. the checksums are working. */
  109552. {
  109553. /* 17 only */
  109554. const int packets[]={17, -1};
  109555. const int *headret[]={head1_0,NULL};
  109556. fprintf(stderr,"testing single page encoding... ");
  109557. test_pack(packets,headret,0,0,0);
  109558. }
  109559. {
  109560. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109561. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109562. const int *headret[]={head1_1,head2_1,NULL};
  109563. fprintf(stderr,"testing basic page encoding... ");
  109564. test_pack(packets,headret,0,0,0);
  109565. }
  109566. {
  109567. /* nil packets; beginning,middle,end */
  109568. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109569. const int *headret[]={head1_2,head2_2,NULL};
  109570. fprintf(stderr,"testing basic nil packets... ");
  109571. test_pack(packets,headret,0,0,0);
  109572. }
  109573. {
  109574. /* large initial packet */
  109575. const int packets[]={4345,259,255,-1};
  109576. const int *headret[]={head1_3,head2_3,NULL};
  109577. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109578. test_pack(packets,headret,0,0,0);
  109579. }
  109580. {
  109581. /* continuing packet test */
  109582. const int packets[]={0,4345,259,255,-1};
  109583. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109584. fprintf(stderr,"testing single packet page span... ");
  109585. test_pack(packets,headret,0,0,0);
  109586. }
  109587. /* page with the 255 segment limit */
  109588. {
  109589. const int packets[]={0,10,10,10,10,10,10,10,10,
  109590. 10,10,10,10,10,10,10,10,
  109591. 10,10,10,10,10,10,10,10,
  109592. 10,10,10,10,10,10,10,10,
  109593. 10,10,10,10,10,10,10,10,
  109594. 10,10,10,10,10,10,10,10,
  109595. 10,10,10,10,10,10,10,10,
  109596. 10,10,10,10,10,10,10,10,
  109597. 10,10,10,10,10,10,10,10,
  109598. 10,10,10,10,10,10,10,10,
  109599. 10,10,10,10,10,10,10,10,
  109600. 10,10,10,10,10,10,10,10,
  109601. 10,10,10,10,10,10,10,10,
  109602. 10,10,10,10,10,10,10,10,
  109603. 10,10,10,10,10,10,10,10,
  109604. 10,10,10,10,10,10,10,10,
  109605. 10,10,10,10,10,10,10,10,
  109606. 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,50,-1};
  109621. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109622. fprintf(stderr,"testing max packet segments... ");
  109623. test_pack(packets,headret,0,0,0);
  109624. }
  109625. {
  109626. /* packet that overspans over an entire page */
  109627. const int packets[]={0,100,9000,259,255,-1};
  109628. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109629. fprintf(stderr,"testing very large packets... ");
  109630. test_pack(packets,headret,0,0,0);
  109631. }
  109632. {
  109633. /* test for the libogg 1.1.1 resync in large continuation bug
  109634. found by Josh Coalson) */
  109635. const int packets[]={0,100,9000,259,255,-1};
  109636. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109637. fprintf(stderr,"testing continuation resync in very large packets... ");
  109638. test_pack(packets,headret,100,2,3);
  109639. }
  109640. {
  109641. /* term only page. why not? */
  109642. const int packets[]={0,100,4080,-1};
  109643. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109644. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109645. test_pack(packets,headret,0,0,0);
  109646. }
  109647. {
  109648. /* build a bunch of pages for testing */
  109649. unsigned char *data=_ogg_malloc(1024*1024);
  109650. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109651. int inptr=0,i,j;
  109652. ogg_page og[5];
  109653. ogg_stream_reset(&os_en);
  109654. for(i=0;pl[i]!=-1;i++){
  109655. ogg_packet op;
  109656. int len=pl[i];
  109657. op.packet=data+inptr;
  109658. op.bytes=len;
  109659. op.e_o_s=(pl[i+1]<0?1:0);
  109660. op.granulepos=(i+1)*1000;
  109661. for(j=0;j<len;j++)data[inptr++]=i+j;
  109662. ogg_stream_packetin(&os_en,&op);
  109663. }
  109664. _ogg_free(data);
  109665. /* retrieve finished pages */
  109666. for(i=0;i<5;i++){
  109667. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109668. fprintf(stderr,"Too few pages output building sync tests!\n");
  109669. exit(1);
  109670. }
  109671. copy_page(&og[i]);
  109672. }
  109673. /* Test lost pages on pagein/packetout: no rollback */
  109674. {
  109675. ogg_page temp;
  109676. ogg_packet test;
  109677. fprintf(stderr,"Testing loss of pages... ");
  109678. ogg_sync_reset(&oy);
  109679. ogg_stream_reset(&os_de);
  109680. for(i=0;i<5;i++){
  109681. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109682. og[i].header_len);
  109683. ogg_sync_wrote(&oy,og[i].header_len);
  109684. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109685. ogg_sync_wrote(&oy,og[i].body_len);
  109686. }
  109687. ogg_sync_pageout(&oy,&temp);
  109688. ogg_stream_pagein(&os_de,&temp);
  109689. ogg_sync_pageout(&oy,&temp);
  109690. ogg_stream_pagein(&os_de,&temp);
  109691. ogg_sync_pageout(&oy,&temp);
  109692. /* skip */
  109693. ogg_sync_pageout(&oy,&temp);
  109694. ogg_stream_pagein(&os_de,&temp);
  109695. /* do we get the expected results/packets? */
  109696. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109697. checkpacket(&test,0,0,0);
  109698. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109699. checkpacket(&test,100,1,-1);
  109700. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109701. checkpacket(&test,4079,2,3000);
  109702. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109703. fprintf(stderr,"Error: loss of page did not return error\n");
  109704. exit(1);
  109705. }
  109706. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109707. checkpacket(&test,76,5,-1);
  109708. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109709. checkpacket(&test,34,6,-1);
  109710. fprintf(stderr,"ok.\n");
  109711. }
  109712. /* Test lost pages on pagein/packetout: rollback with continuation */
  109713. {
  109714. ogg_page temp;
  109715. ogg_packet test;
  109716. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109717. ogg_sync_reset(&oy);
  109718. ogg_stream_reset(&os_de);
  109719. for(i=0;i<5;i++){
  109720. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109721. og[i].header_len);
  109722. ogg_sync_wrote(&oy,og[i].header_len);
  109723. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109724. ogg_sync_wrote(&oy,og[i].body_len);
  109725. }
  109726. ogg_sync_pageout(&oy,&temp);
  109727. ogg_stream_pagein(&os_de,&temp);
  109728. ogg_sync_pageout(&oy,&temp);
  109729. ogg_stream_pagein(&os_de,&temp);
  109730. ogg_sync_pageout(&oy,&temp);
  109731. ogg_stream_pagein(&os_de,&temp);
  109732. ogg_sync_pageout(&oy,&temp);
  109733. /* skip */
  109734. ogg_sync_pageout(&oy,&temp);
  109735. ogg_stream_pagein(&os_de,&temp);
  109736. /* do we get the expected results/packets? */
  109737. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109738. checkpacket(&test,0,0,0);
  109739. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109740. checkpacket(&test,100,1,-1);
  109741. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109742. checkpacket(&test,4079,2,3000);
  109743. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109744. checkpacket(&test,2956,3,4000);
  109745. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109746. fprintf(stderr,"Error: loss of page did not return error\n");
  109747. exit(1);
  109748. }
  109749. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109750. checkpacket(&test,300,13,14000);
  109751. fprintf(stderr,"ok.\n");
  109752. }
  109753. /* the rest only test sync */
  109754. {
  109755. ogg_page og_de;
  109756. /* Test fractional page inputs: incomplete capture */
  109757. fprintf(stderr,"Testing sync on partial inputs... ");
  109758. ogg_sync_reset(&oy);
  109759. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109760. 3);
  109761. ogg_sync_wrote(&oy,3);
  109762. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109763. /* Test fractional page inputs: incomplete fixed header */
  109764. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109765. 20);
  109766. ogg_sync_wrote(&oy,20);
  109767. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109768. /* Test fractional page inputs: incomplete header */
  109769. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109770. 5);
  109771. ogg_sync_wrote(&oy,5);
  109772. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109773. /* Test fractional page inputs: incomplete body */
  109774. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109775. og[1].header_len-28);
  109776. ogg_sync_wrote(&oy,og[1].header_len-28);
  109777. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109778. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109779. ogg_sync_wrote(&oy,1000);
  109780. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109781. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109782. og[1].body_len-1000);
  109783. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109784. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109785. fprintf(stderr,"ok.\n");
  109786. }
  109787. /* Test fractional page inputs: page + incomplete capture */
  109788. {
  109789. ogg_page og_de;
  109790. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109791. ogg_sync_reset(&oy);
  109792. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109793. og[1].header_len);
  109794. ogg_sync_wrote(&oy,og[1].header_len);
  109795. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109796. og[1].body_len);
  109797. ogg_sync_wrote(&oy,og[1].body_len);
  109798. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109799. 20);
  109800. ogg_sync_wrote(&oy,20);
  109801. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109802. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109803. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109804. og[1].header_len-20);
  109805. ogg_sync_wrote(&oy,og[1].header_len-20);
  109806. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109807. og[1].body_len);
  109808. ogg_sync_wrote(&oy,og[1].body_len);
  109809. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109810. fprintf(stderr,"ok.\n");
  109811. }
  109812. /* Test recapture: garbage + page */
  109813. {
  109814. ogg_page og_de;
  109815. fprintf(stderr,"Testing search for capture... ");
  109816. ogg_sync_reset(&oy);
  109817. /* 'garbage' */
  109818. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109819. og[1].body_len);
  109820. ogg_sync_wrote(&oy,og[1].body_len);
  109821. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109822. og[1].header_len);
  109823. ogg_sync_wrote(&oy,og[1].header_len);
  109824. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109825. og[1].body_len);
  109826. ogg_sync_wrote(&oy,og[1].body_len);
  109827. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109828. 20);
  109829. ogg_sync_wrote(&oy,20);
  109830. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109831. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109832. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109833. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109834. og[2].header_len-20);
  109835. ogg_sync_wrote(&oy,og[2].header_len-20);
  109836. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109837. og[2].body_len);
  109838. ogg_sync_wrote(&oy,og[2].body_len);
  109839. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109840. fprintf(stderr,"ok.\n");
  109841. }
  109842. /* Test recapture: page + garbage + page */
  109843. {
  109844. ogg_page og_de;
  109845. fprintf(stderr,"Testing recapture... ");
  109846. ogg_sync_reset(&oy);
  109847. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109848. og[1].header_len);
  109849. ogg_sync_wrote(&oy,og[1].header_len);
  109850. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109851. og[1].body_len);
  109852. ogg_sync_wrote(&oy,og[1].body_len);
  109853. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109854. og[2].header_len);
  109855. ogg_sync_wrote(&oy,og[2].header_len);
  109856. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109857. og[2].header_len);
  109858. ogg_sync_wrote(&oy,og[2].header_len);
  109859. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109860. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109861. og[2].body_len-5);
  109862. ogg_sync_wrote(&oy,og[2].body_len-5);
  109863. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109864. og[3].header_len);
  109865. ogg_sync_wrote(&oy,og[3].header_len);
  109866. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109867. og[3].body_len);
  109868. ogg_sync_wrote(&oy,og[3].body_len);
  109869. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109870. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109871. fprintf(stderr,"ok.\n");
  109872. }
  109873. /* Free page data that was previously copied */
  109874. {
  109875. for(i=0;i<5;i++){
  109876. free_page(&og[i]);
  109877. }
  109878. }
  109879. }
  109880. return(0);
  109881. }
  109882. #endif
  109883. #endif
  109884. /*** End of inlined file: framing.c ***/
  109885. /*** Start of inlined file: analysis.c ***/
  109886. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109887. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109888. // tasks..
  109889. #if JUCE_MSVC
  109890. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109891. #endif
  109892. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109893. #if JUCE_USE_OGGVORBIS
  109894. #include <stdio.h>
  109895. #include <string.h>
  109896. #include <math.h>
  109897. /*** Start of inlined file: codec_internal.h ***/
  109898. #ifndef _V_CODECI_H_
  109899. #define _V_CODECI_H_
  109900. /*** Start of inlined file: envelope.h ***/
  109901. #ifndef _V_ENVELOPE_
  109902. #define _V_ENVELOPE_
  109903. /*** Start of inlined file: mdct.h ***/
  109904. #ifndef _OGG_mdct_H_
  109905. #define _OGG_mdct_H_
  109906. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109907. #ifdef MDCT_INTEGERIZED
  109908. #define DATA_TYPE int
  109909. #define REG_TYPE register int
  109910. #define TRIGBITS 14
  109911. #define cPI3_8 6270
  109912. #define cPI2_8 11585
  109913. #define cPI1_8 15137
  109914. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109915. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109916. #define HALVE(x) ((x)>>1)
  109917. #else
  109918. #define DATA_TYPE float
  109919. #define REG_TYPE float
  109920. #define cPI3_8 .38268343236508977175F
  109921. #define cPI2_8 .70710678118654752441F
  109922. #define cPI1_8 .92387953251128675613F
  109923. #define FLOAT_CONV(x) (x)
  109924. #define MULT_NORM(x) (x)
  109925. #define HALVE(x) ((x)*.5f)
  109926. #endif
  109927. typedef struct {
  109928. int n;
  109929. int log2n;
  109930. DATA_TYPE *trig;
  109931. int *bitrev;
  109932. DATA_TYPE scale;
  109933. } mdct_lookup;
  109934. extern void mdct_init(mdct_lookup *lookup,int n);
  109935. extern void mdct_clear(mdct_lookup *l);
  109936. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109937. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109938. #endif
  109939. /*** End of inlined file: mdct.h ***/
  109940. #define VE_PRE 16
  109941. #define VE_WIN 4
  109942. #define VE_POST 2
  109943. #define VE_AMP (VE_PRE+VE_POST-1)
  109944. #define VE_BANDS 7
  109945. #define VE_NEARDC 15
  109946. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109947. #define VE_MAXSTRETCH 12 /* one-third full block */
  109948. typedef struct {
  109949. float ampbuf[VE_AMP];
  109950. int ampptr;
  109951. float nearDC[VE_NEARDC];
  109952. float nearDC_acc;
  109953. float nearDC_partialacc;
  109954. int nearptr;
  109955. } envelope_filter_state;
  109956. typedef struct {
  109957. int begin;
  109958. int end;
  109959. float *window;
  109960. float total;
  109961. } envelope_band;
  109962. typedef struct {
  109963. int ch;
  109964. int winlength;
  109965. int searchstep;
  109966. float minenergy;
  109967. mdct_lookup mdct;
  109968. float *mdct_win;
  109969. envelope_band band[VE_BANDS];
  109970. envelope_filter_state *filter;
  109971. int stretch;
  109972. int *mark;
  109973. long storage;
  109974. long current;
  109975. long curmark;
  109976. long cursor;
  109977. } envelope_lookup;
  109978. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109979. extern void _ve_envelope_clear(envelope_lookup *e);
  109980. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109981. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109982. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109983. #endif
  109984. /*** End of inlined file: envelope.h ***/
  109985. /*** Start of inlined file: codebook.h ***/
  109986. #ifndef _V_CODEBOOK_H_
  109987. #define _V_CODEBOOK_H_
  109988. /* This structure encapsulates huffman and VQ style encoding books; it
  109989. doesn't do anything specific to either.
  109990. valuelist/quantlist are nonNULL (and q_* significant) only if
  109991. there's entry->value mapping to be done.
  109992. If encode-side mapping must be done (and thus the entry needs to be
  109993. hunted), the auxiliary encode pointer will point to a decision
  109994. tree. This is true of both VQ and huffman, but is mostly useful
  109995. with VQ.
  109996. */
  109997. typedef struct static_codebook{
  109998. long dim; /* codebook dimensions (elements per vector) */
  109999. long entries; /* codebook entries */
  110000. long *lengthlist; /* codeword lengths in bits */
  110001. /* mapping ***************************************************************/
  110002. int maptype; /* 0=none
  110003. 1=implicitly populated values from map column
  110004. 2=listed arbitrary values */
  110005. /* The below does a linear, single monotonic sequence mapping. */
  110006. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110007. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110008. int q_quant; /* bits: 0 < quant <= 16 */
  110009. int q_sequencep; /* bitflag */
  110010. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110011. map == 2: list of dim*entries quantized entry vals
  110012. */
  110013. /* encode helpers ********************************************************/
  110014. struct encode_aux_nearestmatch *nearest_tree;
  110015. struct encode_aux_threshmatch *thresh_tree;
  110016. struct encode_aux_pigeonhole *pigeon_tree;
  110017. int allocedp;
  110018. } static_codebook;
  110019. /* this structures an arbitrary trained book to quickly find the
  110020. nearest cell match */
  110021. typedef struct encode_aux_nearestmatch{
  110022. /* pre-calculated partitioning tree */
  110023. long *ptr0;
  110024. long *ptr1;
  110025. long *p; /* decision points (each is an entry) */
  110026. long *q; /* decision points (each is an entry) */
  110027. long aux; /* number of tree entries */
  110028. long alloc;
  110029. } encode_aux_nearestmatch;
  110030. /* assumes a maptype of 1; encode side only, so that's OK */
  110031. typedef struct encode_aux_threshmatch{
  110032. float *quantthresh;
  110033. long *quantmap;
  110034. int quantvals;
  110035. int threshvals;
  110036. } encode_aux_threshmatch;
  110037. typedef struct encode_aux_pigeonhole{
  110038. float min;
  110039. float del;
  110040. int mapentries;
  110041. int quantvals;
  110042. long *pigeonmap;
  110043. long fittotal;
  110044. long *fitlist;
  110045. long *fitmap;
  110046. long *fitlength;
  110047. } encode_aux_pigeonhole;
  110048. typedef struct codebook{
  110049. long dim; /* codebook dimensions (elements per vector) */
  110050. long entries; /* codebook entries */
  110051. long used_entries; /* populated codebook entries */
  110052. const static_codebook *c;
  110053. /* for encode, the below are entry-ordered, fully populated */
  110054. /* for decode, the below are ordered by bitreversed codeword and only
  110055. used entries are populated */
  110056. float *valuelist; /* list of dim*entries actual entry values */
  110057. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110058. int *dec_index; /* only used if sparseness collapsed */
  110059. char *dec_codelengths;
  110060. ogg_uint32_t *dec_firsttable;
  110061. int dec_firsttablen;
  110062. int dec_maxlength;
  110063. } codebook;
  110064. extern void vorbis_staticbook_clear(static_codebook *b);
  110065. extern void vorbis_staticbook_destroy(static_codebook *b);
  110066. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110067. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110068. extern void vorbis_book_clear(codebook *b);
  110069. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110070. extern float *_book_logdist(const static_codebook *b,float *vals);
  110071. extern float _float32_unpack(long val);
  110072. extern long _float32_pack(float val);
  110073. extern int _best(codebook *book, float *a, int step);
  110074. extern int _ilog(unsigned int v);
  110075. extern long _book_maptype1_quantvals(const static_codebook *b);
  110076. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110077. extern long vorbis_book_codeword(codebook *book,int entry);
  110078. extern long vorbis_book_codelen(codebook *book,int entry);
  110079. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110080. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110081. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110082. extern int vorbis_book_errorv(codebook *book, float *a);
  110083. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110084. oggpack_buffer *b);
  110085. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110086. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110087. oggpack_buffer *b,int n);
  110088. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110089. oggpack_buffer *b,int n);
  110090. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110091. oggpack_buffer *b,int n);
  110092. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110093. long off,int ch,
  110094. oggpack_buffer *b,int n);
  110095. #endif
  110096. /*** End of inlined file: codebook.h ***/
  110097. #define BLOCKTYPE_IMPULSE 0
  110098. #define BLOCKTYPE_PADDING 1
  110099. #define BLOCKTYPE_TRANSITION 0
  110100. #define BLOCKTYPE_LONG 1
  110101. #define PACKETBLOBS 15
  110102. typedef struct vorbis_block_internal{
  110103. float **pcmdelay; /* this is a pointer into local storage */
  110104. float ampmax;
  110105. int blocktype;
  110106. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110107. blob [PACKETBLOBS/2] points to
  110108. the oggpack_buffer in the
  110109. main vorbis_block */
  110110. } vorbis_block_internal;
  110111. typedef void vorbis_look_floor;
  110112. typedef void vorbis_look_residue;
  110113. typedef void vorbis_look_transform;
  110114. /* mode ************************************************************/
  110115. typedef struct {
  110116. int blockflag;
  110117. int windowtype;
  110118. int transformtype;
  110119. int mapping;
  110120. } vorbis_info_mode;
  110121. typedef void vorbis_info_floor;
  110122. typedef void vorbis_info_residue;
  110123. typedef void vorbis_info_mapping;
  110124. /*** Start of inlined file: psy.h ***/
  110125. #ifndef _V_PSY_H_
  110126. #define _V_PSY_H_
  110127. /*** Start of inlined file: smallft.h ***/
  110128. #ifndef _V_SMFT_H_
  110129. #define _V_SMFT_H_
  110130. typedef struct {
  110131. int n;
  110132. float *trigcache;
  110133. int *splitcache;
  110134. } drft_lookup;
  110135. extern void drft_forward(drft_lookup *l,float *data);
  110136. extern void drft_backward(drft_lookup *l,float *data);
  110137. extern void drft_init(drft_lookup *l,int n);
  110138. extern void drft_clear(drft_lookup *l);
  110139. #endif
  110140. /*** End of inlined file: smallft.h ***/
  110141. /*** Start of inlined file: backends.h ***/
  110142. /* this is exposed up here because we need it for static modes.
  110143. Lookups for each backend aren't exposed because there's no reason
  110144. to do so */
  110145. #ifndef _vorbis_backend_h_
  110146. #define _vorbis_backend_h_
  110147. /* this would all be simpler/shorter with templates, but.... */
  110148. /* Floor backend generic *****************************************/
  110149. typedef struct{
  110150. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110151. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110152. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110153. void (*free_info) (vorbis_info_floor *);
  110154. void (*free_look) (vorbis_look_floor *);
  110155. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110156. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110157. void *buffer,float *);
  110158. } vorbis_func_floor;
  110159. typedef struct{
  110160. int order;
  110161. long rate;
  110162. long barkmap;
  110163. int ampbits;
  110164. int ampdB;
  110165. int numbooks; /* <= 16 */
  110166. int books[16];
  110167. float lessthan; /* encode-only config setting hacks for libvorbis */
  110168. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110169. } vorbis_info_floor0;
  110170. #define VIF_POSIT 63
  110171. #define VIF_CLASS 16
  110172. #define VIF_PARTS 31
  110173. typedef struct{
  110174. int partitions; /* 0 to 31 */
  110175. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110176. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110177. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110178. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110179. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110180. int mult; /* 1 2 3 or 4 */
  110181. int postlist[VIF_POSIT+2]; /* first two implicit */
  110182. /* encode side analysis parameters */
  110183. float maxover;
  110184. float maxunder;
  110185. float maxerr;
  110186. float twofitweight;
  110187. float twofitatten;
  110188. int n;
  110189. } vorbis_info_floor1;
  110190. /* Residue backend generic *****************************************/
  110191. typedef struct{
  110192. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110193. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110194. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110195. vorbis_info_residue *);
  110196. void (*free_info) (vorbis_info_residue *);
  110197. void (*free_look) (vorbis_look_residue *);
  110198. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110199. float **,int *,int);
  110200. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110201. vorbis_look_residue *,
  110202. float **,float **,int *,int,long **);
  110203. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110204. float **,int *,int);
  110205. } vorbis_func_residue;
  110206. typedef struct vorbis_info_residue0{
  110207. /* block-partitioned VQ coded straight residue */
  110208. long begin;
  110209. long end;
  110210. /* first stage (lossless partitioning) */
  110211. int grouping; /* group n vectors per partition */
  110212. int partitions; /* possible codebooks for a partition */
  110213. int groupbook; /* huffbook for partitioning */
  110214. int secondstages[64]; /* expanded out to pointers in lookup */
  110215. int booklist[256]; /* list of second stage books */
  110216. float classmetric1[64];
  110217. float classmetric2[64];
  110218. } vorbis_info_residue0;
  110219. /* Mapping backend generic *****************************************/
  110220. typedef struct{
  110221. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110222. oggpack_buffer *);
  110223. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110224. void (*free_info) (vorbis_info_mapping *);
  110225. int (*forward) (struct vorbis_block *vb);
  110226. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110227. } vorbis_func_mapping;
  110228. typedef struct vorbis_info_mapping0{
  110229. int submaps; /* <= 16 */
  110230. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110231. int floorsubmap[16]; /* [mux] submap to floors */
  110232. int residuesubmap[16]; /* [mux] submap to residue */
  110233. int coupling_steps;
  110234. int coupling_mag[256];
  110235. int coupling_ang[256];
  110236. } vorbis_info_mapping0;
  110237. #endif
  110238. /*** End of inlined file: backends.h ***/
  110239. #ifndef EHMER_MAX
  110240. #define EHMER_MAX 56
  110241. #endif
  110242. /* psychoacoustic setup ********************************************/
  110243. #define P_BANDS 17 /* 62Hz to 16kHz */
  110244. #define P_LEVELS 8 /* 30dB to 100dB */
  110245. #define P_LEVEL_0 30. /* 30 dB */
  110246. #define P_NOISECURVES 3
  110247. #define NOISE_COMPAND_LEVELS 40
  110248. typedef struct vorbis_info_psy{
  110249. int blockflag;
  110250. float ath_adjatt;
  110251. float ath_maxatt;
  110252. float tone_masteratt[P_NOISECURVES];
  110253. float tone_centerboost;
  110254. float tone_decay;
  110255. float tone_abs_limit;
  110256. float toneatt[P_BANDS];
  110257. int noisemaskp;
  110258. float noisemaxsupp;
  110259. float noisewindowlo;
  110260. float noisewindowhi;
  110261. int noisewindowlomin;
  110262. int noisewindowhimin;
  110263. int noisewindowfixed;
  110264. float noiseoff[P_NOISECURVES][P_BANDS];
  110265. float noisecompand[NOISE_COMPAND_LEVELS];
  110266. float max_curve_dB;
  110267. int normal_channel_p;
  110268. int normal_point_p;
  110269. int normal_start;
  110270. int normal_partition;
  110271. double normal_thresh;
  110272. } vorbis_info_psy;
  110273. typedef struct{
  110274. int eighth_octave_lines;
  110275. /* for block long/short tuning; encode only */
  110276. float preecho_thresh[VE_BANDS];
  110277. float postecho_thresh[VE_BANDS];
  110278. float stretch_penalty;
  110279. float preecho_minenergy;
  110280. float ampmax_att_per_sec;
  110281. /* channel coupling config */
  110282. int coupling_pkHz[PACKETBLOBS];
  110283. int coupling_pointlimit[2][PACKETBLOBS];
  110284. int coupling_prepointamp[PACKETBLOBS];
  110285. int coupling_postpointamp[PACKETBLOBS];
  110286. int sliding_lowpass[2][PACKETBLOBS];
  110287. } vorbis_info_psy_global;
  110288. typedef struct {
  110289. float ampmax;
  110290. int channels;
  110291. vorbis_info_psy_global *gi;
  110292. int coupling_pointlimit[2][P_NOISECURVES];
  110293. } vorbis_look_psy_global;
  110294. typedef struct {
  110295. int n;
  110296. struct vorbis_info_psy *vi;
  110297. float ***tonecurves;
  110298. float **noiseoffset;
  110299. float *ath;
  110300. long *octave; /* in n.ocshift format */
  110301. long *bark;
  110302. long firstoc;
  110303. long shiftoc;
  110304. int eighth_octave_lines; /* power of two, please */
  110305. int total_octave_lines;
  110306. long rate; /* cache it */
  110307. float m_val; /* Masking compensation value */
  110308. } vorbis_look_psy;
  110309. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110310. vorbis_info_psy_global *gi,int n,long rate);
  110311. extern void _vp_psy_clear(vorbis_look_psy *p);
  110312. extern void *_vi_psy_dup(void *source);
  110313. extern void _vi_psy_free(vorbis_info_psy *i);
  110314. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110315. extern void _vp_remove_floor(vorbis_look_psy *p,
  110316. float *mdct,
  110317. int *icodedflr,
  110318. float *residue,
  110319. int sliding_lowpass);
  110320. extern void _vp_noisemask(vorbis_look_psy *p,
  110321. float *logmdct,
  110322. float *logmask);
  110323. extern void _vp_tonemask(vorbis_look_psy *p,
  110324. float *logfft,
  110325. float *logmask,
  110326. float global_specmax,
  110327. float local_specmax);
  110328. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110329. float *noise,
  110330. float *tone,
  110331. int offset_select,
  110332. float *logmask,
  110333. float *mdct,
  110334. float *logmdct);
  110335. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110336. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110337. vorbis_info_psy_global *g,
  110338. vorbis_look_psy *p,
  110339. vorbis_info_mapping0 *vi,
  110340. float **mdct);
  110341. extern void _vp_couple(int blobno,
  110342. vorbis_info_psy_global *g,
  110343. vorbis_look_psy *p,
  110344. vorbis_info_mapping0 *vi,
  110345. float **res,
  110346. float **mag_memo,
  110347. int **mag_sort,
  110348. int **ifloor,
  110349. int *nonzero,
  110350. int sliding_lowpass);
  110351. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110352. float *in,float *out,int *sortedindex);
  110353. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110354. float *magnitudes,int *sortedindex);
  110355. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110356. vorbis_look_psy *p,
  110357. vorbis_info_mapping0 *vi,
  110358. float **mags);
  110359. extern void hf_reduction(vorbis_info_psy_global *g,
  110360. vorbis_look_psy *p,
  110361. vorbis_info_mapping0 *vi,
  110362. float **mdct);
  110363. #endif
  110364. /*** End of inlined file: psy.h ***/
  110365. /*** Start of inlined file: bitrate.h ***/
  110366. #ifndef _V_BITRATE_H_
  110367. #define _V_BITRATE_H_
  110368. /*** Start of inlined file: os.h ***/
  110369. #ifndef _OS_H
  110370. #define _OS_H
  110371. /********************************************************************
  110372. * *
  110373. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110374. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110375. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110376. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110377. * *
  110378. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110379. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110380. * *
  110381. ********************************************************************
  110382. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110383. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110384. ********************************************************************/
  110385. #ifdef HAVE_CONFIG_H
  110386. #include "config.h"
  110387. #endif
  110388. #include <math.h>
  110389. /*** Start of inlined file: misc.h ***/
  110390. #ifndef _V_RANDOM_H_
  110391. #define _V_RANDOM_H_
  110392. extern int analysis_noisy;
  110393. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110394. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110395. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110396. ogg_int64_t off);
  110397. #ifdef DEBUG_MALLOC
  110398. #define _VDBG_GRAPHFILE "malloc.m"
  110399. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110400. extern void _VDBG_free(void *ptr,char *file,long line);
  110401. #ifndef MISC_C
  110402. #undef _ogg_malloc
  110403. #undef _ogg_calloc
  110404. #undef _ogg_realloc
  110405. #undef _ogg_free
  110406. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110407. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110408. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110409. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110410. #endif
  110411. #endif
  110412. #endif
  110413. /*** End of inlined file: misc.h ***/
  110414. #ifndef _V_IFDEFJAIL_H_
  110415. # define _V_IFDEFJAIL_H_
  110416. # ifdef __GNUC__
  110417. # define STIN static __inline__
  110418. # elif _WIN32
  110419. # define STIN static __inline
  110420. # else
  110421. # define STIN static
  110422. # endif
  110423. #ifdef DJGPP
  110424. # define rint(x) (floor((x)+0.5f))
  110425. #endif
  110426. #ifndef M_PI
  110427. # define M_PI (3.1415926536f)
  110428. #endif
  110429. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110430. # include <malloc.h>
  110431. # define rint(x) (floor((x)+0.5f))
  110432. # define NO_FLOAT_MATH_LIB
  110433. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110434. #endif
  110435. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110436. void *_alloca(size_t size);
  110437. # define alloca _alloca
  110438. #endif
  110439. #ifndef FAST_HYPOT
  110440. # define FAST_HYPOT hypot
  110441. #endif
  110442. #endif
  110443. #ifdef HAVE_ALLOCA_H
  110444. # include <alloca.h>
  110445. #endif
  110446. #ifdef USE_MEMORY_H
  110447. # include <memory.h>
  110448. #endif
  110449. #ifndef min
  110450. # define min(x,y) ((x)>(y)?(y):(x))
  110451. #endif
  110452. #ifndef max
  110453. # define max(x,y) ((x)<(y)?(y):(x))
  110454. #endif
  110455. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110456. # define VORBIS_FPU_CONTROL
  110457. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110458. Because of encapsulation constraints (GCC can't see inside the asm
  110459. block and so we end up doing stupid things like a store/load that
  110460. is collectively a noop), we do it this way */
  110461. /* we must set up the fpu before this works!! */
  110462. typedef ogg_int16_t vorbis_fpu_control;
  110463. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110464. ogg_int16_t ret;
  110465. ogg_int16_t temp;
  110466. __asm__ __volatile__("fnstcw %0\n\t"
  110467. "movw %0,%%dx\n\t"
  110468. "orw $62463,%%dx\n\t"
  110469. "movw %%dx,%1\n\t"
  110470. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110471. *fpu=ret;
  110472. }
  110473. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110474. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110475. }
  110476. /* assumes the FPU is in round mode! */
  110477. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110478. we get extra fst/fld to
  110479. truncate precision */
  110480. int i;
  110481. __asm__("fistl %0": "=m"(i) : "t"(f));
  110482. return(i);
  110483. }
  110484. #endif
  110485. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110486. # define VORBIS_FPU_CONTROL
  110487. typedef ogg_int16_t vorbis_fpu_control;
  110488. static __inline int vorbis_ftoi(double f){
  110489. int i;
  110490. __asm{
  110491. fld f
  110492. fistp i
  110493. }
  110494. return i;
  110495. }
  110496. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110497. }
  110498. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110499. }
  110500. #endif
  110501. #ifndef VORBIS_FPU_CONTROL
  110502. typedef int vorbis_fpu_control;
  110503. static int vorbis_ftoi(double f){
  110504. return (int)(f+.5);
  110505. }
  110506. /* We don't have special code for this compiler/arch, so do it the slow way */
  110507. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110508. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110509. #endif
  110510. #endif /* _OS_H */
  110511. /*** End of inlined file: os.h ***/
  110512. /* encode side bitrate tracking */
  110513. typedef struct bitrate_manager_state {
  110514. int managed;
  110515. long avg_reservoir;
  110516. long minmax_reservoir;
  110517. long avg_bitsper;
  110518. long min_bitsper;
  110519. long max_bitsper;
  110520. long short_per_long;
  110521. double avgfloat;
  110522. vorbis_block *vb;
  110523. int choice;
  110524. } bitrate_manager_state;
  110525. typedef struct bitrate_manager_info{
  110526. long avg_rate;
  110527. long min_rate;
  110528. long max_rate;
  110529. long reservoir_bits;
  110530. double reservoir_bias;
  110531. double slew_damp;
  110532. } bitrate_manager_info;
  110533. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110534. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110535. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110536. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110537. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110538. #endif
  110539. /*** End of inlined file: bitrate.h ***/
  110540. static int ilog(unsigned int v){
  110541. int ret=0;
  110542. while(v){
  110543. ret++;
  110544. v>>=1;
  110545. }
  110546. return(ret);
  110547. }
  110548. static int ilog2(unsigned int v){
  110549. int ret=0;
  110550. if(v)--v;
  110551. while(v){
  110552. ret++;
  110553. v>>=1;
  110554. }
  110555. return(ret);
  110556. }
  110557. typedef struct private_state {
  110558. /* local lookup storage */
  110559. envelope_lookup *ve; /* envelope lookup */
  110560. int window[2];
  110561. vorbis_look_transform **transform[2]; /* block, type */
  110562. drft_lookup fft_look[2];
  110563. int modebits;
  110564. vorbis_look_floor **flr;
  110565. vorbis_look_residue **residue;
  110566. vorbis_look_psy *psy;
  110567. vorbis_look_psy_global *psy_g_look;
  110568. /* local storage, only used on the encoding side. This way the
  110569. application does not need to worry about freeing some packets'
  110570. memory and not others'; packet storage is always tracked.
  110571. Cleared next call to a _dsp_ function */
  110572. unsigned char *header;
  110573. unsigned char *header1;
  110574. unsigned char *header2;
  110575. bitrate_manager_state bms;
  110576. ogg_int64_t sample_count;
  110577. } private_state;
  110578. /* codec_setup_info contains all the setup information specific to the
  110579. specific compression/decompression mode in progress (eg,
  110580. psychoacoustic settings, channel setup, options, codebook
  110581. etc).
  110582. *********************************************************************/
  110583. /*** Start of inlined file: highlevel.h ***/
  110584. typedef struct highlevel_byblocktype {
  110585. double tone_mask_setting;
  110586. double tone_peaklimit_setting;
  110587. double noise_bias_setting;
  110588. double noise_compand_setting;
  110589. } highlevel_byblocktype;
  110590. typedef struct highlevel_encode_setup {
  110591. void *setup;
  110592. int set_in_stone;
  110593. double base_setting;
  110594. double long_setting;
  110595. double short_setting;
  110596. double impulse_noisetune;
  110597. int managed;
  110598. long bitrate_min;
  110599. long bitrate_av;
  110600. double bitrate_av_damp;
  110601. long bitrate_max;
  110602. long bitrate_reservoir;
  110603. double bitrate_reservoir_bias;
  110604. int impulse_block_p;
  110605. int noise_normalize_p;
  110606. double stereo_point_setting;
  110607. double lowpass_kHz;
  110608. double ath_floating_dB;
  110609. double ath_absolute_dB;
  110610. double amplitude_track_dBpersec;
  110611. double trigger_setting;
  110612. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110613. } highlevel_encode_setup;
  110614. /*** End of inlined file: highlevel.h ***/
  110615. typedef struct codec_setup_info {
  110616. /* Vorbis supports only short and long blocks, but allows the
  110617. encoder to choose the sizes */
  110618. long blocksizes[2];
  110619. /* modes are the primary means of supporting on-the-fly different
  110620. blocksizes, different channel mappings (LR or M/A),
  110621. different residue backends, etc. Each mode consists of a
  110622. blocksize flag and a mapping (along with the mapping setup */
  110623. int modes;
  110624. int maps;
  110625. int floors;
  110626. int residues;
  110627. int books;
  110628. int psys; /* encode only */
  110629. vorbis_info_mode *mode_param[64];
  110630. int map_type[64];
  110631. vorbis_info_mapping *map_param[64];
  110632. int floor_type[64];
  110633. vorbis_info_floor *floor_param[64];
  110634. int residue_type[64];
  110635. vorbis_info_residue *residue_param[64];
  110636. static_codebook *book_param[256];
  110637. codebook *fullbooks;
  110638. vorbis_info_psy *psy_param[4]; /* encode only */
  110639. vorbis_info_psy_global psy_g_param;
  110640. bitrate_manager_info bi;
  110641. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110642. highly redundant structure, but
  110643. improves clarity of program flow. */
  110644. int halfrate_flag; /* painless downsample for decode */
  110645. } codec_setup_info;
  110646. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110647. extern void _vp_global_free(vorbis_look_psy_global *look);
  110648. #endif
  110649. /*** End of inlined file: codec_internal.h ***/
  110650. /*** Start of inlined file: registry.h ***/
  110651. #ifndef _V_REG_H_
  110652. #define _V_REG_H_
  110653. #define VI_TRANSFORMB 1
  110654. #define VI_WINDOWB 1
  110655. #define VI_TIMEB 1
  110656. #define VI_FLOORB 2
  110657. #define VI_RESB 3
  110658. #define VI_MAPB 1
  110659. extern vorbis_func_floor *_floor_P[];
  110660. extern vorbis_func_residue *_residue_P[];
  110661. extern vorbis_func_mapping *_mapping_P[];
  110662. #endif
  110663. /*** End of inlined file: registry.h ***/
  110664. /*** Start of inlined file: scales.h ***/
  110665. #ifndef _V_SCALES_H_
  110666. #define _V_SCALES_H_
  110667. #include <math.h>
  110668. /* 20log10(x) */
  110669. #define VORBIS_IEEE_FLOAT32 1
  110670. #ifdef VORBIS_IEEE_FLOAT32
  110671. static float unitnorm(float x){
  110672. union {
  110673. ogg_uint32_t i;
  110674. float f;
  110675. } ix;
  110676. ix.f = x;
  110677. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110678. return ix.f;
  110679. }
  110680. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110681. static float todB(const float *x){
  110682. union {
  110683. ogg_uint32_t i;
  110684. float f;
  110685. } ix;
  110686. ix.f = *x;
  110687. ix.i = ix.i&0x7fffffff;
  110688. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110689. }
  110690. #define todB_nn(x) todB(x)
  110691. #else
  110692. static float unitnorm(float x){
  110693. if(x<0)return(-1.f);
  110694. return(1.f);
  110695. }
  110696. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110697. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110698. #endif
  110699. #define fromdB(x) (exp((x)*.11512925f))
  110700. /* The bark scale equations are approximations, since the original
  110701. table was somewhat hand rolled. The below are chosen to have the
  110702. best possible fit to the rolled tables, thus their somewhat odd
  110703. appearance (these are more accurate and over a longer range than
  110704. the oft-quoted bark equations found in the texts I have). The
  110705. approximations are valid from 0 - 30kHz (nyquist) or so.
  110706. all f in Hz, z in Bark */
  110707. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110708. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110709. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110710. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110711. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110712. 0.0 */
  110713. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110714. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110715. #endif
  110716. /*** End of inlined file: scales.h ***/
  110717. int analysis_noisy=1;
  110718. /* decides between modes, dispatches to the appropriate mapping. */
  110719. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110720. int ret,i;
  110721. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110722. vb->glue_bits=0;
  110723. vb->time_bits=0;
  110724. vb->floor_bits=0;
  110725. vb->res_bits=0;
  110726. /* first things first. Make sure encode is ready */
  110727. for(i=0;i<PACKETBLOBS;i++)
  110728. oggpack_reset(vbi->packetblob[i]);
  110729. /* we only have one mapping type (0), and we let the mapping code
  110730. itself figure out what soft mode to use. This allows easier
  110731. bitrate management */
  110732. if((ret=_mapping_P[0]->forward(vb)))
  110733. return(ret);
  110734. if(op){
  110735. if(vorbis_bitrate_managed(vb))
  110736. /* The app is using a bitmanaged mode... but not using the
  110737. bitrate management interface. */
  110738. return(OV_EINVAL);
  110739. op->packet=oggpack_get_buffer(&vb->opb);
  110740. op->bytes=oggpack_bytes(&vb->opb);
  110741. op->b_o_s=0;
  110742. op->e_o_s=vb->eofflag;
  110743. op->granulepos=vb->granulepos;
  110744. op->packetno=vb->sequence; /* for sake of completeness */
  110745. }
  110746. return(0);
  110747. }
  110748. /* there was no great place to put this.... */
  110749. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110750. int j;
  110751. FILE *of;
  110752. char buffer[80];
  110753. /* if(i==5870){*/
  110754. sprintf(buffer,"%s_%d.m",base,i);
  110755. of=fopen(buffer,"w");
  110756. if(!of)perror("failed to open data dump file");
  110757. for(j=0;j<n;j++){
  110758. if(bark){
  110759. float b=toBARK((4000.f*j/n)+.25);
  110760. fprintf(of,"%f ",b);
  110761. }else
  110762. if(off!=0)
  110763. fprintf(of,"%f ",(double)(j+off)/8000.);
  110764. else
  110765. fprintf(of,"%f ",(double)j);
  110766. if(dB){
  110767. float val;
  110768. if(v[j]==0.)
  110769. val=-140.;
  110770. else
  110771. val=todB(v+j);
  110772. fprintf(of,"%f\n",val);
  110773. }else{
  110774. fprintf(of,"%f\n",v[j]);
  110775. }
  110776. }
  110777. fclose(of);
  110778. /* } */
  110779. }
  110780. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110781. ogg_int64_t off){
  110782. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110783. }
  110784. #endif
  110785. /*** End of inlined file: analysis.c ***/
  110786. /*** Start of inlined file: bitrate.c ***/
  110787. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110788. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110789. // tasks..
  110790. #if JUCE_MSVC
  110791. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110792. #endif
  110793. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110794. #if JUCE_USE_OGGVORBIS
  110795. #include <stdlib.h>
  110796. #include <string.h>
  110797. #include <math.h>
  110798. /* compute bitrate tracking setup */
  110799. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110800. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110801. bitrate_manager_info *bi=&ci->bi;
  110802. memset(bm,0,sizeof(*bm));
  110803. if(bi && (bi->reservoir_bits>0)){
  110804. long ratesamples=vi->rate;
  110805. int halfsamples=ci->blocksizes[0]>>1;
  110806. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110807. bm->managed=1;
  110808. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110809. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110810. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110811. bm->avgfloat=PACKETBLOBS/2;
  110812. /* not a necessary fix, but one that leads to a more balanced
  110813. typical initialization */
  110814. {
  110815. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110816. bm->minmax_reservoir=desired_fill;
  110817. bm->avg_reservoir=desired_fill;
  110818. }
  110819. }
  110820. }
  110821. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110822. memset(bm,0,sizeof(*bm));
  110823. return;
  110824. }
  110825. int vorbis_bitrate_managed(vorbis_block *vb){
  110826. vorbis_dsp_state *vd=vb->vd;
  110827. private_state *b=(private_state*)vd->backend_state;
  110828. bitrate_manager_state *bm=&b->bms;
  110829. if(bm && bm->managed)return(1);
  110830. return(0);
  110831. }
  110832. /* finish taking in the block we just processed */
  110833. int vorbis_bitrate_addblock(vorbis_block *vb){
  110834. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110835. vorbis_dsp_state *vd=vb->vd;
  110836. private_state *b=(private_state*)vd->backend_state;
  110837. bitrate_manager_state *bm=&b->bms;
  110838. vorbis_info *vi=vd->vi;
  110839. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110840. bitrate_manager_info *bi=&ci->bi;
  110841. int choice=rint(bm->avgfloat);
  110842. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110843. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110844. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110845. int samples=ci->blocksizes[vb->W]>>1;
  110846. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110847. if(!bm->managed){
  110848. /* not a bitrate managed stream, but for API simplicity, we'll
  110849. buffer the packet to keep the code path clean */
  110850. if(bm->vb)return(-1); /* one has been submitted without
  110851. being claimed */
  110852. bm->vb=vb;
  110853. return(0);
  110854. }
  110855. bm->vb=vb;
  110856. /* look ahead for avg floater */
  110857. if(bm->avg_bitsper>0){
  110858. double slew=0.;
  110859. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110860. double slewlimit= 15./bi->slew_damp;
  110861. /* choosing a new floater:
  110862. if we're over target, we slew down
  110863. if we're under target, we slew up
  110864. choose slew as follows: look through packetblobs of this frame
  110865. and set slew as the first in the appropriate direction that
  110866. gives us the slew we want. This may mean no slew if delta is
  110867. already favorable.
  110868. Then limit slew to slew max */
  110869. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110870. while(choice>0 && this_bits>avg_target_bits &&
  110871. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110872. choice--;
  110873. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110874. }
  110875. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110876. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110877. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110878. choice++;
  110879. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110880. }
  110881. }
  110882. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110883. if(slew<-slewlimit)slew=-slewlimit;
  110884. if(slew>slewlimit)slew=slewlimit;
  110885. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110886. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110887. }
  110888. /* enforce min(if used) on the current floater (if used) */
  110889. if(bm->min_bitsper>0){
  110890. /* do we need to force the bitrate up? */
  110891. if(this_bits<min_target_bits){
  110892. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110893. choice++;
  110894. if(choice>=PACKETBLOBS)break;
  110895. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110896. }
  110897. }
  110898. }
  110899. /* enforce max (if used) on the current floater (if used) */
  110900. if(bm->max_bitsper>0){
  110901. /* do we need to force the bitrate down? */
  110902. if(this_bits>max_target_bits){
  110903. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110904. choice--;
  110905. if(choice<0)break;
  110906. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110907. }
  110908. }
  110909. }
  110910. /* Choice of packetblobs now made based on floater, and min/max
  110911. requirements. Now boundary check extreme choices */
  110912. if(choice<0){
  110913. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110914. frame will need to be truncated */
  110915. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110916. bm->choice=choice=0;
  110917. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110918. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110919. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110920. }
  110921. }else{
  110922. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110923. if(choice>=PACKETBLOBS)
  110924. choice=PACKETBLOBS-1;
  110925. bm->choice=choice;
  110926. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110927. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110928. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110929. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110930. }
  110931. /* now we have the final packet and the final packet size. Update statistics */
  110932. /* min and max reservoir */
  110933. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110934. if(max_target_bits>0 && this_bits>max_target_bits){
  110935. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110936. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110937. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110938. }else{
  110939. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110940. if(bm->minmax_reservoir>desired_fill){
  110941. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110942. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110943. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110944. }else{
  110945. bm->minmax_reservoir=desired_fill;
  110946. }
  110947. }else{
  110948. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110949. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110950. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110951. }else{
  110952. bm->minmax_reservoir=desired_fill;
  110953. }
  110954. }
  110955. }
  110956. }
  110957. /* avg reservoir */
  110958. if(bm->avg_bitsper>0){
  110959. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110960. bm->avg_reservoir+=this_bits-avg_target_bits;
  110961. }
  110962. return(0);
  110963. }
  110964. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110965. private_state *b=(private_state*)vd->backend_state;
  110966. bitrate_manager_state *bm=&b->bms;
  110967. vorbis_block *vb=bm->vb;
  110968. int choice=PACKETBLOBS/2;
  110969. if(!vb)return 0;
  110970. if(op){
  110971. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110972. if(vorbis_bitrate_managed(vb))
  110973. choice=bm->choice;
  110974. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110975. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110976. op->b_o_s=0;
  110977. op->e_o_s=vb->eofflag;
  110978. op->granulepos=vb->granulepos;
  110979. op->packetno=vb->sequence; /* for sake of completeness */
  110980. }
  110981. bm->vb=0;
  110982. return(1);
  110983. }
  110984. #endif
  110985. /*** End of inlined file: bitrate.c ***/
  110986. /*** Start of inlined file: block.c ***/
  110987. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110988. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110989. // tasks..
  110990. #if JUCE_MSVC
  110991. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110992. #endif
  110993. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110994. #if JUCE_USE_OGGVORBIS
  110995. #include <stdio.h>
  110996. #include <stdlib.h>
  110997. #include <string.h>
  110998. /*** Start of inlined file: window.h ***/
  110999. #ifndef _V_WINDOW_
  111000. #define _V_WINDOW_
  111001. extern float *_vorbis_window_get(int n);
  111002. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111003. int lW,int W,int nW);
  111004. #endif
  111005. /*** End of inlined file: window.h ***/
  111006. /*** Start of inlined file: lpc.h ***/
  111007. #ifndef _V_LPC_H_
  111008. #define _V_LPC_H_
  111009. /* simple linear scale LPC code */
  111010. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111011. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111012. float *data,long n);
  111013. #endif
  111014. /*** End of inlined file: lpc.h ***/
  111015. /* pcm accumulator examples (not exhaustive):
  111016. <-------------- lW ---------------->
  111017. <--------------- W ---------------->
  111018. : .....|..... _______________ |
  111019. : .''' | '''_--- | |\ |
  111020. :.....''' |_____--- '''......| | \_______|
  111021. :.................|__________________|_______|__|______|
  111022. |<------ Sl ------>| > Sr < |endW
  111023. |beginSl |endSl | |endSr
  111024. |beginW |endlW |beginSr
  111025. |< lW >|
  111026. <--------------- W ---------------->
  111027. | | .. ______________ |
  111028. | | ' `/ | ---_ |
  111029. |___.'___/`. | ---_____|
  111030. |_______|__|_______|_________________|
  111031. | >|Sl|< |<------ Sr ----->|endW
  111032. | | |endSl |beginSr |endSr
  111033. |beginW | |endlW
  111034. mult[0] |beginSl mult[n]
  111035. <-------------- lW ----------------->
  111036. |<--W-->|
  111037. : .............. ___ | |
  111038. : .''' |`/ \ | |
  111039. :.....''' |/`....\|...|
  111040. :.........................|___|___|___|
  111041. |Sl |Sr |endW
  111042. | | |endSr
  111043. | |beginSr
  111044. | |endSl
  111045. |beginSl
  111046. |beginW
  111047. */
  111048. /* block abstraction setup *********************************************/
  111049. #ifndef WORD_ALIGN
  111050. #define WORD_ALIGN 8
  111051. #endif
  111052. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111053. int i;
  111054. memset(vb,0,sizeof(*vb));
  111055. vb->vd=v;
  111056. vb->localalloc=0;
  111057. vb->localstore=NULL;
  111058. if(v->analysisp){
  111059. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111060. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111061. vbi->ampmax=-9999;
  111062. for(i=0;i<PACKETBLOBS;i++){
  111063. if(i==PACKETBLOBS/2){
  111064. vbi->packetblob[i]=&vb->opb;
  111065. }else{
  111066. vbi->packetblob[i]=
  111067. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111068. }
  111069. oggpack_writeinit(vbi->packetblob[i]);
  111070. }
  111071. }
  111072. return(0);
  111073. }
  111074. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111075. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111076. if(bytes+vb->localtop>vb->localalloc){
  111077. /* can't just _ogg_realloc... there are outstanding pointers */
  111078. if(vb->localstore){
  111079. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111080. vb->totaluse+=vb->localtop;
  111081. link->next=vb->reap;
  111082. link->ptr=vb->localstore;
  111083. vb->reap=link;
  111084. }
  111085. /* highly conservative */
  111086. vb->localalloc=bytes;
  111087. vb->localstore=_ogg_malloc(vb->localalloc);
  111088. vb->localtop=0;
  111089. }
  111090. {
  111091. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111092. vb->localtop+=bytes;
  111093. return ret;
  111094. }
  111095. }
  111096. /* reap the chain, pull the ripcord */
  111097. void _vorbis_block_ripcord(vorbis_block *vb){
  111098. /* reap the chain */
  111099. struct alloc_chain *reap=vb->reap;
  111100. while(reap){
  111101. struct alloc_chain *next=reap->next;
  111102. _ogg_free(reap->ptr);
  111103. memset(reap,0,sizeof(*reap));
  111104. _ogg_free(reap);
  111105. reap=next;
  111106. }
  111107. /* consolidate storage */
  111108. if(vb->totaluse){
  111109. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111110. vb->localalloc+=vb->totaluse;
  111111. vb->totaluse=0;
  111112. }
  111113. /* pull the ripcord */
  111114. vb->localtop=0;
  111115. vb->reap=NULL;
  111116. }
  111117. int vorbis_block_clear(vorbis_block *vb){
  111118. int i;
  111119. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111120. _vorbis_block_ripcord(vb);
  111121. if(vb->localstore)_ogg_free(vb->localstore);
  111122. if(vbi){
  111123. for(i=0;i<PACKETBLOBS;i++){
  111124. oggpack_writeclear(vbi->packetblob[i]);
  111125. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111126. }
  111127. _ogg_free(vbi);
  111128. }
  111129. memset(vb,0,sizeof(*vb));
  111130. return(0);
  111131. }
  111132. /* Analysis side code, but directly related to blocking. Thus it's
  111133. here and not in analysis.c (which is for analysis transforms only).
  111134. The init is here because some of it is shared */
  111135. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111136. int i;
  111137. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111138. private_state *b=NULL;
  111139. int hs;
  111140. if(ci==NULL) return 1;
  111141. hs=ci->halfrate_flag;
  111142. memset(v,0,sizeof(*v));
  111143. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111144. v->vi=vi;
  111145. b->modebits=ilog2(ci->modes);
  111146. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111147. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111148. /* MDCT is tranform 0 */
  111149. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111150. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111151. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111152. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111153. /* Vorbis I uses only window type 0 */
  111154. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111155. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111156. if(encp){ /* encode/decode differ here */
  111157. /* analysis always needs an fft */
  111158. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111159. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111160. /* finish the codebooks */
  111161. if(!ci->fullbooks){
  111162. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111163. for(i=0;i<ci->books;i++)
  111164. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111165. }
  111166. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111167. for(i=0;i<ci->psys;i++){
  111168. _vp_psy_init(b->psy+i,
  111169. ci->psy_param[i],
  111170. &ci->psy_g_param,
  111171. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111172. vi->rate);
  111173. }
  111174. v->analysisp=1;
  111175. }else{
  111176. /* finish the codebooks */
  111177. if(!ci->fullbooks){
  111178. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111179. for(i=0;i<ci->books;i++){
  111180. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111181. /* decode codebooks are now standalone after init */
  111182. vorbis_staticbook_destroy(ci->book_param[i]);
  111183. ci->book_param[i]=NULL;
  111184. }
  111185. }
  111186. }
  111187. /* initialize the storage vectors. blocksize[1] is small for encode,
  111188. but the correct size for decode */
  111189. v->pcm_storage=ci->blocksizes[1];
  111190. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111191. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111192. {
  111193. int i;
  111194. for(i=0;i<vi->channels;i++)
  111195. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111196. }
  111197. /* all 1 (large block) or 0 (small block) */
  111198. /* explicitly set for the sake of clarity */
  111199. v->lW=0; /* previous window size */
  111200. v->W=0; /* current window size */
  111201. /* all vector indexes */
  111202. v->centerW=ci->blocksizes[1]/2;
  111203. v->pcm_current=v->centerW;
  111204. /* initialize all the backend lookups */
  111205. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111206. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111207. for(i=0;i<ci->floors;i++)
  111208. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111209. look(v,ci->floor_param[i]);
  111210. for(i=0;i<ci->residues;i++)
  111211. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111212. look(v,ci->residue_param[i]);
  111213. return 0;
  111214. }
  111215. /* arbitrary settings and spec-mandated numbers get filled in here */
  111216. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111217. private_state *b=NULL;
  111218. if(_vds_shared_init(v,vi,1))return 1;
  111219. b=(private_state*)v->backend_state;
  111220. b->psy_g_look=_vp_global_look(vi);
  111221. /* Initialize the envelope state storage */
  111222. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111223. _ve_envelope_init(b->ve,vi);
  111224. vorbis_bitrate_init(vi,&b->bms);
  111225. /* compressed audio packets start after the headers
  111226. with sequence number 3 */
  111227. v->sequence=3;
  111228. return(0);
  111229. }
  111230. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111231. int i;
  111232. if(v){
  111233. vorbis_info *vi=v->vi;
  111234. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111235. private_state *b=(private_state*)v->backend_state;
  111236. if(b){
  111237. if(b->ve){
  111238. _ve_envelope_clear(b->ve);
  111239. _ogg_free(b->ve);
  111240. }
  111241. if(b->transform[0]){
  111242. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111243. _ogg_free(b->transform[0][0]);
  111244. _ogg_free(b->transform[0]);
  111245. }
  111246. if(b->transform[1]){
  111247. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111248. _ogg_free(b->transform[1][0]);
  111249. _ogg_free(b->transform[1]);
  111250. }
  111251. if(b->flr){
  111252. for(i=0;i<ci->floors;i++)
  111253. _floor_P[ci->floor_type[i]]->
  111254. free_look(b->flr[i]);
  111255. _ogg_free(b->flr);
  111256. }
  111257. if(b->residue){
  111258. for(i=0;i<ci->residues;i++)
  111259. _residue_P[ci->residue_type[i]]->
  111260. free_look(b->residue[i]);
  111261. _ogg_free(b->residue);
  111262. }
  111263. if(b->psy){
  111264. for(i=0;i<ci->psys;i++)
  111265. _vp_psy_clear(b->psy+i);
  111266. _ogg_free(b->psy);
  111267. }
  111268. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111269. vorbis_bitrate_clear(&b->bms);
  111270. drft_clear(&b->fft_look[0]);
  111271. drft_clear(&b->fft_look[1]);
  111272. }
  111273. if(v->pcm){
  111274. for(i=0;i<vi->channels;i++)
  111275. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111276. _ogg_free(v->pcm);
  111277. if(v->pcmret)_ogg_free(v->pcmret);
  111278. }
  111279. if(b){
  111280. /* free header, header1, header2 */
  111281. if(b->header)_ogg_free(b->header);
  111282. if(b->header1)_ogg_free(b->header1);
  111283. if(b->header2)_ogg_free(b->header2);
  111284. _ogg_free(b);
  111285. }
  111286. memset(v,0,sizeof(*v));
  111287. }
  111288. }
  111289. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111290. int i;
  111291. vorbis_info *vi=v->vi;
  111292. private_state *b=(private_state*)v->backend_state;
  111293. /* free header, header1, header2 */
  111294. if(b->header)_ogg_free(b->header);b->header=NULL;
  111295. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111296. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111297. /* Do we have enough storage space for the requested buffer? If not,
  111298. expand the PCM (and envelope) storage */
  111299. if(v->pcm_current+vals>=v->pcm_storage){
  111300. v->pcm_storage=v->pcm_current+vals*2;
  111301. for(i=0;i<vi->channels;i++){
  111302. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111303. }
  111304. }
  111305. for(i=0;i<vi->channels;i++)
  111306. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111307. return(v->pcmret);
  111308. }
  111309. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111310. int i;
  111311. int order=32;
  111312. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111313. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111314. long j;
  111315. v->preextrapolate=1;
  111316. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111317. for(i=0;i<v->vi->channels;i++){
  111318. /* need to run the extrapolation in reverse! */
  111319. for(j=0;j<v->pcm_current;j++)
  111320. work[j]=v->pcm[i][v->pcm_current-j-1];
  111321. /* prime as above */
  111322. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111323. /* run the predictor filter */
  111324. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111325. order,
  111326. work+v->pcm_current-v->centerW,
  111327. v->centerW);
  111328. for(j=0;j<v->pcm_current;j++)
  111329. v->pcm[i][v->pcm_current-j-1]=work[j];
  111330. }
  111331. }
  111332. }
  111333. /* call with val<=0 to set eof */
  111334. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111335. vorbis_info *vi=v->vi;
  111336. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111337. if(vals<=0){
  111338. int order=32;
  111339. int i;
  111340. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111341. /* if it wasn't done earlier (very short sample) */
  111342. if(!v->preextrapolate)
  111343. _preextrapolate_helper(v);
  111344. /* We're encoding the end of the stream. Just make sure we have
  111345. [at least] a few full blocks of zeroes at the end. */
  111346. /* actually, we don't want zeroes; that could drop a large
  111347. amplitude off a cliff, creating spread spectrum noise that will
  111348. suck to encode. Extrapolate for the sake of cleanliness. */
  111349. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111350. v->eofflag=v->pcm_current;
  111351. v->pcm_current+=ci->blocksizes[1]*3;
  111352. for(i=0;i<vi->channels;i++){
  111353. if(v->eofflag>order*2){
  111354. /* extrapolate with LPC to fill in */
  111355. long n;
  111356. /* make a predictor filter */
  111357. n=v->eofflag;
  111358. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111359. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111360. /* run the predictor filter */
  111361. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111362. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111363. }else{
  111364. /* not enough data to extrapolate (unlikely to happen due to
  111365. guarding the overlap, but bulletproof in case that
  111366. assumtion goes away). zeroes will do. */
  111367. memset(v->pcm[i]+v->eofflag,0,
  111368. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111369. }
  111370. }
  111371. }else{
  111372. if(v->pcm_current+vals>v->pcm_storage)
  111373. return(OV_EINVAL);
  111374. v->pcm_current+=vals;
  111375. /* we may want to reverse extrapolate the beginning of a stream
  111376. too... in case we're beginning on a cliff! */
  111377. /* clumsy, but simple. It only runs once, so simple is good. */
  111378. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111379. _preextrapolate_helper(v);
  111380. }
  111381. return(0);
  111382. }
  111383. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111384. the next block on which to continue analysis */
  111385. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111386. int i;
  111387. vorbis_info *vi=v->vi;
  111388. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111389. private_state *b=(private_state*)v->backend_state;
  111390. vorbis_look_psy_global *g=b->psy_g_look;
  111391. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111392. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111393. /* check to see if we're started... */
  111394. if(!v->preextrapolate)return(0);
  111395. /* check to see if we're done... */
  111396. if(v->eofflag==-1)return(0);
  111397. /* By our invariant, we have lW, W and centerW set. Search for
  111398. the next boundary so we can determine nW (the next window size)
  111399. which lets us compute the shape of the current block's window */
  111400. /* we do an envelope search even on a single blocksize; we may still
  111401. be throwing more bits at impulses, and envelope search handles
  111402. marking impulses too. */
  111403. {
  111404. long bp=_ve_envelope_search(v);
  111405. if(bp==-1){
  111406. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111407. full long block */
  111408. v->nW=0;
  111409. }else{
  111410. if(ci->blocksizes[0]==ci->blocksizes[1])
  111411. v->nW=0;
  111412. else
  111413. v->nW=bp;
  111414. }
  111415. }
  111416. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111417. {
  111418. /* center of next block + next block maximum right side. */
  111419. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111420. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111421. although this check is
  111422. less strict that the
  111423. _ve_envelope_search,
  111424. the search is not run
  111425. if we only use one
  111426. block size */
  111427. }
  111428. /* fill in the block. Note that for a short window, lW and nW are *short*
  111429. regardless of actual settings in the stream */
  111430. _vorbis_block_ripcord(vb);
  111431. vb->lW=v->lW;
  111432. vb->W=v->W;
  111433. vb->nW=v->nW;
  111434. if(v->W){
  111435. if(!v->lW || !v->nW){
  111436. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111437. /*fprintf(stderr,"-");*/
  111438. }else{
  111439. vbi->blocktype=BLOCKTYPE_LONG;
  111440. /*fprintf(stderr,"_");*/
  111441. }
  111442. }else{
  111443. if(_ve_envelope_mark(v)){
  111444. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111445. /*fprintf(stderr,"|");*/
  111446. }else{
  111447. vbi->blocktype=BLOCKTYPE_PADDING;
  111448. /*fprintf(stderr,".");*/
  111449. }
  111450. }
  111451. vb->vd=v;
  111452. vb->sequence=v->sequence++;
  111453. vb->granulepos=v->granulepos;
  111454. vb->pcmend=ci->blocksizes[v->W];
  111455. /* copy the vectors; this uses the local storage in vb */
  111456. /* this tracks 'strongest peak' for later psychoacoustics */
  111457. /* moved to the global psy state; clean this mess up */
  111458. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111459. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111460. vbi->ampmax=g->ampmax;
  111461. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111462. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111463. for(i=0;i<vi->channels;i++){
  111464. vbi->pcmdelay[i]=
  111465. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111466. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111467. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111468. /* before we added the delay
  111469. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111470. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111471. */
  111472. }
  111473. /* handle eof detection: eof==0 means that we've not yet received EOF
  111474. eof>0 marks the last 'real' sample in pcm[]
  111475. eof<0 'no more to do'; doesn't get here */
  111476. if(v->eofflag){
  111477. if(v->centerW>=v->eofflag){
  111478. v->eofflag=-1;
  111479. vb->eofflag=1;
  111480. return(1);
  111481. }
  111482. }
  111483. /* advance storage vectors and clean up */
  111484. {
  111485. int new_centerNext=ci->blocksizes[1]/2;
  111486. int movementW=centerNext-new_centerNext;
  111487. if(movementW>0){
  111488. _ve_envelope_shift(b->ve,movementW);
  111489. v->pcm_current-=movementW;
  111490. for(i=0;i<vi->channels;i++)
  111491. memmove(v->pcm[i],v->pcm[i]+movementW,
  111492. v->pcm_current*sizeof(*v->pcm[i]));
  111493. v->lW=v->W;
  111494. v->W=v->nW;
  111495. v->centerW=new_centerNext;
  111496. if(v->eofflag){
  111497. v->eofflag-=movementW;
  111498. if(v->eofflag<=0)v->eofflag=-1;
  111499. /* do not add padding to end of stream! */
  111500. if(v->centerW>=v->eofflag){
  111501. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111502. }else{
  111503. v->granulepos+=movementW;
  111504. }
  111505. }else{
  111506. v->granulepos+=movementW;
  111507. }
  111508. }
  111509. }
  111510. /* done */
  111511. return(1);
  111512. }
  111513. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111514. vorbis_info *vi=v->vi;
  111515. codec_setup_info *ci;
  111516. int hs;
  111517. if(!v->backend_state)return -1;
  111518. if(!vi)return -1;
  111519. ci=(codec_setup_info*) vi->codec_setup;
  111520. if(!ci)return -1;
  111521. hs=ci->halfrate_flag;
  111522. v->centerW=ci->blocksizes[1]>>(hs+1);
  111523. v->pcm_current=v->centerW>>hs;
  111524. v->pcm_returned=-1;
  111525. v->granulepos=-1;
  111526. v->sequence=-1;
  111527. v->eofflag=0;
  111528. ((private_state *)(v->backend_state))->sample_count=-1;
  111529. return(0);
  111530. }
  111531. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111532. if(_vds_shared_init(v,vi,0)) return 1;
  111533. vorbis_synthesis_restart(v);
  111534. return 0;
  111535. }
  111536. /* Unlike in analysis, the window is only partially applied for each
  111537. block. The time domain envelope is not yet handled at the point of
  111538. calling (as it relies on the previous block). */
  111539. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111540. vorbis_info *vi=v->vi;
  111541. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111542. private_state *b=(private_state*)v->backend_state;
  111543. int hs=ci->halfrate_flag;
  111544. int i,j;
  111545. if(!vb)return(OV_EINVAL);
  111546. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111547. v->lW=v->W;
  111548. v->W=vb->W;
  111549. v->nW=-1;
  111550. if((v->sequence==-1)||
  111551. (v->sequence+1 != vb->sequence)){
  111552. v->granulepos=-1; /* out of sequence; lose count */
  111553. b->sample_count=-1;
  111554. }
  111555. v->sequence=vb->sequence;
  111556. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111557. was called on block */
  111558. int n=ci->blocksizes[v->W]>>(hs+1);
  111559. int n0=ci->blocksizes[0]>>(hs+1);
  111560. int n1=ci->blocksizes[1]>>(hs+1);
  111561. int thisCenter;
  111562. int prevCenter;
  111563. v->glue_bits+=vb->glue_bits;
  111564. v->time_bits+=vb->time_bits;
  111565. v->floor_bits+=vb->floor_bits;
  111566. v->res_bits+=vb->res_bits;
  111567. if(v->centerW){
  111568. thisCenter=n1;
  111569. prevCenter=0;
  111570. }else{
  111571. thisCenter=0;
  111572. prevCenter=n1;
  111573. }
  111574. /* v->pcm is now used like a two-stage double buffer. We don't want
  111575. to have to constantly shift *or* adjust memory usage. Don't
  111576. accept a new block until the old is shifted out */
  111577. for(j=0;j<vi->channels;j++){
  111578. /* the overlap/add section */
  111579. if(v->lW){
  111580. if(v->W){
  111581. /* large/large */
  111582. float *w=_vorbis_window_get(b->window[1]-hs);
  111583. float *pcm=v->pcm[j]+prevCenter;
  111584. float *p=vb->pcm[j];
  111585. for(i=0;i<n1;i++)
  111586. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111587. }else{
  111588. /* large/small */
  111589. float *w=_vorbis_window_get(b->window[0]-hs);
  111590. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111591. float *p=vb->pcm[j];
  111592. for(i=0;i<n0;i++)
  111593. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111594. }
  111595. }else{
  111596. if(v->W){
  111597. /* small/large */
  111598. float *w=_vorbis_window_get(b->window[0]-hs);
  111599. float *pcm=v->pcm[j]+prevCenter;
  111600. float *p=vb->pcm[j]+n1/2-n0/2;
  111601. for(i=0;i<n0;i++)
  111602. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111603. for(;i<n1/2+n0/2;i++)
  111604. pcm[i]=p[i];
  111605. }else{
  111606. /* small/small */
  111607. float *w=_vorbis_window_get(b->window[0]-hs);
  111608. float *pcm=v->pcm[j]+prevCenter;
  111609. float *p=vb->pcm[j];
  111610. for(i=0;i<n0;i++)
  111611. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111612. }
  111613. }
  111614. /* the copy section */
  111615. {
  111616. float *pcm=v->pcm[j]+thisCenter;
  111617. float *p=vb->pcm[j]+n;
  111618. for(i=0;i<n;i++)
  111619. pcm[i]=p[i];
  111620. }
  111621. }
  111622. if(v->centerW)
  111623. v->centerW=0;
  111624. else
  111625. v->centerW=n1;
  111626. /* deal with initial packet state; we do this using the explicit
  111627. pcm_returned==-1 flag otherwise we're sensitive to first block
  111628. being short or long */
  111629. if(v->pcm_returned==-1){
  111630. v->pcm_returned=thisCenter;
  111631. v->pcm_current=thisCenter;
  111632. }else{
  111633. v->pcm_returned=prevCenter;
  111634. v->pcm_current=prevCenter+
  111635. ((ci->blocksizes[v->lW]/4+
  111636. ci->blocksizes[v->W]/4)>>hs);
  111637. }
  111638. }
  111639. /* track the frame number... This is for convenience, but also
  111640. making sure our last packet doesn't end with added padding. If
  111641. the last packet is partial, the number of samples we'll have to
  111642. return will be past the vb->granulepos.
  111643. This is not foolproof! It will be confused if we begin
  111644. decoding at the last page after a seek or hole. In that case,
  111645. we don't have a starting point to judge where the last frame
  111646. is. For this reason, vorbisfile will always try to make sure
  111647. it reads the last two marked pages in proper sequence */
  111648. if(b->sample_count==-1){
  111649. b->sample_count=0;
  111650. }else{
  111651. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111652. }
  111653. if(v->granulepos==-1){
  111654. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111655. v->granulepos=vb->granulepos;
  111656. /* is this a short page? */
  111657. if(b->sample_count>v->granulepos){
  111658. /* corner case; if this is both the first and last audio page,
  111659. then spec says the end is cut, not beginning */
  111660. if(vb->eofflag){
  111661. /* trim the end */
  111662. /* no preceeding granulepos; assume we started at zero (we'd
  111663. have to in a short single-page stream) */
  111664. /* granulepos could be -1 due to a seek, but that would result
  111665. in a long count, not short count */
  111666. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111667. }else{
  111668. /* trim the beginning */
  111669. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111670. if(v->pcm_returned>v->pcm_current)
  111671. v->pcm_returned=v->pcm_current;
  111672. }
  111673. }
  111674. }
  111675. }else{
  111676. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111677. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111678. if(v->granulepos>vb->granulepos){
  111679. long extra=v->granulepos-vb->granulepos;
  111680. if(extra)
  111681. if(vb->eofflag){
  111682. /* partial last frame. Strip the extra samples off */
  111683. v->pcm_current-=extra>>hs;
  111684. } /* else {Shouldn't happen *unless* the bitstream is out of
  111685. spec. Either way, believe the bitstream } */
  111686. } /* else {Shouldn't happen *unless* the bitstream is out of
  111687. spec. Either way, believe the bitstream } */
  111688. v->granulepos=vb->granulepos;
  111689. }
  111690. }
  111691. /* Update, cleanup */
  111692. if(vb->eofflag)v->eofflag=1;
  111693. return(0);
  111694. }
  111695. /* pcm==NULL indicates we just want the pending samples, no more */
  111696. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111697. vorbis_info *vi=v->vi;
  111698. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111699. if(pcm){
  111700. int i;
  111701. for(i=0;i<vi->channels;i++)
  111702. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111703. *pcm=v->pcmret;
  111704. }
  111705. return(v->pcm_current-v->pcm_returned);
  111706. }
  111707. return(0);
  111708. }
  111709. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111710. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111711. v->pcm_returned+=n;
  111712. return(0);
  111713. }
  111714. /* intended for use with a specific vorbisfile feature; we want access
  111715. to the [usually synthetic/postextrapolated] buffer and lapping at
  111716. the end of a decode cycle, specifically, a half-short-block worth.
  111717. This funtion works like pcmout above, except it will also expose
  111718. this implicit buffer data not normally decoded. */
  111719. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111720. vorbis_info *vi=v->vi;
  111721. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111722. int hs=ci->halfrate_flag;
  111723. int n=ci->blocksizes[v->W]>>(hs+1);
  111724. int n0=ci->blocksizes[0]>>(hs+1);
  111725. int n1=ci->blocksizes[1]>>(hs+1);
  111726. int i,j;
  111727. if(v->pcm_returned<0)return 0;
  111728. /* our returned data ends at pcm_returned; because the synthesis pcm
  111729. buffer is a two-fragment ring, that means our data block may be
  111730. fragmented by buffering, wrapping or a short block not filling
  111731. out a buffer. To simplify things, we unfragment if it's at all
  111732. possibly needed. Otherwise, we'd need to call lapout more than
  111733. once as well as hold additional dsp state. Opt for
  111734. simplicity. */
  111735. /* centerW was advanced by blockin; it would be the center of the
  111736. *next* block */
  111737. if(v->centerW==n1){
  111738. /* the data buffer wraps; swap the halves */
  111739. /* slow, sure, small */
  111740. for(j=0;j<vi->channels;j++){
  111741. float *p=v->pcm[j];
  111742. for(i=0;i<n1;i++){
  111743. float temp=p[i];
  111744. p[i]=p[i+n1];
  111745. p[i+n1]=temp;
  111746. }
  111747. }
  111748. v->pcm_current-=n1;
  111749. v->pcm_returned-=n1;
  111750. v->centerW=0;
  111751. }
  111752. /* solidify buffer into contiguous space */
  111753. if((v->lW^v->W)==1){
  111754. /* long/short or short/long */
  111755. for(j=0;j<vi->channels;j++){
  111756. float *s=v->pcm[j];
  111757. float *d=v->pcm[j]+(n1-n0)/2;
  111758. for(i=(n1+n0)/2-1;i>=0;--i)
  111759. d[i]=s[i];
  111760. }
  111761. v->pcm_returned+=(n1-n0)/2;
  111762. v->pcm_current+=(n1-n0)/2;
  111763. }else{
  111764. if(v->lW==0){
  111765. /* short/short */
  111766. for(j=0;j<vi->channels;j++){
  111767. float *s=v->pcm[j];
  111768. float *d=v->pcm[j]+n1-n0;
  111769. for(i=n0-1;i>=0;--i)
  111770. d[i]=s[i];
  111771. }
  111772. v->pcm_returned+=n1-n0;
  111773. v->pcm_current+=n1-n0;
  111774. }
  111775. }
  111776. if(pcm){
  111777. int i;
  111778. for(i=0;i<vi->channels;i++)
  111779. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111780. *pcm=v->pcmret;
  111781. }
  111782. return(n1+n-v->pcm_returned);
  111783. }
  111784. float *vorbis_window(vorbis_dsp_state *v,int W){
  111785. vorbis_info *vi=v->vi;
  111786. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111787. int hs=ci->halfrate_flag;
  111788. private_state *b=(private_state*)v->backend_state;
  111789. if(b->window[W]-1<0)return NULL;
  111790. return _vorbis_window_get(b->window[W]-hs);
  111791. }
  111792. #endif
  111793. /*** End of inlined file: block.c ***/
  111794. /*** Start of inlined file: codebook.c ***/
  111795. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111796. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111797. // tasks..
  111798. #if JUCE_MSVC
  111799. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111800. #endif
  111801. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111802. #if JUCE_USE_OGGVORBIS
  111803. #include <stdlib.h>
  111804. #include <string.h>
  111805. #include <math.h>
  111806. /* packs the given codebook into the bitstream **************************/
  111807. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111808. long i,j;
  111809. int ordered=0;
  111810. /* first the basic parameters */
  111811. oggpack_write(opb,0x564342,24);
  111812. oggpack_write(opb,c->dim,16);
  111813. oggpack_write(opb,c->entries,24);
  111814. /* pack the codewords. There are two packings; length ordered and
  111815. length random. Decide between the two now. */
  111816. for(i=1;i<c->entries;i++)
  111817. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111818. if(i==c->entries)ordered=1;
  111819. if(ordered){
  111820. /* length ordered. We only need to say how many codewords of
  111821. each length. The actual codewords are generated
  111822. deterministically */
  111823. long count=0;
  111824. oggpack_write(opb,1,1); /* ordered */
  111825. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111826. for(i=1;i<c->entries;i++){
  111827. long thisx=c->lengthlist[i];
  111828. long last=c->lengthlist[i-1];
  111829. if(thisx>last){
  111830. for(j=last;j<thisx;j++){
  111831. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111832. count=i;
  111833. }
  111834. }
  111835. }
  111836. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111837. }else{
  111838. /* length random. Again, we don't code the codeword itself, just
  111839. the length. This time, though, we have to encode each length */
  111840. oggpack_write(opb,0,1); /* unordered */
  111841. /* algortihmic mapping has use for 'unused entries', which we tag
  111842. here. The algorithmic mapping happens as usual, but the unused
  111843. entry has no codeword. */
  111844. for(i=0;i<c->entries;i++)
  111845. if(c->lengthlist[i]==0)break;
  111846. if(i==c->entries){
  111847. oggpack_write(opb,0,1); /* no unused entries */
  111848. for(i=0;i<c->entries;i++)
  111849. oggpack_write(opb,c->lengthlist[i]-1,5);
  111850. }else{
  111851. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111852. for(i=0;i<c->entries;i++){
  111853. if(c->lengthlist[i]==0){
  111854. oggpack_write(opb,0,1);
  111855. }else{
  111856. oggpack_write(opb,1,1);
  111857. oggpack_write(opb,c->lengthlist[i]-1,5);
  111858. }
  111859. }
  111860. }
  111861. }
  111862. /* is the entry number the desired return value, or do we have a
  111863. mapping? If we have a mapping, what type? */
  111864. oggpack_write(opb,c->maptype,4);
  111865. switch(c->maptype){
  111866. case 0:
  111867. /* no mapping */
  111868. break;
  111869. case 1:case 2:
  111870. /* implicitly populated value mapping */
  111871. /* explicitly populated value mapping */
  111872. if(!c->quantlist){
  111873. /* no quantlist? error */
  111874. return(-1);
  111875. }
  111876. /* values that define the dequantization */
  111877. oggpack_write(opb,c->q_min,32);
  111878. oggpack_write(opb,c->q_delta,32);
  111879. oggpack_write(opb,c->q_quant-1,4);
  111880. oggpack_write(opb,c->q_sequencep,1);
  111881. {
  111882. int quantvals;
  111883. switch(c->maptype){
  111884. case 1:
  111885. /* a single column of (c->entries/c->dim) quantized values for
  111886. building a full value list algorithmically (square lattice) */
  111887. quantvals=_book_maptype1_quantvals(c);
  111888. break;
  111889. case 2:
  111890. /* every value (c->entries*c->dim total) specified explicitly */
  111891. quantvals=c->entries*c->dim;
  111892. break;
  111893. default: /* NOT_REACHABLE */
  111894. quantvals=-1;
  111895. }
  111896. /* quantized values */
  111897. for(i=0;i<quantvals;i++)
  111898. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111899. }
  111900. break;
  111901. default:
  111902. /* error case; we don't have any other map types now */
  111903. return(-1);
  111904. }
  111905. return(0);
  111906. }
  111907. /* unpacks a codebook from the packet buffer into the codebook struct,
  111908. readies the codebook auxiliary structures for decode *************/
  111909. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111910. long i,j;
  111911. memset(s,0,sizeof(*s));
  111912. s->allocedp=1;
  111913. /* make sure alignment is correct */
  111914. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111915. /* first the basic parameters */
  111916. s->dim=oggpack_read(opb,16);
  111917. s->entries=oggpack_read(opb,24);
  111918. if(s->entries==-1)goto _eofout;
  111919. /* codeword ordering.... length ordered or unordered? */
  111920. switch((int)oggpack_read(opb,1)){
  111921. case 0:
  111922. /* unordered */
  111923. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111924. /* allocated but unused entries? */
  111925. if(oggpack_read(opb,1)){
  111926. /* yes, unused entries */
  111927. for(i=0;i<s->entries;i++){
  111928. if(oggpack_read(opb,1)){
  111929. long num=oggpack_read(opb,5);
  111930. if(num==-1)goto _eofout;
  111931. s->lengthlist[i]=num+1;
  111932. }else
  111933. s->lengthlist[i]=0;
  111934. }
  111935. }else{
  111936. /* all entries used; no tagging */
  111937. for(i=0;i<s->entries;i++){
  111938. long num=oggpack_read(opb,5);
  111939. if(num==-1)goto _eofout;
  111940. s->lengthlist[i]=num+1;
  111941. }
  111942. }
  111943. break;
  111944. case 1:
  111945. /* ordered */
  111946. {
  111947. long length=oggpack_read(opb,5)+1;
  111948. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111949. for(i=0;i<s->entries;){
  111950. long num=oggpack_read(opb,_ilog(s->entries-i));
  111951. if(num==-1)goto _eofout;
  111952. for(j=0;j<num && i<s->entries;j++,i++)
  111953. s->lengthlist[i]=length;
  111954. length++;
  111955. }
  111956. }
  111957. break;
  111958. default:
  111959. /* EOF */
  111960. return(-1);
  111961. }
  111962. /* Do we have a mapping to unpack? */
  111963. switch((s->maptype=oggpack_read(opb,4))){
  111964. case 0:
  111965. /* no mapping */
  111966. break;
  111967. case 1: case 2:
  111968. /* implicitly populated value mapping */
  111969. /* explicitly populated value mapping */
  111970. s->q_min=oggpack_read(opb,32);
  111971. s->q_delta=oggpack_read(opb,32);
  111972. s->q_quant=oggpack_read(opb,4)+1;
  111973. s->q_sequencep=oggpack_read(opb,1);
  111974. {
  111975. int quantvals=0;
  111976. switch(s->maptype){
  111977. case 1:
  111978. quantvals=_book_maptype1_quantvals(s);
  111979. break;
  111980. case 2:
  111981. quantvals=s->entries*s->dim;
  111982. break;
  111983. }
  111984. /* quantized values */
  111985. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111986. for(i=0;i<quantvals;i++)
  111987. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111988. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111989. }
  111990. break;
  111991. default:
  111992. goto _errout;
  111993. }
  111994. /* all set */
  111995. return(0);
  111996. _errout:
  111997. _eofout:
  111998. vorbis_staticbook_clear(s);
  111999. return(-1);
  112000. }
  112001. /* returns the number of bits ************************************************/
  112002. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112003. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112004. return(book->c->lengthlist[a]);
  112005. }
  112006. /* One the encode side, our vector writers are each designed for a
  112007. specific purpose, and the encoder is not flexible without modification:
  112008. The LSP vector coder uses a single stage nearest-match with no
  112009. interleave, so no step and no error return. This is specced by floor0
  112010. and doesn't change.
  112011. Residue0 encoding interleaves, uses multiple stages, and each stage
  112012. peels of a specific amount of resolution from a lattice (thus we want
  112013. to match by threshold, not nearest match). Residue doesn't *have* to
  112014. be encoded that way, but to change it, one will need to add more
  112015. infrastructure on the encode side (decode side is specced and simpler) */
  112016. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112017. /* returns entry number and *modifies a* to the quantization value *****/
  112018. int vorbis_book_errorv(codebook *book,float *a){
  112019. int dim=book->dim,k;
  112020. int best=_best(book,a,1);
  112021. for(k=0;k<dim;k++)
  112022. a[k]=(book->valuelist+best*dim)[k];
  112023. return(best);
  112024. }
  112025. /* returns the number of bits and *modifies a* to the quantization value *****/
  112026. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112027. int k,dim=book->dim;
  112028. for(k=0;k<dim;k++)
  112029. a[k]=(book->valuelist+best*dim)[k];
  112030. return(vorbis_book_encode(book,best,b));
  112031. }
  112032. /* the 'eliminate the decode tree' optimization actually requires the
  112033. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112034. (and one of the first places where carefully thought out design
  112035. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112036. to an MSb bitpacker), but not actually the huge hit it appears to
  112037. be. The first-stage decode table catches most words so that
  112038. bitreverse is not in the main execution path. */
  112039. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112040. int read=book->dec_maxlength;
  112041. long lo,hi;
  112042. long lok = oggpack_look(b,book->dec_firsttablen);
  112043. if (lok >= 0) {
  112044. long entry = book->dec_firsttable[lok];
  112045. if(entry&0x80000000UL){
  112046. lo=(entry>>15)&0x7fff;
  112047. hi=book->used_entries-(entry&0x7fff);
  112048. }else{
  112049. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112050. return(entry-1);
  112051. }
  112052. }else{
  112053. lo=0;
  112054. hi=book->used_entries;
  112055. }
  112056. lok = oggpack_look(b, read);
  112057. while(lok<0 && read>1)
  112058. lok = oggpack_look(b, --read);
  112059. if(lok<0)return -1;
  112060. /* bisect search for the codeword in the ordered list */
  112061. {
  112062. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112063. while(hi-lo>1){
  112064. long p=(hi-lo)>>1;
  112065. long test=book->codelist[lo+p]>testword;
  112066. lo+=p&(test-1);
  112067. hi-=p&(-test);
  112068. }
  112069. if(book->dec_codelengths[lo]<=read){
  112070. oggpack_adv(b, book->dec_codelengths[lo]);
  112071. return(lo);
  112072. }
  112073. }
  112074. oggpack_adv(b, read);
  112075. return(-1);
  112076. }
  112077. /* Decode side is specced and easier, because we don't need to find
  112078. matches using different criteria; we simply read and map. There are
  112079. two things we need to do 'depending':
  112080. We may need to support interleave. We don't really, but it's
  112081. convenient to do it here rather than rebuild the vector later.
  112082. Cascades may be additive or multiplicitive; this is not inherent in
  112083. the codebook, but set in the code using the codebook. Like
  112084. interleaving, it's easiest to do it here.
  112085. addmul==0 -> declarative (set the value)
  112086. addmul==1 -> additive
  112087. addmul==2 -> multiplicitive */
  112088. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112089. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112090. long packed_entry=decode_packed_entry_number(book,b);
  112091. if(packed_entry>=0)
  112092. return(book->dec_index[packed_entry]);
  112093. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112094. return(packed_entry);
  112095. }
  112096. /* returns 0 on OK or -1 on eof *************************************/
  112097. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112098. int step=n/book->dim;
  112099. long *entry = (long*)alloca(sizeof(*entry)*step);
  112100. float **t = (float**)alloca(sizeof(*t)*step);
  112101. int i,j,o;
  112102. for (i = 0; i < step; i++) {
  112103. entry[i]=decode_packed_entry_number(book,b);
  112104. if(entry[i]==-1)return(-1);
  112105. t[i] = book->valuelist+entry[i]*book->dim;
  112106. }
  112107. for(i=0,o=0;i<book->dim;i++,o+=step)
  112108. for (j=0;j<step;j++)
  112109. a[o+j]+=t[j][i];
  112110. return(0);
  112111. }
  112112. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112113. int i,j,entry;
  112114. float *t;
  112115. if(book->dim>8){
  112116. for(i=0;i<n;){
  112117. entry = decode_packed_entry_number(book,b);
  112118. if(entry==-1)return(-1);
  112119. t = book->valuelist+entry*book->dim;
  112120. for (j=0;j<book->dim;)
  112121. a[i++]+=t[j++];
  112122. }
  112123. }else{
  112124. for(i=0;i<n;){
  112125. entry = decode_packed_entry_number(book,b);
  112126. if(entry==-1)return(-1);
  112127. t = book->valuelist+entry*book->dim;
  112128. j=0;
  112129. switch((int)book->dim){
  112130. case 8:
  112131. a[i++]+=t[j++];
  112132. case 7:
  112133. a[i++]+=t[j++];
  112134. case 6:
  112135. a[i++]+=t[j++];
  112136. case 5:
  112137. a[i++]+=t[j++];
  112138. case 4:
  112139. a[i++]+=t[j++];
  112140. case 3:
  112141. a[i++]+=t[j++];
  112142. case 2:
  112143. a[i++]+=t[j++];
  112144. case 1:
  112145. a[i++]+=t[j++];
  112146. case 0:
  112147. break;
  112148. }
  112149. }
  112150. }
  112151. return(0);
  112152. }
  112153. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112154. int i,j,entry;
  112155. float *t;
  112156. for(i=0;i<n;){
  112157. entry = decode_packed_entry_number(book,b);
  112158. if(entry==-1)return(-1);
  112159. t = book->valuelist+entry*book->dim;
  112160. for (j=0;j<book->dim;)
  112161. a[i++]=t[j++];
  112162. }
  112163. return(0);
  112164. }
  112165. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112166. oggpack_buffer *b,int n){
  112167. long i,j,entry;
  112168. int chptr=0;
  112169. for(i=offset/ch;i<(offset+n)/ch;){
  112170. entry = decode_packed_entry_number(book,b);
  112171. if(entry==-1)return(-1);
  112172. {
  112173. const float *t = book->valuelist+entry*book->dim;
  112174. for (j=0;j<book->dim;j++){
  112175. a[chptr++][i]+=t[j];
  112176. if(chptr==ch){
  112177. chptr=0;
  112178. i++;
  112179. }
  112180. }
  112181. }
  112182. }
  112183. return(0);
  112184. }
  112185. #ifdef _V_SELFTEST
  112186. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112187. number of vectors through (keeping track of the quantized values),
  112188. and decode using the unpacked book. quantized version of in should
  112189. exactly equal out */
  112190. #include <stdio.h>
  112191. #include "vorbis/book/lsp20_0.vqh"
  112192. #include "vorbis/book/res0a_13.vqh"
  112193. #define TESTSIZE 40
  112194. float test1[TESTSIZE]={
  112195. 0.105939f,
  112196. 0.215373f,
  112197. 0.429117f,
  112198. 0.587974f,
  112199. 0.181173f,
  112200. 0.296583f,
  112201. 0.515707f,
  112202. 0.715261f,
  112203. 0.162327f,
  112204. 0.263834f,
  112205. 0.342876f,
  112206. 0.406025f,
  112207. 0.103571f,
  112208. 0.223561f,
  112209. 0.368513f,
  112210. 0.540313f,
  112211. 0.136672f,
  112212. 0.395882f,
  112213. 0.587183f,
  112214. 0.652476f,
  112215. 0.114338f,
  112216. 0.417300f,
  112217. 0.525486f,
  112218. 0.698679f,
  112219. 0.147492f,
  112220. 0.324481f,
  112221. 0.643089f,
  112222. 0.757582f,
  112223. 0.139556f,
  112224. 0.215795f,
  112225. 0.324559f,
  112226. 0.399387f,
  112227. 0.120236f,
  112228. 0.267420f,
  112229. 0.446940f,
  112230. 0.608760f,
  112231. 0.115587f,
  112232. 0.287234f,
  112233. 0.571081f,
  112234. 0.708603f,
  112235. };
  112236. float test3[TESTSIZE]={
  112237. 0,1,-2,3,4,-5,6,7,8,9,
  112238. 8,-2,7,-1,4,6,8,3,1,-9,
  112239. 10,11,12,13,14,15,26,17,18,19,
  112240. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112241. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112242. &_vq_book_res0a_13,NULL};
  112243. float *testvec[]={test1,test3};
  112244. int main(){
  112245. oggpack_buffer write;
  112246. oggpack_buffer read;
  112247. long ptr=0,i;
  112248. oggpack_writeinit(&write);
  112249. fprintf(stderr,"Testing codebook abstraction...:\n");
  112250. while(testlist[ptr]){
  112251. codebook c;
  112252. static_codebook s;
  112253. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112254. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112255. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112256. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112257. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112258. /* pack the codebook, write the testvector */
  112259. oggpack_reset(&write);
  112260. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112261. we can write */
  112262. vorbis_staticbook_pack(testlist[ptr],&write);
  112263. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112264. for(i=0;i<TESTSIZE;i+=c.dim){
  112265. int best=_best(&c,qv+i,1);
  112266. vorbis_book_encodev(&c,best,qv+i,&write);
  112267. }
  112268. vorbis_book_clear(&c);
  112269. fprintf(stderr,"OK.\n");
  112270. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112271. /* transfer the write data to a read buffer and unpack/read */
  112272. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112273. if(vorbis_staticbook_unpack(&read,&s)){
  112274. fprintf(stderr,"Error unpacking codebook.\n");
  112275. exit(1);
  112276. }
  112277. if(vorbis_book_init_decode(&c,&s)){
  112278. fprintf(stderr,"Error initializing codebook.\n");
  112279. exit(1);
  112280. }
  112281. for(i=0;i<TESTSIZE;i+=c.dim)
  112282. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112283. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112284. exit(1);
  112285. }
  112286. for(i=0;i<TESTSIZE;i++)
  112287. if(fabs(qv[i]-iv[i])>.000001){
  112288. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112289. iv[i],qv[i],i);
  112290. exit(1);
  112291. }
  112292. fprintf(stderr,"OK\n");
  112293. ptr++;
  112294. }
  112295. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112296. exit(0);
  112297. }
  112298. #endif
  112299. #endif
  112300. /*** End of inlined file: codebook.c ***/
  112301. /*** Start of inlined file: envelope.c ***/
  112302. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112303. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112304. // tasks..
  112305. #if JUCE_MSVC
  112306. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112307. #endif
  112308. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112309. #if JUCE_USE_OGGVORBIS
  112310. #include <stdlib.h>
  112311. #include <string.h>
  112312. #include <stdio.h>
  112313. #include <math.h>
  112314. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112315. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112316. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112317. int ch=vi->channels;
  112318. int i,j;
  112319. int n=e->winlength=128;
  112320. e->searchstep=64; /* not random */
  112321. e->minenergy=gi->preecho_minenergy;
  112322. e->ch=ch;
  112323. e->storage=128;
  112324. e->cursor=ci->blocksizes[1]/2;
  112325. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112326. mdct_init(&e->mdct,n);
  112327. for(i=0;i<n;i++){
  112328. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112329. e->mdct_win[i]*=e->mdct_win[i];
  112330. }
  112331. /* magic follows */
  112332. e->band[0].begin=2; e->band[0].end=4;
  112333. e->band[1].begin=4; e->band[1].end=5;
  112334. e->band[2].begin=6; e->band[2].end=6;
  112335. e->band[3].begin=9; e->band[3].end=8;
  112336. e->band[4].begin=13; e->band[4].end=8;
  112337. e->band[5].begin=17; e->band[5].end=8;
  112338. e->band[6].begin=22; e->band[6].end=8;
  112339. for(j=0;j<VE_BANDS;j++){
  112340. n=e->band[j].end;
  112341. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112342. for(i=0;i<n;i++){
  112343. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112344. e->band[j].total+=e->band[j].window[i];
  112345. }
  112346. e->band[j].total=1./e->band[j].total;
  112347. }
  112348. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112349. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112350. }
  112351. void _ve_envelope_clear(envelope_lookup *e){
  112352. int i;
  112353. mdct_clear(&e->mdct);
  112354. for(i=0;i<VE_BANDS;i++)
  112355. _ogg_free(e->band[i].window);
  112356. _ogg_free(e->mdct_win);
  112357. _ogg_free(e->filter);
  112358. _ogg_free(e->mark);
  112359. memset(e,0,sizeof(*e));
  112360. }
  112361. /* fairly straight threshhold-by-band based until we find something
  112362. that works better and isn't patented. */
  112363. static int _ve_amp(envelope_lookup *ve,
  112364. vorbis_info_psy_global *gi,
  112365. float *data,
  112366. envelope_band *bands,
  112367. envelope_filter_state *filters,
  112368. long pos){
  112369. long n=ve->winlength;
  112370. int ret=0;
  112371. long i,j;
  112372. float decay;
  112373. /* we want to have a 'minimum bar' for energy, else we're just
  112374. basing blocks on quantization noise that outweighs the signal
  112375. itself (for low power signals) */
  112376. float minV=ve->minenergy;
  112377. float *vec=(float*) alloca(n*sizeof(*vec));
  112378. /* stretch is used to gradually lengthen the number of windows
  112379. considered prevoius-to-potential-trigger */
  112380. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112381. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112382. if(penalty<0.f)penalty=0.f;
  112383. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112384. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112385. totalshift+pos*ve->searchstep);*/
  112386. /* window and transform */
  112387. for(i=0;i<n;i++)
  112388. vec[i]=data[i]*ve->mdct_win[i];
  112389. mdct_forward(&ve->mdct,vec,vec);
  112390. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112391. /* near-DC spreading function; this has nothing to do with
  112392. psychoacoustics, just sidelobe leakage and window size */
  112393. {
  112394. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112395. int ptr=filters->nearptr;
  112396. /* the accumulation is regularly refreshed from scratch to avoid
  112397. floating point creep */
  112398. if(ptr==0){
  112399. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112400. filters->nearDC_partialacc=temp;
  112401. }else{
  112402. decay=filters->nearDC_acc+=temp;
  112403. filters->nearDC_partialacc+=temp;
  112404. }
  112405. filters->nearDC_acc-=filters->nearDC[ptr];
  112406. filters->nearDC[ptr]=temp;
  112407. decay*=(1./(VE_NEARDC+1));
  112408. filters->nearptr++;
  112409. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112410. decay=todB(&decay)*.5-15.f;
  112411. }
  112412. /* perform spreading and limiting, also smooth the spectrum. yes,
  112413. the MDCT results in all real coefficients, but it still *behaves*
  112414. like real/imaginary pairs */
  112415. for(i=0;i<n/2;i+=2){
  112416. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112417. val=todB(&val)*.5f;
  112418. if(val<decay)val=decay;
  112419. if(val<minV)val=minV;
  112420. vec[i>>1]=val;
  112421. decay-=8.;
  112422. }
  112423. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112424. /* perform preecho/postecho triggering by band */
  112425. for(j=0;j<VE_BANDS;j++){
  112426. float acc=0.;
  112427. float valmax,valmin;
  112428. /* accumulate amplitude */
  112429. for(i=0;i<bands[j].end;i++)
  112430. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112431. acc*=bands[j].total;
  112432. /* convert amplitude to delta */
  112433. {
  112434. int p,thisx=filters[j].ampptr;
  112435. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112436. p=thisx;
  112437. p--;
  112438. if(p<0)p+=VE_AMP;
  112439. postmax=max(acc,filters[j].ampbuf[p]);
  112440. postmin=min(acc,filters[j].ampbuf[p]);
  112441. for(i=0;i<stretch;i++){
  112442. p--;
  112443. if(p<0)p+=VE_AMP;
  112444. premax=max(premax,filters[j].ampbuf[p]);
  112445. premin=min(premin,filters[j].ampbuf[p]);
  112446. }
  112447. valmin=postmin-premin;
  112448. valmax=postmax-premax;
  112449. /*filters[j].markers[pos]=valmax;*/
  112450. filters[j].ampbuf[thisx]=acc;
  112451. filters[j].ampptr++;
  112452. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112453. }
  112454. /* look at min/max, decide trigger */
  112455. if(valmax>gi->preecho_thresh[j]+penalty){
  112456. ret|=1;
  112457. ret|=4;
  112458. }
  112459. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112460. }
  112461. return(ret);
  112462. }
  112463. #if 0
  112464. static int seq=0;
  112465. static ogg_int64_t totalshift=-1024;
  112466. #endif
  112467. long _ve_envelope_search(vorbis_dsp_state *v){
  112468. vorbis_info *vi=v->vi;
  112469. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112470. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112471. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112472. long i,j;
  112473. int first=ve->current/ve->searchstep;
  112474. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112475. if(first<0)first=0;
  112476. /* make sure we have enough storage to match the PCM */
  112477. if(last+VE_WIN+VE_POST>ve->storage){
  112478. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112479. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112480. }
  112481. for(j=first;j<last;j++){
  112482. int ret=0;
  112483. ve->stretch++;
  112484. if(ve->stretch>VE_MAXSTRETCH*2)
  112485. ve->stretch=VE_MAXSTRETCH*2;
  112486. for(i=0;i<ve->ch;i++){
  112487. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112488. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112489. }
  112490. ve->mark[j+VE_POST]=0;
  112491. if(ret&1){
  112492. ve->mark[j]=1;
  112493. ve->mark[j+1]=1;
  112494. }
  112495. if(ret&2){
  112496. ve->mark[j]=1;
  112497. if(j>0)ve->mark[j-1]=1;
  112498. }
  112499. if(ret&4)ve->stretch=-1;
  112500. }
  112501. ve->current=last*ve->searchstep;
  112502. {
  112503. long centerW=v->centerW;
  112504. long testW=
  112505. centerW+
  112506. ci->blocksizes[v->W]/4+
  112507. ci->blocksizes[1]/2+
  112508. ci->blocksizes[0]/4;
  112509. j=ve->cursor;
  112510. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112511. working back one window */
  112512. if(j>=testW)return(1);
  112513. ve->cursor=j;
  112514. if(ve->mark[j/ve->searchstep]){
  112515. if(j>centerW){
  112516. #if 0
  112517. if(j>ve->curmark){
  112518. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112519. int l,m;
  112520. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112521. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112522. seq,
  112523. (totalshift+ve->cursor)/44100.,
  112524. (totalshift+j)/44100.);
  112525. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112526. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112527. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112528. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112529. for(m=0;m<VE_BANDS;m++){
  112530. char buf[80];
  112531. sprintf(buf,"delL%d",m);
  112532. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112533. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112534. }
  112535. for(m=0;m<VE_BANDS;m++){
  112536. char buf[80];
  112537. sprintf(buf,"delR%d",m);
  112538. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112539. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112540. }
  112541. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112542. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112543. seq++;
  112544. }
  112545. #endif
  112546. ve->curmark=j;
  112547. if(j>=testW)return(1);
  112548. return(0);
  112549. }
  112550. }
  112551. j+=ve->searchstep;
  112552. }
  112553. }
  112554. return(-1);
  112555. }
  112556. int _ve_envelope_mark(vorbis_dsp_state *v){
  112557. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112558. vorbis_info *vi=v->vi;
  112559. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112560. long centerW=v->centerW;
  112561. long beginW=centerW-ci->blocksizes[v->W]/4;
  112562. long endW=centerW+ci->blocksizes[v->W]/4;
  112563. if(v->W){
  112564. beginW-=ci->blocksizes[v->lW]/4;
  112565. endW+=ci->blocksizes[v->nW]/4;
  112566. }else{
  112567. beginW-=ci->blocksizes[0]/4;
  112568. endW+=ci->blocksizes[0]/4;
  112569. }
  112570. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112571. {
  112572. long first=beginW/ve->searchstep;
  112573. long last=endW/ve->searchstep;
  112574. long i;
  112575. for(i=first;i<last;i++)
  112576. if(ve->mark[i])return(1);
  112577. }
  112578. return(0);
  112579. }
  112580. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112581. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112582. ahead of ve->current */
  112583. int smallshift=shift/e->searchstep;
  112584. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112585. #if 0
  112586. for(i=0;i<VE_BANDS*e->ch;i++)
  112587. memmove(e->filter[i].markers,
  112588. e->filter[i].markers+smallshift,
  112589. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112590. totalshift+=shift;
  112591. #endif
  112592. e->current-=shift;
  112593. if(e->curmark>=0)
  112594. e->curmark-=shift;
  112595. e->cursor-=shift;
  112596. }
  112597. #endif
  112598. /*** End of inlined file: envelope.c ***/
  112599. /*** Start of inlined file: floor0.c ***/
  112600. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112601. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112602. // tasks..
  112603. #if JUCE_MSVC
  112604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112605. #endif
  112606. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112607. #if JUCE_USE_OGGVORBIS
  112608. #include <stdlib.h>
  112609. #include <string.h>
  112610. #include <math.h>
  112611. /*** Start of inlined file: lsp.h ***/
  112612. #ifndef _V_LSP_H_
  112613. #define _V_LSP_H_
  112614. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112615. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112616. float *lsp,int m,
  112617. float amp,float ampoffset);
  112618. #endif
  112619. /*** End of inlined file: lsp.h ***/
  112620. #include <stdio.h>
  112621. typedef struct {
  112622. int ln;
  112623. int m;
  112624. int **linearmap;
  112625. int n[2];
  112626. vorbis_info_floor0 *vi;
  112627. long bits;
  112628. long frames;
  112629. } vorbis_look_floor0;
  112630. /***********************************************/
  112631. static void floor0_free_info(vorbis_info_floor *i){
  112632. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112633. if(info){
  112634. memset(info,0,sizeof(*info));
  112635. _ogg_free(info);
  112636. }
  112637. }
  112638. static void floor0_free_look(vorbis_look_floor *i){
  112639. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112640. if(look){
  112641. if(look->linearmap){
  112642. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112643. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112644. _ogg_free(look->linearmap);
  112645. }
  112646. memset(look,0,sizeof(*look));
  112647. _ogg_free(look);
  112648. }
  112649. }
  112650. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112651. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112652. int j;
  112653. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112654. info->order=oggpack_read(opb,8);
  112655. info->rate=oggpack_read(opb,16);
  112656. info->barkmap=oggpack_read(opb,16);
  112657. info->ampbits=oggpack_read(opb,6);
  112658. info->ampdB=oggpack_read(opb,8);
  112659. info->numbooks=oggpack_read(opb,4)+1;
  112660. if(info->order<1)goto err_out;
  112661. if(info->rate<1)goto err_out;
  112662. if(info->barkmap<1)goto err_out;
  112663. if(info->numbooks<1)goto err_out;
  112664. for(j=0;j<info->numbooks;j++){
  112665. info->books[j]=oggpack_read(opb,8);
  112666. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112667. }
  112668. return(info);
  112669. err_out:
  112670. floor0_free_info(info);
  112671. return(NULL);
  112672. }
  112673. /* initialize Bark scale and normalization lookups. We could do this
  112674. with static tables, but Vorbis allows a number of possible
  112675. combinations, so it's best to do it computationally.
  112676. The below is authoritative in terms of defining scale mapping.
  112677. Note that the scale depends on the sampling rate as well as the
  112678. linear block and mapping sizes */
  112679. static void floor0_map_lazy_init(vorbis_block *vb,
  112680. vorbis_info_floor *infoX,
  112681. vorbis_look_floor0 *look){
  112682. if(!look->linearmap[vb->W]){
  112683. vorbis_dsp_state *vd=vb->vd;
  112684. vorbis_info *vi=vd->vi;
  112685. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112686. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112687. int W=vb->W;
  112688. int n=ci->blocksizes[W]/2,j;
  112689. /* we choose a scaling constant so that:
  112690. floor(bark(rate/2-1)*C)=mapped-1
  112691. floor(bark(rate/2)*C)=mapped */
  112692. float scale=look->ln/toBARK(info->rate/2.f);
  112693. /* the mapping from a linear scale to a smaller bark scale is
  112694. straightforward. We do *not* make sure that the linear mapping
  112695. does not skip bark-scale bins; the decoder simply skips them and
  112696. the encoder may do what it wishes in filling them. They're
  112697. necessary in some mapping combinations to keep the scale spacing
  112698. accurate */
  112699. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112700. for(j=0;j<n;j++){
  112701. int val=floor( toBARK((info->rate/2.f)/n*j)
  112702. *scale); /* bark numbers represent band edges */
  112703. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112704. look->linearmap[W][j]=val;
  112705. }
  112706. look->linearmap[W][j]=-1;
  112707. look->n[W]=n;
  112708. }
  112709. }
  112710. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112711. vorbis_info_floor *i){
  112712. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112713. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112714. look->m=info->order;
  112715. look->ln=info->barkmap;
  112716. look->vi=info;
  112717. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112718. return look;
  112719. }
  112720. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112721. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112722. vorbis_info_floor0 *info=look->vi;
  112723. int j,k;
  112724. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112725. if(ampraw>0){ /* also handles the -1 out of data case */
  112726. long maxval=(1<<info->ampbits)-1;
  112727. float amp=(float)ampraw/maxval*info->ampdB;
  112728. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112729. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112730. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112731. codebook *b=ci->fullbooks+info->books[booknum];
  112732. float last=0.f;
  112733. /* the additional b->dim is a guard against any possible stack
  112734. smash; b->dim is provably more than we can overflow the
  112735. vector */
  112736. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112737. for(j=0;j<look->m;j+=b->dim)
  112738. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112739. for(j=0;j<look->m;){
  112740. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112741. last=lsp[j-1];
  112742. }
  112743. lsp[look->m]=amp;
  112744. return(lsp);
  112745. }
  112746. }
  112747. eop:
  112748. return(NULL);
  112749. }
  112750. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112751. void *memo,float *out){
  112752. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112753. vorbis_info_floor0 *info=look->vi;
  112754. floor0_map_lazy_init(vb,info,look);
  112755. if(memo){
  112756. float *lsp=(float *)memo;
  112757. float amp=lsp[look->m];
  112758. /* take the coefficients back to a spectral envelope curve */
  112759. vorbis_lsp_to_curve(out,
  112760. look->linearmap[vb->W],
  112761. look->n[vb->W],
  112762. look->ln,
  112763. lsp,look->m,amp,(float)info->ampdB);
  112764. return(1);
  112765. }
  112766. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112767. return(0);
  112768. }
  112769. /* export hooks */
  112770. vorbis_func_floor floor0_exportbundle={
  112771. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112772. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112773. };
  112774. #endif
  112775. /*** End of inlined file: floor0.c ***/
  112776. /*** Start of inlined file: floor1.c ***/
  112777. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112778. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112779. // tasks..
  112780. #if JUCE_MSVC
  112781. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112782. #endif
  112783. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112784. #if JUCE_USE_OGGVORBIS
  112785. #include <stdlib.h>
  112786. #include <string.h>
  112787. #include <math.h>
  112788. #include <stdio.h>
  112789. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112790. typedef struct {
  112791. int sorted_index[VIF_POSIT+2];
  112792. int forward_index[VIF_POSIT+2];
  112793. int reverse_index[VIF_POSIT+2];
  112794. int hineighbor[VIF_POSIT];
  112795. int loneighbor[VIF_POSIT];
  112796. int posts;
  112797. int n;
  112798. int quant_q;
  112799. vorbis_info_floor1 *vi;
  112800. long phrasebits;
  112801. long postbits;
  112802. long frames;
  112803. } vorbis_look_floor1;
  112804. typedef struct lsfit_acc{
  112805. long x0;
  112806. long x1;
  112807. long xa;
  112808. long ya;
  112809. long x2a;
  112810. long y2a;
  112811. long xya;
  112812. long an;
  112813. } lsfit_acc;
  112814. /***********************************************/
  112815. static void floor1_free_info(vorbis_info_floor *i){
  112816. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112817. if(info){
  112818. memset(info,0,sizeof(*info));
  112819. _ogg_free(info);
  112820. }
  112821. }
  112822. static void floor1_free_look(vorbis_look_floor *i){
  112823. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112824. if(look){
  112825. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112826. (float)look->phrasebits/look->frames,
  112827. (float)look->postbits/look->frames,
  112828. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112829. memset(look,0,sizeof(*look));
  112830. _ogg_free(look);
  112831. }
  112832. }
  112833. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112834. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112835. int j,k;
  112836. int count=0;
  112837. int rangebits;
  112838. int maxposit=info->postlist[1];
  112839. int maxclass=-1;
  112840. /* save out partitions */
  112841. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112842. for(j=0;j<info->partitions;j++){
  112843. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112844. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112845. }
  112846. /* save out partition classes */
  112847. for(j=0;j<maxclass+1;j++){
  112848. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112849. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112850. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112851. for(k=0;k<(1<<info->class_subs[j]);k++)
  112852. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112853. }
  112854. /* save out the post list */
  112855. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112856. oggpack_write(opb,ilog2(maxposit),4);
  112857. rangebits=ilog2(maxposit);
  112858. for(j=0,k=0;j<info->partitions;j++){
  112859. count+=info->class_dim[info->partitionclass[j]];
  112860. for(;k<count;k++)
  112861. oggpack_write(opb,info->postlist[k+2],rangebits);
  112862. }
  112863. }
  112864. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112865. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112866. int j,k,count=0,maxclass=-1,rangebits;
  112867. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112868. /* read partitions */
  112869. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112870. for(j=0;j<info->partitions;j++){
  112871. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112872. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112873. }
  112874. /* read partition classes */
  112875. for(j=0;j<maxclass+1;j++){
  112876. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112877. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112878. if(info->class_subs[j]<0)
  112879. goto err_out;
  112880. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112881. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112882. goto err_out;
  112883. for(k=0;k<(1<<info->class_subs[j]);k++){
  112884. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112885. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112886. goto err_out;
  112887. }
  112888. }
  112889. /* read the post list */
  112890. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112891. rangebits=oggpack_read(opb,4);
  112892. for(j=0,k=0;j<info->partitions;j++){
  112893. count+=info->class_dim[info->partitionclass[j]];
  112894. for(;k<count;k++){
  112895. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112896. if(t<0 || t>=(1<<rangebits))
  112897. goto err_out;
  112898. }
  112899. }
  112900. info->postlist[0]=0;
  112901. info->postlist[1]=1<<rangebits;
  112902. return(info);
  112903. err_out:
  112904. floor1_free_info(info);
  112905. return(NULL);
  112906. }
  112907. static int icomp(const void *a,const void *b){
  112908. return(**(int **)a-**(int **)b);
  112909. }
  112910. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112911. vorbis_info_floor *in){
  112912. int *sortpointer[VIF_POSIT+2];
  112913. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112914. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112915. int i,j,n=0;
  112916. look->vi=info;
  112917. look->n=info->postlist[1];
  112918. /* we drop each position value in-between already decoded values,
  112919. and use linear interpolation to predict each new value past the
  112920. edges. The positions are read in the order of the position
  112921. list... we precompute the bounding positions in the lookup. Of
  112922. course, the neighbors can change (if a position is declined), but
  112923. this is an initial mapping */
  112924. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112925. n+=2;
  112926. look->posts=n;
  112927. /* also store a sorted position index */
  112928. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112929. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112930. /* points from sort order back to range number */
  112931. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112932. /* points from range order to sorted position */
  112933. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112934. /* we actually need the post values too */
  112935. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112936. /* quantize values to multiplier spec */
  112937. switch(info->mult){
  112938. case 1: /* 1024 -> 256 */
  112939. look->quant_q=256;
  112940. break;
  112941. case 2: /* 1024 -> 128 */
  112942. look->quant_q=128;
  112943. break;
  112944. case 3: /* 1024 -> 86 */
  112945. look->quant_q=86;
  112946. break;
  112947. case 4: /* 1024 -> 64 */
  112948. look->quant_q=64;
  112949. break;
  112950. }
  112951. /* discover our neighbors for decode where we don't use fit flags
  112952. (that would push the neighbors outward) */
  112953. for(i=0;i<n-2;i++){
  112954. int lo=0;
  112955. int hi=1;
  112956. int lx=0;
  112957. int hx=look->n;
  112958. int currentx=info->postlist[i+2];
  112959. for(j=0;j<i+2;j++){
  112960. int x=info->postlist[j];
  112961. if(x>lx && x<currentx){
  112962. lo=j;
  112963. lx=x;
  112964. }
  112965. if(x<hx && x>currentx){
  112966. hi=j;
  112967. hx=x;
  112968. }
  112969. }
  112970. look->loneighbor[i]=lo;
  112971. look->hineighbor[i]=hi;
  112972. }
  112973. return(look);
  112974. }
  112975. static int render_point(int x0,int x1,int y0,int y1,int x){
  112976. y0&=0x7fff; /* mask off flag */
  112977. y1&=0x7fff;
  112978. {
  112979. int dy=y1-y0;
  112980. int adx=x1-x0;
  112981. int ady=abs(dy);
  112982. int err=ady*(x-x0);
  112983. int off=err/adx;
  112984. if(dy<0)return(y0-off);
  112985. return(y0+off);
  112986. }
  112987. }
  112988. static int vorbis_dBquant(const float *x){
  112989. int i= *x*7.3142857f+1023.5f;
  112990. if(i>1023)return(1023);
  112991. if(i<0)return(0);
  112992. return i;
  112993. }
  112994. static float FLOOR1_fromdB_LOOKUP[256]={
  112995. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112996. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112997. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112998. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112999. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113000. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113001. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113002. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113003. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113004. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113005. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113006. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113007. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113008. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113009. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113010. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113011. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113012. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113013. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113014. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113015. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113016. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113017. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113018. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113019. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113020. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113021. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113022. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113023. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113024. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113025. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113026. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113027. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113028. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113029. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113030. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113031. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113032. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113033. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113034. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113035. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113036. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113037. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113038. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113039. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113040. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113041. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113042. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113043. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113044. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113045. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113046. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113047. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113048. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113049. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113050. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113051. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113052. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113053. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113054. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113055. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113056. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113057. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113058. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113059. };
  113060. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113061. int dy=y1-y0;
  113062. int adx=x1-x0;
  113063. int ady=abs(dy);
  113064. int base=dy/adx;
  113065. int sy=(dy<0?base-1:base+1);
  113066. int x=x0;
  113067. int y=y0;
  113068. int err=0;
  113069. ady-=abs(base*adx);
  113070. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113071. while(++x<x1){
  113072. err=err+ady;
  113073. if(err>=adx){
  113074. err-=adx;
  113075. y+=sy;
  113076. }else{
  113077. y+=base;
  113078. }
  113079. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113080. }
  113081. }
  113082. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113083. int dy=y1-y0;
  113084. int adx=x1-x0;
  113085. int ady=abs(dy);
  113086. int base=dy/adx;
  113087. int sy=(dy<0?base-1:base+1);
  113088. int x=x0;
  113089. int y=y0;
  113090. int err=0;
  113091. ady-=abs(base*adx);
  113092. d[x]=y;
  113093. while(++x<x1){
  113094. err=err+ady;
  113095. if(err>=adx){
  113096. err-=adx;
  113097. y+=sy;
  113098. }else{
  113099. y+=base;
  113100. }
  113101. d[x]=y;
  113102. }
  113103. }
  113104. /* the floor has already been filtered to only include relevant sections */
  113105. static int accumulate_fit(const float *flr,const float *mdct,
  113106. int x0, int x1,lsfit_acc *a,
  113107. int n,vorbis_info_floor1 *info){
  113108. long i;
  113109. 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;
  113110. memset(a,0,sizeof(*a));
  113111. a->x0=x0;
  113112. a->x1=x1;
  113113. if(x1>=n)x1=n-1;
  113114. for(i=x0;i<=x1;i++){
  113115. int quantized=vorbis_dBquant(flr+i);
  113116. if(quantized){
  113117. if(mdct[i]+info->twofitatten>=flr[i]){
  113118. xa += i;
  113119. ya += quantized;
  113120. x2a += i*i;
  113121. y2a += quantized*quantized;
  113122. xya += i*quantized;
  113123. na++;
  113124. }else{
  113125. xb += i;
  113126. yb += quantized;
  113127. x2b += i*i;
  113128. y2b += quantized*quantized;
  113129. xyb += i*quantized;
  113130. nb++;
  113131. }
  113132. }
  113133. }
  113134. xb+=xa;
  113135. yb+=ya;
  113136. x2b+=x2a;
  113137. y2b+=y2a;
  113138. xyb+=xya;
  113139. nb+=na;
  113140. /* weight toward the actually used frequencies if we meet the threshhold */
  113141. {
  113142. int weight=nb*info->twofitweight/(na+1);
  113143. a->xa=xa*weight+xb;
  113144. a->ya=ya*weight+yb;
  113145. a->x2a=x2a*weight+x2b;
  113146. a->y2a=y2a*weight+y2b;
  113147. a->xya=xya*weight+xyb;
  113148. a->an=na*weight+nb;
  113149. }
  113150. return(na);
  113151. }
  113152. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113153. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113154. long x0=a[0].x0;
  113155. long x1=a[fits-1].x1;
  113156. for(i=0;i<fits;i++){
  113157. x+=a[i].xa;
  113158. y+=a[i].ya;
  113159. x2+=a[i].x2a;
  113160. y2+=a[i].y2a;
  113161. xy+=a[i].xya;
  113162. an+=a[i].an;
  113163. }
  113164. if(*y0>=0){
  113165. x+= x0;
  113166. y+= *y0;
  113167. x2+= x0 * x0;
  113168. y2+= *y0 * *y0;
  113169. xy+= *y0 * x0;
  113170. an++;
  113171. }
  113172. if(*y1>=0){
  113173. x+= x1;
  113174. y+= *y1;
  113175. x2+= x1 * x1;
  113176. y2+= *y1 * *y1;
  113177. xy+= *y1 * x1;
  113178. an++;
  113179. }
  113180. if(an){
  113181. /* need 64 bit multiplies, which C doesn't give portably as int */
  113182. double fx=x;
  113183. double fy=y;
  113184. double fx2=x2;
  113185. double fxy=xy;
  113186. double denom=1./(an*fx2-fx*fx);
  113187. double a=(fy*fx2-fxy*fx)*denom;
  113188. double b=(an*fxy-fx*fy)*denom;
  113189. *y0=rint(a+b*x0);
  113190. *y1=rint(a+b*x1);
  113191. /* limit to our range! */
  113192. if(*y0>1023)*y0=1023;
  113193. if(*y1>1023)*y1=1023;
  113194. if(*y0<0)*y0=0;
  113195. if(*y1<0)*y1=0;
  113196. }else{
  113197. *y0=0;
  113198. *y1=0;
  113199. }
  113200. }
  113201. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113202. long y=0;
  113203. int i;
  113204. for(i=0;i<fits && y==0;i++)
  113205. y+=a[i].ya;
  113206. *y0=*y1=y;
  113207. }*/
  113208. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113209. const float *mdct,
  113210. vorbis_info_floor1 *info){
  113211. int dy=y1-y0;
  113212. int adx=x1-x0;
  113213. int ady=abs(dy);
  113214. int base=dy/adx;
  113215. int sy=(dy<0?base-1:base+1);
  113216. int x=x0;
  113217. int y=y0;
  113218. int err=0;
  113219. int val=vorbis_dBquant(mask+x);
  113220. int mse=0;
  113221. int n=0;
  113222. ady-=abs(base*adx);
  113223. mse=(y-val);
  113224. mse*=mse;
  113225. n++;
  113226. if(mdct[x]+info->twofitatten>=mask[x]){
  113227. if(y+info->maxover<val)return(1);
  113228. if(y-info->maxunder>val)return(1);
  113229. }
  113230. while(++x<x1){
  113231. err=err+ady;
  113232. if(err>=adx){
  113233. err-=adx;
  113234. y+=sy;
  113235. }else{
  113236. y+=base;
  113237. }
  113238. val=vorbis_dBquant(mask+x);
  113239. mse+=((y-val)*(y-val));
  113240. n++;
  113241. if(mdct[x]+info->twofitatten>=mask[x]){
  113242. if(val){
  113243. if(y+info->maxover<val)return(1);
  113244. if(y-info->maxunder>val)return(1);
  113245. }
  113246. }
  113247. }
  113248. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113249. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113250. if(mse/n>info->maxerr)return(1);
  113251. return(0);
  113252. }
  113253. static int post_Y(int *A,int *B,int pos){
  113254. if(A[pos]<0)
  113255. return B[pos];
  113256. if(B[pos]<0)
  113257. return A[pos];
  113258. return (A[pos]+B[pos])>>1;
  113259. }
  113260. int *floor1_fit(vorbis_block *vb,void *look_,
  113261. const float *logmdct, /* in */
  113262. const float *logmask){
  113263. long i,j;
  113264. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113265. vorbis_info_floor1 *info=look->vi;
  113266. long n=look->n;
  113267. long posts=look->posts;
  113268. long nonzero=0;
  113269. lsfit_acc fits[VIF_POSIT+1];
  113270. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113271. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113272. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113273. int hineighbor[VIF_POSIT+2];
  113274. int *output=NULL;
  113275. int memo[VIF_POSIT+2];
  113276. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113277. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113278. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113279. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113280. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113281. /* quantize the relevant floor points and collect them into line fit
  113282. structures (one per minimal division) at the same time */
  113283. if(posts==0){
  113284. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113285. }else{
  113286. for(i=0;i<posts-1;i++)
  113287. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113288. look->sorted_index[i+1],fits+i,
  113289. n,info);
  113290. }
  113291. if(nonzero){
  113292. /* start by fitting the implicit base case.... */
  113293. int y0=-200;
  113294. int y1=-200;
  113295. fit_line(fits,posts-1,&y0,&y1);
  113296. fit_valueA[0]=y0;
  113297. fit_valueB[0]=y0;
  113298. fit_valueB[1]=y1;
  113299. fit_valueA[1]=y1;
  113300. /* Non degenerate case */
  113301. /* start progressive splitting. This is a greedy, non-optimal
  113302. algorithm, but simple and close enough to the best
  113303. answer. */
  113304. for(i=2;i<posts;i++){
  113305. int sortpos=look->reverse_index[i];
  113306. int ln=loneighbor[sortpos];
  113307. int hn=hineighbor[sortpos];
  113308. /* eliminate repeat searches of a particular range with a memo */
  113309. if(memo[ln]!=hn){
  113310. /* haven't performed this error search yet */
  113311. int lsortpos=look->reverse_index[ln];
  113312. int hsortpos=look->reverse_index[hn];
  113313. memo[ln]=hn;
  113314. {
  113315. /* A note: we want to bound/minimize *local*, not global, error */
  113316. int lx=info->postlist[ln];
  113317. int hx=info->postlist[hn];
  113318. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113319. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113320. if(ly==-1 || hy==-1){
  113321. exit(1);
  113322. }
  113323. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113324. /* outside error bounds/begin search area. Split it. */
  113325. int ly0=-200;
  113326. int ly1=-200;
  113327. int hy0=-200;
  113328. int hy1=-200;
  113329. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113330. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113331. /* store new edge values */
  113332. fit_valueB[ln]=ly0;
  113333. if(ln==0)fit_valueA[ln]=ly0;
  113334. fit_valueA[i]=ly1;
  113335. fit_valueB[i]=hy0;
  113336. fit_valueA[hn]=hy1;
  113337. if(hn==1)fit_valueB[hn]=hy1;
  113338. if(ly1>=0 || hy0>=0){
  113339. /* store new neighbor values */
  113340. for(j=sortpos-1;j>=0;j--)
  113341. if(hineighbor[j]==hn)
  113342. hineighbor[j]=i;
  113343. else
  113344. break;
  113345. for(j=sortpos+1;j<posts;j++)
  113346. if(loneighbor[j]==ln)
  113347. loneighbor[j]=i;
  113348. else
  113349. break;
  113350. }
  113351. }else{
  113352. fit_valueA[i]=-200;
  113353. fit_valueB[i]=-200;
  113354. }
  113355. }
  113356. }
  113357. }
  113358. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113359. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113360. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113361. /* fill in posts marked as not using a fit; we will zero
  113362. back out to 'unused' when encoding them so long as curve
  113363. interpolation doesn't force them into use */
  113364. for(i=2;i<posts;i++){
  113365. int ln=look->loneighbor[i-2];
  113366. int hn=look->hineighbor[i-2];
  113367. int x0=info->postlist[ln];
  113368. int x1=info->postlist[hn];
  113369. int y0=output[ln];
  113370. int y1=output[hn];
  113371. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113372. int vx=post_Y(fit_valueA,fit_valueB,i);
  113373. if(vx>=0 && predicted!=vx){
  113374. output[i]=vx;
  113375. }else{
  113376. output[i]= predicted|0x8000;
  113377. }
  113378. }
  113379. }
  113380. return(output);
  113381. }
  113382. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113383. int *A,int *B,
  113384. int del){
  113385. long i;
  113386. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113387. long posts=look->posts;
  113388. int *output=NULL;
  113389. if(A && B){
  113390. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113391. for(i=0;i<posts;i++){
  113392. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113393. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113394. }
  113395. }
  113396. return(output);
  113397. }
  113398. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113399. void*look_,
  113400. int *post,int *ilogmask){
  113401. long i,j;
  113402. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113403. vorbis_info_floor1 *info=look->vi;
  113404. long posts=look->posts;
  113405. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113406. int out[VIF_POSIT+2];
  113407. static_codebook **sbooks=ci->book_param;
  113408. codebook *books=ci->fullbooks;
  113409. static long seq=0;
  113410. /* quantize values to multiplier spec */
  113411. if(post){
  113412. for(i=0;i<posts;i++){
  113413. int val=post[i]&0x7fff;
  113414. switch(info->mult){
  113415. case 1: /* 1024 -> 256 */
  113416. val>>=2;
  113417. break;
  113418. case 2: /* 1024 -> 128 */
  113419. val>>=3;
  113420. break;
  113421. case 3: /* 1024 -> 86 */
  113422. val/=12;
  113423. break;
  113424. case 4: /* 1024 -> 64 */
  113425. val>>=4;
  113426. break;
  113427. }
  113428. post[i]=val | (post[i]&0x8000);
  113429. }
  113430. out[0]=post[0];
  113431. out[1]=post[1];
  113432. /* find prediction values for each post and subtract them */
  113433. for(i=2;i<posts;i++){
  113434. int ln=look->loneighbor[i-2];
  113435. int hn=look->hineighbor[i-2];
  113436. int x0=info->postlist[ln];
  113437. int x1=info->postlist[hn];
  113438. int y0=post[ln];
  113439. int y1=post[hn];
  113440. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113441. if((post[i]&0x8000) || (predicted==post[i])){
  113442. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113443. in interpolation */
  113444. out[i]=0;
  113445. }else{
  113446. int headroom=(look->quant_q-predicted<predicted?
  113447. look->quant_q-predicted:predicted);
  113448. int val=post[i]-predicted;
  113449. /* at this point the 'deviation' value is in the range +/- max
  113450. range, but the real, unique range can always be mapped to
  113451. only [0-maxrange). So we want to wrap the deviation into
  113452. this limited range, but do it in the way that least screws
  113453. an essentially gaussian probability distribution. */
  113454. if(val<0)
  113455. if(val<-headroom)
  113456. val=headroom-val-1;
  113457. else
  113458. val=-1-(val<<1);
  113459. else
  113460. if(val>=headroom)
  113461. val= val+headroom;
  113462. else
  113463. val<<=1;
  113464. out[i]=val;
  113465. post[ln]&=0x7fff;
  113466. post[hn]&=0x7fff;
  113467. }
  113468. }
  113469. /* we have everything we need. pack it out */
  113470. /* mark nontrivial floor */
  113471. oggpack_write(opb,1,1);
  113472. /* beginning/end post */
  113473. look->frames++;
  113474. look->postbits+=ilog(look->quant_q-1)*2;
  113475. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113476. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113477. /* partition by partition */
  113478. for(i=0,j=2;i<info->partitions;i++){
  113479. int classx=info->partitionclass[i];
  113480. int cdim=info->class_dim[classx];
  113481. int csubbits=info->class_subs[classx];
  113482. int csub=1<<csubbits;
  113483. int bookas[8]={0,0,0,0,0,0,0,0};
  113484. int cval=0;
  113485. int cshift=0;
  113486. int k,l;
  113487. /* generate the partition's first stage cascade value */
  113488. if(csubbits){
  113489. int maxval[8];
  113490. for(k=0;k<csub;k++){
  113491. int booknum=info->class_subbook[classx][k];
  113492. if(booknum<0){
  113493. maxval[k]=1;
  113494. }else{
  113495. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113496. }
  113497. }
  113498. for(k=0;k<cdim;k++){
  113499. for(l=0;l<csub;l++){
  113500. int val=out[j+k];
  113501. if(val<maxval[l]){
  113502. bookas[k]=l;
  113503. break;
  113504. }
  113505. }
  113506. cval|= bookas[k]<<cshift;
  113507. cshift+=csubbits;
  113508. }
  113509. /* write it */
  113510. look->phrasebits+=
  113511. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113512. #ifdef TRAIN_FLOOR1
  113513. {
  113514. FILE *of;
  113515. char buffer[80];
  113516. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113517. vb->pcmend/2,posts-2,class);
  113518. of=fopen(buffer,"a");
  113519. fprintf(of,"%d\n",cval);
  113520. fclose(of);
  113521. }
  113522. #endif
  113523. }
  113524. /* write post values */
  113525. for(k=0;k<cdim;k++){
  113526. int book=info->class_subbook[classx][bookas[k]];
  113527. if(book>=0){
  113528. /* hack to allow training with 'bad' books */
  113529. if(out[j+k]<(books+book)->entries)
  113530. look->postbits+=vorbis_book_encode(books+book,
  113531. out[j+k],opb);
  113532. /*else
  113533. fprintf(stderr,"+!");*/
  113534. #ifdef TRAIN_FLOOR1
  113535. {
  113536. FILE *of;
  113537. char buffer[80];
  113538. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113539. vb->pcmend/2,posts-2,class,bookas[k]);
  113540. of=fopen(buffer,"a");
  113541. fprintf(of,"%d\n",out[j+k]);
  113542. fclose(of);
  113543. }
  113544. #endif
  113545. }
  113546. }
  113547. j+=cdim;
  113548. }
  113549. {
  113550. /* generate quantized floor equivalent to what we'd unpack in decode */
  113551. /* render the lines */
  113552. int hx=0;
  113553. int lx=0;
  113554. int ly=post[0]*info->mult;
  113555. for(j=1;j<look->posts;j++){
  113556. int current=look->forward_index[j];
  113557. int hy=post[current]&0x7fff;
  113558. if(hy==post[current]){
  113559. hy*=info->mult;
  113560. hx=info->postlist[current];
  113561. render_line0(lx,hx,ly,hy,ilogmask);
  113562. lx=hx;
  113563. ly=hy;
  113564. }
  113565. }
  113566. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113567. seq++;
  113568. return(1);
  113569. }
  113570. }else{
  113571. oggpack_write(opb,0,1);
  113572. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113573. seq++;
  113574. return(0);
  113575. }
  113576. }
  113577. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113578. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113579. vorbis_info_floor1 *info=look->vi;
  113580. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113581. int i,j,k;
  113582. codebook *books=ci->fullbooks;
  113583. /* unpack wrapped/predicted values from stream */
  113584. if(oggpack_read(&vb->opb,1)==1){
  113585. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113586. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113587. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113588. /* partition by partition */
  113589. for(i=0,j=2;i<info->partitions;i++){
  113590. int classx=info->partitionclass[i];
  113591. int cdim=info->class_dim[classx];
  113592. int csubbits=info->class_subs[classx];
  113593. int csub=1<<csubbits;
  113594. int cval=0;
  113595. /* decode the partition's first stage cascade value */
  113596. if(csubbits){
  113597. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113598. if(cval==-1)goto eop;
  113599. }
  113600. for(k=0;k<cdim;k++){
  113601. int book=info->class_subbook[classx][cval&(csub-1)];
  113602. cval>>=csubbits;
  113603. if(book>=0){
  113604. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113605. goto eop;
  113606. }else{
  113607. fit_value[j+k]=0;
  113608. }
  113609. }
  113610. j+=cdim;
  113611. }
  113612. /* unwrap positive values and reconsitute via linear interpolation */
  113613. for(i=2;i<look->posts;i++){
  113614. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113615. info->postlist[look->hineighbor[i-2]],
  113616. fit_value[look->loneighbor[i-2]],
  113617. fit_value[look->hineighbor[i-2]],
  113618. info->postlist[i]);
  113619. int hiroom=look->quant_q-predicted;
  113620. int loroom=predicted;
  113621. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113622. int val=fit_value[i];
  113623. if(val){
  113624. if(val>=room){
  113625. if(hiroom>loroom){
  113626. val = val-loroom;
  113627. }else{
  113628. val = -1-(val-hiroom);
  113629. }
  113630. }else{
  113631. if(val&1){
  113632. val= -((val+1)>>1);
  113633. }else{
  113634. val>>=1;
  113635. }
  113636. }
  113637. fit_value[i]=val+predicted;
  113638. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113639. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113640. }else{
  113641. fit_value[i]=predicted|0x8000;
  113642. }
  113643. }
  113644. return(fit_value);
  113645. }
  113646. eop:
  113647. return(NULL);
  113648. }
  113649. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113650. float *out){
  113651. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113652. vorbis_info_floor1 *info=look->vi;
  113653. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113654. int n=ci->blocksizes[vb->W]/2;
  113655. int j;
  113656. if(memo){
  113657. /* render the lines */
  113658. int *fit_value=(int *)memo;
  113659. int hx=0;
  113660. int lx=0;
  113661. int ly=fit_value[0]*info->mult;
  113662. for(j=1;j<look->posts;j++){
  113663. int current=look->forward_index[j];
  113664. int hy=fit_value[current]&0x7fff;
  113665. if(hy==fit_value[current]){
  113666. hy*=info->mult;
  113667. hx=info->postlist[current];
  113668. render_line(lx,hx,ly,hy,out);
  113669. lx=hx;
  113670. ly=hy;
  113671. }
  113672. }
  113673. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113674. return(1);
  113675. }
  113676. memset(out,0,sizeof(*out)*n);
  113677. return(0);
  113678. }
  113679. /* export hooks */
  113680. vorbis_func_floor floor1_exportbundle={
  113681. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113682. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113683. };
  113684. #endif
  113685. /*** End of inlined file: floor1.c ***/
  113686. /*** Start of inlined file: info.c ***/
  113687. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113688. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113689. // tasks..
  113690. #if JUCE_MSVC
  113691. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113692. #endif
  113693. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113694. #if JUCE_USE_OGGVORBIS
  113695. /* general handling of the header and the vorbis_info structure (and
  113696. substructures) */
  113697. #include <stdlib.h>
  113698. #include <string.h>
  113699. #include <ctype.h>
  113700. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113701. while(bytes--){
  113702. oggpack_write(o,*s++,8);
  113703. }
  113704. }
  113705. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113706. while(bytes--){
  113707. *buf++=oggpack_read(o,8);
  113708. }
  113709. }
  113710. void vorbis_comment_init(vorbis_comment *vc){
  113711. memset(vc,0,sizeof(*vc));
  113712. }
  113713. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113714. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113715. (vc->comments+2)*sizeof(*vc->user_comments));
  113716. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113717. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113718. vc->comment_lengths[vc->comments]=strlen(comment);
  113719. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113720. strcpy(vc->user_comments[vc->comments], comment);
  113721. vc->comments++;
  113722. vc->user_comments[vc->comments]=NULL;
  113723. }
  113724. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113725. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113726. strcpy(comment, tag);
  113727. strcat(comment, "=");
  113728. strcat(comment, contents);
  113729. vorbis_comment_add(vc, comment);
  113730. }
  113731. /* This is more or less the same as strncasecmp - but that doesn't exist
  113732. * everywhere, and this is a fairly trivial function, so we include it */
  113733. static int tagcompare(const char *s1, const char *s2, int n){
  113734. int c=0;
  113735. while(c < n){
  113736. if(toupper(s1[c]) != toupper(s2[c]))
  113737. return !0;
  113738. c++;
  113739. }
  113740. return 0;
  113741. }
  113742. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113743. long i;
  113744. int found = 0;
  113745. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113746. char *fulltag = (char*)alloca(taglen+ 1);
  113747. strcpy(fulltag, tag);
  113748. strcat(fulltag, "=");
  113749. for(i=0;i<vc->comments;i++){
  113750. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113751. if(count == found)
  113752. /* We return a pointer to the data, not a copy */
  113753. return vc->user_comments[i] + taglen;
  113754. else
  113755. found++;
  113756. }
  113757. }
  113758. return NULL; /* didn't find anything */
  113759. }
  113760. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113761. int i,count=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. count++;
  113769. }
  113770. return count;
  113771. }
  113772. void vorbis_comment_clear(vorbis_comment *vc){
  113773. if(vc){
  113774. long i;
  113775. for(i=0;i<vc->comments;i++)
  113776. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113777. if(vc->user_comments)_ogg_free(vc->user_comments);
  113778. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113779. if(vc->vendor)_ogg_free(vc->vendor);
  113780. }
  113781. memset(vc,0,sizeof(*vc));
  113782. }
  113783. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113784. They may be equal, but short will never ge greater than long */
  113785. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113786. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113787. return ci ? ci->blocksizes[zo] : -1;
  113788. }
  113789. /* used by synthesis, which has a full, alloced vi */
  113790. void vorbis_info_init(vorbis_info *vi){
  113791. memset(vi,0,sizeof(*vi));
  113792. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113793. }
  113794. void vorbis_info_clear(vorbis_info *vi){
  113795. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113796. int i;
  113797. if(ci){
  113798. for(i=0;i<ci->modes;i++)
  113799. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113800. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113801. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113802. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113803. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113804. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113805. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113806. for(i=0;i<ci->books;i++){
  113807. if(ci->book_param[i]){
  113808. /* knows if the book was not alloced */
  113809. vorbis_staticbook_destroy(ci->book_param[i]);
  113810. }
  113811. if(ci->fullbooks)
  113812. vorbis_book_clear(ci->fullbooks+i);
  113813. }
  113814. if(ci->fullbooks)
  113815. _ogg_free(ci->fullbooks);
  113816. for(i=0;i<ci->psys;i++)
  113817. _vi_psy_free(ci->psy_param[i]);
  113818. _ogg_free(ci);
  113819. }
  113820. memset(vi,0,sizeof(*vi));
  113821. }
  113822. /* Header packing/unpacking ********************************************/
  113823. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113824. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113825. if(!ci)return(OV_EFAULT);
  113826. vi->version=oggpack_read(opb,32);
  113827. if(vi->version!=0)return(OV_EVERSION);
  113828. vi->channels=oggpack_read(opb,8);
  113829. vi->rate=oggpack_read(opb,32);
  113830. vi->bitrate_upper=oggpack_read(opb,32);
  113831. vi->bitrate_nominal=oggpack_read(opb,32);
  113832. vi->bitrate_lower=oggpack_read(opb,32);
  113833. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113834. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113835. if(vi->rate<1)goto err_out;
  113836. if(vi->channels<1)goto err_out;
  113837. if(ci->blocksizes[0]<8)goto err_out;
  113838. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113839. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113840. return(0);
  113841. err_out:
  113842. vorbis_info_clear(vi);
  113843. return(OV_EBADHEADER);
  113844. }
  113845. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113846. int i;
  113847. int vendorlen=oggpack_read(opb,32);
  113848. if(vendorlen<0)goto err_out;
  113849. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113850. _v_readstring(opb,vc->vendor,vendorlen);
  113851. vc->comments=oggpack_read(opb,32);
  113852. if(vc->comments<0)goto err_out;
  113853. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113854. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113855. for(i=0;i<vc->comments;i++){
  113856. int len=oggpack_read(opb,32);
  113857. if(len<0)goto err_out;
  113858. vc->comment_lengths[i]=len;
  113859. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113860. _v_readstring(opb,vc->user_comments[i],len);
  113861. }
  113862. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113863. return(0);
  113864. err_out:
  113865. vorbis_comment_clear(vc);
  113866. return(OV_EBADHEADER);
  113867. }
  113868. /* all of the real encoding details are here. The modes, books,
  113869. everything */
  113870. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113871. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113872. int i;
  113873. if(!ci)return(OV_EFAULT);
  113874. /* codebooks */
  113875. ci->books=oggpack_read(opb,8)+1;
  113876. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113877. for(i=0;i<ci->books;i++){
  113878. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113879. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113880. }
  113881. /* time backend settings; hooks are unused */
  113882. {
  113883. int times=oggpack_read(opb,6)+1;
  113884. for(i=0;i<times;i++){
  113885. int test=oggpack_read(opb,16);
  113886. if(test<0 || test>=VI_TIMEB)goto err_out;
  113887. }
  113888. }
  113889. /* floor backend settings */
  113890. ci->floors=oggpack_read(opb,6)+1;
  113891. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113892. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113893. for(i=0;i<ci->floors;i++){
  113894. ci->floor_type[i]=oggpack_read(opb,16);
  113895. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113896. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113897. if(!ci->floor_param[i])goto err_out;
  113898. }
  113899. /* residue backend settings */
  113900. ci->residues=oggpack_read(opb,6)+1;
  113901. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113902. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113903. for(i=0;i<ci->residues;i++){
  113904. ci->residue_type[i]=oggpack_read(opb,16);
  113905. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113906. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113907. if(!ci->residue_param[i])goto err_out;
  113908. }
  113909. /* map backend settings */
  113910. ci->maps=oggpack_read(opb,6)+1;
  113911. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113912. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113913. for(i=0;i<ci->maps;i++){
  113914. ci->map_type[i]=oggpack_read(opb,16);
  113915. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113916. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113917. if(!ci->map_param[i])goto err_out;
  113918. }
  113919. /* mode settings */
  113920. ci->modes=oggpack_read(opb,6)+1;
  113921. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113922. for(i=0;i<ci->modes;i++){
  113923. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113924. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113925. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113926. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113927. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113928. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113929. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113930. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113931. }
  113932. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113933. return(0);
  113934. err_out:
  113935. vorbis_info_clear(vi);
  113936. return(OV_EBADHEADER);
  113937. }
  113938. /* The Vorbis header is in three packets; the initial small packet in
  113939. the first page that identifies basic parameters, a second packet
  113940. with bitstream comments and a third packet that holds the
  113941. codebook. */
  113942. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113943. oggpack_buffer opb;
  113944. if(op){
  113945. oggpack_readinit(&opb,op->packet,op->bytes);
  113946. /* Which of the three types of header is this? */
  113947. /* Also verify header-ness, vorbis */
  113948. {
  113949. char buffer[6];
  113950. int packtype=oggpack_read(&opb,8);
  113951. memset(buffer,0,6);
  113952. _v_readstring(&opb,buffer,6);
  113953. if(memcmp(buffer,"vorbis",6)){
  113954. /* not a vorbis header */
  113955. return(OV_ENOTVORBIS);
  113956. }
  113957. switch(packtype){
  113958. case 0x01: /* least significant *bit* is read first */
  113959. if(!op->b_o_s){
  113960. /* Not the initial packet */
  113961. return(OV_EBADHEADER);
  113962. }
  113963. if(vi->rate!=0){
  113964. /* previously initialized info header */
  113965. return(OV_EBADHEADER);
  113966. }
  113967. return(_vorbis_unpack_info(vi,&opb));
  113968. case 0x03: /* least significant *bit* is read first */
  113969. if(vi->rate==0){
  113970. /* um... we didn't get the initial header */
  113971. return(OV_EBADHEADER);
  113972. }
  113973. return(_vorbis_unpack_comment(vc,&opb));
  113974. case 0x05: /* least significant *bit* is read first */
  113975. if(vi->rate==0 || vc->vendor==NULL){
  113976. /* um... we didn;t get the initial header or comments yet */
  113977. return(OV_EBADHEADER);
  113978. }
  113979. return(_vorbis_unpack_books(vi,&opb));
  113980. default:
  113981. /* Not a valid vorbis header type */
  113982. return(OV_EBADHEADER);
  113983. break;
  113984. }
  113985. }
  113986. }
  113987. return(OV_EBADHEADER);
  113988. }
  113989. /* pack side **********************************************************/
  113990. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113991. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113992. if(!ci)return(OV_EFAULT);
  113993. /* preamble */
  113994. oggpack_write(opb,0x01,8);
  113995. _v_writestring(opb,"vorbis", 6);
  113996. /* basic information about the stream */
  113997. oggpack_write(opb,0x00,32);
  113998. oggpack_write(opb,vi->channels,8);
  113999. oggpack_write(opb,vi->rate,32);
  114000. oggpack_write(opb,vi->bitrate_upper,32);
  114001. oggpack_write(opb,vi->bitrate_nominal,32);
  114002. oggpack_write(opb,vi->bitrate_lower,32);
  114003. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114004. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114005. oggpack_write(opb,1,1);
  114006. return(0);
  114007. }
  114008. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114009. char temp[]="Xiph.Org libVorbis I 20050304";
  114010. int bytes = strlen(temp);
  114011. /* preamble */
  114012. oggpack_write(opb,0x03,8);
  114013. _v_writestring(opb,"vorbis", 6);
  114014. /* vendor */
  114015. oggpack_write(opb,bytes,32);
  114016. _v_writestring(opb,temp, bytes);
  114017. /* comments */
  114018. oggpack_write(opb,vc->comments,32);
  114019. if(vc->comments){
  114020. int i;
  114021. for(i=0;i<vc->comments;i++){
  114022. if(vc->user_comments[i]){
  114023. oggpack_write(opb,vc->comment_lengths[i],32);
  114024. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114025. }else{
  114026. oggpack_write(opb,0,32);
  114027. }
  114028. }
  114029. }
  114030. oggpack_write(opb,1,1);
  114031. return(0);
  114032. }
  114033. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114034. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114035. int i;
  114036. if(!ci)return(OV_EFAULT);
  114037. oggpack_write(opb,0x05,8);
  114038. _v_writestring(opb,"vorbis", 6);
  114039. /* books */
  114040. oggpack_write(opb,ci->books-1,8);
  114041. for(i=0;i<ci->books;i++)
  114042. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114043. /* times; hook placeholders */
  114044. oggpack_write(opb,0,6);
  114045. oggpack_write(opb,0,16);
  114046. /* floors */
  114047. oggpack_write(opb,ci->floors-1,6);
  114048. for(i=0;i<ci->floors;i++){
  114049. oggpack_write(opb,ci->floor_type[i],16);
  114050. if(_floor_P[ci->floor_type[i]]->pack)
  114051. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114052. else
  114053. goto err_out;
  114054. }
  114055. /* residues */
  114056. oggpack_write(opb,ci->residues-1,6);
  114057. for(i=0;i<ci->residues;i++){
  114058. oggpack_write(opb,ci->residue_type[i],16);
  114059. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114060. }
  114061. /* maps */
  114062. oggpack_write(opb,ci->maps-1,6);
  114063. for(i=0;i<ci->maps;i++){
  114064. oggpack_write(opb,ci->map_type[i],16);
  114065. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114066. }
  114067. /* modes */
  114068. oggpack_write(opb,ci->modes-1,6);
  114069. for(i=0;i<ci->modes;i++){
  114070. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114071. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114072. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114073. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114074. }
  114075. oggpack_write(opb,1,1);
  114076. return(0);
  114077. err_out:
  114078. return(-1);
  114079. }
  114080. int vorbis_commentheader_out(vorbis_comment *vc,
  114081. ogg_packet *op){
  114082. oggpack_buffer opb;
  114083. oggpack_writeinit(&opb);
  114084. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114085. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114086. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114087. op->bytes=oggpack_bytes(&opb);
  114088. op->b_o_s=0;
  114089. op->e_o_s=0;
  114090. op->granulepos=0;
  114091. op->packetno=1;
  114092. return 0;
  114093. }
  114094. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114095. vorbis_comment *vc,
  114096. ogg_packet *op,
  114097. ogg_packet *op_comm,
  114098. ogg_packet *op_code){
  114099. int ret=OV_EIMPL;
  114100. vorbis_info *vi=v->vi;
  114101. oggpack_buffer opb;
  114102. private_state *b=(private_state*)v->backend_state;
  114103. if(!b){
  114104. ret=OV_EFAULT;
  114105. goto err_out;
  114106. }
  114107. /* first header packet **********************************************/
  114108. oggpack_writeinit(&opb);
  114109. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114110. /* build the packet */
  114111. if(b->header)_ogg_free(b->header);
  114112. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114113. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114114. op->packet=b->header;
  114115. op->bytes=oggpack_bytes(&opb);
  114116. op->b_o_s=1;
  114117. op->e_o_s=0;
  114118. op->granulepos=0;
  114119. op->packetno=0;
  114120. /* second header packet (comments) **********************************/
  114121. oggpack_reset(&opb);
  114122. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114123. if(b->header1)_ogg_free(b->header1);
  114124. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114125. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114126. op_comm->packet=b->header1;
  114127. op_comm->bytes=oggpack_bytes(&opb);
  114128. op_comm->b_o_s=0;
  114129. op_comm->e_o_s=0;
  114130. op_comm->granulepos=0;
  114131. op_comm->packetno=1;
  114132. /* third header packet (modes/codebooks) ****************************/
  114133. oggpack_reset(&opb);
  114134. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114135. if(b->header2)_ogg_free(b->header2);
  114136. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114137. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114138. op_code->packet=b->header2;
  114139. op_code->bytes=oggpack_bytes(&opb);
  114140. op_code->b_o_s=0;
  114141. op_code->e_o_s=0;
  114142. op_code->granulepos=0;
  114143. op_code->packetno=2;
  114144. oggpack_writeclear(&opb);
  114145. return(0);
  114146. err_out:
  114147. oggpack_writeclear(&opb);
  114148. memset(op,0,sizeof(*op));
  114149. memset(op_comm,0,sizeof(*op_comm));
  114150. memset(op_code,0,sizeof(*op_code));
  114151. if(b->header)_ogg_free(b->header);
  114152. if(b->header1)_ogg_free(b->header1);
  114153. if(b->header2)_ogg_free(b->header2);
  114154. b->header=NULL;
  114155. b->header1=NULL;
  114156. b->header2=NULL;
  114157. return(ret);
  114158. }
  114159. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114160. if(granulepos>=0)
  114161. return((double)granulepos/v->vi->rate);
  114162. return(-1);
  114163. }
  114164. #endif
  114165. /*** End of inlined file: info.c ***/
  114166. /*** Start of inlined file: lpc.c ***/
  114167. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114168. are derived from code written by Jutta Degener and Carsten Bormann;
  114169. thus we include their copyright below. The entirety of this file
  114170. is freely redistributable on the condition that both of these
  114171. copyright notices are preserved without modification. */
  114172. /* Preserved Copyright: *********************************************/
  114173. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114174. Technische Universita"t Berlin
  114175. Any use of this software is permitted provided that this notice is not
  114176. removed and that neither the authors nor the Technische Universita"t
  114177. Berlin are deemed to have made any representations as to the
  114178. suitability of this software for any purpose nor are held responsible
  114179. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114180. THIS SOFTWARE.
  114181. As a matter of courtesy, the authors request to be informed about uses
  114182. this software has found, about bugs in this software, and about any
  114183. improvements that may be of general interest.
  114184. Berlin, 28.11.1994
  114185. Jutta Degener
  114186. Carsten Bormann
  114187. *********************************************************************/
  114188. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114189. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114190. // tasks..
  114191. #if JUCE_MSVC
  114192. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114193. #endif
  114194. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114195. #if JUCE_USE_OGGVORBIS
  114196. #include <stdlib.h>
  114197. #include <string.h>
  114198. #include <math.h>
  114199. /* Autocorrelation LPC coeff generation algorithm invented by
  114200. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114201. /* Input : n elements of time doamin data
  114202. Output: m lpc coefficients, excitation energy */
  114203. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114204. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114205. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114206. double error;
  114207. int i,j;
  114208. /* autocorrelation, p+1 lag coefficients */
  114209. j=m+1;
  114210. while(j--){
  114211. double d=0; /* double needed for accumulator depth */
  114212. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114213. aut[j]=d;
  114214. }
  114215. /* Generate lpc coefficients from autocorr values */
  114216. error=aut[0];
  114217. for(i=0;i<m;i++){
  114218. double r= -aut[i+1];
  114219. if(error==0){
  114220. memset(lpci,0,m*sizeof(*lpci));
  114221. return 0;
  114222. }
  114223. /* Sum up this iteration's reflection coefficient; note that in
  114224. Vorbis we don't save it. If anyone wants to recycle this code
  114225. and needs reflection coefficients, save the results of 'r' from
  114226. each iteration. */
  114227. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114228. r/=error;
  114229. /* Update LPC coefficients and total error */
  114230. lpc[i]=r;
  114231. for(j=0;j<i/2;j++){
  114232. double tmp=lpc[j];
  114233. lpc[j]+=r*lpc[i-1-j];
  114234. lpc[i-1-j]+=r*tmp;
  114235. }
  114236. if(i%2)lpc[j]+=lpc[j]*r;
  114237. error*=1.f-r*r;
  114238. }
  114239. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114240. /* we need the error value to know how big an impulse to hit the
  114241. filter with later */
  114242. return error;
  114243. }
  114244. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114245. float *data,long n){
  114246. /* in: coeff[0...m-1] LPC coefficients
  114247. prime[0...m-1] initial values (allocated size of n+m-1)
  114248. out: data[0...n-1] data samples */
  114249. long i,j,o,p;
  114250. float y;
  114251. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114252. if(!prime)
  114253. for(i=0;i<m;i++)
  114254. work[i]=0.f;
  114255. else
  114256. for(i=0;i<m;i++)
  114257. work[i]=prime[i];
  114258. for(i=0;i<n;i++){
  114259. y=0;
  114260. o=i;
  114261. p=m;
  114262. for(j=0;j<m;j++)
  114263. y-=work[o++]*coeff[--p];
  114264. data[i]=work[o]=y;
  114265. }
  114266. }
  114267. #endif
  114268. /*** End of inlined file: lpc.c ***/
  114269. /*** Start of inlined file: lsp.c ***/
  114270. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114271. an iterative root polisher (CACM algorithm 283). It *is* possible
  114272. to confuse this algorithm into not converging; that should only
  114273. happen with absurdly closely spaced roots (very sharp peaks in the
  114274. LPC f response) which in turn should be impossible in our use of
  114275. the code. If this *does* happen anyway, it's a bug in the floor
  114276. finder; find the cause of the confusion (probably a single bin
  114277. spike or accidental near-float-limit resolution problems) and
  114278. correct it. */
  114279. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114280. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114281. // tasks..
  114282. #if JUCE_MSVC
  114283. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114284. #endif
  114285. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114286. #if JUCE_USE_OGGVORBIS
  114287. #include <math.h>
  114288. #include <string.h>
  114289. #include <stdlib.h>
  114290. /*** Start of inlined file: lookup.h ***/
  114291. #ifndef _V_LOOKUP_H_
  114292. #ifdef FLOAT_LOOKUP
  114293. extern float vorbis_coslook(float a);
  114294. extern float vorbis_invsqlook(float a);
  114295. extern float vorbis_invsq2explook(int a);
  114296. extern float vorbis_fromdBlook(float a);
  114297. #endif
  114298. #ifdef INT_LOOKUP
  114299. extern long vorbis_invsqlook_i(long a,long e);
  114300. extern long vorbis_coslook_i(long a);
  114301. extern float vorbis_fromdBlook_i(long a);
  114302. #endif
  114303. #endif
  114304. /*** End of inlined file: lookup.h ***/
  114305. /* three possible LSP to f curve functions; the exact computation
  114306. (float), a lookup based float implementation, and an integer
  114307. implementation. The float lookup is likely the optimal choice on
  114308. any machine with an FPU. The integer implementation is *not* fixed
  114309. point (due to the need for a large dynamic range and thus a
  114310. seperately tracked exponent) and thus much more complex than the
  114311. relatively simple float implementations. It's mostly for future
  114312. work on a fully fixed point implementation for processors like the
  114313. ARM family. */
  114314. /* undefine both for the 'old' but more precise implementation */
  114315. #define FLOAT_LOOKUP
  114316. #undef INT_LOOKUP
  114317. #ifdef FLOAT_LOOKUP
  114318. /*** Start of inlined file: lookup.c ***/
  114319. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114321. // tasks..
  114322. #if JUCE_MSVC
  114323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114324. #endif
  114325. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114326. #if JUCE_USE_OGGVORBIS
  114327. #include <math.h>
  114328. /*** Start of inlined file: lookup.h ***/
  114329. #ifndef _V_LOOKUP_H_
  114330. #ifdef FLOAT_LOOKUP
  114331. extern float vorbis_coslook(float a);
  114332. extern float vorbis_invsqlook(float a);
  114333. extern float vorbis_invsq2explook(int a);
  114334. extern float vorbis_fromdBlook(float a);
  114335. #endif
  114336. #ifdef INT_LOOKUP
  114337. extern long vorbis_invsqlook_i(long a,long e);
  114338. extern long vorbis_coslook_i(long a);
  114339. extern float vorbis_fromdBlook_i(long a);
  114340. #endif
  114341. #endif
  114342. /*** End of inlined file: lookup.h ***/
  114343. /*** Start of inlined file: lookup_data.h ***/
  114344. #ifndef _V_LOOKUP_DATA_H_
  114345. #ifdef FLOAT_LOOKUP
  114346. #define COS_LOOKUP_SZ 128
  114347. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114348. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114349. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114350. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114351. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114352. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114353. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114354. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114355. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114356. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114357. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114358. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114359. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114360. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114361. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114362. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114363. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114364. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114365. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114366. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114367. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114368. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114369. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114370. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114371. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114372. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114373. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114374. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114375. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114376. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114377. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114378. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114379. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114380. -1.0000000000000f,
  114381. };
  114382. #define INVSQ_LOOKUP_SZ 32
  114383. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114384. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114385. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114386. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114387. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114388. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114389. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114390. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114391. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114392. 1.000000000000f,
  114393. };
  114394. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114395. #define INVSQ2EXP_LOOKUP_MAX 32
  114396. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114397. INVSQ2EXP_LOOKUP_MIN+1]={
  114398. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114399. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114400. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114401. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114402. 256.f, 181.019336f, 128.f, 90.50966799f,
  114403. 64.f, 45.254834f, 32.f, 22.627417f,
  114404. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114405. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114406. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114407. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114408. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114409. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114410. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114411. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114412. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114413. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114414. 1.525878906e-05f,
  114415. };
  114416. #endif
  114417. #define FROMdB_LOOKUP_SZ 35
  114418. #define FROMdB2_LOOKUP_SZ 32
  114419. #define FROMdB_SHIFT 5
  114420. #define FROMdB2_SHIFT 3
  114421. #define FROMdB2_MASK 31
  114422. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114423. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114424. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114425. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114426. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114427. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114428. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114429. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114430. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114431. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114432. };
  114433. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114434. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114435. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114436. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114437. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114438. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114439. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114440. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114441. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114442. };
  114443. #ifdef INT_LOOKUP
  114444. #define INVSQ_LOOKUP_I_SHIFT 10
  114445. #define INVSQ_LOOKUP_I_MASK 1023
  114446. static long INVSQ_LOOKUP_I[64+1]={
  114447. 92682l, 91966l, 91267l, 90583l,
  114448. 89915l, 89261l, 88621l, 87995l,
  114449. 87381l, 86781l, 86192l, 85616l,
  114450. 85051l, 84497l, 83953l, 83420l,
  114451. 82897l, 82384l, 81880l, 81385l,
  114452. 80899l, 80422l, 79953l, 79492l,
  114453. 79039l, 78594l, 78156l, 77726l,
  114454. 77302l, 76885l, 76475l, 76072l,
  114455. 75674l, 75283l, 74898l, 74519l,
  114456. 74146l, 73778l, 73415l, 73058l,
  114457. 72706l, 72359l, 72016l, 71679l,
  114458. 71347l, 71019l, 70695l, 70376l,
  114459. 70061l, 69750l, 69444l, 69141l,
  114460. 68842l, 68548l, 68256l, 67969l,
  114461. 67685l, 67405l, 67128l, 66855l,
  114462. 66585l, 66318l, 66054l, 65794l,
  114463. 65536l,
  114464. };
  114465. #define COS_LOOKUP_I_SHIFT 9
  114466. #define COS_LOOKUP_I_MASK 511
  114467. #define COS_LOOKUP_I_SZ 128
  114468. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114469. 16384l, 16379l, 16364l, 16340l,
  114470. 16305l, 16261l, 16207l, 16143l,
  114471. 16069l, 15986l, 15893l, 15791l,
  114472. 15679l, 15557l, 15426l, 15286l,
  114473. 15137l, 14978l, 14811l, 14635l,
  114474. 14449l, 14256l, 14053l, 13842l,
  114475. 13623l, 13395l, 13160l, 12916l,
  114476. 12665l, 12406l, 12140l, 11866l,
  114477. 11585l, 11297l, 11003l, 10702l,
  114478. 10394l, 10080l, 9760l, 9434l,
  114479. 9102l, 8765l, 8423l, 8076l,
  114480. 7723l, 7366l, 7005l, 6639l,
  114481. 6270l, 5897l, 5520l, 5139l,
  114482. 4756l, 4370l, 3981l, 3590l,
  114483. 3196l, 2801l, 2404l, 2006l,
  114484. 1606l, 1205l, 804l, 402l,
  114485. 0l, -401l, -803l, -1204l,
  114486. -1605l, -2005l, -2403l, -2800l,
  114487. -3195l, -3589l, -3980l, -4369l,
  114488. -4755l, -5138l, -5519l, -5896l,
  114489. -6269l, -6638l, -7004l, -7365l,
  114490. -7722l, -8075l, -8422l, -8764l,
  114491. -9101l, -9433l, -9759l, -10079l,
  114492. -10393l, -10701l, -11002l, -11296l,
  114493. -11584l, -11865l, -12139l, -12405l,
  114494. -12664l, -12915l, -13159l, -13394l,
  114495. -13622l, -13841l, -14052l, -14255l,
  114496. -14448l, -14634l, -14810l, -14977l,
  114497. -15136l, -15285l, -15425l, -15556l,
  114498. -15678l, -15790l, -15892l, -15985l,
  114499. -16068l, -16142l, -16206l, -16260l,
  114500. -16304l, -16339l, -16363l, -16378l,
  114501. -16383l,
  114502. };
  114503. #endif
  114504. #endif
  114505. /*** End of inlined file: lookup_data.h ***/
  114506. #ifdef FLOAT_LOOKUP
  114507. /* interpolated lookup based cos function, domain 0 to PI only */
  114508. float vorbis_coslook(float a){
  114509. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114510. int i=vorbis_ftoi(d-.5);
  114511. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114512. }
  114513. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114514. float vorbis_invsqlook(float a){
  114515. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114516. int i=vorbis_ftoi(d-.5f);
  114517. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114518. }
  114519. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114520. float vorbis_invsq2explook(int a){
  114521. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114522. }
  114523. #include <stdio.h>
  114524. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114525. float vorbis_fromdBlook(float a){
  114526. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114527. return (i<0)?1.f:
  114528. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114529. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114530. }
  114531. #endif
  114532. #ifdef INT_LOOKUP
  114533. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114534. 16.16 format
  114535. returns in m.8 format */
  114536. long vorbis_invsqlook_i(long a,long e){
  114537. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114538. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114539. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114540. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114541. d)>>16); /* result 1.16 */
  114542. e+=32;
  114543. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114544. e=(e>>1)-8;
  114545. return(val>>e);
  114546. }
  114547. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114548. /* a is in n.12 format */
  114549. float vorbis_fromdBlook_i(long a){
  114550. int i=(-a)>>(12-FROMdB2_SHIFT);
  114551. return (i<0)?1.f:
  114552. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114553. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114554. }
  114555. /* interpolated lookup based cos function, domain 0 to PI only */
  114556. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114557. long vorbis_coslook_i(long a){
  114558. int i=a>>COS_LOOKUP_I_SHIFT;
  114559. int d=a&COS_LOOKUP_I_MASK;
  114560. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114561. COS_LOOKUP_I_SHIFT);
  114562. }
  114563. #endif
  114564. #endif
  114565. /*** End of inlined file: lookup.c ***/
  114566. /* catch this in the build system; we #include for
  114567. compilers (like gcc) that can't inline across
  114568. modules */
  114569. /* side effect: changes *lsp to cosines of lsp */
  114570. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114571. float amp,float ampoffset){
  114572. int i;
  114573. float wdel=M_PI/ln;
  114574. vorbis_fpu_control fpu;
  114575. (void) fpu; // to avoid an unused variable warning
  114576. vorbis_fpu_setround(&fpu);
  114577. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114578. i=0;
  114579. while(i<n){
  114580. int k=map[i];
  114581. int qexp;
  114582. float p=.7071067812f;
  114583. float q=.7071067812f;
  114584. float w=vorbis_coslook(wdel*k);
  114585. float *ftmp=lsp;
  114586. int c=m>>1;
  114587. do{
  114588. q*=ftmp[0]-w;
  114589. p*=ftmp[1]-w;
  114590. ftmp+=2;
  114591. }while(--c);
  114592. if(m&1){
  114593. /* odd order filter; slightly assymetric */
  114594. /* the last coefficient */
  114595. q*=ftmp[0]-w;
  114596. q*=q;
  114597. p*=p*(1.f-w*w);
  114598. }else{
  114599. /* even order filter; still symmetric */
  114600. q*=q*(1.f+w);
  114601. p*=p*(1.f-w);
  114602. }
  114603. q=frexp(p+q,&qexp);
  114604. q=vorbis_fromdBlook(amp*
  114605. vorbis_invsqlook(q)*
  114606. vorbis_invsq2explook(qexp+m)-
  114607. ampoffset);
  114608. do{
  114609. curve[i++]*=q;
  114610. }while(map[i]==k);
  114611. }
  114612. vorbis_fpu_restore(fpu);
  114613. }
  114614. #else
  114615. #ifdef INT_LOOKUP
  114616. /*** Start of inlined file: lookup.c ***/
  114617. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114618. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114619. // tasks..
  114620. #if JUCE_MSVC
  114621. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114622. #endif
  114623. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114624. #if JUCE_USE_OGGVORBIS
  114625. #include <math.h>
  114626. /*** Start of inlined file: lookup.h ***/
  114627. #ifndef _V_LOOKUP_H_
  114628. #ifdef FLOAT_LOOKUP
  114629. extern float vorbis_coslook(float a);
  114630. extern float vorbis_invsqlook(float a);
  114631. extern float vorbis_invsq2explook(int a);
  114632. extern float vorbis_fromdBlook(float a);
  114633. #endif
  114634. #ifdef INT_LOOKUP
  114635. extern long vorbis_invsqlook_i(long a,long e);
  114636. extern long vorbis_coslook_i(long a);
  114637. extern float vorbis_fromdBlook_i(long a);
  114638. #endif
  114639. #endif
  114640. /*** End of inlined file: lookup.h ***/
  114641. /*** Start of inlined file: lookup_data.h ***/
  114642. #ifndef _V_LOOKUP_DATA_H_
  114643. #ifdef FLOAT_LOOKUP
  114644. #define COS_LOOKUP_SZ 128
  114645. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114646. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114647. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114648. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114649. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114650. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114651. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114652. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114653. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114654. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114655. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114656. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114657. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114658. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114659. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114660. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114661. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114662. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114663. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114664. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114665. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114666. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114667. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114668. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114669. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114670. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114671. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114672. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114673. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114674. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114675. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114676. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114677. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114678. -1.0000000000000f,
  114679. };
  114680. #define INVSQ_LOOKUP_SZ 32
  114681. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114682. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114683. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114684. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114685. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114686. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114687. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114688. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114689. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114690. 1.000000000000f,
  114691. };
  114692. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114693. #define INVSQ2EXP_LOOKUP_MAX 32
  114694. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114695. INVSQ2EXP_LOOKUP_MIN+1]={
  114696. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114697. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114698. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114699. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114700. 256.f, 181.019336f, 128.f, 90.50966799f,
  114701. 64.f, 45.254834f, 32.f, 22.627417f,
  114702. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114703. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114704. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114705. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114706. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114707. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114708. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114709. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114710. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114711. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114712. 1.525878906e-05f,
  114713. };
  114714. #endif
  114715. #define FROMdB_LOOKUP_SZ 35
  114716. #define FROMdB2_LOOKUP_SZ 32
  114717. #define FROMdB_SHIFT 5
  114718. #define FROMdB2_SHIFT 3
  114719. #define FROMdB2_MASK 31
  114720. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114721. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114722. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114723. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114724. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114725. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114726. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114727. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114728. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114729. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114730. };
  114731. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114732. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114733. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114734. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114735. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114736. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114737. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114738. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114739. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114740. };
  114741. #ifdef INT_LOOKUP
  114742. #define INVSQ_LOOKUP_I_SHIFT 10
  114743. #define INVSQ_LOOKUP_I_MASK 1023
  114744. static long INVSQ_LOOKUP_I[64+1]={
  114745. 92682l, 91966l, 91267l, 90583l,
  114746. 89915l, 89261l, 88621l, 87995l,
  114747. 87381l, 86781l, 86192l, 85616l,
  114748. 85051l, 84497l, 83953l, 83420l,
  114749. 82897l, 82384l, 81880l, 81385l,
  114750. 80899l, 80422l, 79953l, 79492l,
  114751. 79039l, 78594l, 78156l, 77726l,
  114752. 77302l, 76885l, 76475l, 76072l,
  114753. 75674l, 75283l, 74898l, 74519l,
  114754. 74146l, 73778l, 73415l, 73058l,
  114755. 72706l, 72359l, 72016l, 71679l,
  114756. 71347l, 71019l, 70695l, 70376l,
  114757. 70061l, 69750l, 69444l, 69141l,
  114758. 68842l, 68548l, 68256l, 67969l,
  114759. 67685l, 67405l, 67128l, 66855l,
  114760. 66585l, 66318l, 66054l, 65794l,
  114761. 65536l,
  114762. };
  114763. #define COS_LOOKUP_I_SHIFT 9
  114764. #define COS_LOOKUP_I_MASK 511
  114765. #define COS_LOOKUP_I_SZ 128
  114766. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114767. 16384l, 16379l, 16364l, 16340l,
  114768. 16305l, 16261l, 16207l, 16143l,
  114769. 16069l, 15986l, 15893l, 15791l,
  114770. 15679l, 15557l, 15426l, 15286l,
  114771. 15137l, 14978l, 14811l, 14635l,
  114772. 14449l, 14256l, 14053l, 13842l,
  114773. 13623l, 13395l, 13160l, 12916l,
  114774. 12665l, 12406l, 12140l, 11866l,
  114775. 11585l, 11297l, 11003l, 10702l,
  114776. 10394l, 10080l, 9760l, 9434l,
  114777. 9102l, 8765l, 8423l, 8076l,
  114778. 7723l, 7366l, 7005l, 6639l,
  114779. 6270l, 5897l, 5520l, 5139l,
  114780. 4756l, 4370l, 3981l, 3590l,
  114781. 3196l, 2801l, 2404l, 2006l,
  114782. 1606l, 1205l, 804l, 402l,
  114783. 0l, -401l, -803l, -1204l,
  114784. -1605l, -2005l, -2403l, -2800l,
  114785. -3195l, -3589l, -3980l, -4369l,
  114786. -4755l, -5138l, -5519l, -5896l,
  114787. -6269l, -6638l, -7004l, -7365l,
  114788. -7722l, -8075l, -8422l, -8764l,
  114789. -9101l, -9433l, -9759l, -10079l,
  114790. -10393l, -10701l, -11002l, -11296l,
  114791. -11584l, -11865l, -12139l, -12405l,
  114792. -12664l, -12915l, -13159l, -13394l,
  114793. -13622l, -13841l, -14052l, -14255l,
  114794. -14448l, -14634l, -14810l, -14977l,
  114795. -15136l, -15285l, -15425l, -15556l,
  114796. -15678l, -15790l, -15892l, -15985l,
  114797. -16068l, -16142l, -16206l, -16260l,
  114798. -16304l, -16339l, -16363l, -16378l,
  114799. -16383l,
  114800. };
  114801. #endif
  114802. #endif
  114803. /*** End of inlined file: lookup_data.h ***/
  114804. #ifdef FLOAT_LOOKUP
  114805. /* interpolated lookup based cos function, domain 0 to PI only */
  114806. float vorbis_coslook(float a){
  114807. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114808. int i=vorbis_ftoi(d-.5);
  114809. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114810. }
  114811. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114812. float vorbis_invsqlook(float a){
  114813. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114814. int i=vorbis_ftoi(d-.5f);
  114815. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114816. }
  114817. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114818. float vorbis_invsq2explook(int a){
  114819. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114820. }
  114821. #include <stdio.h>
  114822. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114823. float vorbis_fromdBlook(float a){
  114824. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114825. return (i<0)?1.f:
  114826. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114827. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114828. }
  114829. #endif
  114830. #ifdef INT_LOOKUP
  114831. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114832. 16.16 format
  114833. returns in m.8 format */
  114834. long vorbis_invsqlook_i(long a,long e){
  114835. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114836. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114837. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114838. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114839. d)>>16); /* result 1.16 */
  114840. e+=32;
  114841. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114842. e=(e>>1)-8;
  114843. return(val>>e);
  114844. }
  114845. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114846. /* a is in n.12 format */
  114847. float vorbis_fromdBlook_i(long a){
  114848. int i=(-a)>>(12-FROMdB2_SHIFT);
  114849. return (i<0)?1.f:
  114850. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114851. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114852. }
  114853. /* interpolated lookup based cos function, domain 0 to PI only */
  114854. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114855. long vorbis_coslook_i(long a){
  114856. int i=a>>COS_LOOKUP_I_SHIFT;
  114857. int d=a&COS_LOOKUP_I_MASK;
  114858. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114859. COS_LOOKUP_I_SHIFT);
  114860. }
  114861. #endif
  114862. #endif
  114863. /*** End of inlined file: lookup.c ***/
  114864. /* catch this in the build system; we #include for
  114865. compilers (like gcc) that can't inline across
  114866. modules */
  114867. static int MLOOP_1[64]={
  114868. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114869. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114870. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114871. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114872. };
  114873. static int MLOOP_2[64]={
  114874. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114875. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114876. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114877. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114878. };
  114879. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114880. /* side effect: changes *lsp to cosines of lsp */
  114881. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114882. float amp,float ampoffset){
  114883. /* 0 <= m < 256 */
  114884. /* set up for using all int later */
  114885. int i;
  114886. int ampoffseti=rint(ampoffset*4096.f);
  114887. int ampi=rint(amp*16.f);
  114888. long *ilsp=alloca(m*sizeof(*ilsp));
  114889. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114890. i=0;
  114891. while(i<n){
  114892. int j,k=map[i];
  114893. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114894. unsigned long qi=46341;
  114895. int qexp=0,shift;
  114896. long wi=vorbis_coslook_i(k*65536/ln);
  114897. qi*=labs(ilsp[0]-wi);
  114898. pi*=labs(ilsp[1]-wi);
  114899. for(j=3;j<m;j+=2){
  114900. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114901. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114902. shift=MLOOP_3[(pi|qi)>>16];
  114903. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114904. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114905. qexp+=shift;
  114906. }
  114907. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114908. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114909. shift=MLOOP_3[(pi|qi)>>16];
  114910. /* pi,qi normalized collectively, both tracked using qexp */
  114911. if(m&1){
  114912. /* odd order filter; slightly assymetric */
  114913. /* the last coefficient */
  114914. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114915. pi=(pi>>shift)<<14;
  114916. qexp+=shift;
  114917. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114918. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114919. shift=MLOOP_3[(pi|qi)>>16];
  114920. pi>>=shift;
  114921. qi>>=shift;
  114922. qexp+=shift-14*((m+1)>>1);
  114923. pi=((pi*pi)>>16);
  114924. qi=((qi*qi)>>16);
  114925. qexp=qexp*2+m;
  114926. pi*=(1<<14)-((wi*wi)>>14);
  114927. qi+=pi>>14;
  114928. }else{
  114929. /* even order filter; still symmetric */
  114930. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114931. worth tracking step by step */
  114932. pi>>=shift;
  114933. qi>>=shift;
  114934. qexp+=shift-7*m;
  114935. pi=((pi*pi)>>16);
  114936. qi=((qi*qi)>>16);
  114937. qexp=qexp*2+m;
  114938. pi*=(1<<14)-wi;
  114939. qi*=(1<<14)+wi;
  114940. qi=(qi+pi)>>14;
  114941. }
  114942. /* we've let the normalization drift because it wasn't important;
  114943. however, for the lookup, things must be normalized again. We
  114944. need at most one right shift or a number of left shifts */
  114945. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114946. qi>>=1; qexp++;
  114947. }else
  114948. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114949. qi<<=1; qexp--;
  114950. }
  114951. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114952. vorbis_invsqlook_i(qi,qexp)-
  114953. /* m.8, m+n<=8 */
  114954. ampoffseti); /* 8.12[0] */
  114955. curve[i]*=amp;
  114956. while(map[++i]==k)curve[i]*=amp;
  114957. }
  114958. }
  114959. #else
  114960. /* old, nonoptimized but simple version for any poor sap who needs to
  114961. figure out what the hell this code does, or wants the other
  114962. fraction of a dB precision */
  114963. /* side effect: changes *lsp to cosines of lsp */
  114964. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114965. float amp,float ampoffset){
  114966. int i;
  114967. float wdel=M_PI/ln;
  114968. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114969. i=0;
  114970. while(i<n){
  114971. int j,k=map[i];
  114972. float p=.5f;
  114973. float q=.5f;
  114974. float w=2.f*cos(wdel*k);
  114975. for(j=1;j<m;j+=2){
  114976. q *= w-lsp[j-1];
  114977. p *= w-lsp[j];
  114978. }
  114979. if(j==m){
  114980. /* odd order filter; slightly assymetric */
  114981. /* the last coefficient */
  114982. q*=w-lsp[j-1];
  114983. p*=p*(4.f-w*w);
  114984. q*=q;
  114985. }else{
  114986. /* even order filter; still symmetric */
  114987. p*=p*(2.f-w);
  114988. q*=q*(2.f+w);
  114989. }
  114990. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114991. curve[i]*=q;
  114992. while(map[++i]==k)curve[i]*=q;
  114993. }
  114994. }
  114995. #endif
  114996. #endif
  114997. static void cheby(float *g, int ord) {
  114998. int i, j;
  114999. g[0] *= .5f;
  115000. for(i=2; i<= ord; i++) {
  115001. for(j=ord; j >= i; j--) {
  115002. g[j-2] -= g[j];
  115003. g[j] += g[j];
  115004. }
  115005. }
  115006. }
  115007. static int comp(const void *a,const void *b){
  115008. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115009. }
  115010. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115011. but there are root sets for which it gets into limit cycles
  115012. (exacerbated by zero suppression) and fails. We can't afford to
  115013. fail, even if the failure is 1 in 100,000,000, so we now use
  115014. Laguerre and later polish with Newton-Raphson (which can then
  115015. afford to fail) */
  115016. #define EPSILON 10e-7
  115017. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115018. int i,m;
  115019. double lastdelta=0.f;
  115020. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115021. for(i=0;i<=ord;i++)defl[i]=a[i];
  115022. for(m=ord;m>0;m--){
  115023. double newx=0.f,delta;
  115024. /* iterate a root */
  115025. while(1){
  115026. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115027. /* eval the polynomial and its first two derivatives */
  115028. for(i=m;i>0;i--){
  115029. ppp = newx*ppp + pp;
  115030. pp = newx*pp + p;
  115031. p = newx*p + defl[i-1];
  115032. }
  115033. /* Laguerre's method */
  115034. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115035. if(denom<0)
  115036. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115037. if(pp>0){
  115038. denom = pp + sqrt(denom);
  115039. if(denom<EPSILON)denom=EPSILON;
  115040. }else{
  115041. denom = pp - sqrt(denom);
  115042. if(denom>-(EPSILON))denom=-(EPSILON);
  115043. }
  115044. delta = m*p/denom;
  115045. newx -= delta;
  115046. if(delta<0.f)delta*=-1;
  115047. if(fabs(delta/newx)<10e-12)break;
  115048. lastdelta=delta;
  115049. }
  115050. r[m-1]=newx;
  115051. /* forward deflation */
  115052. for(i=m;i>0;i--)
  115053. defl[i-1]+=newx*defl[i];
  115054. defl++;
  115055. }
  115056. return(0);
  115057. }
  115058. /* for spit-and-polish only */
  115059. static int Newton_Raphson(float *a,int ord,float *r){
  115060. int i, k, count=0;
  115061. double error=1.f;
  115062. double *root=(double*)alloca(ord*sizeof(*root));
  115063. for(i=0; i<ord;i++) root[i] = r[i];
  115064. while(error>1e-20){
  115065. error=0;
  115066. for(i=0; i<ord; i++) { /* Update each point. */
  115067. double pp=0.,delta;
  115068. double rooti=root[i];
  115069. double p=a[ord];
  115070. for(k=ord-1; k>= 0; k--) {
  115071. pp= pp* rooti + p;
  115072. p = p * rooti + a[k];
  115073. }
  115074. delta = p/pp;
  115075. root[i] -= delta;
  115076. error+= delta*delta;
  115077. }
  115078. if(count>40)return(-1);
  115079. count++;
  115080. }
  115081. /* Replaced the original bubble sort with a real sort. With your
  115082. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115083. for(i=0; i<ord;i++) r[i] = root[i];
  115084. return(0);
  115085. }
  115086. /* Convert lpc coefficients to lsp coefficients */
  115087. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115088. int order2=(m+1)>>1;
  115089. int g1_order,g2_order;
  115090. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115091. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115092. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115093. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115094. int i;
  115095. /* even and odd are slightly different base cases */
  115096. g1_order=(m+1)>>1;
  115097. g2_order=(m) >>1;
  115098. /* Compute the lengths of the x polynomials. */
  115099. /* Compute the first half of K & R F1 & F2 polynomials. */
  115100. /* Compute half of the symmetric and antisymmetric polynomials. */
  115101. /* Remove the roots at +1 and -1. */
  115102. g1[g1_order] = 1.f;
  115103. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115104. g2[g2_order] = 1.f;
  115105. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115106. if(g1_order>g2_order){
  115107. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115108. }else{
  115109. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115110. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115111. }
  115112. /* Convert into polynomials in cos(alpha) */
  115113. cheby(g1,g1_order);
  115114. cheby(g2,g2_order);
  115115. /* Find the roots of the 2 even polynomials.*/
  115116. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115117. Laguerre_With_Deflation(g2,g2_order,g2r))
  115118. return(-1);
  115119. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115120. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115121. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115122. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115123. for(i=0;i<g1_order;i++)
  115124. lsp[i*2] = acos(g1r[i]);
  115125. for(i=0;i<g2_order;i++)
  115126. lsp[i*2+1] = acos(g2r[i]);
  115127. return(0);
  115128. }
  115129. #endif
  115130. /*** End of inlined file: lsp.c ***/
  115131. /*** Start of inlined file: mapping0.c ***/
  115132. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115133. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115134. // tasks..
  115135. #if JUCE_MSVC
  115136. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115137. #endif
  115138. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115139. #if JUCE_USE_OGGVORBIS
  115140. #include <stdlib.h>
  115141. #include <stdio.h>
  115142. #include <string.h>
  115143. #include <math.h>
  115144. /* simplistic, wasteful way of doing this (unique lookup for each
  115145. mode/submapping); there should be a central repository for
  115146. identical lookups. That will require minor work, so I'm putting it
  115147. off as low priority.
  115148. Why a lookup for each backend in a given mode? Because the
  115149. blocksize is set by the mode, and low backend lookups may require
  115150. parameters from other areas of the mode/mapping */
  115151. static void mapping0_free_info(vorbis_info_mapping *i){
  115152. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115153. if(info){
  115154. memset(info,0,sizeof(*info));
  115155. _ogg_free(info);
  115156. }
  115157. }
  115158. static int ilog3(unsigned int v){
  115159. int ret=0;
  115160. if(v)--v;
  115161. while(v){
  115162. ret++;
  115163. v>>=1;
  115164. }
  115165. return(ret);
  115166. }
  115167. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115168. oggpack_buffer *opb){
  115169. int i;
  115170. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115171. /* another 'we meant to do it this way' hack... up to beta 4, we
  115172. packed 4 binary zeros here to signify one submapping in use. We
  115173. now redefine that to mean four bitflags that indicate use of
  115174. deeper features; bit0:submappings, bit1:coupling,
  115175. bit2,3:reserved. This is backward compatable with all actual uses
  115176. of the beta code. */
  115177. if(info->submaps>1){
  115178. oggpack_write(opb,1,1);
  115179. oggpack_write(opb,info->submaps-1,4);
  115180. }else
  115181. oggpack_write(opb,0,1);
  115182. if(info->coupling_steps>0){
  115183. oggpack_write(opb,1,1);
  115184. oggpack_write(opb,info->coupling_steps-1,8);
  115185. for(i=0;i<info->coupling_steps;i++){
  115186. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115187. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115188. }
  115189. }else
  115190. oggpack_write(opb,0,1);
  115191. oggpack_write(opb,0,2); /* 2,3:reserved */
  115192. /* we don't write the channel submappings if we only have one... */
  115193. if(info->submaps>1){
  115194. for(i=0;i<vi->channels;i++)
  115195. oggpack_write(opb,info->chmuxlist[i],4);
  115196. }
  115197. for(i=0;i<info->submaps;i++){
  115198. oggpack_write(opb,0,8); /* time submap unused */
  115199. oggpack_write(opb,info->floorsubmap[i],8);
  115200. oggpack_write(opb,info->residuesubmap[i],8);
  115201. }
  115202. }
  115203. /* also responsible for range checking */
  115204. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115205. int i;
  115206. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115207. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115208. memset(info,0,sizeof(*info));
  115209. if(oggpack_read(opb,1))
  115210. info->submaps=oggpack_read(opb,4)+1;
  115211. else
  115212. info->submaps=1;
  115213. if(oggpack_read(opb,1)){
  115214. info->coupling_steps=oggpack_read(opb,8)+1;
  115215. for(i=0;i<info->coupling_steps;i++){
  115216. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115217. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115218. if(testM<0 ||
  115219. testA<0 ||
  115220. testM==testA ||
  115221. testM>=vi->channels ||
  115222. testA>=vi->channels) goto err_out;
  115223. }
  115224. }
  115225. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115226. if(info->submaps>1){
  115227. for(i=0;i<vi->channels;i++){
  115228. info->chmuxlist[i]=oggpack_read(opb,4);
  115229. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115230. }
  115231. }
  115232. for(i=0;i<info->submaps;i++){
  115233. oggpack_read(opb,8); /* time submap unused */
  115234. info->floorsubmap[i]=oggpack_read(opb,8);
  115235. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115236. info->residuesubmap[i]=oggpack_read(opb,8);
  115237. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115238. }
  115239. return info;
  115240. err_out:
  115241. mapping0_free_info(info);
  115242. return(NULL);
  115243. }
  115244. #if 0
  115245. static long seq=0;
  115246. static ogg_int64_t total=0;
  115247. static float FLOOR1_fromdB_LOOKUP[256]={
  115248. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115249. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115250. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115251. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115252. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115253. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115254. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115255. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115256. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115257. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115258. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115259. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115260. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115261. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115262. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115263. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115264. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115265. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115266. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115267. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115268. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115269. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115270. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115271. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115272. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115273. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115274. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115275. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115276. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115277. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115278. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115279. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115280. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115281. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115282. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115283. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115284. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115285. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115286. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115287. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115288. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115289. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115290. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115291. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115292. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115293. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115294. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115295. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115296. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115297. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115298. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115299. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115300. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115301. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115302. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115303. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115304. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115305. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115306. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115307. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115308. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115309. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115310. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115311. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115312. };
  115313. #endif
  115314. extern int *floor1_fit(vorbis_block *vb,void *look,
  115315. const float *logmdct, /* in */
  115316. const float *logmask);
  115317. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115318. int *A,int *B,
  115319. int del);
  115320. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115321. void*look,
  115322. int *post,int *ilogmask);
  115323. static int mapping0_forward(vorbis_block *vb){
  115324. vorbis_dsp_state *vd=vb->vd;
  115325. vorbis_info *vi=vd->vi;
  115326. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115327. private_state *b=(private_state*)vb->vd->backend_state;
  115328. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115329. int n=vb->pcmend;
  115330. int i,j,k;
  115331. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115332. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115333. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115334. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115335. float global_ampmax=vbi->ampmax;
  115336. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115337. int blocktype=vbi->blocktype;
  115338. int modenumber=vb->W;
  115339. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115340. vorbis_look_psy *psy_look=
  115341. b->psy+blocktype+(vb->W?2:0);
  115342. vb->mode=modenumber;
  115343. for(i=0;i<vi->channels;i++){
  115344. float scale=4.f/n;
  115345. float scale_dB;
  115346. float *pcm =vb->pcm[i];
  115347. float *logfft =pcm;
  115348. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115349. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115350. todB estimation used on IEEE 754
  115351. compliant machines had a bug that
  115352. returned dB values about a third
  115353. of a decibel too high. The bug
  115354. was harmless because tunings
  115355. implicitly took that into
  115356. account. However, fixing the bug
  115357. in the estimator requires
  115358. changing all the tunings as well.
  115359. For now, it's easier to sync
  115360. things back up here, and
  115361. recalibrate the tunings in the
  115362. next major model upgrade. */
  115363. #if 0
  115364. if(vi->channels==2)
  115365. if(i==0)
  115366. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115367. else
  115368. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115369. #endif
  115370. /* window the PCM data */
  115371. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115372. #if 0
  115373. if(vi->channels==2)
  115374. if(i==0)
  115375. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115376. else
  115377. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115378. #endif
  115379. /* transform the PCM data */
  115380. /* only MDCT right now.... */
  115381. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115382. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115383. drft_forward(&b->fft_look[vb->W],pcm);
  115384. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115385. original todB estimation used on
  115386. IEEE 754 compliant machines had a
  115387. bug that returned dB values about
  115388. a third of a decibel too high.
  115389. The bug was harmless because
  115390. tunings implicitly took that into
  115391. account. However, fixing the bug
  115392. in the estimator requires
  115393. changing all the tunings as well.
  115394. For now, it's easier to sync
  115395. things back up here, and
  115396. recalibrate the tunings in the
  115397. next major model upgrade. */
  115398. local_ampmax[i]=logfft[0];
  115399. for(j=1;j<n-1;j+=2){
  115400. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115401. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115402. .345 is a hack; the original todB
  115403. estimation used on IEEE 754
  115404. compliant machines had a bug that
  115405. returned dB values about a third
  115406. of a decibel too high. The bug
  115407. was harmless because tunings
  115408. implicitly took that into
  115409. account. However, fixing the bug
  115410. in the estimator requires
  115411. changing all the tunings as well.
  115412. For now, it's easier to sync
  115413. things back up here, and
  115414. recalibrate the tunings in the
  115415. next major model upgrade. */
  115416. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115417. }
  115418. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115419. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115420. #if 0
  115421. if(vi->channels==2){
  115422. if(i==0){
  115423. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115424. }else{
  115425. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115426. }
  115427. }
  115428. #endif
  115429. }
  115430. {
  115431. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115432. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115433. for(i=0;i<vi->channels;i++){
  115434. /* the encoder setup assumes that all the modes used by any
  115435. specific bitrate tweaking use the same floor */
  115436. int submap=info->chmuxlist[i];
  115437. /* the following makes things clearer to *me* anyway */
  115438. float *mdct =gmdct[i];
  115439. float *logfft =vb->pcm[i];
  115440. float *logmdct =logfft+n/2;
  115441. float *logmask =logfft;
  115442. vb->mode=modenumber;
  115443. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115444. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115445. for(j=0;j<n/2;j++)
  115446. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115447. todB estimation used on IEEE 754
  115448. compliant machines had a bug that
  115449. returned dB values about a third
  115450. of a decibel too high. The bug
  115451. was harmless because tunings
  115452. implicitly took that into
  115453. account. However, fixing the bug
  115454. in the estimator requires
  115455. changing all the tunings as well.
  115456. For now, it's easier to sync
  115457. things back up here, and
  115458. recalibrate the tunings in the
  115459. next major model upgrade. */
  115460. #if 0
  115461. if(vi->channels==2){
  115462. if(i==0)
  115463. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115464. else
  115465. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115466. }else{
  115467. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115468. }
  115469. #endif
  115470. /* first step; noise masking. Not only does 'noise masking'
  115471. give us curves from which we can decide how much resolution
  115472. to give noise parts of the spectrum, it also implicitly hands
  115473. us a tonality estimate (the larger the value in the
  115474. 'noise_depth' vector, the more tonal that area is) */
  115475. _vp_noisemask(psy_look,
  115476. logmdct,
  115477. noise); /* noise does not have by-frequency offset
  115478. bias applied yet */
  115479. #if 0
  115480. if(vi->channels==2){
  115481. if(i==0)
  115482. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115483. else
  115484. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115485. }
  115486. #endif
  115487. /* second step: 'all the other crap'; all the stuff that isn't
  115488. computed/fit for bitrate management goes in the second psy
  115489. vector. This includes tone masking, peak limiting and ATH */
  115490. _vp_tonemask(psy_look,
  115491. logfft,
  115492. tone,
  115493. global_ampmax,
  115494. local_ampmax[i]);
  115495. #if 0
  115496. if(vi->channels==2){
  115497. if(i==0)
  115498. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115499. else
  115500. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115501. }
  115502. #endif
  115503. /* third step; we offset the noise vectors, overlay tone
  115504. masking. We then do a floor1-specific line fit. If we're
  115505. performing bitrate management, the line fit is performed
  115506. multiple times for up/down tweakage on demand. */
  115507. #if 0
  115508. {
  115509. float aotuv[psy_look->n];
  115510. #endif
  115511. _vp_offset_and_mix(psy_look,
  115512. noise,
  115513. tone,
  115514. 1,
  115515. logmask,
  115516. mdct,
  115517. logmdct);
  115518. #if 0
  115519. if(vi->channels==2){
  115520. if(i==0)
  115521. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115522. else
  115523. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115524. }
  115525. }
  115526. #endif
  115527. #if 0
  115528. if(vi->channels==2){
  115529. if(i==0)
  115530. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115531. else
  115532. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115533. }
  115534. #endif
  115535. /* this algorithm is hardwired to floor 1 for now; abort out if
  115536. we're *not* floor1. This won't happen unless someone has
  115537. broken the encode setup lib. Guard it anyway. */
  115538. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115539. floor_posts[i][PACKETBLOBS/2]=
  115540. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115541. logmdct,
  115542. logmask);
  115543. /* are we managing bitrate? If so, perform two more fits for
  115544. later rate tweaking (fits represent hi/lo) */
  115545. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115546. /* higher rate by way of lower noise curve */
  115547. _vp_offset_and_mix(psy_look,
  115548. noise,
  115549. tone,
  115550. 2,
  115551. logmask,
  115552. mdct,
  115553. logmdct);
  115554. #if 0
  115555. if(vi->channels==2){
  115556. if(i==0)
  115557. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115558. else
  115559. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115560. }
  115561. #endif
  115562. floor_posts[i][PACKETBLOBS-1]=
  115563. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115564. logmdct,
  115565. logmask);
  115566. /* lower rate by way of higher noise curve */
  115567. _vp_offset_and_mix(psy_look,
  115568. noise,
  115569. tone,
  115570. 0,
  115571. logmask,
  115572. mdct,
  115573. logmdct);
  115574. #if 0
  115575. if(vi->channels==2)
  115576. if(i==0)
  115577. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115578. else
  115579. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115580. #endif
  115581. floor_posts[i][0]=
  115582. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115583. logmdct,
  115584. logmask);
  115585. /* we also interpolate a range of intermediate curves for
  115586. intermediate rates */
  115587. for(k=1;k<PACKETBLOBS/2;k++)
  115588. floor_posts[i][k]=
  115589. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115590. floor_posts[i][0],
  115591. floor_posts[i][PACKETBLOBS/2],
  115592. k*65536/(PACKETBLOBS/2));
  115593. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115594. floor_posts[i][k]=
  115595. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115596. floor_posts[i][PACKETBLOBS/2],
  115597. floor_posts[i][PACKETBLOBS-1],
  115598. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115599. }
  115600. }
  115601. }
  115602. vbi->ampmax=global_ampmax;
  115603. /*
  115604. the next phases are performed once for vbr-only and PACKETBLOB
  115605. times for bitrate managed modes.
  115606. 1) encode actual mode being used
  115607. 2) encode the floor for each channel, compute coded mask curve/res
  115608. 3) normalize and couple.
  115609. 4) encode residue
  115610. 5) save packet bytes to the packetblob vector
  115611. */
  115612. /* iterate over the many masking curve fits we've created */
  115613. {
  115614. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115615. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115616. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115617. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115618. float **mag_memo;
  115619. int **mag_sort;
  115620. if(info->coupling_steps){
  115621. mag_memo=_vp_quantize_couple_memo(vb,
  115622. &ci->psy_g_param,
  115623. psy_look,
  115624. info,
  115625. gmdct);
  115626. mag_sort=_vp_quantize_couple_sort(vb,
  115627. psy_look,
  115628. info,
  115629. mag_memo);
  115630. hf_reduction(&ci->psy_g_param,
  115631. psy_look,
  115632. info,
  115633. mag_memo);
  115634. }
  115635. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115636. if(psy_look->vi->normal_channel_p){
  115637. for(i=0;i<vi->channels;i++){
  115638. float *mdct =gmdct[i];
  115639. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115640. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115641. }
  115642. }
  115643. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115644. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115645. k++){
  115646. oggpack_buffer *opb=vbi->packetblob[k];
  115647. /* start out our new packet blob with packet type and mode */
  115648. /* Encode the packet type */
  115649. oggpack_write(opb,0,1);
  115650. /* Encode the modenumber */
  115651. /* Encode frame mode, pre,post windowsize, then dispatch */
  115652. oggpack_write(opb,modenumber,b->modebits);
  115653. if(vb->W){
  115654. oggpack_write(opb,vb->lW,1);
  115655. oggpack_write(opb,vb->nW,1);
  115656. }
  115657. /* encode floor, compute masking curve, sep out residue */
  115658. for(i=0;i<vi->channels;i++){
  115659. int submap=info->chmuxlist[i];
  115660. float *mdct =gmdct[i];
  115661. float *res =vb->pcm[i];
  115662. int *ilogmask=ilogmaskch[i]=
  115663. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115664. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115665. floor_posts[i][k],
  115666. ilogmask);
  115667. #if 0
  115668. {
  115669. char buf[80];
  115670. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115671. float work[n/2];
  115672. for(j=0;j<n/2;j++)
  115673. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115674. _analysis_output(buf,seq,work,n/2,1,1,0);
  115675. }
  115676. #endif
  115677. _vp_remove_floor(psy_look,
  115678. mdct,
  115679. ilogmask,
  115680. res,
  115681. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115682. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115683. #if 0
  115684. {
  115685. char buf[80];
  115686. float work[n/2];
  115687. for(j=0;j<n/2;j++)
  115688. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115689. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115690. _analysis_output(buf,seq,work,n/2,1,1,0);
  115691. }
  115692. #endif
  115693. }
  115694. /* our iteration is now based on masking curve, not prequant and
  115695. coupling. Only one prequant/coupling step */
  115696. /* quantize/couple */
  115697. /* incomplete implementation that assumes the tree is all depth
  115698. one, or no tree at all */
  115699. if(info->coupling_steps){
  115700. _vp_couple(k,
  115701. &ci->psy_g_param,
  115702. psy_look,
  115703. info,
  115704. vb->pcm,
  115705. mag_memo,
  115706. mag_sort,
  115707. ilogmaskch,
  115708. nonzero,
  115709. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115710. }
  115711. /* classify and encode by submap */
  115712. for(i=0;i<info->submaps;i++){
  115713. int ch_in_bundle=0;
  115714. long **classifications;
  115715. int resnum=info->residuesubmap[i];
  115716. for(j=0;j<vi->channels;j++){
  115717. if(info->chmuxlist[j]==i){
  115718. zerobundle[ch_in_bundle]=0;
  115719. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115720. res_bundle[ch_in_bundle]=vb->pcm[j];
  115721. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115722. }
  115723. }
  115724. classifications=_residue_P[ci->residue_type[resnum]]->
  115725. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115726. _residue_P[ci->residue_type[resnum]]->
  115727. forward(opb,vb,b->residue[resnum],
  115728. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115729. }
  115730. /* ok, done encoding. Next protopacket. */
  115731. }
  115732. }
  115733. #if 0
  115734. seq++;
  115735. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115736. #endif
  115737. return(0);
  115738. }
  115739. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115740. vorbis_dsp_state *vd=vb->vd;
  115741. vorbis_info *vi=vd->vi;
  115742. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115743. private_state *b=(private_state*)vd->backend_state;
  115744. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115745. int i,j;
  115746. long n=vb->pcmend=ci->blocksizes[vb->W];
  115747. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115748. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115749. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115750. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115751. /* recover the spectral envelope; store it in the PCM vector for now */
  115752. for(i=0;i<vi->channels;i++){
  115753. int submap=info->chmuxlist[i];
  115754. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115755. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115756. if(floormemo[i])
  115757. nonzero[i]=1;
  115758. else
  115759. nonzero[i]=0;
  115760. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115761. }
  115762. /* channel coupling can 'dirty' the nonzero listing */
  115763. for(i=0;i<info->coupling_steps;i++){
  115764. if(nonzero[info->coupling_mag[i]] ||
  115765. nonzero[info->coupling_ang[i]]){
  115766. nonzero[info->coupling_mag[i]]=1;
  115767. nonzero[info->coupling_ang[i]]=1;
  115768. }
  115769. }
  115770. /* recover the residue into our working vectors */
  115771. for(i=0;i<info->submaps;i++){
  115772. int ch_in_bundle=0;
  115773. for(j=0;j<vi->channels;j++){
  115774. if(info->chmuxlist[j]==i){
  115775. if(nonzero[j])
  115776. zerobundle[ch_in_bundle]=1;
  115777. else
  115778. zerobundle[ch_in_bundle]=0;
  115779. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115780. }
  115781. }
  115782. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115783. inverse(vb,b->residue[info->residuesubmap[i]],
  115784. pcmbundle,zerobundle,ch_in_bundle);
  115785. }
  115786. /* channel coupling */
  115787. for(i=info->coupling_steps-1;i>=0;i--){
  115788. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115789. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115790. for(j=0;j<n/2;j++){
  115791. float mag=pcmM[j];
  115792. float ang=pcmA[j];
  115793. if(mag>0)
  115794. if(ang>0){
  115795. pcmM[j]=mag;
  115796. pcmA[j]=mag-ang;
  115797. }else{
  115798. pcmA[j]=mag;
  115799. pcmM[j]=mag+ang;
  115800. }
  115801. else
  115802. if(ang>0){
  115803. pcmM[j]=mag;
  115804. pcmA[j]=mag+ang;
  115805. }else{
  115806. pcmA[j]=mag;
  115807. pcmM[j]=mag-ang;
  115808. }
  115809. }
  115810. }
  115811. /* compute and apply spectral envelope */
  115812. for(i=0;i<vi->channels;i++){
  115813. float *pcm=vb->pcm[i];
  115814. int submap=info->chmuxlist[i];
  115815. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115816. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115817. floormemo[i],pcm);
  115818. }
  115819. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115820. /* only MDCT right now.... */
  115821. for(i=0;i<vi->channels;i++){
  115822. float *pcm=vb->pcm[i];
  115823. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115824. }
  115825. /* all done! */
  115826. return(0);
  115827. }
  115828. /* export hooks */
  115829. vorbis_func_mapping mapping0_exportbundle={
  115830. &mapping0_pack,
  115831. &mapping0_unpack,
  115832. &mapping0_free_info,
  115833. &mapping0_forward,
  115834. &mapping0_inverse
  115835. };
  115836. #endif
  115837. /*** End of inlined file: mapping0.c ***/
  115838. /*** Start of inlined file: mdct.c ***/
  115839. /* this can also be run as an integer transform by uncommenting a
  115840. define in mdct.h; the integerization is a first pass and although
  115841. it's likely stable for Vorbis, the dynamic range is constrained and
  115842. roundoff isn't done (so it's noisy). Consider it functional, but
  115843. only a starting point. There's no point on a machine with an FPU */
  115844. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115845. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115846. // tasks..
  115847. #if JUCE_MSVC
  115848. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115849. #endif
  115850. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115851. #if JUCE_USE_OGGVORBIS
  115852. #include <stdio.h>
  115853. #include <stdlib.h>
  115854. #include <string.h>
  115855. #include <math.h>
  115856. /* build lookups for trig functions; also pre-figure scaling and
  115857. some window function algebra. */
  115858. void mdct_init(mdct_lookup *lookup,int n){
  115859. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115860. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115861. int i;
  115862. int n2=n>>1;
  115863. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115864. lookup->n=n;
  115865. lookup->trig=T;
  115866. lookup->bitrev=bitrev;
  115867. /* trig lookups... */
  115868. for(i=0;i<n/4;i++){
  115869. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115870. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115871. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115872. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115873. }
  115874. for(i=0;i<n/8;i++){
  115875. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115876. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115877. }
  115878. /* bitreverse lookup... */
  115879. {
  115880. int mask=(1<<(log2n-1))-1,i,j;
  115881. int msb=1<<(log2n-2);
  115882. for(i=0;i<n/8;i++){
  115883. int acc=0;
  115884. for(j=0;msb>>j;j++)
  115885. if((msb>>j)&i)acc|=1<<j;
  115886. bitrev[i*2]=((~acc)&mask)-1;
  115887. bitrev[i*2+1]=acc;
  115888. }
  115889. }
  115890. lookup->scale=FLOAT_CONV(4.f/n);
  115891. }
  115892. /* 8 point butterfly (in place, 4 register) */
  115893. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115894. REG_TYPE r0 = x[6] + x[2];
  115895. REG_TYPE r1 = x[6] - x[2];
  115896. REG_TYPE r2 = x[4] + x[0];
  115897. REG_TYPE r3 = x[4] - x[0];
  115898. x[6] = r0 + r2;
  115899. x[4] = r0 - r2;
  115900. r0 = x[5] - x[1];
  115901. r2 = x[7] - x[3];
  115902. x[0] = r1 + r0;
  115903. x[2] = r1 - r0;
  115904. r0 = x[5] + x[1];
  115905. r1 = x[7] + x[3];
  115906. x[3] = r2 + r3;
  115907. x[1] = r2 - r3;
  115908. x[7] = r1 + r0;
  115909. x[5] = r1 - r0;
  115910. }
  115911. /* 16 point butterfly (in place, 4 register) */
  115912. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115913. REG_TYPE r0 = x[1] - x[9];
  115914. REG_TYPE r1 = x[0] - x[8];
  115915. x[8] += x[0];
  115916. x[9] += x[1];
  115917. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115918. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115919. r0 = x[3] - x[11];
  115920. r1 = x[10] - x[2];
  115921. x[10] += x[2];
  115922. x[11] += x[3];
  115923. x[2] = r0;
  115924. x[3] = r1;
  115925. r0 = x[12] - x[4];
  115926. r1 = x[13] - x[5];
  115927. x[12] += x[4];
  115928. x[13] += x[5];
  115929. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115930. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115931. r0 = x[14] - x[6];
  115932. r1 = x[15] - x[7];
  115933. x[14] += x[6];
  115934. x[15] += x[7];
  115935. x[6] = r0;
  115936. x[7] = r1;
  115937. mdct_butterfly_8(x);
  115938. mdct_butterfly_8(x+8);
  115939. }
  115940. /* 32 point butterfly (in place, 4 register) */
  115941. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115942. REG_TYPE r0 = x[30] - x[14];
  115943. REG_TYPE r1 = x[31] - x[15];
  115944. x[30] += x[14];
  115945. x[31] += x[15];
  115946. x[14] = r0;
  115947. x[15] = r1;
  115948. r0 = x[28] - x[12];
  115949. r1 = x[29] - x[13];
  115950. x[28] += x[12];
  115951. x[29] += x[13];
  115952. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115953. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115954. r0 = x[26] - x[10];
  115955. r1 = x[27] - x[11];
  115956. x[26] += x[10];
  115957. x[27] += x[11];
  115958. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115959. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115960. r0 = x[24] - x[8];
  115961. r1 = x[25] - x[9];
  115962. x[24] += x[8];
  115963. x[25] += x[9];
  115964. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115965. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115966. r0 = x[22] - x[6];
  115967. r1 = x[7] - x[23];
  115968. x[22] += x[6];
  115969. x[23] += x[7];
  115970. x[6] = r1;
  115971. x[7] = r0;
  115972. r0 = x[4] - x[20];
  115973. r1 = x[5] - x[21];
  115974. x[20] += x[4];
  115975. x[21] += x[5];
  115976. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115977. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115978. r0 = x[2] - x[18];
  115979. r1 = x[3] - x[19];
  115980. x[18] += x[2];
  115981. x[19] += x[3];
  115982. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115983. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115984. r0 = x[0] - x[16];
  115985. r1 = x[1] - x[17];
  115986. x[16] += x[0];
  115987. x[17] += x[1];
  115988. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115989. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115990. mdct_butterfly_16(x);
  115991. mdct_butterfly_16(x+16);
  115992. }
  115993. /* N point first stage butterfly (in place, 2 register) */
  115994. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115995. DATA_TYPE *x,
  115996. int points){
  115997. DATA_TYPE *x1 = x + points - 8;
  115998. DATA_TYPE *x2 = x + (points>>1) - 8;
  115999. REG_TYPE r0;
  116000. REG_TYPE r1;
  116001. do{
  116002. r0 = x1[6] - x2[6];
  116003. r1 = x1[7] - x2[7];
  116004. x1[6] += x2[6];
  116005. x1[7] += x2[7];
  116006. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116007. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116008. r0 = x1[4] - x2[4];
  116009. r1 = x1[5] - x2[5];
  116010. x1[4] += x2[4];
  116011. x1[5] += x2[5];
  116012. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116013. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116014. r0 = x1[2] - x2[2];
  116015. r1 = x1[3] - x2[3];
  116016. x1[2] += x2[2];
  116017. x1[3] += x2[3];
  116018. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116019. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116020. r0 = x1[0] - x2[0];
  116021. r1 = x1[1] - x2[1];
  116022. x1[0] += x2[0];
  116023. x1[1] += x2[1];
  116024. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116025. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116026. x1-=8;
  116027. x2-=8;
  116028. T+=16;
  116029. }while(x2>=x);
  116030. }
  116031. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116032. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116033. DATA_TYPE *x,
  116034. int points,
  116035. int trigint){
  116036. DATA_TYPE *x1 = x + points - 8;
  116037. DATA_TYPE *x2 = x + (points>>1) - 8;
  116038. REG_TYPE r0;
  116039. REG_TYPE r1;
  116040. do{
  116041. r0 = x1[6] - x2[6];
  116042. r1 = x1[7] - x2[7];
  116043. x1[6] += x2[6];
  116044. x1[7] += x2[7];
  116045. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116046. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116047. T+=trigint;
  116048. r0 = x1[4] - x2[4];
  116049. r1 = x1[5] - x2[5];
  116050. x1[4] += x2[4];
  116051. x1[5] += x2[5];
  116052. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116053. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116054. T+=trigint;
  116055. r0 = x1[2] - x2[2];
  116056. r1 = x1[3] - x2[3];
  116057. x1[2] += x2[2];
  116058. x1[3] += x2[3];
  116059. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116060. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116061. T+=trigint;
  116062. r0 = x1[0] - x2[0];
  116063. r1 = x1[1] - x2[1];
  116064. x1[0] += x2[0];
  116065. x1[1] += x2[1];
  116066. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116067. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116068. T+=trigint;
  116069. x1-=8;
  116070. x2-=8;
  116071. }while(x2>=x);
  116072. }
  116073. STIN void mdct_butterflies(mdct_lookup *init,
  116074. DATA_TYPE *x,
  116075. int points){
  116076. DATA_TYPE *T=init->trig;
  116077. int stages=init->log2n-5;
  116078. int i,j;
  116079. if(--stages>0){
  116080. mdct_butterfly_first(T,x,points);
  116081. }
  116082. for(i=1;--stages>0;i++){
  116083. for(j=0;j<(1<<i);j++)
  116084. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116085. }
  116086. for(j=0;j<points;j+=32)
  116087. mdct_butterfly_32(x+j);
  116088. }
  116089. void mdct_clear(mdct_lookup *l){
  116090. if(l){
  116091. if(l->trig)_ogg_free(l->trig);
  116092. if(l->bitrev)_ogg_free(l->bitrev);
  116093. memset(l,0,sizeof(*l));
  116094. }
  116095. }
  116096. STIN void mdct_bitreverse(mdct_lookup *init,
  116097. DATA_TYPE *x){
  116098. int n = init->n;
  116099. int *bit = init->bitrev;
  116100. DATA_TYPE *w0 = x;
  116101. DATA_TYPE *w1 = x = w0+(n>>1);
  116102. DATA_TYPE *T = init->trig+n;
  116103. do{
  116104. DATA_TYPE *x0 = x+bit[0];
  116105. DATA_TYPE *x1 = x+bit[1];
  116106. REG_TYPE r0 = x0[1] - x1[1];
  116107. REG_TYPE r1 = x0[0] + x1[0];
  116108. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116109. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116110. w1 -= 4;
  116111. r0 = HALVE(x0[1] + x1[1]);
  116112. r1 = HALVE(x0[0] - x1[0]);
  116113. w0[0] = r0 + r2;
  116114. w1[2] = r0 - r2;
  116115. w0[1] = r1 + r3;
  116116. w1[3] = r3 - r1;
  116117. x0 = x+bit[2];
  116118. x1 = x+bit[3];
  116119. r0 = x0[1] - x1[1];
  116120. r1 = x0[0] + x1[0];
  116121. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116122. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116123. r0 = HALVE(x0[1] + x1[1]);
  116124. r1 = HALVE(x0[0] - x1[0]);
  116125. w0[2] = r0 + r2;
  116126. w1[0] = r0 - r2;
  116127. w0[3] = r1 + r3;
  116128. w1[1] = r3 - r1;
  116129. T += 4;
  116130. bit += 4;
  116131. w0 += 4;
  116132. }while(w0<w1);
  116133. }
  116134. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116135. int n=init->n;
  116136. int n2=n>>1;
  116137. int n4=n>>2;
  116138. /* rotate */
  116139. DATA_TYPE *iX = in+n2-7;
  116140. DATA_TYPE *oX = out+n2+n4;
  116141. DATA_TYPE *T = init->trig+n4;
  116142. do{
  116143. oX -= 4;
  116144. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116145. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116146. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116147. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116148. iX -= 8;
  116149. T += 4;
  116150. }while(iX>=in);
  116151. iX = in+n2-8;
  116152. oX = out+n2+n4;
  116153. T = init->trig+n4;
  116154. do{
  116155. T -= 4;
  116156. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116157. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116158. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116159. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116160. iX -= 8;
  116161. oX += 4;
  116162. }while(iX>=in);
  116163. mdct_butterflies(init,out+n2,n2);
  116164. mdct_bitreverse(init,out);
  116165. /* roatate + window */
  116166. {
  116167. DATA_TYPE *oX1=out+n2+n4;
  116168. DATA_TYPE *oX2=out+n2+n4;
  116169. DATA_TYPE *iX =out;
  116170. T =init->trig+n2;
  116171. do{
  116172. oX1-=4;
  116173. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116174. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116175. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116176. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116177. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116178. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116179. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116180. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116181. oX2+=4;
  116182. iX += 8;
  116183. T += 8;
  116184. }while(iX<oX1);
  116185. iX=out+n2+n4;
  116186. oX1=out+n4;
  116187. oX2=oX1;
  116188. do{
  116189. oX1-=4;
  116190. iX-=4;
  116191. oX2[0] = -(oX1[3] = iX[3]);
  116192. oX2[1] = -(oX1[2] = iX[2]);
  116193. oX2[2] = -(oX1[1] = iX[1]);
  116194. oX2[3] = -(oX1[0] = iX[0]);
  116195. oX2+=4;
  116196. }while(oX2<iX);
  116197. iX=out+n2+n4;
  116198. oX1=out+n2+n4;
  116199. oX2=out+n2;
  116200. do{
  116201. oX1-=4;
  116202. oX1[0]= iX[3];
  116203. oX1[1]= iX[2];
  116204. oX1[2]= iX[1];
  116205. oX1[3]= iX[0];
  116206. iX+=4;
  116207. }while(oX1>oX2);
  116208. }
  116209. }
  116210. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116211. int n=init->n;
  116212. int n2=n>>1;
  116213. int n4=n>>2;
  116214. int n8=n>>3;
  116215. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116216. DATA_TYPE *w2=w+n2;
  116217. /* rotate */
  116218. /* window + rotate + step 1 */
  116219. REG_TYPE r0;
  116220. REG_TYPE r1;
  116221. DATA_TYPE *x0=in+n2+n4;
  116222. DATA_TYPE *x1=x0+1;
  116223. DATA_TYPE *T=init->trig+n2;
  116224. int i=0;
  116225. for(i=0;i<n8;i+=2){
  116226. x0 -=4;
  116227. T-=2;
  116228. r0= x0[2] + x1[0];
  116229. r1= x0[0] + x1[2];
  116230. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116231. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116232. x1 +=4;
  116233. }
  116234. x1=in+1;
  116235. for(;i<n2-n8;i+=2){
  116236. T-=2;
  116237. x0 -=4;
  116238. r0= x0[2] - x1[0];
  116239. r1= x0[0] - x1[2];
  116240. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116241. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116242. x1 +=4;
  116243. }
  116244. x0=in+n;
  116245. for(;i<n2;i+=2){
  116246. T-=2;
  116247. x0 -=4;
  116248. r0= -x0[2] - x1[0];
  116249. r1= -x0[0] - x1[2];
  116250. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116251. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116252. x1 +=4;
  116253. }
  116254. mdct_butterflies(init,w+n2,n2);
  116255. mdct_bitreverse(init,w);
  116256. /* roatate + window */
  116257. T=init->trig+n2;
  116258. x0=out+n2;
  116259. for(i=0;i<n4;i++){
  116260. x0--;
  116261. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116262. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116263. w+=2;
  116264. T+=2;
  116265. }
  116266. }
  116267. #endif
  116268. /*** End of inlined file: mdct.c ***/
  116269. /*** Start of inlined file: psy.c ***/
  116270. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116271. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116272. // tasks..
  116273. #if JUCE_MSVC
  116274. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116275. #endif
  116276. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116277. #if JUCE_USE_OGGVORBIS
  116278. #include <stdlib.h>
  116279. #include <math.h>
  116280. #include <string.h>
  116281. /*** Start of inlined file: masking.h ***/
  116282. #ifndef _V_MASKING_H_
  116283. #define _V_MASKING_H_
  116284. /* more detailed ATH; the bass if flat to save stressing the floor
  116285. overly for only a bin or two of savings. */
  116286. #define MAX_ATH 88
  116287. static float ATH[]={
  116288. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116289. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116290. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116291. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116292. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116293. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116294. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116295. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116296. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116297. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116298. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116299. };
  116300. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116301. replaced by an empirically collected data set. The previously
  116302. published values were, far too often, simply on crack. */
  116303. #define EHMER_OFFSET 16
  116304. #define EHMER_MAX 56
  116305. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116306. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116307. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116308. for collection of these curves) */
  116309. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116310. /* 62.5 Hz */
  116311. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116312. -60, -60, -60, -60, -62, -62, -65, -73,
  116313. -69, -68, -68, -67, -70, -70, -72, -74,
  116314. -75, -79, -79, -80, -83, -88, -93, -100,
  116315. -110, -999, -999, -999, -999, -999, -999, -999,
  116316. -999, -999, -999, -999, -999, -999, -999, -999,
  116317. -999, -999, -999, -999, -999, -999, -999, -999},
  116318. { -48, -48, -48, -48, -48, -48, -48, -48,
  116319. -48, -48, -48, -48, -48, -53, -61, -66,
  116320. -66, -68, -67, -70, -76, -76, -72, -73,
  116321. -75, -76, -78, -79, -83, -88, -93, -100,
  116322. -110, -999, -999, -999, -999, -999, -999, -999,
  116323. -999, -999, -999, -999, -999, -999, -999, -999,
  116324. -999, -999, -999, -999, -999, -999, -999, -999},
  116325. { -37, -37, -37, -37, -37, -37, -37, -37,
  116326. -38, -40, -42, -46, -48, -53, -55, -62,
  116327. -65, -58, -56, -56, -61, -60, -65, -67,
  116328. -69, -71, -77, -77, -78, -80, -82, -84,
  116329. -88, -93, -98, -106, -112, -999, -999, -999,
  116330. -999, -999, -999, -999, -999, -999, -999, -999,
  116331. -999, -999, -999, -999, -999, -999, -999, -999},
  116332. { -25, -25, -25, -25, -25, -25, -25, -25,
  116333. -25, -26, -27, -29, -32, -38, -48, -52,
  116334. -52, -50, -48, -48, -51, -52, -54, -60,
  116335. -67, -67, -66, -68, -69, -73, -73, -76,
  116336. -80, -81, -81, -85, -85, -86, -88, -93,
  116337. -100, -110, -999, -999, -999, -999, -999, -999,
  116338. -999, -999, -999, -999, -999, -999, -999, -999},
  116339. { -16, -16, -16, -16, -16, -16, -16, -16,
  116340. -17, -19, -20, -22, -26, -28, -31, -40,
  116341. -47, -39, -39, -40, -42, -43, -47, -51,
  116342. -57, -52, -55, -55, -60, -58, -62, -63,
  116343. -70, -67, -69, -72, -73, -77, -80, -82,
  116344. -83, -87, -90, -94, -98, -104, -115, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999},
  116346. { -8, -8, -8, -8, -8, -8, -8, -8,
  116347. -8, -8, -10, -11, -15, -19, -25, -30,
  116348. -34, -31, -30, -31, -29, -32, -35, -42,
  116349. -48, -42, -44, -46, -50, -50, -51, -52,
  116350. -59, -54, -55, -55, -58, -62, -63, -66,
  116351. -72, -73, -76, -75, -78, -80, -80, -81,
  116352. -84, -88, -90, -94, -98, -101, -106, -110}},
  116353. /* 88Hz */
  116354. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116355. -66, -66, -66, -66, -66, -67, -67, -67,
  116356. -76, -72, -71, -74, -76, -76, -75, -78,
  116357. -79, -79, -81, -83, -86, -89, -93, -97,
  116358. -100, -105, -110, -999, -999, -999, -999, -999,
  116359. -999, -999, -999, -999, -999, -999, -999, -999,
  116360. -999, -999, -999, -999, -999, -999, -999, -999},
  116361. { -47, -47, -47, -47, -47, -47, -47, -47,
  116362. -47, -47, -47, -48, -51, -55, -59, -66,
  116363. -66, -66, -67, -66, -68, -69, -70, -74,
  116364. -79, -77, -77, -78, -80, -81, -82, -84,
  116365. -86, -88, -91, -95, -100, -108, -116, -999,
  116366. -999, -999, -999, -999, -999, -999, -999, -999,
  116367. -999, -999, -999, -999, -999, -999, -999, -999},
  116368. { -36, -36, -36, -36, -36, -36, -36, -36,
  116369. -36, -37, -37, -41, -44, -48, -51, -58,
  116370. -62, -60, -57, -59, -59, -60, -63, -65,
  116371. -72, -71, -70, -72, -74, -77, -76, -78,
  116372. -81, -81, -80, -83, -86, -91, -96, -100,
  116373. -105, -110, -999, -999, -999, -999, -999, -999,
  116374. -999, -999, -999, -999, -999, -999, -999, -999},
  116375. { -28, -28, -28, -28, -28, -28, -28, -28,
  116376. -28, -30, -32, -32, -33, -35, -41, -49,
  116377. -50, -49, -47, -48, -48, -52, -51, -57,
  116378. -65, -61, -59, -61, -64, -69, -70, -74,
  116379. -77, -77, -78, -81, -84, -85, -87, -90,
  116380. -92, -96, -100, -107, -112, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999},
  116382. { -19, -19, -19, -19, -19, -19, -19, -19,
  116383. -20, -21, -23, -27, -30, -35, -36, -41,
  116384. -46, -44, -42, -40, -41, -41, -43, -48,
  116385. -55, -53, -52, -53, -56, -59, -58, -60,
  116386. -67, -66, -69, -71, -72, -75, -79, -81,
  116387. -84, -87, -90, -93, -97, -101, -107, -114,
  116388. -999, -999, -999, -999, -999, -999, -999, -999},
  116389. { -9, -9, -9, -9, -9, -9, -9, -9,
  116390. -11, -12, -12, -15, -16, -20, -23, -30,
  116391. -37, -34, -33, -34, -31, -32, -32, -38,
  116392. -47, -44, -41, -40, -47, -49, -46, -46,
  116393. -58, -50, -50, -54, -58, -62, -64, -67,
  116394. -67, -70, -72, -76, -79, -83, -87, -91,
  116395. -96, -100, -104, -110, -999, -999, -999, -999}},
  116396. /* 125 Hz */
  116397. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116398. -62, -62, -63, -64, -66, -67, -66, -68,
  116399. -75, -72, -76, -75, -76, -78, -79, -82,
  116400. -84, -85, -90, -94, -101, -110, -999, -999,
  116401. -999, -999, -999, -999, -999, -999, -999, -999,
  116402. -999, -999, -999, -999, -999, -999, -999, -999,
  116403. -999, -999, -999, -999, -999, -999, -999, -999},
  116404. { -59, -59, -59, -59, -59, -59, -59, -59,
  116405. -59, -59, -59, -60, -60, -61, -63, -66,
  116406. -71, -68, -70, -70, -71, -72, -72, -75,
  116407. -81, -78, -79, -82, -83, -86, -90, -97,
  116408. -103, -113, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -999, -999, -999, -999,
  116410. -999, -999, -999, -999, -999, -999, -999, -999},
  116411. { -53, -53, -53, -53, -53, -53, -53, -53,
  116412. -53, -54, -55, -57, -56, -57, -55, -61,
  116413. -65, -60, -60, -62, -63, -63, -66, -68,
  116414. -74, -73, -75, -75, -78, -80, -80, -82,
  116415. -85, -90, -96, -101, -108, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999},
  116418. { -46, -46, -46, -46, -46, -46, -46, -46,
  116419. -46, -46, -47, -47, -47, -47, -48, -51,
  116420. -57, -51, -49, -50, -51, -53, -54, -59,
  116421. -66, -60, -62, -67, -67, -70, -72, -75,
  116422. -76, -78, -81, -85, -88, -94, -97, -104,
  116423. -112, -999, -999, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999},
  116425. { -36, -36, -36, -36, -36, -36, -36, -36,
  116426. -39, -41, -42, -42, -39, -38, -41, -43,
  116427. -52, -44, -40, -39, -37, -37, -40, -47,
  116428. -54, -50, -48, -50, -55, -61, -59, -62,
  116429. -66, -66, -66, -69, -69, -73, -74, -74,
  116430. -75, -77, -79, -82, -87, -91, -95, -100,
  116431. -108, -115, -999, -999, -999, -999, -999, -999},
  116432. { -28, -26, -24, -22, -20, -20, -23, -29,
  116433. -30, -31, -28, -27, -28, -28, -28, -35,
  116434. -40, -33, -32, -29, -30, -30, -30, -37,
  116435. -45, -41, -37, -38, -45, -47, -47, -48,
  116436. -53, -49, -48, -50, -49, -49, -51, -52,
  116437. -58, -56, -57, -56, -60, -61, -62, -70,
  116438. -72, -74, -78, -83, -88, -93, -100, -106}},
  116439. /* 177 Hz */
  116440. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -110, -105, -100, -95, -91, -87, -83,
  116442. -80, -78, -76, -78, -78, -81, -83, -85,
  116443. -86, -85, -86, -87, -90, -97, -107, -999,
  116444. -999, -999, -999, -999, -999, -999, -999, -999,
  116445. -999, -999, -999, -999, -999, -999, -999, -999,
  116446. -999, -999, -999, -999, -999, -999, -999, -999},
  116447. {-999, -999, -999, -110, -105, -100, -95, -90,
  116448. -85, -81, -77, -73, -70, -67, -67, -68,
  116449. -75, -73, -70, -69, -70, -72, -75, -79,
  116450. -84, -83, -84, -86, -88, -89, -89, -93,
  116451. -98, -105, -112, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -999, -999, -999,
  116453. -999, -999, -999, -999, -999, -999, -999, -999},
  116454. {-105, -100, -95, -90, -85, -80, -76, -71,
  116455. -68, -68, -65, -63, -63, -62, -62, -64,
  116456. -65, -64, -61, -62, -63, -64, -66, -68,
  116457. -73, -73, -74, -75, -76, -81, -83, -85,
  116458. -88, -89, -92, -95, -100, -108, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999},
  116461. { -80, -75, -71, -68, -65, -63, -62, -61,
  116462. -61, -61, -61, -59, -56, -57, -53, -50,
  116463. -58, -52, -50, -50, -52, -53, -54, -58,
  116464. -67, -63, -67, -68, -72, -75, -78, -80,
  116465. -81, -81, -82, -85, -89, -90, -93, -97,
  116466. -101, -107, -114, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999},
  116468. { -65, -61, -59, -57, -56, -55, -55, -56,
  116469. -56, -57, -55, -53, -52, -47, -44, -44,
  116470. -50, -44, -41, -39, -39, -42, -40, -46,
  116471. -51, -49, -50, -53, -54, -63, -60, -61,
  116472. -62, -66, -66, -66, -70, -73, -74, -75,
  116473. -76, -75, -79, -85, -89, -91, -96, -102,
  116474. -110, -999, -999, -999, -999, -999, -999, -999},
  116475. { -52, -50, -49, -49, -48, -48, -48, -49,
  116476. -50, -50, -49, -46, -43, -39, -35, -33,
  116477. -38, -36, -32, -29, -32, -32, -32, -35,
  116478. -44, -39, -38, -38, -46, -50, -45, -46,
  116479. -53, -50, -50, -50, -54, -54, -53, -53,
  116480. -56, -57, -59, -66, -70, -72, -74, -79,
  116481. -83, -85, -90, -97, -114, -999, -999, -999}},
  116482. /* 250 Hz */
  116483. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116484. -100, -95, -90, -86, -80, -75, -75, -79,
  116485. -80, -79, -80, -81, -82, -88, -95, -103,
  116486. -110, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -999, -999, -999, -999, -999,
  116488. -999, -999, -999, -999, -999, -999, -999, -999,
  116489. -999, -999, -999, -999, -999, -999, -999, -999},
  116490. {-999, -999, -999, -999, -108, -103, -98, -93,
  116491. -88, -83, -79, -78, -75, -71, -67, -68,
  116492. -73, -73, -72, -73, -75, -77, -80, -82,
  116493. -88, -93, -100, -107, -114, -999, -999, -999,
  116494. -999, -999, -999, -999, -999, -999, -999, -999,
  116495. -999, -999, -999, -999, -999, -999, -999, -999,
  116496. -999, -999, -999, -999, -999, -999, -999, -999},
  116497. {-999, -999, -999, -110, -105, -101, -96, -90,
  116498. -86, -81, -77, -73, -69, -66, -61, -62,
  116499. -66, -64, -62, -65, -66, -70, -72, -76,
  116500. -81, -80, -84, -90, -95, -102, -110, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999},
  116504. {-999, -999, -999, -107, -103, -97, -92, -88,
  116505. -83, -79, -74, -70, -66, -59, -53, -58,
  116506. -62, -55, -54, -54, -54, -58, -61, -62,
  116507. -72, -70, -72, -75, -78, -80, -81, -80,
  116508. -83, -83, -88, -93, -100, -107, -115, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999},
  116511. {-999, -999, -999, -105, -100, -95, -90, -85,
  116512. -80, -75, -70, -66, -62, -56, -48, -44,
  116513. -48, -46, -46, -43, -46, -48, -48, -51,
  116514. -58, -58, -59, -60, -62, -62, -61, -61,
  116515. -65, -64, -65, -68, -70, -74, -75, -78,
  116516. -81, -86, -95, -110, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999},
  116518. {-999, -999, -105, -100, -95, -90, -85, -80,
  116519. -75, -70, -65, -61, -55, -49, -39, -33,
  116520. -40, -35, -32, -38, -40, -33, -35, -37,
  116521. -46, -41, -45, -44, -46, -42, -45, -46,
  116522. -52, -50, -50, -50, -54, -54, -55, -57,
  116523. -62, -64, -66, -68, -70, -76, -81, -90,
  116524. -100, -110, -999, -999, -999, -999, -999, -999}},
  116525. /* 354 hz */
  116526. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116527. -105, -98, -90, -85, -82, -83, -80, -78,
  116528. -84, -79, -80, -83, -87, -89, -91, -93,
  116529. -99, -106, -117, -999, -999, -999, -999, -999,
  116530. -999, -999, -999, -999, -999, -999, -999, -999,
  116531. -999, -999, -999, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999},
  116533. {-999, -999, -999, -999, -999, -999, -999, -999,
  116534. -105, -98, -90, -85, -80, -75, -70, -68,
  116535. -74, -72, -74, -77, -80, -82, -85, -87,
  116536. -92, -89, -91, -95, -100, -106, -112, -999,
  116537. -999, -999, -999, -999, -999, -999, -999, -999,
  116538. -999, -999, -999, -999, -999, -999, -999, -999,
  116539. -999, -999, -999, -999, -999, -999, -999, -999},
  116540. {-999, -999, -999, -999, -999, -999, -999, -999,
  116541. -105, -98, -90, -83, -75, -71, -63, -64,
  116542. -67, -62, -64, -67, -70, -73, -77, -81,
  116543. -84, -83, -85, -89, -90, -93, -98, -104,
  116544. -109, -114, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -999, -999, -999, -999,
  116546. -999, -999, -999, -999, -999, -999, -999, -999},
  116547. {-999, -999, -999, -999, -999, -999, -999, -999,
  116548. -103, -96, -88, -81, -75, -68, -58, -54,
  116549. -56, -54, -56, -56, -58, -60, -63, -66,
  116550. -74, -69, -72, -72, -75, -74, -77, -81,
  116551. -81, -82, -84, -87, -93, -96, -99, -104,
  116552. -110, -999, -999, -999, -999, -999, -999, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999},
  116554. {-999, -999, -999, -999, -999, -108, -102, -96,
  116555. -91, -85, -80, -74, -68, -60, -51, -46,
  116556. -48, -46, -43, -45, -47, -47, -49, -48,
  116557. -56, -53, -55, -58, -57, -63, -58, -60,
  116558. -66, -64, -67, -70, -70, -74, -77, -84,
  116559. -86, -89, -91, -93, -94, -101, -109, -118,
  116560. -999, -999, -999, -999, -999, -999, -999, -999},
  116561. {-999, -999, -999, -108, -103, -98, -93, -88,
  116562. -83, -78, -73, -68, -60, -53, -44, -35,
  116563. -38, -38, -34, -34, -36, -40, -41, -44,
  116564. -51, -45, -46, -47, -46, -54, -50, -49,
  116565. -50, -50, -50, -51, -54, -57, -58, -60,
  116566. -66, -66, -66, -64, -65, -68, -77, -82,
  116567. -87, -95, -110, -999, -999, -999, -999, -999}},
  116568. /* 500 Hz */
  116569. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116570. -107, -102, -97, -92, -87, -83, -78, -75,
  116571. -82, -79, -83, -85, -89, -92, -95, -98,
  116572. -101, -105, -109, -113, -999, -999, -999, -999,
  116573. -999, -999, -999, -999, -999, -999, -999, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999},
  116576. {-999, -999, -999, -999, -999, -999, -999, -106,
  116577. -100, -95, -90, -86, -81, -78, -74, -69,
  116578. -74, -74, -76, -79, -83, -84, -86, -89,
  116579. -92, -97, -93, -100, -103, -107, -110, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -999, -999, -999, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -999},
  116583. {-999, -999, -999, -999, -999, -999, -106, -100,
  116584. -95, -90, -87, -83, -80, -75, -69, -60,
  116585. -66, -66, -68, -70, -74, -78, -79, -81,
  116586. -81, -83, -84, -87, -93, -96, -99, -103,
  116587. -107, -110, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999,
  116589. -999, -999, -999, -999, -999, -999, -999, -999},
  116590. {-999, -999, -999, -999, -999, -108, -103, -98,
  116591. -93, -89, -85, -82, -78, -71, -62, -55,
  116592. -58, -58, -54, -54, -55, -59, -61, -62,
  116593. -70, -66, -66, -67, -70, -72, -75, -78,
  116594. -84, -84, -84, -88, -91, -90, -95, -98,
  116595. -102, -103, -106, -110, -999, -999, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999},
  116597. {-999, -999, -999, -999, -108, -103, -98, -94,
  116598. -90, -87, -82, -79, -73, -67, -58, -47,
  116599. -50, -45, -41, -45, -48, -44, -44, -49,
  116600. -54, -51, -48, -47, -49, -50, -51, -57,
  116601. -58, -60, -63, -69, -70, -69, -71, -74,
  116602. -78, -82, -90, -95, -101, -105, -110, -999,
  116603. -999, -999, -999, -999, -999, -999, -999, -999},
  116604. {-999, -999, -999, -105, -101, -97, -93, -90,
  116605. -85, -80, -77, -72, -65, -56, -48, -37,
  116606. -40, -36, -34, -40, -50, -47, -38, -41,
  116607. -47, -38, -35, -39, -38, -43, -40, -45,
  116608. -50, -45, -44, -47, -50, -55, -48, -48,
  116609. -52, -66, -70, -76, -82, -90, -97, -105,
  116610. -110, -999, -999, -999, -999, -999, -999, -999}},
  116611. /* 707 Hz */
  116612. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -108, -103, -98, -93, -86, -79, -76,
  116614. -83, -81, -85, -87, -89, -93, -98, -102,
  116615. -107, -112, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999},
  116619. {-999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -108, -103, -98, -93, -86, -79, -71,
  116621. -77, -74, -77, -79, -81, -84, -85, -90,
  116622. -92, -93, -92, -98, -101, -108, -112, -999,
  116623. -999, -999, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999},
  116626. {-999, -999, -999, -999, -999, -999, -999, -999,
  116627. -108, -103, -98, -93, -87, -78, -68, -65,
  116628. -66, -62, -65, -67, -70, -73, -75, -78,
  116629. -82, -82, -83, -84, -91, -93, -98, -102,
  116630. -106, -110, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999},
  116633. {-999, -999, -999, -999, -999, -999, -999, -999,
  116634. -105, -100, -95, -90, -82, -74, -62, -57,
  116635. -58, -56, -51, -52, -52, -54, -54, -58,
  116636. -66, -59, -60, -63, -66, -69, -73, -79,
  116637. -83, -84, -80, -81, -81, -82, -88, -92,
  116638. -98, -105, -113, -999, -999, -999, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999},
  116640. {-999, -999, -999, -999, -999, -999, -999, -107,
  116641. -102, -97, -92, -84, -79, -69, -57, -47,
  116642. -52, -47, -44, -45, -50, -52, -42, -42,
  116643. -53, -43, -43, -48, -51, -56, -55, -52,
  116644. -57, -59, -61, -62, -67, -71, -78, -83,
  116645. -86, -94, -98, -103, -110, -999, -999, -999,
  116646. -999, -999, -999, -999, -999, -999, -999, -999},
  116647. {-999, -999, -999, -999, -999, -999, -105, -100,
  116648. -95, -90, -84, -78, -70, -61, -51, -41,
  116649. -40, -38, -40, -46, -52, -51, -41, -40,
  116650. -46, -40, -38, -38, -41, -46, -41, -46,
  116651. -47, -43, -43, -45, -41, -45, -56, -67,
  116652. -68, -83, -87, -90, -95, -102, -107, -113,
  116653. -999, -999, -999, -999, -999, -999, -999, -999}},
  116654. /* 1000 Hz */
  116655. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -109, -105, -101, -96, -91, -84, -77,
  116657. -82, -82, -85, -89, -94, -100, -106, -110,
  116658. -999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999},
  116662. {-999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -106, -103, -98, -92, -85, -80, -71,
  116664. -75, -72, -76, -80, -84, -86, -89, -93,
  116665. -100, -107, -113, -999, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999},
  116669. {-999, -999, -999, -999, -999, -999, -999, -107,
  116670. -104, -101, -97, -92, -88, -84, -80, -64,
  116671. -66, -63, -64, -66, -69, -73, -77, -83,
  116672. -83, -86, -91, -98, -104, -111, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999},
  116676. {-999, -999, -999, -999, -999, -999, -999, -107,
  116677. -104, -101, -97, -92, -90, -84, -74, -57,
  116678. -58, -52, -55, -54, -50, -52, -50, -52,
  116679. -63, -62, -69, -76, -77, -78, -78, -79,
  116680. -82, -88, -94, -100, -106, -111, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999},
  116683. {-999, -999, -999, -999, -999, -999, -106, -102,
  116684. -98, -95, -90, -85, -83, -78, -70, -50,
  116685. -50, -41, -44, -49, -47, -50, -50, -44,
  116686. -55, -46, -47, -48, -48, -54, -49, -49,
  116687. -58, -62, -71, -81, -87, -92, -97, -102,
  116688. -108, -114, -999, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999},
  116690. {-999, -999, -999, -999, -999, -999, -106, -102,
  116691. -98, -95, -90, -85, -83, -78, -70, -45,
  116692. -43, -41, -47, -50, -51, -50, -49, -45,
  116693. -47, -41, -44, -41, -39, -43, -38, -37,
  116694. -40, -41, -44, -50, -58, -65, -73, -79,
  116695. -85, -92, -97, -101, -105, -109, -113, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999}},
  116697. /* 1414 Hz */
  116698. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116699. -999, -999, -999, -107, -100, -95, -87, -81,
  116700. -85, -83, -88, -93, -100, -107, -114, -999,
  116701. -999, -999, -999, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999},
  116705. {-999, -999, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -107, -101, -95, -88, -83, -76,
  116707. -73, -72, -79, -84, -90, -95, -100, -105,
  116708. -110, -115, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999},
  116712. {-999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -104, -98, -92, -87, -81, -70,
  116714. -65, -62, -67, -71, -74, -80, -85, -91,
  116715. -95, -99, -103, -108, -111, -114, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999},
  116719. {-999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -103, -97, -90, -85, -76, -60,
  116721. -56, -54, -60, -62, -61, -56, -63, -65,
  116722. -73, -74, -77, -75, -78, -81, -86, -87,
  116723. -88, -91, -94, -98, -103, -110, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999},
  116726. {-999, -999, -999, -999, -999, -999, -999, -105,
  116727. -100, -97, -92, -86, -81, -79, -70, -57,
  116728. -51, -47, -51, -58, -60, -56, -53, -50,
  116729. -58, -52, -50, -50, -53, -55, -64, -69,
  116730. -71, -85, -82, -78, -81, -85, -95, -102,
  116731. -112, -999, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999},
  116733. {-999, -999, -999, -999, -999, -999, -999, -105,
  116734. -100, -97, -92, -85, -83, -79, -72, -49,
  116735. -40, -43, -43, -54, -56, -51, -50, -40,
  116736. -43, -38, -36, -35, -37, -38, -37, -44,
  116737. -54, -60, -57, -60, -70, -75, -84, -92,
  116738. -103, -112, -999, -999, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999}},
  116740. /* 2000 Hz */
  116741. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -110, -102, -95, -89, -82,
  116743. -83, -84, -90, -92, -99, -107, -113, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999},
  116748. {-999, -999, -999, -999, -999, -999, -999, -999,
  116749. -999, -999, -107, -101, -95, -89, -83, -72,
  116750. -74, -78, -85, -88, -88, -90, -92, -98,
  116751. -105, -111, -999, -999, -999, -999, -999, -999,
  116752. -999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999},
  116755. {-999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -109, -103, -97, -93, -87, -81, -70,
  116757. -70, -67, -75, -73, -76, -79, -81, -83,
  116758. -88, -89, -97, -103, -110, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999},
  116762. {-999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -107, -100, -94, -88, -83, -75, -63,
  116764. -59, -59, -63, -66, -60, -62, -67, -67,
  116765. -77, -76, -81, -88, -86, -92, -96, -102,
  116766. -109, -116, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999},
  116769. {-999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -105, -98, -92, -86, -81, -73, -56,
  116771. -52, -47, -55, -60, -58, -52, -51, -45,
  116772. -49, -50, -53, -54, -61, -71, -70, -69,
  116773. -78, -79, -87, -90, -96, -104, -112, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999},
  116776. {-999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -103, -96, -90, -86, -78, -70, -51,
  116778. -42, -47, -48, -55, -54, -54, -53, -42,
  116779. -35, -28, -33, -38, -37, -44, -47, -49,
  116780. -54, -63, -68, -78, -82, -89, -94, -99,
  116781. -104, -109, -114, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999}},
  116783. /* 2828 Hz */
  116784. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116785. -999, -999, -999, -999, -110, -100, -90, -79,
  116786. -85, -81, -82, -82, -89, -94, -99, -103,
  116787. -109, -115, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999},
  116791. {-999, -999, -999, -999, -999, -999, -999, -999,
  116792. -999, -999, -999, -999, -105, -97, -85, -72,
  116793. -74, -70, -70, -70, -76, -85, -91, -93,
  116794. -97, -103, -109, -115, -999, -999, -999, -999,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999},
  116798. {-999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -112, -93, -81, -68,
  116800. -62, -60, -60, -57, -63, -70, -77, -82,
  116801. -90, -93, -98, -104, -109, -113, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999},
  116805. {-999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -113, -100, -93, -84, -63,
  116807. -58, -48, -53, -54, -52, -52, -57, -64,
  116808. -66, -76, -83, -81, -85, -85, -90, -95,
  116809. -98, -101, -103, -106, -108, -111, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999},
  116812. {-999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -105, -95, -86, -74, -53,
  116814. -50, -38, -43, -49, -43, -42, -39, -39,
  116815. -46, -52, -57, -56, -72, -69, -74, -81,
  116816. -87, -92, -94, -97, -99, -102, -105, -108,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999},
  116819. {-999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -108, -99, -90, -76, -66, -45,
  116821. -43, -41, -44, -47, -43, -47, -40, -30,
  116822. -31, -31, -39, -33, -40, -41, -43, -53,
  116823. -59, -70, -73, -77, -79, -82, -84, -87,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999}},
  116826. /* 4000 Hz */
  116827. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116828. -999, -999, -999, -999, -999, -110, -91, -76,
  116829. -75, -85, -93, -98, -104, -110, -999, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999},
  116834. {-999, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -999, -999, -999, -999, -110, -91, -70,
  116836. -70, -75, -86, -89, -94, -98, -101, -106,
  116837. -110, -999, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999},
  116841. {-999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -110, -95, -80, -60,
  116843. -65, -64, -74, -83, -88, -91, -95, -99,
  116844. -103, -107, -110, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999},
  116848. {-999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -110, -95, -80, -58,
  116850. -55, -49, -66, -68, -71, -78, -78, -80,
  116851. -88, -85, -89, -97, -100, -105, -110, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999},
  116855. {-999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -110, -95, -80, -53,
  116857. -52, -41, -59, -59, -49, -58, -56, -63,
  116858. -86, -79, -90, -93, -98, -103, -107, -112,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999},
  116862. {-999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -110, -97, -91, -73, -45,
  116864. -40, -33, -53, -61, -49, -54, -50, -50,
  116865. -60, -52, -67, -74, -81, -92, -96, -100,
  116866. -105, -110, -999, -999, -999, -999, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999}},
  116869. /* 5657 Hz */
  116870. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116871. -999, -999, -999, -113, -106, -99, -92, -77,
  116872. -80, -88, -97, -106, -115, -999, -999, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999},
  116877. {-999, -999, -999, -999, -999, -999, -999, -999,
  116878. -999, -999, -116, -109, -102, -95, -89, -74,
  116879. -72, -88, -87, -95, -102, -109, -116, -999,
  116880. -999, -999, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999},
  116884. {-999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -116, -109, -102, -95, -89, -75,
  116886. -66, -74, -77, -78, -86, -87, -90, -96,
  116887. -105, -115, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999},
  116891. {-999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -115, -108, -101, -94, -88, -66,
  116893. -56, -61, -70, -65, -78, -72, -83, -84,
  116894. -93, -98, -105, -110, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999},
  116898. {-999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -110, -105, -95, -89, -82, -57,
  116900. -52, -52, -59, -56, -59, -58, -69, -67,
  116901. -88, -82, -82, -89, -94, -100, -108, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999},
  116905. {-999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -110, -101, -96, -90, -83, -77, -54,
  116907. -43, -38, -50, -48, -52, -48, -42, -42,
  116908. -51, -52, -53, -59, -65, -71, -78, -85,
  116909. -95, -999, -999, -999, -999, -999, -999, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999}},
  116912. /* 8000 Hz */
  116913. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116914. -999, -999, -999, -999, -120, -105, -86, -68,
  116915. -78, -79, -90, -100, -110, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999},
  116920. {-999, -999, -999, -999, -999, -999, -999, -999,
  116921. -999, -999, -999, -999, -120, -105, -86, -66,
  116922. -73, -77, -88, -96, -105, -115, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999},
  116927. {-999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -120, -105, -92, -80, -61,
  116929. -64, -68, -80, -87, -92, -100, -110, -999,
  116930. -999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999},
  116934. {-999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -120, -104, -91, -79, -52,
  116936. -60, -54, -64, -69, -77, -80, -82, -84,
  116937. -85, -87, -88, -90, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999},
  116941. {-999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -118, -100, -87, -77, -49,
  116943. -50, -44, -58, -61, -61, -67, -65, -62,
  116944. -62, -62, -65, -68, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999},
  116948. {-999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -115, -98, -84, -62, -49,
  116950. -44, -38, -46, -49, -49, -46, -39, -37,
  116951. -39, -40, -42, -43, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999}},
  116955. /* 11314 Hz */
  116956. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116957. -999, -999, -999, -999, -999, -110, -88, -74,
  116958. -77, -82, -82, -85, -90, -94, -99, -104,
  116959. -999, -999, -999, -999, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999},
  116963. {-999, -999, -999, -999, -999, -999, -999, -999,
  116964. -999, -999, -999, -999, -999, -110, -88, -66,
  116965. -70, -81, -80, -81, -84, -88, -91, -93,
  116966. -999, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999},
  116970. {-999, -999, -999, -999, -999, -999, -999, -999,
  116971. -999, -999, -999, -999, -999, -110, -88, -61,
  116972. -63, -70, -71, -74, -77, -80, -83, -85,
  116973. -999, -999, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999},
  116977. {-999, -999, -999, -999, -999, -999, -999, -999,
  116978. -999, -999, -999, -999, -999, -110, -86, -62,
  116979. -63, -62, -62, -58, -52, -50, -50, -52,
  116980. -54, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999},
  116984. {-999, -999, -999, -999, -999, -999, -999, -999,
  116985. -999, -999, -999, -999, -118, -108, -84, -53,
  116986. -50, -50, -50, -55, -47, -45, -40, -40,
  116987. -40, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999},
  116991. {-999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -999, -118, -100, -73, -43,
  116993. -37, -42, -43, -53, -38, -37, -35, -35,
  116994. -38, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999}},
  116998. /* 16000 Hz */
  116999. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117000. -999, -999, -999, -110, -100, -91, -84, -74,
  117001. -80, -80, -80, -80, -80, -999, -999, -999,
  117002. -999, -999, -999, -999, -999, -999, -999, -999,
  117003. -999, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999},
  117006. {-999, -999, -999, -999, -999, -999, -999, -999,
  117007. -999, -999, -999, -110, -100, -91, -84, -74,
  117008. -68, -68, -68, -68, -68, -999, -999, -999,
  117009. -999, -999, -999, -999, -999, -999, -999, -999,
  117010. -999, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999},
  117013. {-999, -999, -999, -999, -999, -999, -999, -999,
  117014. -999, -999, -999, -110, -100, -86, -78, -70,
  117015. -60, -45, -30, -21, -999, -999, -999, -999,
  117016. -999, -999, -999, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999},
  117020. {-999, -999, -999, -999, -999, -999, -999, -999,
  117021. -999, -999, -999, -110, -100, -87, -78, -67,
  117022. -48, -38, -29, -21, -999, -999, -999, -999,
  117023. -999, -999, -999, -999, -999, -999, -999, -999,
  117024. -999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999},
  117027. {-999, -999, -999, -999, -999, -999, -999, -999,
  117028. -999, -999, -999, -110, -100, -86, -69, -56,
  117029. -45, -35, -33, -29, -999, -999, -999, -999,
  117030. -999, -999, -999, -999, -999, -999, -999, -999,
  117031. -999, -999, -999, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999},
  117034. {-999, -999, -999, -999, -999, -999, -999, -999,
  117035. -999, -999, -999, -110, -100, -83, -71, -48,
  117036. -27, -38, -37, -34, -999, -999, -999, -999,
  117037. -999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -999, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999}}
  117041. };
  117042. #endif
  117043. /*** End of inlined file: masking.h ***/
  117044. #define NEGINF -9999.f
  117045. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117046. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117047. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117048. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117049. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117050. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117051. look->channels=vi->channels;
  117052. look->ampmax=-9999.;
  117053. look->gi=gi;
  117054. return(look);
  117055. }
  117056. void _vp_global_free(vorbis_look_psy_global *look){
  117057. if(look){
  117058. memset(look,0,sizeof(*look));
  117059. _ogg_free(look);
  117060. }
  117061. }
  117062. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117063. if(i){
  117064. memset(i,0,sizeof(*i));
  117065. _ogg_free(i);
  117066. }
  117067. }
  117068. void _vi_psy_free(vorbis_info_psy *i){
  117069. if(i){
  117070. memset(i,0,sizeof(*i));
  117071. _ogg_free(i);
  117072. }
  117073. }
  117074. static void min_curve(float *c,
  117075. float *c2){
  117076. int i;
  117077. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117078. }
  117079. static void max_curve(float *c,
  117080. float *c2){
  117081. int i;
  117082. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117083. }
  117084. static void attenuate_curve(float *c,float att){
  117085. int i;
  117086. for(i=0;i<EHMER_MAX;i++)
  117087. c[i]+=att;
  117088. }
  117089. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117090. float center_boost, float center_decay_rate){
  117091. int i,j,k,m;
  117092. float ath[EHMER_MAX];
  117093. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117094. float athc[P_LEVELS][EHMER_MAX];
  117095. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117096. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117097. memset(workc,0,sizeof(workc));
  117098. for(i=0;i<P_BANDS;i++){
  117099. /* we add back in the ATH to avoid low level curves falling off to
  117100. -infinity and unnecessarily cutting off high level curves in the
  117101. curve limiting (last step). */
  117102. /* A half-band's settings must be valid over the whole band, and
  117103. it's better to mask too little than too much */
  117104. int ath_offset=i*4;
  117105. for(j=0;j<EHMER_MAX;j++){
  117106. float min=999.;
  117107. for(k=0;k<4;k++)
  117108. if(j+k+ath_offset<MAX_ATH){
  117109. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117110. }else{
  117111. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117112. }
  117113. ath[j]=min;
  117114. }
  117115. /* copy curves into working space, replicate the 50dB curve to 30
  117116. and 40, replicate the 100dB curve to 110 */
  117117. for(j=0;j<6;j++)
  117118. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117119. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117120. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117121. /* apply centered curve boost/decay */
  117122. for(j=0;j<P_LEVELS;j++){
  117123. for(k=0;k<EHMER_MAX;k++){
  117124. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117125. if(adj<0. && center_boost>0)adj=0.;
  117126. if(adj>0. && center_boost<0)adj=0.;
  117127. workc[i][j][k]+=adj;
  117128. }
  117129. }
  117130. /* normalize curves so the driving amplitude is 0dB */
  117131. /* make temp curves with the ATH overlayed */
  117132. for(j=0;j<P_LEVELS;j++){
  117133. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117134. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117135. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117136. max_curve(athc[j],workc[i][j]);
  117137. }
  117138. /* Now limit the louder curves.
  117139. the idea is this: We don't know what the playback attenuation
  117140. will be; 0dB SL moves every time the user twiddles the volume
  117141. knob. So that means we have to use a single 'most pessimal' curve
  117142. for all masking amplitudes, right? Wrong. The *loudest* sound
  117143. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117144. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117145. etc... */
  117146. for(j=1;j<P_LEVELS;j++){
  117147. min_curve(athc[j],athc[j-1]);
  117148. min_curve(workc[i][j],athc[j]);
  117149. }
  117150. }
  117151. for(i=0;i<P_BANDS;i++){
  117152. int hi_curve,lo_curve,bin;
  117153. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117154. /* low frequency curves are measured with greater resolution than
  117155. the MDCT/FFT will actually give us; we want the curve applied
  117156. to the tone data to be pessimistic and thus apply the minimum
  117157. masking possible for a given bin. That means that a single bin
  117158. could span more than one octave and that the curve will be a
  117159. composite of multiple octaves. It also may mean that a single
  117160. bin may span > an eighth of an octave and that the eighth
  117161. octave values may also be composited. */
  117162. /* which octave curves will we be compositing? */
  117163. bin=floor(fromOC(i*.5)/binHz);
  117164. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117165. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117166. if(lo_curve>i)lo_curve=i;
  117167. if(lo_curve<0)lo_curve=0;
  117168. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117169. for(m=0;m<P_LEVELS;m++){
  117170. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117171. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117172. /* render the curve into bins, then pull values back into curve.
  117173. The point is that any inherent subsampling aliasing results in
  117174. a safe minimum */
  117175. for(k=lo_curve;k<=hi_curve;k++){
  117176. int l=0;
  117177. for(j=0;j<EHMER_MAX;j++){
  117178. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117179. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117180. if(lo_bin<0)lo_bin=0;
  117181. if(lo_bin>n)lo_bin=n;
  117182. if(lo_bin<l)l=lo_bin;
  117183. if(hi_bin<0)hi_bin=0;
  117184. if(hi_bin>n)hi_bin=n;
  117185. for(;l<hi_bin && l<n;l++)
  117186. if(brute_buffer[l]>workc[k][m][j])
  117187. brute_buffer[l]=workc[k][m][j];
  117188. }
  117189. for(;l<n;l++)
  117190. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117191. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117192. }
  117193. /* be equally paranoid about being valid up to next half ocatve */
  117194. if(i+1<P_BANDS){
  117195. int l=0;
  117196. k=i+1;
  117197. for(j=0;j<EHMER_MAX;j++){
  117198. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117199. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117200. if(lo_bin<0)lo_bin=0;
  117201. if(lo_bin>n)lo_bin=n;
  117202. if(lo_bin<l)l=lo_bin;
  117203. if(hi_bin<0)hi_bin=0;
  117204. if(hi_bin>n)hi_bin=n;
  117205. for(;l<hi_bin && l<n;l++)
  117206. if(brute_buffer[l]>workc[k][m][j])
  117207. brute_buffer[l]=workc[k][m][j];
  117208. }
  117209. for(;l<n;l++)
  117210. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117211. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117212. }
  117213. for(j=0;j<EHMER_MAX;j++){
  117214. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117215. if(bin<0){
  117216. ret[i][m][j+2]=-999.;
  117217. }else{
  117218. if(bin>=n){
  117219. ret[i][m][j+2]=-999.;
  117220. }else{
  117221. ret[i][m][j+2]=brute_buffer[bin];
  117222. }
  117223. }
  117224. }
  117225. /* add fenceposts */
  117226. for(j=0;j<EHMER_OFFSET;j++)
  117227. if(ret[i][m][j+2]>-200.f)break;
  117228. ret[i][m][0]=j;
  117229. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117230. if(ret[i][m][j+2]>-200.f)
  117231. break;
  117232. ret[i][m][1]=j;
  117233. }
  117234. }
  117235. return(ret);
  117236. }
  117237. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117238. vorbis_info_psy_global *gi,int n,long rate){
  117239. long i,j,lo=-99,hi=1;
  117240. long maxoc;
  117241. memset(p,0,sizeof(*p));
  117242. p->eighth_octave_lines=gi->eighth_octave_lines;
  117243. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117244. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117245. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117246. p->total_octave_lines=maxoc-p->firstoc+1;
  117247. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117248. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117249. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117250. p->vi=vi;
  117251. p->n=n;
  117252. p->rate=rate;
  117253. /* AoTuV HF weighting */
  117254. p->m_val = 1.;
  117255. if(rate < 26000) p->m_val = 0;
  117256. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117257. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117258. /* set up the lookups for a given blocksize and sample rate */
  117259. for(i=0,j=0;i<MAX_ATH-1;i++){
  117260. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117261. float base=ATH[i];
  117262. if(j<endpos){
  117263. float delta=(ATH[i+1]-base)/(endpos-j);
  117264. for(;j<endpos && j<n;j++){
  117265. p->ath[j]=base+100.;
  117266. base+=delta;
  117267. }
  117268. }
  117269. }
  117270. for(i=0;i<n;i++){
  117271. float bark=toBARK(rate/(2*n)*i);
  117272. for(;lo+vi->noisewindowlomin<i &&
  117273. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117274. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117275. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117276. p->bark[i]=((lo-1)<<16)+(hi-1);
  117277. }
  117278. for(i=0;i<n;i++)
  117279. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117280. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117281. vi->tone_centerboost,vi->tone_decay);
  117282. /* set up rolling noise median */
  117283. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117284. for(i=0;i<P_NOISECURVES;i++)
  117285. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117286. for(i=0;i<n;i++){
  117287. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117288. int inthalfoc;
  117289. float del;
  117290. if(halfoc<0)halfoc=0;
  117291. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117292. inthalfoc=(int)halfoc;
  117293. del=halfoc-inthalfoc;
  117294. for(j=0;j<P_NOISECURVES;j++)
  117295. p->noiseoffset[j][i]=
  117296. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117297. p->vi->noiseoff[j][inthalfoc+1]*del;
  117298. }
  117299. #if 0
  117300. {
  117301. static int ls=0;
  117302. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117303. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117304. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117305. }
  117306. #endif
  117307. }
  117308. void _vp_psy_clear(vorbis_look_psy *p){
  117309. int i,j;
  117310. if(p){
  117311. if(p->ath)_ogg_free(p->ath);
  117312. if(p->octave)_ogg_free(p->octave);
  117313. if(p->bark)_ogg_free(p->bark);
  117314. if(p->tonecurves){
  117315. for(i=0;i<P_BANDS;i++){
  117316. for(j=0;j<P_LEVELS;j++){
  117317. _ogg_free(p->tonecurves[i][j]);
  117318. }
  117319. _ogg_free(p->tonecurves[i]);
  117320. }
  117321. _ogg_free(p->tonecurves);
  117322. }
  117323. if(p->noiseoffset){
  117324. for(i=0;i<P_NOISECURVES;i++){
  117325. _ogg_free(p->noiseoffset[i]);
  117326. }
  117327. _ogg_free(p->noiseoffset);
  117328. }
  117329. memset(p,0,sizeof(*p));
  117330. }
  117331. }
  117332. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117333. static void seed_curve(float *seed,
  117334. const float **curves,
  117335. float amp,
  117336. int oc, int n,
  117337. int linesper,float dBoffset){
  117338. int i,post1;
  117339. int seedptr;
  117340. const float *posts,*curve;
  117341. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117342. choice=max(choice,0);
  117343. choice=min(choice,P_LEVELS-1);
  117344. posts=curves[choice];
  117345. curve=posts+2;
  117346. post1=(int)posts[1];
  117347. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117348. for(i=posts[0];i<post1;i++){
  117349. if(seedptr>0){
  117350. float lin=amp+curve[i];
  117351. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117352. }
  117353. seedptr+=linesper;
  117354. if(seedptr>=n)break;
  117355. }
  117356. }
  117357. static void seed_loop(vorbis_look_psy *p,
  117358. const float ***curves,
  117359. const float *f,
  117360. const float *flr,
  117361. float *seed,
  117362. float specmax){
  117363. vorbis_info_psy *vi=p->vi;
  117364. long n=p->n,i;
  117365. float dBoffset=vi->max_curve_dB-specmax;
  117366. /* prime the working vector with peak values */
  117367. for(i=0;i<n;i++){
  117368. float max=f[i];
  117369. long oc=p->octave[i];
  117370. while(i+1<n && p->octave[i+1]==oc){
  117371. i++;
  117372. if(f[i]>max)max=f[i];
  117373. }
  117374. if(max+6.f>flr[i]){
  117375. oc=oc>>p->shiftoc;
  117376. if(oc>=P_BANDS)oc=P_BANDS-1;
  117377. if(oc<0)oc=0;
  117378. seed_curve(seed,
  117379. curves[oc],
  117380. max,
  117381. p->octave[i]-p->firstoc,
  117382. p->total_octave_lines,
  117383. p->eighth_octave_lines,
  117384. dBoffset);
  117385. }
  117386. }
  117387. }
  117388. static void seed_chase(float *seeds, int linesper, long n){
  117389. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117390. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117391. long stack=0;
  117392. long pos=0;
  117393. long i;
  117394. for(i=0;i<n;i++){
  117395. if(stack<2){
  117396. posstack[stack]=i;
  117397. ampstack[stack++]=seeds[i];
  117398. }else{
  117399. while(1){
  117400. if(seeds[i]<ampstack[stack-1]){
  117401. posstack[stack]=i;
  117402. ampstack[stack++]=seeds[i];
  117403. break;
  117404. }else{
  117405. if(i<posstack[stack-1]+linesper){
  117406. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117407. i<posstack[stack-2]+linesper){
  117408. /* we completely overlap, making stack-1 irrelevant. pop it */
  117409. stack--;
  117410. continue;
  117411. }
  117412. }
  117413. posstack[stack]=i;
  117414. ampstack[stack++]=seeds[i];
  117415. break;
  117416. }
  117417. }
  117418. }
  117419. }
  117420. /* the stack now contains only the positions that are relevant. Scan
  117421. 'em straight through */
  117422. for(i=0;i<stack;i++){
  117423. long endpos;
  117424. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117425. endpos=posstack[i+1];
  117426. }else{
  117427. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117428. discarded in short frames */
  117429. }
  117430. if(endpos>n)endpos=n;
  117431. for(;pos<endpos;pos++)
  117432. seeds[pos]=ampstack[i];
  117433. }
  117434. /* there. Linear time. I now remember this was on a problem set I
  117435. had in Grad Skool... I didn't solve it at the time ;-) */
  117436. }
  117437. /* bleaugh, this is more complicated than it needs to be */
  117438. #include<stdio.h>
  117439. static void max_seeds(vorbis_look_psy *p,
  117440. float *seed,
  117441. float *flr){
  117442. long n=p->total_octave_lines;
  117443. int linesper=p->eighth_octave_lines;
  117444. long linpos=0;
  117445. long pos;
  117446. seed_chase(seed,linesper,n); /* for masking */
  117447. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117448. while(linpos+1<p->n){
  117449. float minV=seed[pos];
  117450. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117451. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117452. while(pos+1<=end){
  117453. pos++;
  117454. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117455. minV=seed[pos];
  117456. }
  117457. end=pos+p->firstoc;
  117458. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117459. if(flr[linpos]<minV)flr[linpos]=minV;
  117460. }
  117461. {
  117462. float minV=seed[p->total_octave_lines-1];
  117463. for(;linpos<p->n;linpos++)
  117464. if(flr[linpos]<minV)flr[linpos]=minV;
  117465. }
  117466. }
  117467. static void bark_noise_hybridmp(int n,const long *b,
  117468. const float *f,
  117469. float *noise,
  117470. const float offset,
  117471. const int fixed){
  117472. float *N=(float*) alloca(n*sizeof(*N));
  117473. float *X=(float*) alloca(n*sizeof(*N));
  117474. float *XX=(float*) alloca(n*sizeof(*N));
  117475. float *Y=(float*) alloca(n*sizeof(*N));
  117476. float *XY=(float*) alloca(n*sizeof(*N));
  117477. float tN, tX, tXX, tY, tXY;
  117478. int i;
  117479. int lo, hi;
  117480. float R, A, B, D;
  117481. float w, x, y;
  117482. tN = tX = tXX = tY = tXY = 0.f;
  117483. y = f[0] + offset;
  117484. if (y < 1.f) y = 1.f;
  117485. w = y * y * .5;
  117486. tN += w;
  117487. tX += w;
  117488. tY += w * y;
  117489. N[0] = tN;
  117490. X[0] = tX;
  117491. XX[0] = tXX;
  117492. Y[0] = tY;
  117493. XY[0] = tXY;
  117494. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117495. y = f[i] + offset;
  117496. if (y < 1.f) y = 1.f;
  117497. w = y * y;
  117498. tN += w;
  117499. tX += w * x;
  117500. tXX += w * x * x;
  117501. tY += w * y;
  117502. tXY += w * x * y;
  117503. N[i] = tN;
  117504. X[i] = tX;
  117505. XX[i] = tXX;
  117506. Y[i] = tY;
  117507. XY[i] = tXY;
  117508. }
  117509. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117510. lo = b[i] >> 16;
  117511. if( lo>=0 ) break;
  117512. hi = b[i] & 0xffff;
  117513. tN = N[hi] + N[-lo];
  117514. tX = X[hi] - X[-lo];
  117515. tXX = XX[hi] + XX[-lo];
  117516. tY = Y[hi] + Y[-lo];
  117517. tXY = XY[hi] - XY[-lo];
  117518. A = tY * tXX - tX * tXY;
  117519. B = tN * tXY - tX * tY;
  117520. D = tN * tXX - tX * tX;
  117521. R = (A + x * B) / D;
  117522. if (R < 0.f)
  117523. R = 0.f;
  117524. noise[i] = R - offset;
  117525. }
  117526. for ( ;; i++, x += 1.f) {
  117527. lo = b[i] >> 16;
  117528. hi = b[i] & 0xffff;
  117529. if(hi>=n)break;
  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) R = 0.f;
  117540. noise[i] = R - offset;
  117541. }
  117542. for ( ; i < n; i++, x += 1.f) {
  117543. R = (A + x * B) / D;
  117544. if (R < 0.f) R = 0.f;
  117545. noise[i] = R - offset;
  117546. }
  117547. if (fixed <= 0) return;
  117548. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117549. hi = i + fixed / 2;
  117550. lo = hi - fixed;
  117551. if(lo>=0)break;
  117552. tN = N[hi] + N[-lo];
  117553. tX = X[hi] - X[-lo];
  117554. tXX = XX[hi] + XX[-lo];
  117555. tY = Y[hi] + Y[-lo];
  117556. tXY = XY[hi] - XY[-lo];
  117557. A = tY * tXX - tX * tXY;
  117558. B = tN * tXY - tX * tY;
  117559. D = tN * tXX - tX * tX;
  117560. R = (A + x * B) / D;
  117561. if (R - offset < noise[i]) noise[i] = R - offset;
  117562. }
  117563. for ( ;; i++, x += 1.f) {
  117564. hi = i + fixed / 2;
  117565. lo = hi - fixed;
  117566. if(hi>=n)break;
  117567. tN = N[hi] - N[lo];
  117568. tX = X[hi] - X[lo];
  117569. tXX = XX[hi] - XX[lo];
  117570. tY = Y[hi] - Y[lo];
  117571. tXY = XY[hi] - XY[lo];
  117572. A = tY * tXX - tX * tXY;
  117573. B = tN * tXY - tX * tY;
  117574. D = tN * tXX - tX * tX;
  117575. R = (A + x * B) / D;
  117576. if (R - offset < noise[i]) noise[i] = R - offset;
  117577. }
  117578. for ( ; i < n; i++, x += 1.f) {
  117579. R = (A + x * B) / D;
  117580. if (R - offset < noise[i]) noise[i] = R - offset;
  117581. }
  117582. }
  117583. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117584. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117585. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117586. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117587. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117588. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117589. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117590. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117591. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117592. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117593. 973377.F, 913981.F, 858210.F, 805842.F,
  117594. 756669.F, 710497.F, 667142.F, 626433.F,
  117595. 588208.F, 552316.F, 518613.F, 486967.F,
  117596. 457252.F, 429351.F, 403152.F, 378551.F,
  117597. 355452.F, 333762.F, 313396.F, 294273.F,
  117598. 276316.F, 259455.F, 243623.F, 228757.F,
  117599. 214798.F, 201691.F, 189384.F, 177828.F,
  117600. 166977.F, 156788.F, 147221.F, 138237.F,
  117601. 129802.F, 121881.F, 114444.F, 107461.F,
  117602. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117603. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117604. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117605. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117606. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117607. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117608. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117609. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117610. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117611. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117612. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117613. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117614. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117615. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117616. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117617. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117618. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117619. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117620. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117621. 842.910F, 791.475F, 743.179F, 697.830F,
  117622. 655.249F, 615.265F, 577.722F, 542.469F,
  117623. 509.367F, 478.286F, 449.101F, 421.696F,
  117624. 395.964F, 371.803F, 349.115F, 327.812F,
  117625. 307.809F, 289.026F, 271.390F, 254.830F,
  117626. 239.280F, 224.679F, 210.969F, 198.096F,
  117627. 186.008F, 174.658F, 164.000F, 153.993F,
  117628. 144.596F, 135.773F, 127.488F, 119.708F,
  117629. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117630. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117631. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117632. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117633. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117634. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117635. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117636. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117637. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117638. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117639. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117640. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117641. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117642. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117643. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117644. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117645. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117646. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117647. 1.20790F, 1.13419F, 1.06499F, 1.F
  117648. };
  117649. void _vp_remove_floor(vorbis_look_psy *p,
  117650. float *mdct,
  117651. int *codedflr,
  117652. float *residue,
  117653. int sliding_lowpass){
  117654. int i,n=p->n;
  117655. if(sliding_lowpass>n)sliding_lowpass=n;
  117656. for(i=0;i<sliding_lowpass;i++){
  117657. residue[i]=
  117658. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117659. }
  117660. for(;i<n;i++)
  117661. residue[i]=0.;
  117662. }
  117663. void _vp_noisemask(vorbis_look_psy *p,
  117664. float *logmdct,
  117665. float *logmask){
  117666. int i,n=p->n;
  117667. float *work=(float*) alloca(n*sizeof(*work));
  117668. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117669. 140.,-1);
  117670. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117671. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117672. p->vi->noisewindowfixed);
  117673. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117674. #if 0
  117675. {
  117676. static int seq=0;
  117677. float work2[n];
  117678. for(i=0;i<n;i++){
  117679. work2[i]=logmask[i]+work[i];
  117680. }
  117681. if(seq&1)
  117682. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117683. else
  117684. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117685. if(seq&1)
  117686. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117687. else
  117688. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117689. seq++;
  117690. }
  117691. #endif
  117692. for(i=0;i<n;i++){
  117693. int dB=logmask[i]+.5;
  117694. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117695. if(dB<0)dB=0;
  117696. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117697. }
  117698. }
  117699. void _vp_tonemask(vorbis_look_psy *p,
  117700. float *logfft,
  117701. float *logmask,
  117702. float global_specmax,
  117703. float local_specmax){
  117704. int i,n=p->n;
  117705. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117706. float att=local_specmax+p->vi->ath_adjatt;
  117707. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117708. /* set the ATH (floating below localmax, not global max by a
  117709. specified att) */
  117710. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117711. for(i=0;i<n;i++)
  117712. logmask[i]=p->ath[i]+att;
  117713. /* tone masking */
  117714. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117715. max_seeds(p,seed,logmask);
  117716. }
  117717. void _vp_offset_and_mix(vorbis_look_psy *p,
  117718. float *noise,
  117719. float *tone,
  117720. int offset_select,
  117721. float *logmask,
  117722. float *mdct,
  117723. float *logmdct){
  117724. int i,n=p->n;
  117725. float de, coeffi, cx;/* AoTuV */
  117726. float toneatt=p->vi->tone_masteratt[offset_select];
  117727. cx = p->m_val;
  117728. for(i=0;i<n;i++){
  117729. float val= noise[i]+p->noiseoffset[offset_select][i];
  117730. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117731. logmask[i]=max(val,tone[i]+toneatt);
  117732. /* AoTuV */
  117733. /** @ M1 **
  117734. The following codes improve a noise problem.
  117735. A fundamental idea uses the value of masking and carries out
  117736. the relative compensation of the MDCT.
  117737. However, this code is not perfect and all noise problems cannot be solved.
  117738. by Aoyumi @ 2004/04/18
  117739. */
  117740. if(offset_select == 1) {
  117741. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117742. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117743. if(val > coeffi){
  117744. /* mdct value is > -17.2 dB below floor */
  117745. de = 1.0-((val-coeffi)*0.005*cx);
  117746. /* pro-rated attenuation:
  117747. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117748. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117749. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117750. etc... */
  117751. if(de < 0) de = 0.0001;
  117752. }else
  117753. /* mdct value is <= -17.2 dB below floor */
  117754. de = 1.0-((val-coeffi)*0.0003*cx);
  117755. /* pro-rated attenuation:
  117756. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117757. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117758. etc... */
  117759. mdct[i] *= de;
  117760. }
  117761. }
  117762. }
  117763. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117764. vorbis_info *vi=vd->vi;
  117765. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117766. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117767. int n=ci->blocksizes[vd->W]/2;
  117768. float secs=(float)n/vi->rate;
  117769. amp+=secs*gi->ampmax_att_per_sec;
  117770. if(amp<-9999)amp=-9999;
  117771. return(amp);
  117772. }
  117773. static void couple_lossless(float A, float B,
  117774. float *qA, float *qB){
  117775. int test1=fabs(*qA)>fabs(*qB);
  117776. test1-= fabs(*qA)<fabs(*qB);
  117777. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117778. if(test1==1){
  117779. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117780. }else{
  117781. float temp=*qB;
  117782. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117783. *qA=temp;
  117784. }
  117785. if(*qB>fabs(*qA)*1.9999f){
  117786. *qB= -fabs(*qA)*2.f;
  117787. *qA= -*qA;
  117788. }
  117789. }
  117790. static float hypot_lookup[32]={
  117791. -0.009935, -0.011245, -0.012726, -0.014397,
  117792. -0.016282, -0.018407, -0.020800, -0.023494,
  117793. -0.026522, -0.029923, -0.033737, -0.038010,
  117794. -0.042787, -0.048121, -0.054064, -0.060671,
  117795. -0.068000, -0.076109, -0.085054, -0.094892,
  117796. -0.105675, -0.117451, -0.130260, -0.144134,
  117797. -0.159093, -0.175146, -0.192286, -0.210490,
  117798. -0.229718, -0.249913, -0.271001, -0.292893};
  117799. static void precomputed_couple_point(float premag,
  117800. int floorA,int floorB,
  117801. float *mag, float *ang){
  117802. int test=(floorA>floorB)-1;
  117803. int offset=31-abs(floorA-floorB);
  117804. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117805. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117806. *mag=premag*floormag;
  117807. *ang=0.f;
  117808. }
  117809. /* just like below, this is currently set up to only do
  117810. single-step-depth coupling. Otherwise, we'd have to do more
  117811. copying (which will be inevitable later) */
  117812. /* doing the real circular magnitude calculation is audibly superior
  117813. to (A+B)/sqrt(2) */
  117814. static float dipole_hypot(float a, float b){
  117815. if(a>0.){
  117816. if(b>0.)return sqrt(a*a+b*b);
  117817. if(a>-b)return sqrt(a*a-b*b);
  117818. return -sqrt(b*b-a*a);
  117819. }
  117820. if(b<0.)return -sqrt(a*a+b*b);
  117821. if(-a>b)return -sqrt(a*a-b*b);
  117822. return sqrt(b*b-a*a);
  117823. }
  117824. static float round_hypot(float a, float b){
  117825. if(a>0.){
  117826. if(b>0.)return sqrt(a*a+b*b);
  117827. if(a>-b)return sqrt(a*a+b*b);
  117828. return -sqrt(b*b+a*a);
  117829. }
  117830. if(b<0.)return -sqrt(a*a+b*b);
  117831. if(-a>b)return -sqrt(a*a+b*b);
  117832. return sqrt(b*b+a*a);
  117833. }
  117834. /* revert to round hypot for now */
  117835. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117836. vorbis_info_psy_global *g,
  117837. vorbis_look_psy *p,
  117838. vorbis_info_mapping0 *vi,
  117839. float **mdct){
  117840. int i,j,n=p->n;
  117841. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117842. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117843. for(i=0;i<vi->coupling_steps;i++){
  117844. float *mdctM=mdct[vi->coupling_mag[i]];
  117845. float *mdctA=mdct[vi->coupling_ang[i]];
  117846. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117847. for(j=0;j<limit;j++)
  117848. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117849. for(;j<n;j++)
  117850. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117851. }
  117852. return(ret);
  117853. }
  117854. /* this is for per-channel noise normalization */
  117855. static int apsort(const void *a, const void *b){
  117856. float f1=fabs(**(float**)a);
  117857. float f2=fabs(**(float**)b);
  117858. return (f1<f2)-(f1>f2);
  117859. }
  117860. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117861. vorbis_look_psy *p,
  117862. vorbis_info_mapping0 *vi,
  117863. float **mags){
  117864. if(p->vi->normal_point_p){
  117865. int i,j,k,n=p->n;
  117866. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117867. int partition=p->vi->normal_partition;
  117868. float **work=(float**) alloca(sizeof(*work)*partition);
  117869. for(i=0;i<vi->coupling_steps;i++){
  117870. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117871. for(j=0;j<n;j+=partition){
  117872. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117873. qsort(work,partition,sizeof(*work),apsort);
  117874. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117875. }
  117876. }
  117877. return(ret);
  117878. }
  117879. return(NULL);
  117880. }
  117881. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117882. float *magnitudes,int *sortedindex){
  117883. int i,j,n=p->n;
  117884. vorbis_info_psy *vi=p->vi;
  117885. int partition=vi->normal_partition;
  117886. float **work=(float**) alloca(sizeof(*work)*partition);
  117887. int start=vi->normal_start;
  117888. for(j=start;j<n;j+=partition){
  117889. if(j+partition>n)partition=n-j;
  117890. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117891. qsort(work,partition,sizeof(*work),apsort);
  117892. for(i=0;i<partition;i++){
  117893. sortedindex[i+j-start]=work[i]-magnitudes;
  117894. }
  117895. }
  117896. }
  117897. void _vp_noise_normalize(vorbis_look_psy *p,
  117898. float *in,float *out,int *sortedindex){
  117899. int flag=0,i,j=0,n=p->n;
  117900. vorbis_info_psy *vi=p->vi;
  117901. int partition=vi->normal_partition;
  117902. int start=vi->normal_start;
  117903. if(start>n)start=n;
  117904. if(vi->normal_channel_p){
  117905. for(;j<start;j++)
  117906. out[j]=rint(in[j]);
  117907. for(;j+partition<=n;j+=partition){
  117908. float acc=0.;
  117909. int k;
  117910. for(i=j;i<j+partition;i++)
  117911. acc+=in[i]*in[i];
  117912. for(i=0;i<partition;i++){
  117913. k=sortedindex[i+j-start];
  117914. if(in[k]*in[k]>=.25f){
  117915. out[k]=rint(in[k]);
  117916. acc-=in[k]*in[k];
  117917. flag=1;
  117918. }else{
  117919. if(acc<vi->normal_thresh)break;
  117920. out[k]=unitnorm(in[k]);
  117921. acc-=1.;
  117922. }
  117923. }
  117924. for(;i<partition;i++){
  117925. k=sortedindex[i+j-start];
  117926. out[k]=0.;
  117927. }
  117928. }
  117929. }
  117930. for(;j<n;j++)
  117931. out[j]=rint(in[j]);
  117932. }
  117933. void _vp_couple(int blobno,
  117934. vorbis_info_psy_global *g,
  117935. vorbis_look_psy *p,
  117936. vorbis_info_mapping0 *vi,
  117937. float **res,
  117938. float **mag_memo,
  117939. int **mag_sort,
  117940. int **ifloor,
  117941. int *nonzero,
  117942. int sliding_lowpass){
  117943. int i,j,k,n=p->n;
  117944. /* perform any requested channel coupling */
  117945. /* point stereo can only be used in a first stage (in this encoder)
  117946. because of the dependency on floor lookups */
  117947. for(i=0;i<vi->coupling_steps;i++){
  117948. /* once we're doing multistage coupling in which a channel goes
  117949. through more than one coupling step, the floor vector
  117950. magnitudes will also have to be recalculated an propogated
  117951. along with PCM. Right now, we're not (that will wait until 5.1
  117952. most likely), so the code isn't here yet. The memory management
  117953. here is all assuming single depth couplings anyway. */
  117954. /* make sure coupling a zero and a nonzero channel results in two
  117955. nonzero channels. */
  117956. if(nonzero[vi->coupling_mag[i]] ||
  117957. nonzero[vi->coupling_ang[i]]){
  117958. float *rM=res[vi->coupling_mag[i]];
  117959. float *rA=res[vi->coupling_ang[i]];
  117960. float *qM=rM+n;
  117961. float *qA=rA+n;
  117962. int *floorM=ifloor[vi->coupling_mag[i]];
  117963. int *floorA=ifloor[vi->coupling_ang[i]];
  117964. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117965. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117966. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117967. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117968. int pointlimit=limit;
  117969. nonzero[vi->coupling_mag[i]]=1;
  117970. nonzero[vi->coupling_ang[i]]=1;
  117971. /* The threshold of a stereo is changed with the size of n */
  117972. if(n > 1000)
  117973. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117974. for(j=0;j<p->n;j+=partition){
  117975. float acc=0.f;
  117976. for(k=0;k<partition;k++){
  117977. int l=k+j;
  117978. if(l<sliding_lowpass){
  117979. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117980. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117981. precomputed_couple_point(mag_memo[i][l],
  117982. floorM[l],floorA[l],
  117983. qM+l,qA+l);
  117984. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117985. }else{
  117986. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117987. }
  117988. }else{
  117989. qM[l]=0.;
  117990. qA[l]=0.;
  117991. }
  117992. }
  117993. if(p->vi->normal_point_p){
  117994. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117995. int l=mag_sort[i][j+k];
  117996. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117997. qM[l]=unitnorm(qM[l]);
  117998. acc-=1.f;
  117999. }
  118000. }
  118001. }
  118002. }
  118003. }
  118004. }
  118005. }
  118006. /* AoTuV */
  118007. /** @ M2 **
  118008. The boost problem by the combination of noise normalization and point stereo is eased.
  118009. However, this is a temporary patch.
  118010. by Aoyumi @ 2004/04/18
  118011. */
  118012. void hf_reduction(vorbis_info_psy_global *g,
  118013. vorbis_look_psy *p,
  118014. vorbis_info_mapping0 *vi,
  118015. float **mdct){
  118016. int i,j,n=p->n, de=0.3*p->m_val;
  118017. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118018. for(i=0; i<vi->coupling_steps; i++){
  118019. /* for(j=start; j<limit; j++){} // ???*/
  118020. for(j=limit; j<n; j++)
  118021. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118022. }
  118023. }
  118024. #endif
  118025. /*** End of inlined file: psy.c ***/
  118026. /*** Start of inlined file: registry.c ***/
  118027. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118028. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118029. // tasks..
  118030. #if JUCE_MSVC
  118031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118032. #endif
  118033. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118034. #if JUCE_USE_OGGVORBIS
  118035. /* seems like major overkill now; the backend numbers will grow into
  118036. the infrastructure soon enough */
  118037. extern vorbis_func_floor floor0_exportbundle;
  118038. extern vorbis_func_floor floor1_exportbundle;
  118039. extern vorbis_func_residue residue0_exportbundle;
  118040. extern vorbis_func_residue residue1_exportbundle;
  118041. extern vorbis_func_residue residue2_exportbundle;
  118042. extern vorbis_func_mapping mapping0_exportbundle;
  118043. vorbis_func_floor *_floor_P[]={
  118044. &floor0_exportbundle,
  118045. &floor1_exportbundle,
  118046. };
  118047. vorbis_func_residue *_residue_P[]={
  118048. &residue0_exportbundle,
  118049. &residue1_exportbundle,
  118050. &residue2_exportbundle,
  118051. };
  118052. vorbis_func_mapping *_mapping_P[]={
  118053. &mapping0_exportbundle,
  118054. };
  118055. #endif
  118056. /*** End of inlined file: registry.c ***/
  118057. /*** Start of inlined file: res0.c ***/
  118058. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118059. encode/decode loops are coded for clarity and performance is not
  118060. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118061. it's slow. */
  118062. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118063. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118064. // tasks..
  118065. #if JUCE_MSVC
  118066. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118067. #endif
  118068. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118069. #if JUCE_USE_OGGVORBIS
  118070. #include <stdlib.h>
  118071. #include <string.h>
  118072. #include <math.h>
  118073. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118074. #include <stdio.h>
  118075. #endif
  118076. typedef struct {
  118077. vorbis_info_residue0 *info;
  118078. int parts;
  118079. int stages;
  118080. codebook *fullbooks;
  118081. codebook *phrasebook;
  118082. codebook ***partbooks;
  118083. int partvals;
  118084. int **decodemap;
  118085. long postbits;
  118086. long phrasebits;
  118087. long frames;
  118088. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118089. int train_seq;
  118090. long *training_data[8][64];
  118091. float training_max[8][64];
  118092. float training_min[8][64];
  118093. float tmin;
  118094. float tmax;
  118095. #endif
  118096. } vorbis_look_residue0;
  118097. void res0_free_info(vorbis_info_residue *i){
  118098. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118099. if(info){
  118100. memset(info,0,sizeof(*info));
  118101. _ogg_free(info);
  118102. }
  118103. }
  118104. void res0_free_look(vorbis_look_residue *i){
  118105. int j;
  118106. if(i){
  118107. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118108. #ifdef TRAIN_RES
  118109. {
  118110. int j,k,l;
  118111. for(j=0;j<look->parts;j++){
  118112. /*fprintf(stderr,"partition %d: ",j);*/
  118113. for(k=0;k<8;k++)
  118114. if(look->training_data[k][j]){
  118115. char buffer[80];
  118116. FILE *of;
  118117. codebook *statebook=look->partbooks[j][k];
  118118. /* long and short into the same bucket by current convention */
  118119. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118120. of=fopen(buffer,"a");
  118121. for(l=0;l<statebook->entries;l++)
  118122. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118123. fclose(of);
  118124. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118125. look->training_min[k][j],look->training_max[k][j]);*/
  118126. _ogg_free(look->training_data[k][j]);
  118127. look->training_data[k][j]=NULL;
  118128. }
  118129. /*fprintf(stderr,"\n");*/
  118130. }
  118131. }
  118132. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118133. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118134. (float)look->phrasebits/look->frames,
  118135. (float)look->postbits/look->frames,
  118136. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118137. #endif
  118138. /*vorbis_info_residue0 *info=look->info;
  118139. fprintf(stderr,
  118140. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118141. "(%g/frame) \n",look->frames,look->phrasebits,
  118142. look->resbitsflat,
  118143. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118144. for(j=0;j<look->parts;j++){
  118145. long acc=0;
  118146. fprintf(stderr,"\t[%d] == ",j);
  118147. for(k=0;k<look->stages;k++)
  118148. if((info->secondstages[j]>>k)&1){
  118149. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118150. acc+=look->resbits[j][k];
  118151. }
  118152. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118153. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118154. }
  118155. fprintf(stderr,"\n");*/
  118156. for(j=0;j<look->parts;j++)
  118157. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118158. _ogg_free(look->partbooks);
  118159. for(j=0;j<look->partvals;j++)
  118160. _ogg_free(look->decodemap[j]);
  118161. _ogg_free(look->decodemap);
  118162. memset(look,0,sizeof(*look));
  118163. _ogg_free(look);
  118164. }
  118165. }
  118166. static int icount(unsigned int v){
  118167. int ret=0;
  118168. while(v){
  118169. ret+=v&1;
  118170. v>>=1;
  118171. }
  118172. return(ret);
  118173. }
  118174. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118175. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118176. int j,acc=0;
  118177. oggpack_write(opb,info->begin,24);
  118178. oggpack_write(opb,info->end,24);
  118179. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118180. code with a partitioned book */
  118181. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118182. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118183. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118184. bitmask of one indicates this partition class has bits to write
  118185. this pass */
  118186. for(j=0;j<info->partitions;j++){
  118187. if(ilog(info->secondstages[j])>3){
  118188. /* yes, this is a minor hack due to not thinking ahead */
  118189. oggpack_write(opb,info->secondstages[j],3);
  118190. oggpack_write(opb,1,1);
  118191. oggpack_write(opb,info->secondstages[j]>>3,5);
  118192. }else
  118193. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118194. acc+=icount(info->secondstages[j]);
  118195. }
  118196. for(j=0;j<acc;j++)
  118197. oggpack_write(opb,info->booklist[j],8);
  118198. }
  118199. /* vorbis_info is for range checking */
  118200. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118201. int j,acc=0;
  118202. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118203. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118204. info->begin=oggpack_read(opb,24);
  118205. info->end=oggpack_read(opb,24);
  118206. info->grouping=oggpack_read(opb,24)+1;
  118207. info->partitions=oggpack_read(opb,6)+1;
  118208. info->groupbook=oggpack_read(opb,8);
  118209. for(j=0;j<info->partitions;j++){
  118210. int cascade=oggpack_read(opb,3);
  118211. if(oggpack_read(opb,1))
  118212. cascade|=(oggpack_read(opb,5)<<3);
  118213. info->secondstages[j]=cascade;
  118214. acc+=icount(cascade);
  118215. }
  118216. for(j=0;j<acc;j++)
  118217. info->booklist[j]=oggpack_read(opb,8);
  118218. if(info->groupbook>=ci->books)goto errout;
  118219. for(j=0;j<acc;j++)
  118220. if(info->booklist[j]>=ci->books)goto errout;
  118221. return(info);
  118222. errout:
  118223. res0_free_info(info);
  118224. return(NULL);
  118225. }
  118226. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118227. vorbis_info_residue *vr){
  118228. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118229. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118230. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118231. int j,k,acc=0;
  118232. int dim;
  118233. int maxstage=0;
  118234. look->info=info;
  118235. look->parts=info->partitions;
  118236. look->fullbooks=ci->fullbooks;
  118237. look->phrasebook=ci->fullbooks+info->groupbook;
  118238. dim=look->phrasebook->dim;
  118239. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118240. for(j=0;j<look->parts;j++){
  118241. int stages=ilog(info->secondstages[j]);
  118242. if(stages){
  118243. if(stages>maxstage)maxstage=stages;
  118244. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118245. for(k=0;k<stages;k++)
  118246. if(info->secondstages[j]&(1<<k)){
  118247. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118248. #ifdef TRAIN_RES
  118249. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118250. sizeof(***look->training_data));
  118251. #endif
  118252. }
  118253. }
  118254. }
  118255. look->partvals=rint(pow((float)look->parts,(float)dim));
  118256. look->stages=maxstage;
  118257. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118258. for(j=0;j<look->partvals;j++){
  118259. long val=j;
  118260. long mult=look->partvals/look->parts;
  118261. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118262. for(k=0;k<dim;k++){
  118263. long deco=val/mult;
  118264. val-=deco*mult;
  118265. mult/=look->parts;
  118266. look->decodemap[j][k]=deco;
  118267. }
  118268. }
  118269. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118270. {
  118271. static int train_seq=0;
  118272. look->train_seq=train_seq++;
  118273. }
  118274. #endif
  118275. return(look);
  118276. }
  118277. /* break an abstraction and copy some code for performance purposes */
  118278. static int local_book_besterror(codebook *book,float *a){
  118279. int dim=book->dim,i,k,o;
  118280. int best=0;
  118281. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118282. /* find the quant val of each scalar */
  118283. for(k=0,o=dim;k<dim;++k){
  118284. float val=a[--o];
  118285. i=tt->threshvals>>1;
  118286. if(val<tt->quantthresh[i]){
  118287. if(val<tt->quantthresh[i-1]){
  118288. for(--i;i>0;--i)
  118289. if(val>=tt->quantthresh[i-1])
  118290. break;
  118291. }
  118292. }else{
  118293. for(++i;i<tt->threshvals-1;++i)
  118294. if(val<tt->quantthresh[i])break;
  118295. }
  118296. best=(best*tt->quantvals)+tt->quantmap[i];
  118297. }
  118298. /* regular lattices are easy :-) */
  118299. if(book->c->lengthlist[best]<=0){
  118300. const static_codebook *c=book->c;
  118301. int i,j;
  118302. float bestf=0.f;
  118303. float *e=book->valuelist;
  118304. best=-1;
  118305. for(i=0;i<book->entries;i++){
  118306. if(c->lengthlist[i]>0){
  118307. float thisx=0.f;
  118308. for(j=0;j<dim;j++){
  118309. float val=(e[j]-a[j]);
  118310. thisx+=val*val;
  118311. }
  118312. if(best==-1 || thisx<bestf){
  118313. bestf=thisx;
  118314. best=i;
  118315. }
  118316. }
  118317. e+=dim;
  118318. }
  118319. }
  118320. {
  118321. float *ptr=book->valuelist+best*dim;
  118322. for(i=0;i<dim;i++)
  118323. *a++ -= *ptr++;
  118324. }
  118325. return(best);
  118326. }
  118327. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118328. codebook *book,long *acc){
  118329. int i,bits=0;
  118330. int dim=book->dim;
  118331. int step=n/dim;
  118332. for(i=0;i<step;i++){
  118333. int entry=local_book_besterror(book,vec+i*dim);
  118334. #ifdef TRAIN_RES
  118335. acc[entry]++;
  118336. #endif
  118337. bits+=vorbis_book_encode(book,entry,opb);
  118338. }
  118339. return(bits);
  118340. }
  118341. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118342. float **in,int ch){
  118343. long i,j,k;
  118344. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118345. vorbis_info_residue0 *info=look->info;
  118346. /* move all this setup out later */
  118347. int samples_per_partition=info->grouping;
  118348. int possible_partitions=info->partitions;
  118349. int n=info->end-info->begin;
  118350. int partvals=n/samples_per_partition;
  118351. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118352. float scale=100./samples_per_partition;
  118353. /* we find the partition type for each partition of each
  118354. channel. We'll go back and do the interleaved encoding in a
  118355. bit. For now, clarity */
  118356. for(i=0;i<ch;i++){
  118357. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118358. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118359. }
  118360. for(i=0;i<partvals;i++){
  118361. int offset=i*samples_per_partition+info->begin;
  118362. for(j=0;j<ch;j++){
  118363. float max=0.;
  118364. float ent=0.;
  118365. for(k=0;k<samples_per_partition;k++){
  118366. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118367. ent+=fabs(rint(in[j][offset+k]));
  118368. }
  118369. ent*=scale;
  118370. for(k=0;k<possible_partitions-1;k++)
  118371. if(max<=info->classmetric1[k] &&
  118372. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118373. break;
  118374. partword[j][i]=k;
  118375. }
  118376. }
  118377. #ifdef TRAIN_RESAUX
  118378. {
  118379. FILE *of;
  118380. char buffer[80];
  118381. for(i=0;i<ch;i++){
  118382. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118383. of=fopen(buffer,"a");
  118384. for(j=0;j<partvals;j++)
  118385. fprintf(of,"%ld, ",partword[i][j]);
  118386. fprintf(of,"\n");
  118387. fclose(of);
  118388. }
  118389. }
  118390. #endif
  118391. look->frames++;
  118392. return(partword);
  118393. }
  118394. /* designed for stereo or other modes where the partition size is an
  118395. integer multiple of the number of channels encoded in the current
  118396. submap */
  118397. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118398. int ch){
  118399. long i,j,k,l;
  118400. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118401. vorbis_info_residue0 *info=look->info;
  118402. /* move all this setup out later */
  118403. int samples_per_partition=info->grouping;
  118404. int possible_partitions=info->partitions;
  118405. int n=info->end-info->begin;
  118406. int partvals=n/samples_per_partition;
  118407. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118408. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118409. FILE *of;
  118410. char buffer[80];
  118411. #endif
  118412. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118413. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118414. for(i=0,l=info->begin/ch;i<partvals;i++){
  118415. float magmax=0.f;
  118416. float angmax=0.f;
  118417. for(j=0;j<samples_per_partition;j+=ch){
  118418. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118419. for(k=1;k<ch;k++)
  118420. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118421. l++;
  118422. }
  118423. for(j=0;j<possible_partitions-1;j++)
  118424. if(magmax<=info->classmetric1[j] &&
  118425. angmax<=info->classmetric2[j])
  118426. break;
  118427. partword[0][i]=j;
  118428. }
  118429. #ifdef TRAIN_RESAUX
  118430. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118431. of=fopen(buffer,"a");
  118432. for(i=0;i<partvals;i++)
  118433. fprintf(of,"%ld, ",partword[0][i]);
  118434. fprintf(of,"\n");
  118435. fclose(of);
  118436. #endif
  118437. look->frames++;
  118438. return(partword);
  118439. }
  118440. static int _01forward(oggpack_buffer *opb,
  118441. vorbis_block *vb,vorbis_look_residue *vl,
  118442. float **in,int ch,
  118443. long **partword,
  118444. int (*encode)(oggpack_buffer *,float *,int,
  118445. codebook *,long *)){
  118446. long i,j,k,s;
  118447. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118448. vorbis_info_residue0 *info=look->info;
  118449. /* move all this setup out later */
  118450. int samples_per_partition=info->grouping;
  118451. int possible_partitions=info->partitions;
  118452. int partitions_per_word=look->phrasebook->dim;
  118453. int n=info->end-info->begin;
  118454. int partvals=n/samples_per_partition;
  118455. long resbits[128];
  118456. long resvals[128];
  118457. #ifdef TRAIN_RES
  118458. for(i=0;i<ch;i++)
  118459. for(j=info->begin;j<info->end;j++){
  118460. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118461. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118462. }
  118463. #endif
  118464. memset(resbits,0,sizeof(resbits));
  118465. memset(resvals,0,sizeof(resvals));
  118466. /* we code the partition words for each channel, then the residual
  118467. words for a partition per channel until we've written all the
  118468. residual words for that partition word. Then write the next
  118469. partition channel words... */
  118470. for(s=0;s<look->stages;s++){
  118471. for(i=0;i<partvals;){
  118472. /* first we encode a partition codeword for each channel */
  118473. if(s==0){
  118474. for(j=0;j<ch;j++){
  118475. long val=partword[j][i];
  118476. for(k=1;k<partitions_per_word;k++){
  118477. val*=possible_partitions;
  118478. if(i+k<partvals)
  118479. val+=partword[j][i+k];
  118480. }
  118481. /* training hack */
  118482. if(val<look->phrasebook->entries)
  118483. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118484. #if 0 /*def TRAIN_RES*/
  118485. else
  118486. fprintf(stderr,"!");
  118487. #endif
  118488. }
  118489. }
  118490. /* now we encode interleaved residual values for the partitions */
  118491. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118492. long offset=i*samples_per_partition+info->begin;
  118493. for(j=0;j<ch;j++){
  118494. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118495. if(info->secondstages[partword[j][i]]&(1<<s)){
  118496. codebook *statebook=look->partbooks[partword[j][i]][s];
  118497. if(statebook){
  118498. int ret;
  118499. long *accumulator=NULL;
  118500. #ifdef TRAIN_RES
  118501. accumulator=look->training_data[s][partword[j][i]];
  118502. {
  118503. int l;
  118504. float *samples=in[j]+offset;
  118505. for(l=0;l<samples_per_partition;l++){
  118506. if(samples[l]<look->training_min[s][partword[j][i]])
  118507. look->training_min[s][partword[j][i]]=samples[l];
  118508. if(samples[l]>look->training_max[s][partword[j][i]])
  118509. look->training_max[s][partword[j][i]]=samples[l];
  118510. }
  118511. }
  118512. #endif
  118513. ret=encode(opb,in[j]+offset,samples_per_partition,
  118514. statebook,accumulator);
  118515. look->postbits+=ret;
  118516. resbits[partword[j][i]]+=ret;
  118517. }
  118518. }
  118519. }
  118520. }
  118521. }
  118522. }
  118523. /*{
  118524. long total=0;
  118525. long totalbits=0;
  118526. fprintf(stderr,"%d :: ",vb->mode);
  118527. for(k=0;k<possible_partitions;k++){
  118528. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118529. total+=resvals[k];
  118530. totalbits+=resbits[k];
  118531. }
  118532. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118533. }*/
  118534. return(0);
  118535. }
  118536. /* a truncated packet here just means 'stop working'; it's not an error */
  118537. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118538. float **in,int ch,
  118539. long (*decodepart)(codebook *, float *,
  118540. oggpack_buffer *,int)){
  118541. long i,j,k,l,s;
  118542. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118543. vorbis_info_residue0 *info=look->info;
  118544. /* move all this setup out later */
  118545. int samples_per_partition=info->grouping;
  118546. int partitions_per_word=look->phrasebook->dim;
  118547. int n=info->end-info->begin;
  118548. int partvals=n/samples_per_partition;
  118549. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118550. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118551. for(j=0;j<ch;j++)
  118552. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118553. for(s=0;s<look->stages;s++){
  118554. /* each loop decodes on partition codeword containing
  118555. partitions_pre_word partitions */
  118556. for(i=0,l=0;i<partvals;l++){
  118557. if(s==0){
  118558. /* fetch the partition word for each channel */
  118559. for(j=0;j<ch;j++){
  118560. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118561. if(temp==-1)goto eopbreak;
  118562. partword[j][l]=look->decodemap[temp];
  118563. if(partword[j][l]==NULL)goto errout;
  118564. }
  118565. }
  118566. /* now we decode residual values for the partitions */
  118567. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118568. for(j=0;j<ch;j++){
  118569. long offset=info->begin+i*samples_per_partition;
  118570. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118571. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118572. if(stagebook){
  118573. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118574. samples_per_partition)==-1)goto eopbreak;
  118575. }
  118576. }
  118577. }
  118578. }
  118579. }
  118580. errout:
  118581. eopbreak:
  118582. return(0);
  118583. }
  118584. #if 0
  118585. /* residue 0 and 1 are just slight variants of one another. 0 is
  118586. interleaved, 1 is not */
  118587. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118588. float **in,int *nonzero,int ch){
  118589. /* we encode only the nonzero parts of a bundle */
  118590. int i,used=0;
  118591. for(i=0;i<ch;i++)
  118592. if(nonzero[i])
  118593. in[used++]=in[i];
  118594. if(used)
  118595. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118596. return(_01class(vb,vl,in,used));
  118597. else
  118598. return(0);
  118599. }
  118600. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118601. float **in,float **out,int *nonzero,int ch,
  118602. long **partword){
  118603. /* we encode only the nonzero parts of a bundle */
  118604. int i,j,used=0,n=vb->pcmend/2;
  118605. for(i=0;i<ch;i++)
  118606. if(nonzero[i]){
  118607. if(out)
  118608. for(j=0;j<n;j++)
  118609. out[i][j]+=in[i][j];
  118610. in[used++]=in[i];
  118611. }
  118612. if(used){
  118613. int ret=_01forward(vb,vl,in,used,partword,
  118614. _interleaved_encodepart);
  118615. if(out){
  118616. used=0;
  118617. for(i=0;i<ch;i++)
  118618. if(nonzero[i]){
  118619. for(j=0;j<n;j++)
  118620. out[i][j]-=in[used][j];
  118621. used++;
  118622. }
  118623. }
  118624. return(ret);
  118625. }else{
  118626. return(0);
  118627. }
  118628. }
  118629. #endif
  118630. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118631. float **in,int *nonzero,int ch){
  118632. int i,used=0;
  118633. for(i=0;i<ch;i++)
  118634. if(nonzero[i])
  118635. in[used++]=in[i];
  118636. if(used)
  118637. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118638. else
  118639. return(0);
  118640. }
  118641. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118642. float **in,float **out,int *nonzero,int ch,
  118643. long **partword){
  118644. int i,j,used=0,n=vb->pcmend/2;
  118645. for(i=0;i<ch;i++)
  118646. if(nonzero[i]){
  118647. if(out)
  118648. for(j=0;j<n;j++)
  118649. out[i][j]+=in[i][j];
  118650. in[used++]=in[i];
  118651. }
  118652. if(used){
  118653. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118654. if(out){
  118655. used=0;
  118656. for(i=0;i<ch;i++)
  118657. if(nonzero[i]){
  118658. for(j=0;j<n;j++)
  118659. out[i][j]-=in[used][j];
  118660. used++;
  118661. }
  118662. }
  118663. return(ret);
  118664. }else{
  118665. return(0);
  118666. }
  118667. }
  118668. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118669. float **in,int *nonzero,int ch){
  118670. int i,used=0;
  118671. for(i=0;i<ch;i++)
  118672. if(nonzero[i])
  118673. in[used++]=in[i];
  118674. if(used)
  118675. return(_01class(vb,vl,in,used));
  118676. else
  118677. return(0);
  118678. }
  118679. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118680. float **in,int *nonzero,int ch){
  118681. int i,used=0;
  118682. for(i=0;i<ch;i++)
  118683. if(nonzero[i])
  118684. in[used++]=in[i];
  118685. if(used)
  118686. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118687. else
  118688. return(0);
  118689. }
  118690. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118691. float **in,int *nonzero,int ch){
  118692. int i,used=0;
  118693. for(i=0;i<ch;i++)
  118694. if(nonzero[i])used++;
  118695. if(used)
  118696. return(_2class(vb,vl,in,ch));
  118697. else
  118698. return(0);
  118699. }
  118700. /* res2 is slightly more different; all the channels are interleaved
  118701. into a single vector and encoded. */
  118702. int res2_forward(oggpack_buffer *opb,
  118703. vorbis_block *vb,vorbis_look_residue *vl,
  118704. float **in,float **out,int *nonzero,int ch,
  118705. long **partword){
  118706. long i,j,k,n=vb->pcmend/2,used=0;
  118707. /* don't duplicate the code; use a working vector hack for now and
  118708. reshape ourselves into a single channel res1 */
  118709. /* ugly; reallocs for each coupling pass :-( */
  118710. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118711. for(i=0;i<ch;i++){
  118712. float *pcm=in[i];
  118713. if(nonzero[i])used++;
  118714. for(j=0,k=i;j<n;j++,k+=ch)
  118715. work[k]=pcm[j];
  118716. }
  118717. if(used){
  118718. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118719. /* update the sofar vector */
  118720. if(out){
  118721. for(i=0;i<ch;i++){
  118722. float *pcm=in[i];
  118723. float *sofar=out[i];
  118724. for(j=0,k=i;j<n;j++,k+=ch)
  118725. sofar[j]+=pcm[j]-work[k];
  118726. }
  118727. }
  118728. return(ret);
  118729. }else{
  118730. return(0);
  118731. }
  118732. }
  118733. /* duplicate code here as speed is somewhat more important */
  118734. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118735. float **in,int *nonzero,int ch){
  118736. long i,k,l,s;
  118737. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118738. vorbis_info_residue0 *info=look->info;
  118739. /* move all this setup out later */
  118740. int samples_per_partition=info->grouping;
  118741. int partitions_per_word=look->phrasebook->dim;
  118742. int n=info->end-info->begin;
  118743. int partvals=n/samples_per_partition;
  118744. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118745. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118746. for(i=0;i<ch;i++)if(nonzero[i])break;
  118747. if(i==ch)return(0); /* no nonzero vectors */
  118748. for(s=0;s<look->stages;s++){
  118749. for(i=0,l=0;i<partvals;l++){
  118750. if(s==0){
  118751. /* fetch the partition word */
  118752. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118753. if(temp==-1)goto eopbreak;
  118754. partword[l]=look->decodemap[temp];
  118755. if(partword[l]==NULL)goto errout;
  118756. }
  118757. /* now we decode residual values for the partitions */
  118758. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118759. if(info->secondstages[partword[l][k]]&(1<<s)){
  118760. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118761. if(stagebook){
  118762. if(vorbis_book_decodevv_add(stagebook,in,
  118763. i*samples_per_partition+info->begin,ch,
  118764. &vb->opb,samples_per_partition)==-1)
  118765. goto eopbreak;
  118766. }
  118767. }
  118768. }
  118769. }
  118770. errout:
  118771. eopbreak:
  118772. return(0);
  118773. }
  118774. vorbis_func_residue residue0_exportbundle={
  118775. NULL,
  118776. &res0_unpack,
  118777. &res0_look,
  118778. &res0_free_info,
  118779. &res0_free_look,
  118780. NULL,
  118781. NULL,
  118782. &res0_inverse
  118783. };
  118784. vorbis_func_residue residue1_exportbundle={
  118785. &res0_pack,
  118786. &res0_unpack,
  118787. &res0_look,
  118788. &res0_free_info,
  118789. &res0_free_look,
  118790. &res1_class,
  118791. &res1_forward,
  118792. &res1_inverse
  118793. };
  118794. vorbis_func_residue residue2_exportbundle={
  118795. &res0_pack,
  118796. &res0_unpack,
  118797. &res0_look,
  118798. &res0_free_info,
  118799. &res0_free_look,
  118800. &res2_class,
  118801. &res2_forward,
  118802. &res2_inverse
  118803. };
  118804. #endif
  118805. /*** End of inlined file: res0.c ***/
  118806. /*** Start of inlined file: sharedbook.c ***/
  118807. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118808. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118809. // tasks..
  118810. #if JUCE_MSVC
  118811. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118812. #endif
  118813. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118814. #if JUCE_USE_OGGVORBIS
  118815. #include <stdlib.h>
  118816. #include <math.h>
  118817. #include <string.h>
  118818. /**** pack/unpack helpers ******************************************/
  118819. int _ilog(unsigned int v){
  118820. int ret=0;
  118821. while(v){
  118822. ret++;
  118823. v>>=1;
  118824. }
  118825. return(ret);
  118826. }
  118827. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118828. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118829. Why not IEEE? It's just not that important here. */
  118830. #define VQ_FEXP 10
  118831. #define VQ_FMAN 21
  118832. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118833. /* doesn't currently guard under/overflow */
  118834. long _float32_pack(float val){
  118835. int sign=0;
  118836. long exp;
  118837. long mant;
  118838. if(val<0){
  118839. sign=0x80000000;
  118840. val= -val;
  118841. }
  118842. exp= floor(log(val)/log(2.f));
  118843. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118844. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118845. return(sign|exp|mant);
  118846. }
  118847. float _float32_unpack(long val){
  118848. double mant=val&0x1fffff;
  118849. int sign=val&0x80000000;
  118850. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118851. if(sign)mant= -mant;
  118852. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118853. }
  118854. /* given a list of word lengths, generate a list of codewords. Works
  118855. for length ordered or unordered, always assigns the lowest valued
  118856. codewords first. Extended to handle unused entries (length 0) */
  118857. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118858. long i,j,count=0;
  118859. ogg_uint32_t marker[33];
  118860. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118861. memset(marker,0,sizeof(marker));
  118862. for(i=0;i<n;i++){
  118863. long length=l[i];
  118864. if(length>0){
  118865. ogg_uint32_t entry=marker[length];
  118866. /* when we claim a node for an entry, we also claim the nodes
  118867. below it (pruning off the imagined tree that may have dangled
  118868. from it) as well as blocking the use of any nodes directly
  118869. above for leaves */
  118870. /* update ourself */
  118871. if(length<32 && (entry>>length)){
  118872. /* error condition; the lengths must specify an overpopulated tree */
  118873. _ogg_free(r);
  118874. return(NULL);
  118875. }
  118876. r[count++]=entry;
  118877. /* Look to see if the next shorter marker points to the node
  118878. above. if so, update it and repeat. */
  118879. {
  118880. for(j=length;j>0;j--){
  118881. if(marker[j]&1){
  118882. /* have to jump branches */
  118883. if(j==1)
  118884. marker[1]++;
  118885. else
  118886. marker[j]=marker[j-1]<<1;
  118887. break; /* invariant says next upper marker would already
  118888. have been moved if it was on the same path */
  118889. }
  118890. marker[j]++;
  118891. }
  118892. }
  118893. /* prune the tree; the implicit invariant says all the longer
  118894. markers were dangling from our just-taken node. Dangle them
  118895. from our *new* node. */
  118896. for(j=length+1;j<33;j++)
  118897. if((marker[j]>>1) == entry){
  118898. entry=marker[j];
  118899. marker[j]=marker[j-1]<<1;
  118900. }else
  118901. break;
  118902. }else
  118903. if(sparsecount==0)count++;
  118904. }
  118905. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118906. endian */
  118907. for(i=0,count=0;i<n;i++){
  118908. ogg_uint32_t temp=0;
  118909. for(j=0;j<l[i];j++){
  118910. temp<<=1;
  118911. temp|=(r[count]>>j)&1;
  118912. }
  118913. if(sparsecount){
  118914. if(l[i])
  118915. r[count++]=temp;
  118916. }else
  118917. r[count++]=temp;
  118918. }
  118919. return(r);
  118920. }
  118921. /* there might be a straightforward one-line way to do the below
  118922. that's portable and totally safe against roundoff, but I haven't
  118923. thought of it. Therefore, we opt on the side of caution */
  118924. long _book_maptype1_quantvals(const static_codebook *b){
  118925. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118926. /* the above *should* be reliable, but we'll not assume that FP is
  118927. ever reliable when bitstream sync is at stake; verify via integer
  118928. means that vals really is the greatest value of dim for which
  118929. vals^b->bim <= b->entries */
  118930. /* treat the above as an initial guess */
  118931. while(1){
  118932. long acc=1;
  118933. long acc1=1;
  118934. int i;
  118935. for(i=0;i<b->dim;i++){
  118936. acc*=vals;
  118937. acc1*=vals+1;
  118938. }
  118939. if(acc<=b->entries && acc1>b->entries){
  118940. return(vals);
  118941. }else{
  118942. if(acc>b->entries){
  118943. vals--;
  118944. }else{
  118945. vals++;
  118946. }
  118947. }
  118948. }
  118949. }
  118950. /* unpack the quantized list of values for encode/decode ***********/
  118951. /* we need to deal with two map types: in map type 1, the values are
  118952. generated algorithmically (each column of the vector counts through
  118953. the values in the quant vector). in map type 2, all the values came
  118954. in in an explicit list. Both value lists must be unpacked */
  118955. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118956. long j,k,count=0;
  118957. if(b->maptype==1 || b->maptype==2){
  118958. int quantvals;
  118959. float mindel=_float32_unpack(b->q_min);
  118960. float delta=_float32_unpack(b->q_delta);
  118961. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118962. /* maptype 1 and 2 both use a quantized value vector, but
  118963. different sizes */
  118964. switch(b->maptype){
  118965. case 1:
  118966. /* most of the time, entries%dimensions == 0, but we need to be
  118967. well defined. We define that the possible vales at each
  118968. scalar is values == entries/dim. If entries%dim != 0, we'll
  118969. have 'too few' values (values*dim<entries), which means that
  118970. we'll have 'left over' entries; left over entries use zeroed
  118971. values (and are wasted). So don't generate codebooks like
  118972. that */
  118973. quantvals=_book_maptype1_quantvals(b);
  118974. for(j=0;j<b->entries;j++){
  118975. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118976. float last=0.f;
  118977. int indexdiv=1;
  118978. for(k=0;k<b->dim;k++){
  118979. int index= (j/indexdiv)%quantvals;
  118980. float val=b->quantlist[index];
  118981. val=fabs(val)*delta+mindel+last;
  118982. if(b->q_sequencep)last=val;
  118983. if(sparsemap)
  118984. r[sparsemap[count]*b->dim+k]=val;
  118985. else
  118986. r[count*b->dim+k]=val;
  118987. indexdiv*=quantvals;
  118988. }
  118989. count++;
  118990. }
  118991. }
  118992. break;
  118993. case 2:
  118994. for(j=0;j<b->entries;j++){
  118995. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118996. float last=0.f;
  118997. for(k=0;k<b->dim;k++){
  118998. float val=b->quantlist[j*b->dim+k];
  118999. val=fabs(val)*delta+mindel+last;
  119000. if(b->q_sequencep)last=val;
  119001. if(sparsemap)
  119002. r[sparsemap[count]*b->dim+k]=val;
  119003. else
  119004. r[count*b->dim+k]=val;
  119005. }
  119006. count++;
  119007. }
  119008. }
  119009. break;
  119010. }
  119011. return(r);
  119012. }
  119013. return(NULL);
  119014. }
  119015. void vorbis_staticbook_clear(static_codebook *b){
  119016. if(b->allocedp){
  119017. if(b->quantlist)_ogg_free(b->quantlist);
  119018. if(b->lengthlist)_ogg_free(b->lengthlist);
  119019. if(b->nearest_tree){
  119020. _ogg_free(b->nearest_tree->ptr0);
  119021. _ogg_free(b->nearest_tree->ptr1);
  119022. _ogg_free(b->nearest_tree->p);
  119023. _ogg_free(b->nearest_tree->q);
  119024. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119025. _ogg_free(b->nearest_tree);
  119026. }
  119027. if(b->thresh_tree){
  119028. _ogg_free(b->thresh_tree->quantthresh);
  119029. _ogg_free(b->thresh_tree->quantmap);
  119030. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119031. _ogg_free(b->thresh_tree);
  119032. }
  119033. memset(b,0,sizeof(*b));
  119034. }
  119035. }
  119036. void vorbis_staticbook_destroy(static_codebook *b){
  119037. if(b->allocedp){
  119038. vorbis_staticbook_clear(b);
  119039. _ogg_free(b);
  119040. }
  119041. }
  119042. void vorbis_book_clear(codebook *b){
  119043. /* static book is not cleared; we're likely called on the lookup and
  119044. the static codebook belongs to the info struct */
  119045. if(b->valuelist)_ogg_free(b->valuelist);
  119046. if(b->codelist)_ogg_free(b->codelist);
  119047. if(b->dec_index)_ogg_free(b->dec_index);
  119048. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119049. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119050. memset(b,0,sizeof(*b));
  119051. }
  119052. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119053. memset(c,0,sizeof(*c));
  119054. c->c=s;
  119055. c->entries=s->entries;
  119056. c->used_entries=s->entries;
  119057. c->dim=s->dim;
  119058. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119059. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119060. return(0);
  119061. }
  119062. static int sort32a(const void *a,const void *b){
  119063. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119064. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119065. }
  119066. /* decode codebook arrangement is more heavily optimized than encode */
  119067. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119068. int i,j,n=0,tabn;
  119069. int *sortindex;
  119070. memset(c,0,sizeof(*c));
  119071. /* count actually used entries */
  119072. for(i=0;i<s->entries;i++)
  119073. if(s->lengthlist[i]>0)
  119074. n++;
  119075. c->entries=s->entries;
  119076. c->used_entries=n;
  119077. c->dim=s->dim;
  119078. /* two different remappings go on here.
  119079. First, we collapse the likely sparse codebook down only to
  119080. actually represented values/words. This collapsing needs to be
  119081. indexed as map-valueless books are used to encode original entry
  119082. positions as integers.
  119083. Second, we reorder all vectors, including the entry index above,
  119084. by sorted bitreversed codeword to allow treeless decode. */
  119085. {
  119086. /* perform sort */
  119087. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119088. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119089. if(codes==NULL)goto err_out;
  119090. for(i=0;i<n;i++){
  119091. codes[i]=ogg_bitreverse(codes[i]);
  119092. codep[i]=codes+i;
  119093. }
  119094. qsort(codep,n,sizeof(*codep),sort32a);
  119095. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119096. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119097. /* the index is a reverse index */
  119098. for(i=0;i<n;i++){
  119099. int position=codep[i]-codes;
  119100. sortindex[position]=i;
  119101. }
  119102. for(i=0;i<n;i++)
  119103. c->codelist[sortindex[i]]=codes[i];
  119104. _ogg_free(codes);
  119105. }
  119106. c->valuelist=_book_unquantize(s,n,sortindex);
  119107. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119108. for(n=0,i=0;i<s->entries;i++)
  119109. if(s->lengthlist[i]>0)
  119110. c->dec_index[sortindex[n++]]=i;
  119111. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119112. for(n=0,i=0;i<s->entries;i++)
  119113. if(s->lengthlist[i]>0)
  119114. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119115. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119116. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119117. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119118. tabn=1<<c->dec_firsttablen;
  119119. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119120. c->dec_maxlength=0;
  119121. for(i=0;i<n;i++){
  119122. if(c->dec_maxlength<c->dec_codelengths[i])
  119123. c->dec_maxlength=c->dec_codelengths[i];
  119124. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119125. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119126. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119127. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119128. }
  119129. }
  119130. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119131. hints for the non-direct-hits */
  119132. {
  119133. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119134. long lo=0,hi=0;
  119135. for(i=0;i<tabn;i++){
  119136. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119137. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119138. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119139. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119140. /* we only actually have 15 bits per hint to play with here.
  119141. In order to overflow gracefully (nothing breaks, efficiency
  119142. just drops), encode as the difference from the extremes. */
  119143. {
  119144. unsigned long loval=lo;
  119145. unsigned long hival=n-hi;
  119146. if(loval>0x7fff)loval=0x7fff;
  119147. if(hival>0x7fff)hival=0x7fff;
  119148. c->dec_firsttable[ogg_bitreverse(word)]=
  119149. 0x80000000UL | (loval<<15) | hival;
  119150. }
  119151. }
  119152. }
  119153. }
  119154. return(0);
  119155. err_out:
  119156. vorbis_book_clear(c);
  119157. return(-1);
  119158. }
  119159. static float _dist(int el,float *ref, float *b,int step){
  119160. int i;
  119161. float acc=0.f;
  119162. for(i=0;i<el;i++){
  119163. float val=(ref[i]-b[i*step]);
  119164. acc+=val*val;
  119165. }
  119166. return(acc);
  119167. }
  119168. int _best(codebook *book, float *a, int step){
  119169. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119170. #if 0
  119171. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119172. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119173. #endif
  119174. int dim=book->dim;
  119175. int k,o;
  119176. /*int savebest=-1;
  119177. float saverr;*/
  119178. /* do we have a threshhold encode hint? */
  119179. if(tt){
  119180. int index=0,i;
  119181. /* find the quant val of each scalar */
  119182. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119183. i=tt->threshvals>>1;
  119184. if(a[o]<tt->quantthresh[i]){
  119185. for(;i>0;i--)
  119186. if(a[o]>=tt->quantthresh[i-1])
  119187. break;
  119188. }else{
  119189. for(i++;i<tt->threshvals-1;i++)
  119190. if(a[o]<tt->quantthresh[i])break;
  119191. }
  119192. index=(index*tt->quantvals)+tt->quantmap[i];
  119193. }
  119194. /* regular lattices are easy :-) */
  119195. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119196. use a decision tree after all
  119197. and fall through*/
  119198. return(index);
  119199. }
  119200. #if 0
  119201. /* do we have a pigeonhole encode hint? */
  119202. if(pt){
  119203. const static_codebook *c=book->c;
  119204. int i,besti=-1;
  119205. float best=0.f;
  119206. int entry=0;
  119207. /* dealing with sequentialness is a pain in the ass */
  119208. if(c->q_sequencep){
  119209. int pv;
  119210. long mul=1;
  119211. float qlast=0;
  119212. for(k=0,o=0;k<dim;k++,o+=step){
  119213. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119214. if(pv<0 || pv>=pt->mapentries)break;
  119215. entry+=pt->pigeonmap[pv]*mul;
  119216. mul*=pt->quantvals;
  119217. qlast+=pv*pt->del+pt->min;
  119218. }
  119219. }else{
  119220. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119221. int pv=(int)((a[o]-pt->min)/pt->del);
  119222. if(pv<0 || pv>=pt->mapentries)break;
  119223. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119224. }
  119225. }
  119226. /* must be within the pigeonholable range; if we quant outside (or
  119227. in an entry that we define no list for), brute force it */
  119228. if(k==dim && pt->fitlength[entry]){
  119229. /* search the abbreviated list */
  119230. long *list=pt->fitlist+pt->fitmap[entry];
  119231. for(i=0;i<pt->fitlength[entry];i++){
  119232. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119233. if(besti==-1 || this<best){
  119234. best=this;
  119235. besti=list[i];
  119236. }
  119237. }
  119238. return(besti);
  119239. }
  119240. }
  119241. if(nt){
  119242. /* optimized using the decision tree */
  119243. while(1){
  119244. float c=0.f;
  119245. float *p=book->valuelist+nt->p[ptr];
  119246. float *q=book->valuelist+nt->q[ptr];
  119247. for(k=0,o=0;k<dim;k++,o+=step)
  119248. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119249. if(c>0.f) /* in A */
  119250. ptr= -nt->ptr0[ptr];
  119251. else /* in B */
  119252. ptr= -nt->ptr1[ptr];
  119253. if(ptr<=0)break;
  119254. }
  119255. return(-ptr);
  119256. }
  119257. #endif
  119258. /* brute force it! */
  119259. {
  119260. const static_codebook *c=book->c;
  119261. int i,besti=-1;
  119262. float best=0.f;
  119263. float *e=book->valuelist;
  119264. for(i=0;i<book->entries;i++){
  119265. if(c->lengthlist[i]>0){
  119266. float thisx=_dist(dim,e,a,step);
  119267. if(besti==-1 || thisx<best){
  119268. best=thisx;
  119269. besti=i;
  119270. }
  119271. }
  119272. e+=dim;
  119273. }
  119274. /*if(savebest!=-1 && savebest!=besti){
  119275. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119276. "original:");
  119277. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119278. fprintf(stderr,"\n"
  119279. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119280. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119281. (book->valuelist+savebest*dim)[i]);
  119282. fprintf(stderr,"\n"
  119283. "bruteforce (entry %d, err %g):",besti,best);
  119284. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119285. (book->valuelist+besti*dim)[i]);
  119286. fprintf(stderr,"\n");
  119287. }*/
  119288. return(besti);
  119289. }
  119290. }
  119291. long vorbis_book_codeword(codebook *book,int entry){
  119292. if(book->c) /* only use with encode; decode optimizations are
  119293. allowed to break this */
  119294. return book->codelist[entry];
  119295. return -1;
  119296. }
  119297. long vorbis_book_codelen(codebook *book,int entry){
  119298. if(book->c) /* only use with encode; decode optimizations are
  119299. allowed to break this */
  119300. return book->c->lengthlist[entry];
  119301. return -1;
  119302. }
  119303. #ifdef _V_SELFTEST
  119304. /* Unit tests of the dequantizer; this stuff will be OK
  119305. cross-platform, I simply want to be sure that special mapping cases
  119306. actually work properly; a bug could go unnoticed for a while */
  119307. #include <stdio.h>
  119308. /* cases:
  119309. no mapping
  119310. full, explicit mapping
  119311. algorithmic mapping
  119312. nonsequential
  119313. sequential
  119314. */
  119315. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119316. static long partial_quantlist1[]={0,7,2};
  119317. /* no mapping */
  119318. static_codebook test1={
  119319. 4,16,
  119320. NULL,
  119321. 0,
  119322. 0,0,0,0,
  119323. NULL,
  119324. NULL,NULL
  119325. };
  119326. static float *test1_result=NULL;
  119327. /* linear, full mapping, nonsequential */
  119328. static_codebook test2={
  119329. 4,3,
  119330. NULL,
  119331. 2,
  119332. -533200896,1611661312,4,0,
  119333. full_quantlist1,
  119334. NULL,NULL
  119335. };
  119336. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119337. /* linear, full mapping, sequential */
  119338. static_codebook test3={
  119339. 4,3,
  119340. NULL,
  119341. 2,
  119342. -533200896,1611661312,4,1,
  119343. full_quantlist1,
  119344. NULL,NULL
  119345. };
  119346. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119347. /* linear, algorithmic mapping, nonsequential */
  119348. static_codebook test4={
  119349. 3,27,
  119350. NULL,
  119351. 1,
  119352. -533200896,1611661312,4,0,
  119353. partial_quantlist1,
  119354. NULL,NULL
  119355. };
  119356. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119357. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119358. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119359. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119360. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119361. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119362. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119363. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119364. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119365. /* linear, algorithmic mapping, sequential */
  119366. static_codebook test5={
  119367. 3,27,
  119368. NULL,
  119369. 1,
  119370. -533200896,1611661312,4,1,
  119371. partial_quantlist1,
  119372. NULL,NULL
  119373. };
  119374. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119375. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119376. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119377. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119378. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119379. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119380. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119381. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119382. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119383. void run_test(static_codebook *b,float *comp){
  119384. float *out=_book_unquantize(b,b->entries,NULL);
  119385. int i;
  119386. if(comp){
  119387. if(!out){
  119388. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119389. exit(1);
  119390. }
  119391. for(i=0;i<b->entries*b->dim;i++)
  119392. if(fabs(out[i]-comp[i])>.0001){
  119393. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119394. "position %d, %g != %g\n",i,out[i],comp[i]);
  119395. exit(1);
  119396. }
  119397. }else{
  119398. if(out){
  119399. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119400. " correct result should have been NULL\n");
  119401. exit(1);
  119402. }
  119403. }
  119404. }
  119405. int main(){
  119406. /* run the nine dequant tests, and compare to the hand-rolled results */
  119407. fprintf(stderr,"Dequant test 1... ");
  119408. run_test(&test1,test1_result);
  119409. fprintf(stderr,"OK\nDequant test 2... ");
  119410. run_test(&test2,test2_result);
  119411. fprintf(stderr,"OK\nDequant test 3... ");
  119412. run_test(&test3,test3_result);
  119413. fprintf(stderr,"OK\nDequant test 4... ");
  119414. run_test(&test4,test4_result);
  119415. fprintf(stderr,"OK\nDequant test 5... ");
  119416. run_test(&test5,test5_result);
  119417. fprintf(stderr,"OK\n\n");
  119418. return(0);
  119419. }
  119420. #endif
  119421. #endif
  119422. /*** End of inlined file: sharedbook.c ***/
  119423. /*** Start of inlined file: smallft.c ***/
  119424. /* FFT implementation from OggSquish, minus cosine transforms,
  119425. * minus all but radix 2/4 case. In Vorbis we only need this
  119426. * cut-down version.
  119427. *
  119428. * To do more than just power-of-two sized vectors, see the full
  119429. * version I wrote for NetLib.
  119430. *
  119431. * Note that the packing is a little strange; rather than the FFT r/i
  119432. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119433. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119434. * FORTRAN version
  119435. */
  119436. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119437. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119438. // tasks..
  119439. #if JUCE_MSVC
  119440. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119441. #endif
  119442. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119443. #if JUCE_USE_OGGVORBIS
  119444. #include <stdlib.h>
  119445. #include <string.h>
  119446. #include <math.h>
  119447. static void drfti1(int n, float *wa, int *ifac){
  119448. static int ntryh[4] = { 4,2,3,5 };
  119449. static float tpi = 6.28318530717958648f;
  119450. float arg,argh,argld,fi;
  119451. int ntry=0,i,j=-1;
  119452. int k1, l1, l2, ib;
  119453. int ld, ii, ip, is, nq, nr;
  119454. int ido, ipm, nfm1;
  119455. int nl=n;
  119456. int nf=0;
  119457. L101:
  119458. j++;
  119459. if (j < 4)
  119460. ntry=ntryh[j];
  119461. else
  119462. ntry+=2;
  119463. L104:
  119464. nq=nl/ntry;
  119465. nr=nl-ntry*nq;
  119466. if (nr!=0) goto L101;
  119467. nf++;
  119468. ifac[nf+1]=ntry;
  119469. nl=nq;
  119470. if(ntry!=2)goto L107;
  119471. if(nf==1)goto L107;
  119472. for (i=1;i<nf;i++){
  119473. ib=nf-i+1;
  119474. ifac[ib+1]=ifac[ib];
  119475. }
  119476. ifac[2] = 2;
  119477. L107:
  119478. if(nl!=1)goto L104;
  119479. ifac[0]=n;
  119480. ifac[1]=nf;
  119481. argh=tpi/n;
  119482. is=0;
  119483. nfm1=nf-1;
  119484. l1=1;
  119485. if(nfm1==0)return;
  119486. for (k1=0;k1<nfm1;k1++){
  119487. ip=ifac[k1+2];
  119488. ld=0;
  119489. l2=l1*ip;
  119490. ido=n/l2;
  119491. ipm=ip-1;
  119492. for (j=0;j<ipm;j++){
  119493. ld+=l1;
  119494. i=is;
  119495. argld=(float)ld*argh;
  119496. fi=0.f;
  119497. for (ii=2;ii<ido;ii+=2){
  119498. fi+=1.f;
  119499. arg=fi*argld;
  119500. wa[i++]=cos(arg);
  119501. wa[i++]=sin(arg);
  119502. }
  119503. is+=ido;
  119504. }
  119505. l1=l2;
  119506. }
  119507. }
  119508. static void fdrffti(int n, float *wsave, int *ifac){
  119509. if (n == 1) return;
  119510. drfti1(n, wsave+n, ifac);
  119511. }
  119512. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119513. int i,k;
  119514. float ti2,tr2;
  119515. int t0,t1,t2,t3,t4,t5,t6;
  119516. t1=0;
  119517. t0=(t2=l1*ido);
  119518. t3=ido<<1;
  119519. for(k=0;k<l1;k++){
  119520. ch[t1<<1]=cc[t1]+cc[t2];
  119521. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119522. t1+=ido;
  119523. t2+=ido;
  119524. }
  119525. if(ido<2)return;
  119526. if(ido==2)goto L105;
  119527. t1=0;
  119528. t2=t0;
  119529. for(k=0;k<l1;k++){
  119530. t3=t2;
  119531. t4=(t1<<1)+(ido<<1);
  119532. t5=t1;
  119533. t6=t1+t1;
  119534. for(i=2;i<ido;i+=2){
  119535. t3+=2;
  119536. t4-=2;
  119537. t5+=2;
  119538. t6+=2;
  119539. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119540. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119541. ch[t6]=cc[t5]+ti2;
  119542. ch[t4]=ti2-cc[t5];
  119543. ch[t6-1]=cc[t5-1]+tr2;
  119544. ch[t4-1]=cc[t5-1]-tr2;
  119545. }
  119546. t1+=ido;
  119547. t2+=ido;
  119548. }
  119549. if(ido%2==1)return;
  119550. L105:
  119551. t3=(t2=(t1=ido)-1);
  119552. t2+=t0;
  119553. for(k=0;k<l1;k++){
  119554. ch[t1]=-cc[t2];
  119555. ch[t1-1]=cc[t3];
  119556. t1+=ido<<1;
  119557. t2+=ido;
  119558. t3+=ido;
  119559. }
  119560. }
  119561. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119562. float *wa2,float *wa3){
  119563. static float hsqt2 = .70710678118654752f;
  119564. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119565. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119566. t0=l1*ido;
  119567. t1=t0;
  119568. t4=t1<<1;
  119569. t2=t1+(t1<<1);
  119570. t3=0;
  119571. for(k=0;k<l1;k++){
  119572. tr1=cc[t1]+cc[t2];
  119573. tr2=cc[t3]+cc[t4];
  119574. ch[t5=t3<<2]=tr1+tr2;
  119575. ch[(ido<<2)+t5-1]=tr2-tr1;
  119576. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119577. ch[t5]=cc[t2]-cc[t1];
  119578. t1+=ido;
  119579. t2+=ido;
  119580. t3+=ido;
  119581. t4+=ido;
  119582. }
  119583. if(ido<2)return;
  119584. if(ido==2)goto L105;
  119585. t1=0;
  119586. for(k=0;k<l1;k++){
  119587. t2=t1;
  119588. t4=t1<<2;
  119589. t5=(t6=ido<<1)+t4;
  119590. for(i=2;i<ido;i+=2){
  119591. t3=(t2+=2);
  119592. t4+=2;
  119593. t5-=2;
  119594. t3+=t0;
  119595. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119596. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119597. t3+=t0;
  119598. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119599. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119600. t3+=t0;
  119601. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119602. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119603. tr1=cr2+cr4;
  119604. tr4=cr4-cr2;
  119605. ti1=ci2+ci4;
  119606. ti4=ci2-ci4;
  119607. ti2=cc[t2]+ci3;
  119608. ti3=cc[t2]-ci3;
  119609. tr2=cc[t2-1]+cr3;
  119610. tr3=cc[t2-1]-cr3;
  119611. ch[t4-1]=tr1+tr2;
  119612. ch[t4]=ti1+ti2;
  119613. ch[t5-1]=tr3-ti4;
  119614. ch[t5]=tr4-ti3;
  119615. ch[t4+t6-1]=ti4+tr3;
  119616. ch[t4+t6]=tr4+ti3;
  119617. ch[t5+t6-1]=tr2-tr1;
  119618. ch[t5+t6]=ti1-ti2;
  119619. }
  119620. t1+=ido;
  119621. }
  119622. if(ido&1)return;
  119623. L105:
  119624. t2=(t1=t0+ido-1)+(t0<<1);
  119625. t3=ido<<2;
  119626. t4=ido;
  119627. t5=ido<<1;
  119628. t6=ido;
  119629. for(k=0;k<l1;k++){
  119630. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119631. tr1=hsqt2*(cc[t1]-cc[t2]);
  119632. ch[t4-1]=tr1+cc[t6-1];
  119633. ch[t4+t5-1]=cc[t6-1]-tr1;
  119634. ch[t4]=ti1-cc[t1+t0];
  119635. ch[t4+t5]=ti1+cc[t1+t0];
  119636. t1+=ido;
  119637. t2+=ido;
  119638. t4+=t3;
  119639. t6+=ido;
  119640. }
  119641. }
  119642. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119643. float *c2,float *ch,float *ch2,float *wa){
  119644. static float tpi=6.283185307179586f;
  119645. int idij,ipph,i,j,k,l,ic,ik,is;
  119646. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119647. float dc2,ai1,ai2,ar1,ar2,ds2;
  119648. int nbd;
  119649. float dcp,arg,dsp,ar1h,ar2h;
  119650. int idp2,ipp2;
  119651. arg=tpi/(float)ip;
  119652. dcp=cos(arg);
  119653. dsp=sin(arg);
  119654. ipph=(ip+1)>>1;
  119655. ipp2=ip;
  119656. idp2=ido;
  119657. nbd=(ido-1)>>1;
  119658. t0=l1*ido;
  119659. t10=ip*ido;
  119660. if(ido==1)goto L119;
  119661. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119662. t1=0;
  119663. for(j=1;j<ip;j++){
  119664. t1+=t0;
  119665. t2=t1;
  119666. for(k=0;k<l1;k++){
  119667. ch[t2]=c1[t2];
  119668. t2+=ido;
  119669. }
  119670. }
  119671. is=-ido;
  119672. t1=0;
  119673. if(nbd>l1){
  119674. for(j=1;j<ip;j++){
  119675. t1+=t0;
  119676. is+=ido;
  119677. t2= -ido+t1;
  119678. for(k=0;k<l1;k++){
  119679. idij=is-1;
  119680. t2+=ido;
  119681. t3=t2;
  119682. for(i=2;i<ido;i+=2){
  119683. idij+=2;
  119684. t3+=2;
  119685. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119686. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119687. }
  119688. }
  119689. }
  119690. }else{
  119691. for(j=1;j<ip;j++){
  119692. is+=ido;
  119693. idij=is-1;
  119694. t1+=t0;
  119695. t2=t1;
  119696. for(i=2;i<ido;i+=2){
  119697. idij+=2;
  119698. t2+=2;
  119699. t3=t2;
  119700. for(k=0;k<l1;k++){
  119701. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119702. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119703. t3+=ido;
  119704. }
  119705. }
  119706. }
  119707. }
  119708. t1=0;
  119709. t2=ipp2*t0;
  119710. if(nbd<l1){
  119711. for(j=1;j<ipph;j++){
  119712. t1+=t0;
  119713. t2-=t0;
  119714. t3=t1;
  119715. t4=t2;
  119716. for(i=2;i<ido;i+=2){
  119717. t3+=2;
  119718. t4+=2;
  119719. t5=t3-ido;
  119720. t6=t4-ido;
  119721. for(k=0;k<l1;k++){
  119722. t5+=ido;
  119723. t6+=ido;
  119724. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119725. c1[t6-1]=ch[t5]-ch[t6];
  119726. c1[t5]=ch[t5]+ch[t6];
  119727. c1[t6]=ch[t6-1]-ch[t5-1];
  119728. }
  119729. }
  119730. }
  119731. }else{
  119732. for(j=1;j<ipph;j++){
  119733. t1+=t0;
  119734. t2-=t0;
  119735. t3=t1;
  119736. t4=t2;
  119737. for(k=0;k<l1;k++){
  119738. t5=t3;
  119739. t6=t4;
  119740. for(i=2;i<ido;i+=2){
  119741. t5+=2;
  119742. t6+=2;
  119743. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119744. c1[t6-1]=ch[t5]-ch[t6];
  119745. c1[t5]=ch[t5]+ch[t6];
  119746. c1[t6]=ch[t6-1]-ch[t5-1];
  119747. }
  119748. t3+=ido;
  119749. t4+=ido;
  119750. }
  119751. }
  119752. }
  119753. L119:
  119754. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119755. t1=0;
  119756. t2=ipp2*idl1;
  119757. for(j=1;j<ipph;j++){
  119758. t1+=t0;
  119759. t2-=t0;
  119760. t3=t1-ido;
  119761. t4=t2-ido;
  119762. for(k=0;k<l1;k++){
  119763. t3+=ido;
  119764. t4+=ido;
  119765. c1[t3]=ch[t3]+ch[t4];
  119766. c1[t4]=ch[t4]-ch[t3];
  119767. }
  119768. }
  119769. ar1=1.f;
  119770. ai1=0.f;
  119771. t1=0;
  119772. t2=ipp2*idl1;
  119773. t3=(ip-1)*idl1;
  119774. for(l=1;l<ipph;l++){
  119775. t1+=idl1;
  119776. t2-=idl1;
  119777. ar1h=dcp*ar1-dsp*ai1;
  119778. ai1=dcp*ai1+dsp*ar1;
  119779. ar1=ar1h;
  119780. t4=t1;
  119781. t5=t2;
  119782. t6=t3;
  119783. t7=idl1;
  119784. for(ik=0;ik<idl1;ik++){
  119785. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119786. ch2[t5++]=ai1*c2[t6++];
  119787. }
  119788. dc2=ar1;
  119789. ds2=ai1;
  119790. ar2=ar1;
  119791. ai2=ai1;
  119792. t4=idl1;
  119793. t5=(ipp2-1)*idl1;
  119794. for(j=2;j<ipph;j++){
  119795. t4+=idl1;
  119796. t5-=idl1;
  119797. ar2h=dc2*ar2-ds2*ai2;
  119798. ai2=dc2*ai2+ds2*ar2;
  119799. ar2=ar2h;
  119800. t6=t1;
  119801. t7=t2;
  119802. t8=t4;
  119803. t9=t5;
  119804. for(ik=0;ik<idl1;ik++){
  119805. ch2[t6++]+=ar2*c2[t8++];
  119806. ch2[t7++]+=ai2*c2[t9++];
  119807. }
  119808. }
  119809. }
  119810. t1=0;
  119811. for(j=1;j<ipph;j++){
  119812. t1+=idl1;
  119813. t2=t1;
  119814. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119815. }
  119816. if(ido<l1)goto L132;
  119817. t1=0;
  119818. t2=0;
  119819. for(k=0;k<l1;k++){
  119820. t3=t1;
  119821. t4=t2;
  119822. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119823. t1+=ido;
  119824. t2+=t10;
  119825. }
  119826. goto L135;
  119827. L132:
  119828. for(i=0;i<ido;i++){
  119829. t1=i;
  119830. t2=i;
  119831. for(k=0;k<l1;k++){
  119832. cc[t2]=ch[t1];
  119833. t1+=ido;
  119834. t2+=t10;
  119835. }
  119836. }
  119837. L135:
  119838. t1=0;
  119839. t2=ido<<1;
  119840. t3=0;
  119841. t4=ipp2*t0;
  119842. for(j=1;j<ipph;j++){
  119843. t1+=t2;
  119844. t3+=t0;
  119845. t4-=t0;
  119846. t5=t1;
  119847. t6=t3;
  119848. t7=t4;
  119849. for(k=0;k<l1;k++){
  119850. cc[t5-1]=ch[t6];
  119851. cc[t5]=ch[t7];
  119852. t5+=t10;
  119853. t6+=ido;
  119854. t7+=ido;
  119855. }
  119856. }
  119857. if(ido==1)return;
  119858. if(nbd<l1)goto L141;
  119859. t1=-ido;
  119860. t3=0;
  119861. t4=0;
  119862. t5=ipp2*t0;
  119863. for(j=1;j<ipph;j++){
  119864. t1+=t2;
  119865. t3+=t2;
  119866. t4+=t0;
  119867. t5-=t0;
  119868. t6=t1;
  119869. t7=t3;
  119870. t8=t4;
  119871. t9=t5;
  119872. for(k=0;k<l1;k++){
  119873. for(i=2;i<ido;i+=2){
  119874. ic=idp2-i;
  119875. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119876. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119877. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119878. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119879. }
  119880. t6+=t10;
  119881. t7+=t10;
  119882. t8+=ido;
  119883. t9+=ido;
  119884. }
  119885. }
  119886. return;
  119887. L141:
  119888. t1=-ido;
  119889. t3=0;
  119890. t4=0;
  119891. t5=ipp2*t0;
  119892. for(j=1;j<ipph;j++){
  119893. t1+=t2;
  119894. t3+=t2;
  119895. t4+=t0;
  119896. t5-=t0;
  119897. for(i=2;i<ido;i+=2){
  119898. t6=idp2+t1-i;
  119899. t7=i+t3;
  119900. t8=i+t4;
  119901. t9=i+t5;
  119902. for(k=0;k<l1;k++){
  119903. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119904. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119905. cc[t7]=ch[t8]+ch[t9];
  119906. cc[t6]=ch[t9]-ch[t8];
  119907. t6+=t10;
  119908. t7+=t10;
  119909. t8+=ido;
  119910. t9+=ido;
  119911. }
  119912. }
  119913. }
  119914. }
  119915. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119916. int i,k1,l1,l2;
  119917. int na,kh,nf;
  119918. int ip,iw,ido,idl1,ix2,ix3;
  119919. nf=ifac[1];
  119920. na=1;
  119921. l2=n;
  119922. iw=n;
  119923. for(k1=0;k1<nf;k1++){
  119924. kh=nf-k1;
  119925. ip=ifac[kh+1];
  119926. l1=l2/ip;
  119927. ido=n/l2;
  119928. idl1=ido*l1;
  119929. iw-=(ip-1)*ido;
  119930. na=1-na;
  119931. if(ip!=4)goto L102;
  119932. ix2=iw+ido;
  119933. ix3=ix2+ido;
  119934. if(na!=0)
  119935. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119936. else
  119937. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119938. goto L110;
  119939. L102:
  119940. if(ip!=2)goto L104;
  119941. if(na!=0)goto L103;
  119942. dradf2(ido,l1,c,ch,wa+iw-1);
  119943. goto L110;
  119944. L103:
  119945. dradf2(ido,l1,ch,c,wa+iw-1);
  119946. goto L110;
  119947. L104:
  119948. if(ido==1)na=1-na;
  119949. if(na!=0)goto L109;
  119950. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119951. na=1;
  119952. goto L110;
  119953. L109:
  119954. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119955. na=0;
  119956. L110:
  119957. l2=l1;
  119958. }
  119959. if(na==1)return;
  119960. for(i=0;i<n;i++)c[i]=ch[i];
  119961. }
  119962. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119963. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119964. float ti2,tr2;
  119965. t0=l1*ido;
  119966. t1=0;
  119967. t2=0;
  119968. t3=(ido<<1)-1;
  119969. for(k=0;k<l1;k++){
  119970. ch[t1]=cc[t2]+cc[t3+t2];
  119971. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119972. t2=(t1+=ido)<<1;
  119973. }
  119974. if(ido<2)return;
  119975. if(ido==2)goto L105;
  119976. t1=0;
  119977. t2=0;
  119978. for(k=0;k<l1;k++){
  119979. t3=t1;
  119980. t5=(t4=t2)+(ido<<1);
  119981. t6=t0+t1;
  119982. for(i=2;i<ido;i+=2){
  119983. t3+=2;
  119984. t4+=2;
  119985. t5-=2;
  119986. t6+=2;
  119987. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119988. tr2=cc[t4-1]-cc[t5-1];
  119989. ch[t3]=cc[t4]-cc[t5];
  119990. ti2=cc[t4]+cc[t5];
  119991. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119992. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119993. }
  119994. t2=(t1+=ido)<<1;
  119995. }
  119996. if(ido%2==1)return;
  119997. L105:
  119998. t1=ido-1;
  119999. t2=ido-1;
  120000. for(k=0;k<l1;k++){
  120001. ch[t1]=cc[t2]+cc[t2];
  120002. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120003. t1+=ido;
  120004. t2+=ido<<1;
  120005. }
  120006. }
  120007. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120008. float *wa2){
  120009. static float taur = -.5f;
  120010. static float taui = .8660254037844386f;
  120011. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120012. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120013. t0=l1*ido;
  120014. t1=0;
  120015. t2=t0<<1;
  120016. t3=ido<<1;
  120017. t4=ido+(ido<<1);
  120018. t5=0;
  120019. for(k=0;k<l1;k++){
  120020. tr2=cc[t3-1]+cc[t3-1];
  120021. cr2=cc[t5]+(taur*tr2);
  120022. ch[t1]=cc[t5]+tr2;
  120023. ci3=taui*(cc[t3]+cc[t3]);
  120024. ch[t1+t0]=cr2-ci3;
  120025. ch[t1+t2]=cr2+ci3;
  120026. t1+=ido;
  120027. t3+=t4;
  120028. t5+=t4;
  120029. }
  120030. if(ido==1)return;
  120031. t1=0;
  120032. t3=ido<<1;
  120033. for(k=0;k<l1;k++){
  120034. t7=t1+(t1<<1);
  120035. t6=(t5=t7+t3);
  120036. t8=t1;
  120037. t10=(t9=t1+t0)+t0;
  120038. for(i=2;i<ido;i+=2){
  120039. t5+=2;
  120040. t6-=2;
  120041. t7+=2;
  120042. t8+=2;
  120043. t9+=2;
  120044. t10+=2;
  120045. tr2=cc[t5-1]+cc[t6-1];
  120046. cr2=cc[t7-1]+(taur*tr2);
  120047. ch[t8-1]=cc[t7-1]+tr2;
  120048. ti2=cc[t5]-cc[t6];
  120049. ci2=cc[t7]+(taur*ti2);
  120050. ch[t8]=cc[t7]+ti2;
  120051. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120052. ci3=taui*(cc[t5]+cc[t6]);
  120053. dr2=cr2-ci3;
  120054. dr3=cr2+ci3;
  120055. di2=ci2+cr3;
  120056. di3=ci2-cr3;
  120057. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120058. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120059. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120060. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120061. }
  120062. t1+=ido;
  120063. }
  120064. }
  120065. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120066. float *wa2,float *wa3){
  120067. static float sqrt2=1.414213562373095f;
  120068. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120069. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120070. t0=l1*ido;
  120071. t1=0;
  120072. t2=ido<<2;
  120073. t3=0;
  120074. t6=ido<<1;
  120075. for(k=0;k<l1;k++){
  120076. t4=t3+t6;
  120077. t5=t1;
  120078. tr3=cc[t4-1]+cc[t4-1];
  120079. tr4=cc[t4]+cc[t4];
  120080. tr1=cc[t3]-cc[(t4+=t6)-1];
  120081. tr2=cc[t3]+cc[t4-1];
  120082. ch[t5]=tr2+tr3;
  120083. ch[t5+=t0]=tr1-tr4;
  120084. ch[t5+=t0]=tr2-tr3;
  120085. ch[t5+=t0]=tr1+tr4;
  120086. t1+=ido;
  120087. t3+=t2;
  120088. }
  120089. if(ido<2)return;
  120090. if(ido==2)goto L105;
  120091. t1=0;
  120092. for(k=0;k<l1;k++){
  120093. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120094. t7=t1;
  120095. for(i=2;i<ido;i+=2){
  120096. t2+=2;
  120097. t3+=2;
  120098. t4-=2;
  120099. t5-=2;
  120100. t7+=2;
  120101. ti1=cc[t2]+cc[t5];
  120102. ti2=cc[t2]-cc[t5];
  120103. ti3=cc[t3]-cc[t4];
  120104. tr4=cc[t3]+cc[t4];
  120105. tr1=cc[t2-1]-cc[t5-1];
  120106. tr2=cc[t2-1]+cc[t5-1];
  120107. ti4=cc[t3-1]-cc[t4-1];
  120108. tr3=cc[t3-1]+cc[t4-1];
  120109. ch[t7-1]=tr2+tr3;
  120110. cr3=tr2-tr3;
  120111. ch[t7]=ti2+ti3;
  120112. ci3=ti2-ti3;
  120113. cr2=tr1-tr4;
  120114. cr4=tr1+tr4;
  120115. ci2=ti1+ti4;
  120116. ci4=ti1-ti4;
  120117. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120118. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120119. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120120. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120121. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120122. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120123. }
  120124. t1+=ido;
  120125. }
  120126. if(ido%2 == 1)return;
  120127. L105:
  120128. t1=ido;
  120129. t2=ido<<2;
  120130. t3=ido-1;
  120131. t4=ido+(ido<<1);
  120132. for(k=0;k<l1;k++){
  120133. t5=t3;
  120134. ti1=cc[t1]+cc[t4];
  120135. ti2=cc[t4]-cc[t1];
  120136. tr1=cc[t1-1]-cc[t4-1];
  120137. tr2=cc[t1-1]+cc[t4-1];
  120138. ch[t5]=tr2+tr2;
  120139. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120140. ch[t5+=t0]=ti2+ti2;
  120141. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120142. t3+=ido;
  120143. t1+=t2;
  120144. t4+=t2;
  120145. }
  120146. }
  120147. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120148. float *c2,float *ch,float *ch2,float *wa){
  120149. static float tpi=6.283185307179586f;
  120150. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120151. t11,t12;
  120152. float dc2,ai1,ai2,ar1,ar2,ds2;
  120153. int nbd;
  120154. float dcp,arg,dsp,ar1h,ar2h;
  120155. int ipp2;
  120156. t10=ip*ido;
  120157. t0=l1*ido;
  120158. arg=tpi/(float)ip;
  120159. dcp=cos(arg);
  120160. dsp=sin(arg);
  120161. nbd=(ido-1)>>1;
  120162. ipp2=ip;
  120163. ipph=(ip+1)>>1;
  120164. if(ido<l1)goto L103;
  120165. t1=0;
  120166. t2=0;
  120167. for(k=0;k<l1;k++){
  120168. t3=t1;
  120169. t4=t2;
  120170. for(i=0;i<ido;i++){
  120171. ch[t3]=cc[t4];
  120172. t3++;
  120173. t4++;
  120174. }
  120175. t1+=ido;
  120176. t2+=t10;
  120177. }
  120178. goto L106;
  120179. L103:
  120180. t1=0;
  120181. for(i=0;i<ido;i++){
  120182. t2=t1;
  120183. t3=t1;
  120184. for(k=0;k<l1;k++){
  120185. ch[t2]=cc[t3];
  120186. t2+=ido;
  120187. t3+=t10;
  120188. }
  120189. t1++;
  120190. }
  120191. L106:
  120192. t1=0;
  120193. t2=ipp2*t0;
  120194. t7=(t5=ido<<1);
  120195. for(j=1;j<ipph;j++){
  120196. t1+=t0;
  120197. t2-=t0;
  120198. t3=t1;
  120199. t4=t2;
  120200. t6=t5;
  120201. for(k=0;k<l1;k++){
  120202. ch[t3]=cc[t6-1]+cc[t6-1];
  120203. ch[t4]=cc[t6]+cc[t6];
  120204. t3+=ido;
  120205. t4+=ido;
  120206. t6+=t10;
  120207. }
  120208. t5+=t7;
  120209. }
  120210. if (ido == 1)goto L116;
  120211. if(nbd<l1)goto L112;
  120212. t1=0;
  120213. t2=ipp2*t0;
  120214. t7=0;
  120215. for(j=1;j<ipph;j++){
  120216. t1+=t0;
  120217. t2-=t0;
  120218. t3=t1;
  120219. t4=t2;
  120220. t7+=(ido<<1);
  120221. t8=t7;
  120222. for(k=0;k<l1;k++){
  120223. t5=t3;
  120224. t6=t4;
  120225. t9=t8;
  120226. t11=t8;
  120227. for(i=2;i<ido;i+=2){
  120228. t5+=2;
  120229. t6+=2;
  120230. t9+=2;
  120231. t11-=2;
  120232. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120233. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120234. ch[t5]=cc[t9]-cc[t11];
  120235. ch[t6]=cc[t9]+cc[t11];
  120236. }
  120237. t3+=ido;
  120238. t4+=ido;
  120239. t8+=t10;
  120240. }
  120241. }
  120242. goto L116;
  120243. L112:
  120244. t1=0;
  120245. t2=ipp2*t0;
  120246. t7=0;
  120247. for(j=1;j<ipph;j++){
  120248. t1+=t0;
  120249. t2-=t0;
  120250. t3=t1;
  120251. t4=t2;
  120252. t7+=(ido<<1);
  120253. t8=t7;
  120254. t9=t7;
  120255. for(i=2;i<ido;i+=2){
  120256. t3+=2;
  120257. t4+=2;
  120258. t8+=2;
  120259. t9-=2;
  120260. t5=t3;
  120261. t6=t4;
  120262. t11=t8;
  120263. t12=t9;
  120264. for(k=0;k<l1;k++){
  120265. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120266. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120267. ch[t5]=cc[t11]-cc[t12];
  120268. ch[t6]=cc[t11]+cc[t12];
  120269. t5+=ido;
  120270. t6+=ido;
  120271. t11+=t10;
  120272. t12+=t10;
  120273. }
  120274. }
  120275. }
  120276. L116:
  120277. ar1=1.f;
  120278. ai1=0.f;
  120279. t1=0;
  120280. t9=(t2=ipp2*idl1);
  120281. t3=(ip-1)*idl1;
  120282. for(l=1;l<ipph;l++){
  120283. t1+=idl1;
  120284. t2-=idl1;
  120285. ar1h=dcp*ar1-dsp*ai1;
  120286. ai1=dcp*ai1+dsp*ar1;
  120287. ar1=ar1h;
  120288. t4=t1;
  120289. t5=t2;
  120290. t6=0;
  120291. t7=idl1;
  120292. t8=t3;
  120293. for(ik=0;ik<idl1;ik++){
  120294. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120295. c2[t5++]=ai1*ch2[t8++];
  120296. }
  120297. dc2=ar1;
  120298. ds2=ai1;
  120299. ar2=ar1;
  120300. ai2=ai1;
  120301. t6=idl1;
  120302. t7=t9-idl1;
  120303. for(j=2;j<ipph;j++){
  120304. t6+=idl1;
  120305. t7-=idl1;
  120306. ar2h=dc2*ar2-ds2*ai2;
  120307. ai2=dc2*ai2+ds2*ar2;
  120308. ar2=ar2h;
  120309. t4=t1;
  120310. t5=t2;
  120311. t11=t6;
  120312. t12=t7;
  120313. for(ik=0;ik<idl1;ik++){
  120314. c2[t4++]+=ar2*ch2[t11++];
  120315. c2[t5++]+=ai2*ch2[t12++];
  120316. }
  120317. }
  120318. }
  120319. t1=0;
  120320. for(j=1;j<ipph;j++){
  120321. t1+=idl1;
  120322. t2=t1;
  120323. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120324. }
  120325. t1=0;
  120326. t2=ipp2*t0;
  120327. for(j=1;j<ipph;j++){
  120328. t1+=t0;
  120329. t2-=t0;
  120330. t3=t1;
  120331. t4=t2;
  120332. for(k=0;k<l1;k++){
  120333. ch[t3]=c1[t3]-c1[t4];
  120334. ch[t4]=c1[t3]+c1[t4];
  120335. t3+=ido;
  120336. t4+=ido;
  120337. }
  120338. }
  120339. if(ido==1)goto L132;
  120340. if(nbd<l1)goto L128;
  120341. t1=0;
  120342. t2=ipp2*t0;
  120343. for(j=1;j<ipph;j++){
  120344. t1+=t0;
  120345. t2-=t0;
  120346. t3=t1;
  120347. t4=t2;
  120348. for(k=0;k<l1;k++){
  120349. t5=t3;
  120350. t6=t4;
  120351. for(i=2;i<ido;i+=2){
  120352. t5+=2;
  120353. t6+=2;
  120354. ch[t5-1]=c1[t5-1]-c1[t6];
  120355. ch[t6-1]=c1[t5-1]+c1[t6];
  120356. ch[t5]=c1[t5]+c1[t6-1];
  120357. ch[t6]=c1[t5]-c1[t6-1];
  120358. }
  120359. t3+=ido;
  120360. t4+=ido;
  120361. }
  120362. }
  120363. goto L132;
  120364. L128:
  120365. t1=0;
  120366. t2=ipp2*t0;
  120367. for(j=1;j<ipph;j++){
  120368. t1+=t0;
  120369. t2-=t0;
  120370. t3=t1;
  120371. t4=t2;
  120372. for(i=2;i<ido;i+=2){
  120373. t3+=2;
  120374. t4+=2;
  120375. t5=t3;
  120376. t6=t4;
  120377. for(k=0;k<l1;k++){
  120378. ch[t5-1]=c1[t5-1]-c1[t6];
  120379. ch[t6-1]=c1[t5-1]+c1[t6];
  120380. ch[t5]=c1[t5]+c1[t6-1];
  120381. ch[t6]=c1[t5]-c1[t6-1];
  120382. t5+=ido;
  120383. t6+=ido;
  120384. }
  120385. }
  120386. }
  120387. L132:
  120388. if(ido==1)return;
  120389. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120390. t1=0;
  120391. for(j=1;j<ip;j++){
  120392. t2=(t1+=t0);
  120393. for(k=0;k<l1;k++){
  120394. c1[t2]=ch[t2];
  120395. t2+=ido;
  120396. }
  120397. }
  120398. if(nbd>l1)goto L139;
  120399. is= -ido-1;
  120400. t1=0;
  120401. for(j=1;j<ip;j++){
  120402. is+=ido;
  120403. t1+=t0;
  120404. idij=is;
  120405. t2=t1;
  120406. for(i=2;i<ido;i+=2){
  120407. t2+=2;
  120408. idij+=2;
  120409. t3=t2;
  120410. for(k=0;k<l1;k++){
  120411. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120412. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120413. t3+=ido;
  120414. }
  120415. }
  120416. }
  120417. return;
  120418. L139:
  120419. is= -ido-1;
  120420. t1=0;
  120421. for(j=1;j<ip;j++){
  120422. is+=ido;
  120423. t1+=t0;
  120424. t2=t1;
  120425. for(k=0;k<l1;k++){
  120426. idij=is;
  120427. t3=t2;
  120428. for(i=2;i<ido;i+=2){
  120429. idij+=2;
  120430. t3+=2;
  120431. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120432. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120433. }
  120434. t2+=ido;
  120435. }
  120436. }
  120437. }
  120438. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120439. int i,k1,l1,l2;
  120440. int na;
  120441. int nf,ip,iw,ix2,ix3,ido,idl1;
  120442. nf=ifac[1];
  120443. na=0;
  120444. l1=1;
  120445. iw=1;
  120446. for(k1=0;k1<nf;k1++){
  120447. ip=ifac[k1 + 2];
  120448. l2=ip*l1;
  120449. ido=n/l2;
  120450. idl1=ido*l1;
  120451. if(ip!=4)goto L103;
  120452. ix2=iw+ido;
  120453. ix3=ix2+ido;
  120454. if(na!=0)
  120455. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120456. else
  120457. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120458. na=1-na;
  120459. goto L115;
  120460. L103:
  120461. if(ip!=2)goto L106;
  120462. if(na!=0)
  120463. dradb2(ido,l1,ch,c,wa+iw-1);
  120464. else
  120465. dradb2(ido,l1,c,ch,wa+iw-1);
  120466. na=1-na;
  120467. goto L115;
  120468. L106:
  120469. if(ip!=3)goto L109;
  120470. ix2=iw+ido;
  120471. if(na!=0)
  120472. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120473. else
  120474. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120475. na=1-na;
  120476. goto L115;
  120477. L109:
  120478. /* The radix five case can be translated later..... */
  120479. /* if(ip!=5)goto L112;
  120480. ix2=iw+ido;
  120481. ix3=ix2+ido;
  120482. ix4=ix3+ido;
  120483. if(na!=0)
  120484. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120485. else
  120486. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120487. na=1-na;
  120488. goto L115;
  120489. L112:*/
  120490. if(na!=0)
  120491. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120492. else
  120493. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120494. if(ido==1)na=1-na;
  120495. L115:
  120496. l1=l2;
  120497. iw+=(ip-1)*ido;
  120498. }
  120499. if(na==0)return;
  120500. for(i=0;i<n;i++)c[i]=ch[i];
  120501. }
  120502. void drft_forward(drft_lookup *l,float *data){
  120503. if(l->n==1)return;
  120504. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120505. }
  120506. void drft_backward(drft_lookup *l,float *data){
  120507. if (l->n==1)return;
  120508. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120509. }
  120510. void drft_init(drft_lookup *l,int n){
  120511. l->n=n;
  120512. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120513. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120514. fdrffti(n, l->trigcache, l->splitcache);
  120515. }
  120516. void drft_clear(drft_lookup *l){
  120517. if(l){
  120518. if(l->trigcache)_ogg_free(l->trigcache);
  120519. if(l->splitcache)_ogg_free(l->splitcache);
  120520. memset(l,0,sizeof(*l));
  120521. }
  120522. }
  120523. #endif
  120524. /*** End of inlined file: smallft.c ***/
  120525. /*** Start of inlined file: synthesis.c ***/
  120526. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120527. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120528. // tasks..
  120529. #if JUCE_MSVC
  120530. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120531. #endif
  120532. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120533. #if JUCE_USE_OGGVORBIS
  120534. #include <stdio.h>
  120535. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120536. vorbis_dsp_state *vd=vb->vd;
  120537. private_state *b=(private_state*)vd->backend_state;
  120538. vorbis_info *vi=vd->vi;
  120539. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120540. oggpack_buffer *opb=&vb->opb;
  120541. int type,mode,i;
  120542. /* first things first. Make sure decode is ready */
  120543. _vorbis_block_ripcord(vb);
  120544. oggpack_readinit(opb,op->packet,op->bytes);
  120545. /* Check the packet type */
  120546. if(oggpack_read(opb,1)!=0){
  120547. /* Oops. This is not an audio data packet */
  120548. return(OV_ENOTAUDIO);
  120549. }
  120550. /* read our mode and pre/post windowsize */
  120551. mode=oggpack_read(opb,b->modebits);
  120552. if(mode==-1)return(OV_EBADPACKET);
  120553. vb->mode=mode;
  120554. vb->W=ci->mode_param[mode]->blockflag;
  120555. if(vb->W){
  120556. /* this doesn;t get mapped through mode selection as it's used
  120557. only for window selection */
  120558. vb->lW=oggpack_read(opb,1);
  120559. vb->nW=oggpack_read(opb,1);
  120560. if(vb->nW==-1) return(OV_EBADPACKET);
  120561. }else{
  120562. vb->lW=0;
  120563. vb->nW=0;
  120564. }
  120565. /* more setup */
  120566. vb->granulepos=op->granulepos;
  120567. vb->sequence=op->packetno;
  120568. vb->eofflag=op->e_o_s;
  120569. /* alloc pcm passback storage */
  120570. vb->pcmend=ci->blocksizes[vb->W];
  120571. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120572. for(i=0;i<vi->channels;i++)
  120573. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120574. /* unpack_header enforces range checking */
  120575. type=ci->map_type[ci->mode_param[mode]->mapping];
  120576. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120577. mapping]));
  120578. }
  120579. /* used to track pcm position without actually performing decode.
  120580. Useful for sequential 'fast forward' */
  120581. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120582. vorbis_dsp_state *vd=vb->vd;
  120583. private_state *b=(private_state*)vd->backend_state;
  120584. vorbis_info *vi=vd->vi;
  120585. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120586. oggpack_buffer *opb=&vb->opb;
  120587. int mode;
  120588. /* first things first. Make sure decode is ready */
  120589. _vorbis_block_ripcord(vb);
  120590. oggpack_readinit(opb,op->packet,op->bytes);
  120591. /* Check the packet type */
  120592. if(oggpack_read(opb,1)!=0){
  120593. /* Oops. This is not an audio data packet */
  120594. return(OV_ENOTAUDIO);
  120595. }
  120596. /* read our mode and pre/post windowsize */
  120597. mode=oggpack_read(opb,b->modebits);
  120598. if(mode==-1)return(OV_EBADPACKET);
  120599. vb->mode=mode;
  120600. vb->W=ci->mode_param[mode]->blockflag;
  120601. if(vb->W){
  120602. vb->lW=oggpack_read(opb,1);
  120603. vb->nW=oggpack_read(opb,1);
  120604. if(vb->nW==-1) return(OV_EBADPACKET);
  120605. }else{
  120606. vb->lW=0;
  120607. vb->nW=0;
  120608. }
  120609. /* more setup */
  120610. vb->granulepos=op->granulepos;
  120611. vb->sequence=op->packetno;
  120612. vb->eofflag=op->e_o_s;
  120613. /* no pcm */
  120614. vb->pcmend=0;
  120615. vb->pcm=NULL;
  120616. return(0);
  120617. }
  120618. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120619. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120620. oggpack_buffer opb;
  120621. int mode;
  120622. oggpack_readinit(&opb,op->packet,op->bytes);
  120623. /* Check the packet type */
  120624. if(oggpack_read(&opb,1)!=0){
  120625. /* Oops. This is not an audio data packet */
  120626. return(OV_ENOTAUDIO);
  120627. }
  120628. {
  120629. int modebits=0;
  120630. int v=ci->modes;
  120631. while(v>1){
  120632. modebits++;
  120633. v>>=1;
  120634. }
  120635. /* read our mode and pre/post windowsize */
  120636. mode=oggpack_read(&opb,modebits);
  120637. }
  120638. if(mode==-1)return(OV_EBADPACKET);
  120639. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120640. }
  120641. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120642. /* set / clear half-sample-rate mode */
  120643. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120644. /* right now, our MDCT can't handle < 64 sample windows. */
  120645. if(ci->blocksizes[0]<=64 && flag)return -1;
  120646. ci->halfrate_flag=(flag?1:0);
  120647. return 0;
  120648. }
  120649. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120650. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120651. return ci->halfrate_flag;
  120652. }
  120653. #endif
  120654. /*** End of inlined file: synthesis.c ***/
  120655. /*** Start of inlined file: vorbisenc.c ***/
  120656. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120657. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120658. // tasks..
  120659. #if JUCE_MSVC
  120660. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120661. #endif
  120662. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120663. #if JUCE_USE_OGGVORBIS
  120664. #include <stdlib.h>
  120665. #include <string.h>
  120666. #include <math.h>
  120667. /* careful with this; it's using static array sizing to make managing
  120668. all the modes a little less annoying. If we use a residue backend
  120669. with > 12 partition types, or a different division of iteration,
  120670. this needs to be updated. */
  120671. typedef struct {
  120672. static_codebook *books[12][3];
  120673. } static_bookblock;
  120674. typedef struct {
  120675. int res_type;
  120676. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120677. vorbis_info_residue0 *res;
  120678. static_codebook *book_aux;
  120679. static_codebook *book_aux_managed;
  120680. static_bookblock *books_base;
  120681. static_bookblock *books_base_managed;
  120682. } vorbis_residue_template;
  120683. typedef struct {
  120684. vorbis_info_mapping0 *map;
  120685. vorbis_residue_template *res;
  120686. } vorbis_mapping_template;
  120687. typedef struct vp_adjblock{
  120688. int block[P_BANDS];
  120689. } vp_adjblock;
  120690. typedef struct {
  120691. int data[NOISE_COMPAND_LEVELS];
  120692. } compandblock;
  120693. /* high level configuration information for setting things up
  120694. step-by-step with the detailed vorbis_encode_ctl interface.
  120695. There's a fair amount of redundancy such that interactive setup
  120696. does not directly deal with any vorbis_info or codec_setup_info
  120697. initialization; it's all stored (until full init) in this highlevel
  120698. setup, then flushed out to the real codec setup structs later. */
  120699. typedef struct {
  120700. int att[P_NOISECURVES];
  120701. float boost;
  120702. float decay;
  120703. } att3;
  120704. typedef struct { int data[P_NOISECURVES]; } adj3;
  120705. typedef struct {
  120706. int pre[PACKETBLOBS];
  120707. int post[PACKETBLOBS];
  120708. float kHz[PACKETBLOBS];
  120709. float lowpasskHz[PACKETBLOBS];
  120710. } adj_stereo;
  120711. typedef struct {
  120712. int lo;
  120713. int hi;
  120714. int fixed;
  120715. } noiseguard;
  120716. typedef struct {
  120717. int data[P_NOISECURVES][17];
  120718. } noise3;
  120719. typedef struct {
  120720. int mappings;
  120721. double *rate_mapping;
  120722. double *quality_mapping;
  120723. int coupling_restriction;
  120724. long samplerate_min_restriction;
  120725. long samplerate_max_restriction;
  120726. int *blocksize_short;
  120727. int *blocksize_long;
  120728. att3 *psy_tone_masteratt;
  120729. int *psy_tone_0dB;
  120730. int *psy_tone_dBsuppress;
  120731. vp_adjblock *psy_tone_adj_impulse;
  120732. vp_adjblock *psy_tone_adj_long;
  120733. vp_adjblock *psy_tone_adj_other;
  120734. noiseguard *psy_noiseguards;
  120735. noise3 *psy_noise_bias_impulse;
  120736. noise3 *psy_noise_bias_padding;
  120737. noise3 *psy_noise_bias_trans;
  120738. noise3 *psy_noise_bias_long;
  120739. int *psy_noise_dBsuppress;
  120740. compandblock *psy_noise_compand;
  120741. double *psy_noise_compand_short_mapping;
  120742. double *psy_noise_compand_long_mapping;
  120743. int *psy_noise_normal_start[2];
  120744. int *psy_noise_normal_partition[2];
  120745. double *psy_noise_normal_thresh;
  120746. int *psy_ath_float;
  120747. int *psy_ath_abs;
  120748. double *psy_lowpass;
  120749. vorbis_info_psy_global *global_params;
  120750. double *global_mapping;
  120751. adj_stereo *stereo_modes;
  120752. static_codebook ***floor_books;
  120753. vorbis_info_floor1 *floor_params;
  120754. int *floor_short_mapping;
  120755. int *floor_long_mapping;
  120756. vorbis_mapping_template *maps;
  120757. } ve_setup_data_template;
  120758. /* a few static coder conventions */
  120759. static vorbis_info_mode _mode_template[2]={
  120760. {0,0,0,0},
  120761. {1,0,0,1}
  120762. };
  120763. static vorbis_info_mapping0 _map_nominal[2]={
  120764. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120765. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120766. };
  120767. /*** Start of inlined file: setup_44.h ***/
  120768. /*** Start of inlined file: floor_all.h ***/
  120769. /*** Start of inlined file: floor_books.h ***/
  120770. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120771. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120772. };
  120773. static static_codebook _huff_book_line_256x7_0sub1 = {
  120774. 1, 9,
  120775. _huff_lengthlist_line_256x7_0sub1,
  120776. 0, 0, 0, 0, 0,
  120777. NULL,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. 0
  120782. };
  120783. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120785. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120786. };
  120787. static static_codebook _huff_book_line_256x7_0sub2 = {
  120788. 1, 25,
  120789. _huff_lengthlist_line_256x7_0sub2,
  120790. 0, 0, 0, 0, 0,
  120791. NULL,
  120792. NULL,
  120793. NULL,
  120794. NULL,
  120795. 0
  120796. };
  120797. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120800. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120801. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120802. };
  120803. static static_codebook _huff_book_line_256x7_0sub3 = {
  120804. 1, 64,
  120805. _huff_lengthlist_line_256x7_0sub3,
  120806. 0, 0, 0, 0, 0,
  120807. NULL,
  120808. NULL,
  120809. NULL,
  120810. NULL,
  120811. 0
  120812. };
  120813. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120814. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120815. };
  120816. static static_codebook _huff_book_line_256x7_1sub1 = {
  120817. 1, 9,
  120818. _huff_lengthlist_line_256x7_1sub1,
  120819. 0, 0, 0, 0, 0,
  120820. NULL,
  120821. NULL,
  120822. NULL,
  120823. NULL,
  120824. 0
  120825. };
  120826. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120828. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120829. };
  120830. static static_codebook _huff_book_line_256x7_1sub2 = {
  120831. 1, 25,
  120832. _huff_lengthlist_line_256x7_1sub2,
  120833. 0, 0, 0, 0, 0,
  120834. NULL,
  120835. NULL,
  120836. NULL,
  120837. NULL,
  120838. 0
  120839. };
  120840. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120843. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120844. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120845. };
  120846. static static_codebook _huff_book_line_256x7_1sub3 = {
  120847. 1, 64,
  120848. _huff_lengthlist_line_256x7_1sub3,
  120849. 0, 0, 0, 0, 0,
  120850. NULL,
  120851. NULL,
  120852. NULL,
  120853. NULL,
  120854. 0
  120855. };
  120856. static long _huff_lengthlist_line_256x7_class0[] = {
  120857. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120858. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120859. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120860. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120861. };
  120862. static static_codebook _huff_book_line_256x7_class0 = {
  120863. 1, 64,
  120864. _huff_lengthlist_line_256x7_class0,
  120865. 0, 0, 0, 0, 0,
  120866. NULL,
  120867. NULL,
  120868. NULL,
  120869. NULL,
  120870. 0
  120871. };
  120872. static long _huff_lengthlist_line_256x7_class1[] = {
  120873. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120874. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120875. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120876. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120877. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120878. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120879. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120880. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120881. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120882. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120883. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120884. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120885. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120886. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120887. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120888. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120889. };
  120890. static static_codebook _huff_book_line_256x7_class1 = {
  120891. 1, 256,
  120892. _huff_lengthlist_line_256x7_class1,
  120893. 0, 0, 0, 0, 0,
  120894. NULL,
  120895. NULL,
  120896. NULL,
  120897. NULL,
  120898. 0
  120899. };
  120900. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120901. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120902. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120903. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120904. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120905. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120906. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120907. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120908. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120909. };
  120910. static static_codebook _huff_book_line_512x17_0sub0 = {
  120911. 1, 128,
  120912. _huff_lengthlist_line_512x17_0sub0,
  120913. 0, 0, 0, 0, 0,
  120914. NULL,
  120915. NULL,
  120916. NULL,
  120917. NULL,
  120918. 0
  120919. };
  120920. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120921. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120922. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120923. };
  120924. static static_codebook _huff_book_line_512x17_1sub0 = {
  120925. 1, 32,
  120926. _huff_lengthlist_line_512x17_1sub0,
  120927. 0, 0, 0, 0, 0,
  120928. NULL,
  120929. NULL,
  120930. NULL,
  120931. NULL,
  120932. 0
  120933. };
  120934. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120937. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120938. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120939. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120940. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120941. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120942. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120943. };
  120944. static static_codebook _huff_book_line_512x17_1sub1 = {
  120945. 1, 128,
  120946. _huff_lengthlist_line_512x17_1sub1,
  120947. 0, 0, 0, 0, 0,
  120948. NULL,
  120949. NULL,
  120950. NULL,
  120951. NULL,
  120952. 0
  120953. };
  120954. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120955. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120956. 5, 3,
  120957. };
  120958. static static_codebook _huff_book_line_512x17_2sub1 = {
  120959. 1, 18,
  120960. _huff_lengthlist_line_512x17_2sub1,
  120961. 0, 0, 0, 0, 0,
  120962. NULL,
  120963. NULL,
  120964. NULL,
  120965. NULL,
  120966. 0
  120967. };
  120968. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120970. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120971. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120972. 9, 8,
  120973. };
  120974. static static_codebook _huff_book_line_512x17_2sub2 = {
  120975. 1, 50,
  120976. _huff_lengthlist_line_512x17_2sub2,
  120977. 0, 0, 0, 0, 0,
  120978. NULL,
  120979. NULL,
  120980. NULL,
  120981. NULL,
  120982. 0
  120983. };
  120984. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120989. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120990. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120991. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120992. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120993. };
  120994. static static_codebook _huff_book_line_512x17_2sub3 = {
  120995. 1, 128,
  120996. _huff_lengthlist_line_512x17_2sub3,
  120997. 0, 0, 0, 0, 0,
  120998. NULL,
  120999. NULL,
  121000. NULL,
  121001. NULL,
  121002. 0
  121003. };
  121004. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121005. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121006. 5, 5,
  121007. };
  121008. static static_codebook _huff_book_line_512x17_3sub1 = {
  121009. 1, 18,
  121010. _huff_lengthlist_line_512x17_3sub1,
  121011. 0, 0, 0, 0, 0,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. 0
  121017. };
  121018. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121020. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121021. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121022. 11,14,
  121023. };
  121024. static static_codebook _huff_book_line_512x17_3sub2 = {
  121025. 1, 50,
  121026. _huff_lengthlist_line_512x17_3sub2,
  121027. 0, 0, 0, 0, 0,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. NULL,
  121032. 0
  121033. };
  121034. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121038. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121039. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121040. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121041. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121042. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121043. };
  121044. static static_codebook _huff_book_line_512x17_3sub3 = {
  121045. 1, 128,
  121046. _huff_lengthlist_line_512x17_3sub3,
  121047. 0, 0, 0, 0, 0,
  121048. NULL,
  121049. NULL,
  121050. NULL,
  121051. NULL,
  121052. 0
  121053. };
  121054. static long _huff_lengthlist_line_512x17_class1[] = {
  121055. 1, 2, 3, 6, 5, 4, 7, 7,
  121056. };
  121057. static static_codebook _huff_book_line_512x17_class1 = {
  121058. 1, 8,
  121059. _huff_lengthlist_line_512x17_class1,
  121060. 0, 0, 0, 0, 0,
  121061. NULL,
  121062. NULL,
  121063. NULL,
  121064. NULL,
  121065. 0
  121066. };
  121067. static long _huff_lengthlist_line_512x17_class2[] = {
  121068. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121069. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121070. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121071. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121072. };
  121073. static static_codebook _huff_book_line_512x17_class2 = {
  121074. 1, 64,
  121075. _huff_lengthlist_line_512x17_class2,
  121076. 0, 0, 0, 0, 0,
  121077. NULL,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. 0
  121082. };
  121083. static long _huff_lengthlist_line_512x17_class3[] = {
  121084. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121085. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121086. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121087. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121088. };
  121089. static static_codebook _huff_book_line_512x17_class3 = {
  121090. 1, 64,
  121091. _huff_lengthlist_line_512x17_class3,
  121092. 0, 0, 0, 0, 0,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. 0
  121098. };
  121099. static long _huff_lengthlist_line_128x4_class0[] = {
  121100. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121101. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121102. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121103. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121104. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121105. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121106. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121107. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121108. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121109. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121110. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121111. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121112. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121113. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121114. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121115. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121116. };
  121117. static static_codebook _huff_book_line_128x4_class0 = {
  121118. 1, 256,
  121119. _huff_lengthlist_line_128x4_class0,
  121120. 0, 0, 0, 0, 0,
  121121. NULL,
  121122. NULL,
  121123. NULL,
  121124. NULL,
  121125. 0
  121126. };
  121127. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121128. 2, 2, 2, 2,
  121129. };
  121130. static static_codebook _huff_book_line_128x4_0sub0 = {
  121131. 1, 4,
  121132. _huff_lengthlist_line_128x4_0sub0,
  121133. 0, 0, 0, 0, 0,
  121134. NULL,
  121135. NULL,
  121136. NULL,
  121137. NULL,
  121138. 0
  121139. };
  121140. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121141. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121142. };
  121143. static static_codebook _huff_book_line_128x4_0sub1 = {
  121144. 1, 10,
  121145. _huff_lengthlist_line_128x4_0sub1,
  121146. 0, 0, 0, 0, 0,
  121147. NULL,
  121148. NULL,
  121149. NULL,
  121150. NULL,
  121151. 0
  121152. };
  121153. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121155. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121156. };
  121157. static static_codebook _huff_book_line_128x4_0sub2 = {
  121158. 1, 25,
  121159. _huff_lengthlist_line_128x4_0sub2,
  121160. 0, 0, 0, 0, 0,
  121161. NULL,
  121162. NULL,
  121163. NULL,
  121164. NULL,
  121165. 0
  121166. };
  121167. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121170. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121171. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121172. };
  121173. static static_codebook _huff_book_line_128x4_0sub3 = {
  121174. 1, 64,
  121175. _huff_lengthlist_line_128x4_0sub3,
  121176. 0, 0, 0, 0, 0,
  121177. NULL,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. 0
  121182. };
  121183. static long _huff_lengthlist_line_256x4_class0[] = {
  121184. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121185. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121186. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121187. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121188. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121189. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121190. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121191. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121192. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121193. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121194. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121195. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121196. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121197. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121198. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121199. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121200. };
  121201. static static_codebook _huff_book_line_256x4_class0 = {
  121202. 1, 256,
  121203. _huff_lengthlist_line_256x4_class0,
  121204. 0, 0, 0, 0, 0,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. 0
  121210. };
  121211. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121212. 2, 2, 2, 2,
  121213. };
  121214. static static_codebook _huff_book_line_256x4_0sub0 = {
  121215. 1, 4,
  121216. _huff_lengthlist_line_256x4_0sub0,
  121217. 0, 0, 0, 0, 0,
  121218. NULL,
  121219. NULL,
  121220. NULL,
  121221. NULL,
  121222. 0
  121223. };
  121224. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121225. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121226. };
  121227. static static_codebook _huff_book_line_256x4_0sub1 = {
  121228. 1, 10,
  121229. _huff_lengthlist_line_256x4_0sub1,
  121230. 0, 0, 0, 0, 0,
  121231. NULL,
  121232. NULL,
  121233. NULL,
  121234. NULL,
  121235. 0
  121236. };
  121237. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121239. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121240. };
  121241. static static_codebook _huff_book_line_256x4_0sub2 = {
  121242. 1, 25,
  121243. _huff_lengthlist_line_256x4_0sub2,
  121244. 0, 0, 0, 0, 0,
  121245. NULL,
  121246. NULL,
  121247. NULL,
  121248. NULL,
  121249. 0
  121250. };
  121251. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121254. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121255. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121256. };
  121257. static static_codebook _huff_book_line_256x4_0sub3 = {
  121258. 1, 64,
  121259. _huff_lengthlist_line_256x4_0sub3,
  121260. 0, 0, 0, 0, 0,
  121261. NULL,
  121262. NULL,
  121263. NULL,
  121264. NULL,
  121265. 0
  121266. };
  121267. static long _huff_lengthlist_line_128x7_class0[] = {
  121268. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121269. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121270. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121271. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121272. };
  121273. static static_codebook _huff_book_line_128x7_class0 = {
  121274. 1, 64,
  121275. _huff_lengthlist_line_128x7_class0,
  121276. 0, 0, 0, 0, 0,
  121277. NULL,
  121278. NULL,
  121279. NULL,
  121280. NULL,
  121281. 0
  121282. };
  121283. static long _huff_lengthlist_line_128x7_class1[] = {
  121284. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121285. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121286. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121287. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121288. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121289. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121290. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121291. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121292. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121293. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121294. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121295. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121296. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121297. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121298. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121299. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121300. };
  121301. static static_codebook _huff_book_line_128x7_class1 = {
  121302. 1, 256,
  121303. _huff_lengthlist_line_128x7_class1,
  121304. 0, 0, 0, 0, 0,
  121305. NULL,
  121306. NULL,
  121307. NULL,
  121308. NULL,
  121309. 0
  121310. };
  121311. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121312. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121313. };
  121314. static static_codebook _huff_book_line_128x7_0sub1 = {
  121315. 1, 9,
  121316. _huff_lengthlist_line_128x7_0sub1,
  121317. 0, 0, 0, 0, 0,
  121318. NULL,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. 0
  121323. };
  121324. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121326. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121327. };
  121328. static static_codebook _huff_book_line_128x7_0sub2 = {
  121329. 1, 25,
  121330. _huff_lengthlist_line_128x7_0sub2,
  121331. 0, 0, 0, 0, 0,
  121332. NULL,
  121333. NULL,
  121334. NULL,
  121335. NULL,
  121336. 0
  121337. };
  121338. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121341. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121342. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121343. };
  121344. static static_codebook _huff_book_line_128x7_0sub3 = {
  121345. 1, 64,
  121346. _huff_lengthlist_line_128x7_0sub3,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121355. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121356. };
  121357. static static_codebook _huff_book_line_128x7_1sub1 = {
  121358. 1, 9,
  121359. _huff_lengthlist_line_128x7_1sub1,
  121360. 0, 0, 0, 0, 0,
  121361. NULL,
  121362. NULL,
  121363. NULL,
  121364. NULL,
  121365. 0
  121366. };
  121367. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121369. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121370. };
  121371. static static_codebook _huff_book_line_128x7_1sub2 = {
  121372. 1, 25,
  121373. _huff_lengthlist_line_128x7_1sub2,
  121374. 0, 0, 0, 0, 0,
  121375. NULL,
  121376. NULL,
  121377. NULL,
  121378. NULL,
  121379. 0
  121380. };
  121381. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121384. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121385. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121386. };
  121387. static static_codebook _huff_book_line_128x7_1sub3 = {
  121388. 1, 64,
  121389. _huff_lengthlist_line_128x7_1sub3,
  121390. 0, 0, 0, 0, 0,
  121391. NULL,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _huff_lengthlist_line_128x11_class1[] = {
  121398. 1, 6, 3, 7, 2, 4, 5, 7,
  121399. };
  121400. static static_codebook _huff_book_line_128x11_class1 = {
  121401. 1, 8,
  121402. _huff_lengthlist_line_128x11_class1,
  121403. 0, 0, 0, 0, 0,
  121404. NULL,
  121405. NULL,
  121406. NULL,
  121407. NULL,
  121408. 0
  121409. };
  121410. static long _huff_lengthlist_line_128x11_class2[] = {
  121411. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121412. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121413. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121414. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121415. };
  121416. static static_codebook _huff_book_line_128x11_class2 = {
  121417. 1, 64,
  121418. _huff_lengthlist_line_128x11_class2,
  121419. 0, 0, 0, 0, 0,
  121420. NULL,
  121421. NULL,
  121422. NULL,
  121423. NULL,
  121424. 0
  121425. };
  121426. static long _huff_lengthlist_line_128x11_class3[] = {
  121427. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121428. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121429. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121430. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121431. };
  121432. static static_codebook _huff_book_line_128x11_class3 = {
  121433. 1, 64,
  121434. _huff_lengthlist_line_128x11_class3,
  121435. 0, 0, 0, 0, 0,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. NULL,
  121440. 0
  121441. };
  121442. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121443. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121444. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121445. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121446. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121447. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121448. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121449. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121450. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121451. };
  121452. static static_codebook _huff_book_line_128x11_0sub0 = {
  121453. 1, 128,
  121454. _huff_lengthlist_line_128x11_0sub0,
  121455. 0, 0, 0, 0, 0,
  121456. NULL,
  121457. NULL,
  121458. NULL,
  121459. NULL,
  121460. 0
  121461. };
  121462. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121463. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121464. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121465. };
  121466. static static_codebook _huff_book_line_128x11_1sub0 = {
  121467. 1, 32,
  121468. _huff_lengthlist_line_128x11_1sub0,
  121469. 0, 0, 0, 0, 0,
  121470. NULL,
  121471. NULL,
  121472. NULL,
  121473. NULL,
  121474. 0
  121475. };
  121476. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121480. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121481. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121482. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121483. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121484. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121485. };
  121486. static static_codebook _huff_book_line_128x11_1sub1 = {
  121487. 1, 128,
  121488. _huff_lengthlist_line_128x11_1sub1,
  121489. 0, 0, 0, 0, 0,
  121490. NULL,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. 0
  121495. };
  121496. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121497. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121498. 5, 5,
  121499. };
  121500. static static_codebook _huff_book_line_128x11_2sub1 = {
  121501. 1, 18,
  121502. _huff_lengthlist_line_128x11_2sub1,
  121503. 0, 0, 0, 0, 0,
  121504. NULL,
  121505. NULL,
  121506. NULL,
  121507. NULL,
  121508. 0
  121509. };
  121510. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121513. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121514. 8,11,
  121515. };
  121516. static static_codebook _huff_book_line_128x11_2sub2 = {
  121517. 1, 50,
  121518. _huff_lengthlist_line_128x11_2sub2,
  121519. 0, 0, 0, 0, 0,
  121520. NULL,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. 0
  121525. };
  121526. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121530. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121531. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121532. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121533. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121534. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121535. };
  121536. static static_codebook _huff_book_line_128x11_2sub3 = {
  121537. 1, 128,
  121538. _huff_lengthlist_line_128x11_2sub3,
  121539. 0, 0, 0, 0, 0,
  121540. NULL,
  121541. NULL,
  121542. NULL,
  121543. NULL,
  121544. 0
  121545. };
  121546. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121547. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121548. 5, 4,
  121549. };
  121550. static static_codebook _huff_book_line_128x11_3sub1 = {
  121551. 1, 18,
  121552. _huff_lengthlist_line_128x11_3sub1,
  121553. 0, 0, 0, 0, 0,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. NULL,
  121558. 0
  121559. };
  121560. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121562. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121563. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121564. 12, 6,
  121565. };
  121566. static static_codebook _huff_book_line_128x11_3sub2 = {
  121567. 1, 50,
  121568. _huff_lengthlist_line_128x11_3sub2,
  121569. 0, 0, 0, 0, 0,
  121570. NULL,
  121571. NULL,
  121572. NULL,
  121573. NULL,
  121574. 0
  121575. };
  121576. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121580. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121581. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121585. };
  121586. static static_codebook _huff_book_line_128x11_3sub3 = {
  121587. 1, 128,
  121588. _huff_lengthlist_line_128x11_3sub3,
  121589. 0, 0, 0, 0, 0,
  121590. NULL,
  121591. NULL,
  121592. NULL,
  121593. NULL,
  121594. 0
  121595. };
  121596. static long _huff_lengthlist_line_128x17_class1[] = {
  121597. 1, 3, 4, 7, 2, 5, 6, 7,
  121598. };
  121599. static static_codebook _huff_book_line_128x17_class1 = {
  121600. 1, 8,
  121601. _huff_lengthlist_line_128x17_class1,
  121602. 0, 0, 0, 0, 0,
  121603. NULL,
  121604. NULL,
  121605. NULL,
  121606. NULL,
  121607. 0
  121608. };
  121609. static long _huff_lengthlist_line_128x17_class2[] = {
  121610. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121611. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121612. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121613. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121614. };
  121615. static static_codebook _huff_book_line_128x17_class2 = {
  121616. 1, 64,
  121617. _huff_lengthlist_line_128x17_class2,
  121618. 0, 0, 0, 0, 0,
  121619. NULL,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. 0
  121624. };
  121625. static long _huff_lengthlist_line_128x17_class3[] = {
  121626. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121627. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121628. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121629. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121630. };
  121631. static static_codebook _huff_book_line_128x17_class3 = {
  121632. 1, 64,
  121633. _huff_lengthlist_line_128x17_class3,
  121634. 0, 0, 0, 0, 0,
  121635. NULL,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. 0
  121640. };
  121641. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121642. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121643. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121644. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121645. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121646. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121647. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121648. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121649. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121650. };
  121651. static static_codebook _huff_book_line_128x17_0sub0 = {
  121652. 1, 128,
  121653. _huff_lengthlist_line_128x17_0sub0,
  121654. 0, 0, 0, 0, 0,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. NULL,
  121659. 0
  121660. };
  121661. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121662. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121663. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121664. };
  121665. static static_codebook _huff_book_line_128x17_1sub0 = {
  121666. 1, 32,
  121667. _huff_lengthlist_line_128x17_1sub0,
  121668. 0, 0, 0, 0, 0,
  121669. NULL,
  121670. NULL,
  121671. NULL,
  121672. NULL,
  121673. 0
  121674. };
  121675. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121679. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121680. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121681. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121682. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121683. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121684. };
  121685. static static_codebook _huff_book_line_128x17_1sub1 = {
  121686. 1, 128,
  121687. _huff_lengthlist_line_128x17_1sub1,
  121688. 0, 0, 0, 0, 0,
  121689. NULL,
  121690. NULL,
  121691. NULL,
  121692. NULL,
  121693. 0
  121694. };
  121695. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121696. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121697. 9, 4,
  121698. };
  121699. static static_codebook _huff_book_line_128x17_2sub1 = {
  121700. 1, 18,
  121701. _huff_lengthlist_line_128x17_2sub1,
  121702. 0, 0, 0, 0, 0,
  121703. NULL,
  121704. NULL,
  121705. NULL,
  121706. NULL,
  121707. 0
  121708. };
  121709. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121712. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121713. 13,13,
  121714. };
  121715. static static_codebook _huff_book_line_128x17_2sub2 = {
  121716. 1, 50,
  121717. _huff_lengthlist_line_128x17_2sub2,
  121718. 0, 0, 0, 0, 0,
  121719. NULL,
  121720. NULL,
  121721. NULL,
  121722. NULL,
  121723. 0
  121724. };
  121725. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121730. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121731. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121732. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121733. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121734. };
  121735. static static_codebook _huff_book_line_128x17_2sub3 = {
  121736. 1, 128,
  121737. _huff_lengthlist_line_128x17_2sub3,
  121738. 0, 0, 0, 0, 0,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. NULL,
  121743. 0
  121744. };
  121745. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121746. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121747. 6, 4,
  121748. };
  121749. static static_codebook _huff_book_line_128x17_3sub1 = {
  121750. 1, 18,
  121751. _huff_lengthlist_line_128x17_3sub1,
  121752. 0, 0, 0, 0, 0,
  121753. NULL,
  121754. NULL,
  121755. NULL,
  121756. NULL,
  121757. 0
  121758. };
  121759. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121762. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121763. 10, 8,
  121764. };
  121765. static static_codebook _huff_book_line_128x17_3sub2 = {
  121766. 1, 50,
  121767. _huff_lengthlist_line_128x17_3sub2,
  121768. 0, 0, 0, 0, 0,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. 0
  121774. };
  121775. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121780. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121781. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121784. };
  121785. static static_codebook _huff_book_line_128x17_3sub3 = {
  121786. 1, 128,
  121787. _huff_lengthlist_line_128x17_3sub3,
  121788. 0, 0, 0, 0, 0,
  121789. NULL,
  121790. NULL,
  121791. NULL,
  121792. NULL,
  121793. 0
  121794. };
  121795. static long _huff_lengthlist_line_1024x27_class1[] = {
  121796. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121797. };
  121798. static static_codebook _huff_book_line_1024x27_class1 = {
  121799. 1, 16,
  121800. _huff_lengthlist_line_1024x27_class1,
  121801. 0, 0, 0, 0, 0,
  121802. NULL,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. 0
  121807. };
  121808. static long _huff_lengthlist_line_1024x27_class2[] = {
  121809. 1, 4, 2, 6, 3, 7, 5, 7,
  121810. };
  121811. static static_codebook _huff_book_line_1024x27_class2 = {
  121812. 1, 8,
  121813. _huff_lengthlist_line_1024x27_class2,
  121814. 0, 0, 0, 0, 0,
  121815. NULL,
  121816. NULL,
  121817. NULL,
  121818. NULL,
  121819. 0
  121820. };
  121821. static long _huff_lengthlist_line_1024x27_class3[] = {
  121822. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121823. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121824. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121825. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121826. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121827. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121828. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121829. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121830. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121831. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121832. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121833. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121834. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121835. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121836. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121837. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121838. };
  121839. static static_codebook _huff_book_line_1024x27_class3 = {
  121840. 1, 256,
  121841. _huff_lengthlist_line_1024x27_class3,
  121842. 0, 0, 0, 0, 0,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. NULL,
  121847. 0
  121848. };
  121849. static long _huff_lengthlist_line_1024x27_class4[] = {
  121850. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121851. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121852. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121853. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121854. };
  121855. static static_codebook _huff_book_line_1024x27_class4 = {
  121856. 1, 64,
  121857. _huff_lengthlist_line_1024x27_class4,
  121858. 0, 0, 0, 0, 0,
  121859. NULL,
  121860. NULL,
  121861. NULL,
  121862. NULL,
  121863. 0
  121864. };
  121865. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121866. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121867. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121868. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121869. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121870. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121871. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121872. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121873. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121874. };
  121875. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121876. 1, 128,
  121877. _huff_lengthlist_line_1024x27_0sub0,
  121878. 0, 0, 0, 0, 0,
  121879. NULL,
  121880. NULL,
  121881. NULL,
  121882. NULL,
  121883. 0
  121884. };
  121885. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121886. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121887. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121888. };
  121889. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121890. 1, 32,
  121891. _huff_lengthlist_line_1024x27_1sub0,
  121892. 0, 0, 0, 0, 0,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. NULL,
  121897. 0
  121898. };
  121899. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121903. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121904. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121905. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121906. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121907. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121908. };
  121909. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121910. 1, 128,
  121911. _huff_lengthlist_line_1024x27_1sub1,
  121912. 0, 0, 0, 0, 0,
  121913. NULL,
  121914. NULL,
  121915. NULL,
  121916. NULL,
  121917. 0
  121918. };
  121919. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121920. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121921. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121922. };
  121923. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121924. 1, 32,
  121925. _huff_lengthlist_line_1024x27_2sub0,
  121926. 0, 0, 0, 0, 0,
  121927. NULL,
  121928. NULL,
  121929. NULL,
  121930. NULL,
  121931. 0
  121932. };
  121933. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121937. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121938. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121939. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121940. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121941. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121942. };
  121943. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121944. 1, 128,
  121945. _huff_lengthlist_line_1024x27_2sub1,
  121946. 0, 0, 0, 0, 0,
  121947. NULL,
  121948. NULL,
  121949. NULL,
  121950. NULL,
  121951. 0
  121952. };
  121953. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121954. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121955. 5, 5,
  121956. };
  121957. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121958. 1, 18,
  121959. _huff_lengthlist_line_1024x27_3sub1,
  121960. 0, 0, 0, 0, 0,
  121961. NULL,
  121962. NULL,
  121963. NULL,
  121964. NULL,
  121965. 0
  121966. };
  121967. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121970. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121971. 9,11,
  121972. };
  121973. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121974. 1, 50,
  121975. _huff_lengthlist_line_1024x27_3sub2,
  121976. 0, 0, 0, 0, 0,
  121977. NULL,
  121978. NULL,
  121979. NULL,
  121980. NULL,
  121981. 0
  121982. };
  121983. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121988. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121989. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121990. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121991. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121992. };
  121993. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121994. 1, 128,
  121995. _huff_lengthlist_line_1024x27_3sub3,
  121996. 0, 0, 0, 0, 0,
  121997. NULL,
  121998. NULL,
  121999. NULL,
  122000. NULL,
  122001. 0
  122002. };
  122003. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122004. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122005. 5, 4,
  122006. };
  122007. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122008. 1, 18,
  122009. _huff_lengthlist_line_1024x27_4sub1,
  122010. 0, 0, 0, 0, 0,
  122011. NULL,
  122012. NULL,
  122013. NULL,
  122014. NULL,
  122015. 0
  122016. };
  122017. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122020. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122021. 9,12,
  122022. };
  122023. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122024. 1, 50,
  122025. _huff_lengthlist_line_1024x27_4sub2,
  122026. 0, 0, 0, 0, 0,
  122027. NULL,
  122028. NULL,
  122029. NULL,
  122030. NULL,
  122031. 0
  122032. };
  122033. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122038. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122041. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122042. };
  122043. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122044. 1, 128,
  122045. _huff_lengthlist_line_1024x27_4sub3,
  122046. 0, 0, 0, 0, 0,
  122047. NULL,
  122048. NULL,
  122049. NULL,
  122050. NULL,
  122051. 0
  122052. };
  122053. static long _huff_lengthlist_line_2048x27_class1[] = {
  122054. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122055. };
  122056. static static_codebook _huff_book_line_2048x27_class1 = {
  122057. 1, 16,
  122058. _huff_lengthlist_line_2048x27_class1,
  122059. 0, 0, 0, 0, 0,
  122060. NULL,
  122061. NULL,
  122062. NULL,
  122063. NULL,
  122064. 0
  122065. };
  122066. static long _huff_lengthlist_line_2048x27_class2[] = {
  122067. 1, 2, 3, 6, 4, 7, 5, 7,
  122068. };
  122069. static static_codebook _huff_book_line_2048x27_class2 = {
  122070. 1, 8,
  122071. _huff_lengthlist_line_2048x27_class2,
  122072. 0, 0, 0, 0, 0,
  122073. NULL,
  122074. NULL,
  122075. NULL,
  122076. NULL,
  122077. 0
  122078. };
  122079. static long _huff_lengthlist_line_2048x27_class3[] = {
  122080. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122081. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122082. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122083. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122084. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122085. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122086. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122087. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122088. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122089. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122090. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122091. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122092. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122093. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122094. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122095. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122096. };
  122097. static static_codebook _huff_book_line_2048x27_class3 = {
  122098. 1, 256,
  122099. _huff_lengthlist_line_2048x27_class3,
  122100. 0, 0, 0, 0, 0,
  122101. NULL,
  122102. NULL,
  122103. NULL,
  122104. NULL,
  122105. 0
  122106. };
  122107. static long _huff_lengthlist_line_2048x27_class4[] = {
  122108. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122109. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122110. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122111. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122112. };
  122113. static static_codebook _huff_book_line_2048x27_class4 = {
  122114. 1, 64,
  122115. _huff_lengthlist_line_2048x27_class4,
  122116. 0, 0, 0, 0, 0,
  122117. NULL,
  122118. NULL,
  122119. NULL,
  122120. NULL,
  122121. 0
  122122. };
  122123. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122124. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122125. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122126. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122127. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122128. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122129. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122130. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122131. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122132. };
  122133. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122134. 1, 128,
  122135. _huff_lengthlist_line_2048x27_0sub0,
  122136. 0, 0, 0, 0, 0,
  122137. NULL,
  122138. NULL,
  122139. NULL,
  122140. NULL,
  122141. 0
  122142. };
  122143. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122144. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122145. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122146. };
  122147. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122148. 1, 32,
  122149. _huff_lengthlist_line_2048x27_1sub0,
  122150. 0, 0, 0, 0, 0,
  122151. NULL,
  122152. NULL,
  122153. NULL,
  122154. NULL,
  122155. 0
  122156. };
  122157. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122161. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122162. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122163. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122164. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122165. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122166. };
  122167. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122168. 1, 128,
  122169. _huff_lengthlist_line_2048x27_1sub1,
  122170. 0, 0, 0, 0, 0,
  122171. NULL,
  122172. NULL,
  122173. NULL,
  122174. NULL,
  122175. 0
  122176. };
  122177. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122178. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122179. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122180. };
  122181. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122182. 1, 32,
  122183. _huff_lengthlist_line_2048x27_2sub0,
  122184. 0, 0, 0, 0, 0,
  122185. NULL,
  122186. NULL,
  122187. NULL,
  122188. NULL,
  122189. 0
  122190. };
  122191. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122195. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122196. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122197. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122198. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122199. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122200. };
  122201. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122202. 1, 128,
  122203. _huff_lengthlist_line_2048x27_2sub1,
  122204. 0, 0, 0, 0, 0,
  122205. NULL,
  122206. NULL,
  122207. NULL,
  122208. NULL,
  122209. 0
  122210. };
  122211. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122212. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122213. 5, 5,
  122214. };
  122215. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122216. 1, 18,
  122217. _huff_lengthlist_line_2048x27_3sub1,
  122218. 0, 0, 0, 0, 0,
  122219. NULL,
  122220. NULL,
  122221. NULL,
  122222. NULL,
  122223. 0
  122224. };
  122225. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122228. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122229. 10,12,
  122230. };
  122231. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122232. 1, 50,
  122233. _huff_lengthlist_line_2048x27_3sub2,
  122234. 0, 0, 0, 0, 0,
  122235. NULL,
  122236. NULL,
  122237. NULL,
  122238. NULL,
  122239. 0
  122240. };
  122241. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122246. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122247. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122248. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122249. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122250. };
  122251. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122252. 1, 128,
  122253. _huff_lengthlist_line_2048x27_3sub3,
  122254. 0, 0, 0, 0, 0,
  122255. NULL,
  122256. NULL,
  122257. NULL,
  122258. NULL,
  122259. 0
  122260. };
  122261. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122262. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122263. 4, 5,
  122264. };
  122265. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122266. 1, 18,
  122267. _huff_lengthlist_line_2048x27_4sub1,
  122268. 0, 0, 0, 0, 0,
  122269. NULL,
  122270. NULL,
  122271. NULL,
  122272. NULL,
  122273. 0
  122274. };
  122275. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122278. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122279. 10,10,
  122280. };
  122281. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122282. 1, 50,
  122283. _huff_lengthlist_line_2048x27_4sub2,
  122284. 0, 0, 0, 0, 0,
  122285. NULL,
  122286. NULL,
  122287. NULL,
  122288. NULL,
  122289. 0
  122290. };
  122291. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122296. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122297. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122298. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122299. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122300. };
  122301. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122302. 1, 128,
  122303. _huff_lengthlist_line_2048x27_4sub3,
  122304. 0, 0, 0, 0, 0,
  122305. NULL,
  122306. NULL,
  122307. NULL,
  122308. NULL,
  122309. 0
  122310. };
  122311. static long _huff_lengthlist_line_256x4low_class0[] = {
  122312. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122313. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122314. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122315. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122316. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122317. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122318. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122319. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122320. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122321. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122322. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122323. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122324. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122325. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122326. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122327. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122328. };
  122329. static static_codebook _huff_book_line_256x4low_class0 = {
  122330. 1, 256,
  122331. _huff_lengthlist_line_256x4low_class0,
  122332. 0, 0, 0, 0, 0,
  122333. NULL,
  122334. NULL,
  122335. NULL,
  122336. NULL,
  122337. 0
  122338. };
  122339. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122340. 1, 3, 2, 3,
  122341. };
  122342. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122343. 1, 4,
  122344. _huff_lengthlist_line_256x4low_0sub0,
  122345. 0, 0, 0, 0, 0,
  122346. NULL,
  122347. NULL,
  122348. NULL,
  122349. NULL,
  122350. 0
  122351. };
  122352. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122353. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122354. };
  122355. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122356. 1, 10,
  122357. _huff_lengthlist_line_256x4low_0sub1,
  122358. 0, 0, 0, 0, 0,
  122359. NULL,
  122360. NULL,
  122361. NULL,
  122362. NULL,
  122363. 0
  122364. };
  122365. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122367. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122368. };
  122369. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122370. 1, 25,
  122371. _huff_lengthlist_line_256x4low_0sub2,
  122372. 0, 0, 0, 0, 0,
  122373. NULL,
  122374. NULL,
  122375. NULL,
  122376. NULL,
  122377. 0
  122378. };
  122379. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122382. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122383. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122384. };
  122385. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122386. 1, 64,
  122387. _huff_lengthlist_line_256x4low_0sub3,
  122388. 0, 0, 0, 0, 0,
  122389. NULL,
  122390. NULL,
  122391. NULL,
  122392. NULL,
  122393. 0
  122394. };
  122395. /*** End of inlined file: floor_books.h ***/
  122396. static static_codebook *_floor_128x4_books[]={
  122397. &_huff_book_line_128x4_class0,
  122398. &_huff_book_line_128x4_0sub0,
  122399. &_huff_book_line_128x4_0sub1,
  122400. &_huff_book_line_128x4_0sub2,
  122401. &_huff_book_line_128x4_0sub3,
  122402. };
  122403. static static_codebook *_floor_256x4_books[]={
  122404. &_huff_book_line_256x4_class0,
  122405. &_huff_book_line_256x4_0sub0,
  122406. &_huff_book_line_256x4_0sub1,
  122407. &_huff_book_line_256x4_0sub2,
  122408. &_huff_book_line_256x4_0sub3,
  122409. };
  122410. static static_codebook *_floor_128x7_books[]={
  122411. &_huff_book_line_128x7_class0,
  122412. &_huff_book_line_128x7_class1,
  122413. &_huff_book_line_128x7_0sub1,
  122414. &_huff_book_line_128x7_0sub2,
  122415. &_huff_book_line_128x7_0sub3,
  122416. &_huff_book_line_128x7_1sub1,
  122417. &_huff_book_line_128x7_1sub2,
  122418. &_huff_book_line_128x7_1sub3,
  122419. };
  122420. static static_codebook *_floor_256x7_books[]={
  122421. &_huff_book_line_256x7_class0,
  122422. &_huff_book_line_256x7_class1,
  122423. &_huff_book_line_256x7_0sub1,
  122424. &_huff_book_line_256x7_0sub2,
  122425. &_huff_book_line_256x7_0sub3,
  122426. &_huff_book_line_256x7_1sub1,
  122427. &_huff_book_line_256x7_1sub2,
  122428. &_huff_book_line_256x7_1sub3,
  122429. };
  122430. static static_codebook *_floor_128x11_books[]={
  122431. &_huff_book_line_128x11_class1,
  122432. &_huff_book_line_128x11_class2,
  122433. &_huff_book_line_128x11_class3,
  122434. &_huff_book_line_128x11_0sub0,
  122435. &_huff_book_line_128x11_1sub0,
  122436. &_huff_book_line_128x11_1sub1,
  122437. &_huff_book_line_128x11_2sub1,
  122438. &_huff_book_line_128x11_2sub2,
  122439. &_huff_book_line_128x11_2sub3,
  122440. &_huff_book_line_128x11_3sub1,
  122441. &_huff_book_line_128x11_3sub2,
  122442. &_huff_book_line_128x11_3sub3,
  122443. };
  122444. static static_codebook *_floor_128x17_books[]={
  122445. &_huff_book_line_128x17_class1,
  122446. &_huff_book_line_128x17_class2,
  122447. &_huff_book_line_128x17_class3,
  122448. &_huff_book_line_128x17_0sub0,
  122449. &_huff_book_line_128x17_1sub0,
  122450. &_huff_book_line_128x17_1sub1,
  122451. &_huff_book_line_128x17_2sub1,
  122452. &_huff_book_line_128x17_2sub2,
  122453. &_huff_book_line_128x17_2sub3,
  122454. &_huff_book_line_128x17_3sub1,
  122455. &_huff_book_line_128x17_3sub2,
  122456. &_huff_book_line_128x17_3sub3,
  122457. };
  122458. static static_codebook *_floor_256x4low_books[]={
  122459. &_huff_book_line_256x4low_class0,
  122460. &_huff_book_line_256x4low_0sub0,
  122461. &_huff_book_line_256x4low_0sub1,
  122462. &_huff_book_line_256x4low_0sub2,
  122463. &_huff_book_line_256x4low_0sub3,
  122464. };
  122465. static static_codebook *_floor_1024x27_books[]={
  122466. &_huff_book_line_1024x27_class1,
  122467. &_huff_book_line_1024x27_class2,
  122468. &_huff_book_line_1024x27_class3,
  122469. &_huff_book_line_1024x27_class4,
  122470. &_huff_book_line_1024x27_0sub0,
  122471. &_huff_book_line_1024x27_1sub0,
  122472. &_huff_book_line_1024x27_1sub1,
  122473. &_huff_book_line_1024x27_2sub0,
  122474. &_huff_book_line_1024x27_2sub1,
  122475. &_huff_book_line_1024x27_3sub1,
  122476. &_huff_book_line_1024x27_3sub2,
  122477. &_huff_book_line_1024x27_3sub3,
  122478. &_huff_book_line_1024x27_4sub1,
  122479. &_huff_book_line_1024x27_4sub2,
  122480. &_huff_book_line_1024x27_4sub3,
  122481. };
  122482. static static_codebook *_floor_2048x27_books[]={
  122483. &_huff_book_line_2048x27_class1,
  122484. &_huff_book_line_2048x27_class2,
  122485. &_huff_book_line_2048x27_class3,
  122486. &_huff_book_line_2048x27_class4,
  122487. &_huff_book_line_2048x27_0sub0,
  122488. &_huff_book_line_2048x27_1sub0,
  122489. &_huff_book_line_2048x27_1sub1,
  122490. &_huff_book_line_2048x27_2sub0,
  122491. &_huff_book_line_2048x27_2sub1,
  122492. &_huff_book_line_2048x27_3sub1,
  122493. &_huff_book_line_2048x27_3sub2,
  122494. &_huff_book_line_2048x27_3sub3,
  122495. &_huff_book_line_2048x27_4sub1,
  122496. &_huff_book_line_2048x27_4sub2,
  122497. &_huff_book_line_2048x27_4sub3,
  122498. };
  122499. static static_codebook *_floor_512x17_books[]={
  122500. &_huff_book_line_512x17_class1,
  122501. &_huff_book_line_512x17_class2,
  122502. &_huff_book_line_512x17_class3,
  122503. &_huff_book_line_512x17_0sub0,
  122504. &_huff_book_line_512x17_1sub0,
  122505. &_huff_book_line_512x17_1sub1,
  122506. &_huff_book_line_512x17_2sub1,
  122507. &_huff_book_line_512x17_2sub2,
  122508. &_huff_book_line_512x17_2sub3,
  122509. &_huff_book_line_512x17_3sub1,
  122510. &_huff_book_line_512x17_3sub2,
  122511. &_huff_book_line_512x17_3sub3,
  122512. };
  122513. static static_codebook **_floor_books[10]={
  122514. _floor_128x4_books,
  122515. _floor_256x4_books,
  122516. _floor_128x7_books,
  122517. _floor_256x7_books,
  122518. _floor_128x11_books,
  122519. _floor_128x17_books,
  122520. _floor_256x4low_books,
  122521. _floor_1024x27_books,
  122522. _floor_2048x27_books,
  122523. _floor_512x17_books,
  122524. };
  122525. static vorbis_info_floor1 _floor[10]={
  122526. /* 128 x 4 */
  122527. {
  122528. 1,{0},{4},{2},{0},
  122529. {{1,2,3,4}},
  122530. 4,{0,128, 33,8,16,70},
  122531. 60,30,500, 1.,18., -1
  122532. },
  122533. /* 256 x 4 */
  122534. {
  122535. 1,{0},{4},{2},{0},
  122536. {{1,2,3,4}},
  122537. 4,{0,256, 66,16,32,140},
  122538. 60,30,500, 1.,18., -1
  122539. },
  122540. /* 128 x 7 */
  122541. {
  122542. 2,{0,1},{3,4},{2,2},{0,1},
  122543. {{-1,2,3,4},{-1,5,6,7}},
  122544. 4,{0,128, 14,4,58, 2,8,28,90},
  122545. 60,30,500, 1.,18., -1
  122546. },
  122547. /* 256 x 7 */
  122548. {
  122549. 2,{0,1},{3,4},{2,2},{0,1},
  122550. {{-1,2,3,4},{-1,5,6,7}},
  122551. 4,{0,256, 28,8,116, 4,16,56,180},
  122552. 60,30,500, 1.,18., -1
  122553. },
  122554. /* 128 x 11 */
  122555. {
  122556. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122557. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122558. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122559. 60,30,500, 1,18., -1
  122560. },
  122561. /* 128 x 17 */
  122562. {
  122563. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122564. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122565. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122566. 60,30,500, 1,18., -1
  122567. },
  122568. /* 256 x 4 (low bitrate version) */
  122569. {
  122570. 1,{0},{4},{2},{0},
  122571. {{1,2,3,4}},
  122572. 4,{0,256, 66,16,32,140},
  122573. 60,30,500, 1.,18., -1
  122574. },
  122575. /* 1024 x 27 */
  122576. {
  122577. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122578. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122579. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122580. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122581. 60,30,500, 3,18., -1 /* lowpass */
  122582. },
  122583. /* 2048 x 27 */
  122584. {
  122585. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122586. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122587. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122588. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122589. 60,30,500, 3,18., -1 /* lowpass */
  122590. },
  122591. /* 512 x 17 */
  122592. {
  122593. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122594. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122595. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122596. 7,23,39, 55,79,110, 156,232,360},
  122597. 60,30,500, 1,18., -1 /* lowpass! */
  122598. },
  122599. };
  122600. /*** End of inlined file: floor_all.h ***/
  122601. /*** Start of inlined file: residue_44.h ***/
  122602. /*** Start of inlined file: res_books_stereo.h ***/
  122603. static long _vq_quantlist__16c0_s_p1_0[] = {
  122604. 1,
  122605. 0,
  122606. 2,
  122607. };
  122608. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122609. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122610. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122615. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122620. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  122655. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122660. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122665. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122701. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122706. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122711. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 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,
  123020. };
  123021. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123022. -0.5, 0.5,
  123023. };
  123024. static long _vq_quantmap__16c0_s_p1_0[] = {
  123025. 1, 0, 2,
  123026. };
  123027. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123028. _vq_quantthresh__16c0_s_p1_0,
  123029. _vq_quantmap__16c0_s_p1_0,
  123030. 3,
  123031. 3
  123032. };
  123033. static static_codebook _16c0_s_p1_0 = {
  123034. 8, 6561,
  123035. _vq_lengthlist__16c0_s_p1_0,
  123036. 1, -535822336, 1611661312, 2, 0,
  123037. _vq_quantlist__16c0_s_p1_0,
  123038. NULL,
  123039. &_vq_auxt__16c0_s_p1_0,
  123040. NULL,
  123041. 0
  123042. };
  123043. static long _vq_quantlist__16c0_s_p2_0[] = {
  123044. 2,
  123045. 1,
  123046. 3,
  123047. 0,
  123048. 4,
  123049. };
  123050. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0,
  123091. };
  123092. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123093. -1.5, -0.5, 0.5, 1.5,
  123094. };
  123095. static long _vq_quantmap__16c0_s_p2_0[] = {
  123096. 3, 1, 0, 2, 4,
  123097. };
  123098. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123099. _vq_quantthresh__16c0_s_p2_0,
  123100. _vq_quantmap__16c0_s_p2_0,
  123101. 5,
  123102. 5
  123103. };
  123104. static static_codebook _16c0_s_p2_0 = {
  123105. 4, 625,
  123106. _vq_lengthlist__16c0_s_p2_0,
  123107. 1, -533725184, 1611661312, 3, 0,
  123108. _vq_quantlist__16c0_s_p2_0,
  123109. NULL,
  123110. &_vq_auxt__16c0_s_p2_0,
  123111. NULL,
  123112. 0
  123113. };
  123114. static long _vq_quantlist__16c0_s_p3_0[] = {
  123115. 2,
  123116. 1,
  123117. 3,
  123118. 0,
  123119. 4,
  123120. };
  123121. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123122. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0,
  123162. };
  123163. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123164. -1.5, -0.5, 0.5, 1.5,
  123165. };
  123166. static long _vq_quantmap__16c0_s_p3_0[] = {
  123167. 3, 1, 0, 2, 4,
  123168. };
  123169. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123170. _vq_quantthresh__16c0_s_p3_0,
  123171. _vq_quantmap__16c0_s_p3_0,
  123172. 5,
  123173. 5
  123174. };
  123175. static static_codebook _16c0_s_p3_0 = {
  123176. 4, 625,
  123177. _vq_lengthlist__16c0_s_p3_0,
  123178. 1, -533725184, 1611661312, 3, 0,
  123179. _vq_quantlist__16c0_s_p3_0,
  123180. NULL,
  123181. &_vq_auxt__16c0_s_p3_0,
  123182. NULL,
  123183. 0
  123184. };
  123185. static long _vq_quantlist__16c0_s_p4_0[] = {
  123186. 4,
  123187. 3,
  123188. 5,
  123189. 2,
  123190. 6,
  123191. 1,
  123192. 7,
  123193. 0,
  123194. 8,
  123195. };
  123196. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123197. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123198. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123199. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123200. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123201. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0,
  123203. };
  123204. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123205. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123206. };
  123207. static long _vq_quantmap__16c0_s_p4_0[] = {
  123208. 7, 5, 3, 1, 0, 2, 4, 6,
  123209. 8,
  123210. };
  123211. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123212. _vq_quantthresh__16c0_s_p4_0,
  123213. _vq_quantmap__16c0_s_p4_0,
  123214. 9,
  123215. 9
  123216. };
  123217. static static_codebook _16c0_s_p4_0 = {
  123218. 2, 81,
  123219. _vq_lengthlist__16c0_s_p4_0,
  123220. 1, -531628032, 1611661312, 4, 0,
  123221. _vq_quantlist__16c0_s_p4_0,
  123222. NULL,
  123223. &_vq_auxt__16c0_s_p4_0,
  123224. NULL,
  123225. 0
  123226. };
  123227. static long _vq_quantlist__16c0_s_p5_0[] = {
  123228. 4,
  123229. 3,
  123230. 5,
  123231. 2,
  123232. 6,
  123233. 1,
  123234. 7,
  123235. 0,
  123236. 8,
  123237. };
  123238. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123239. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123240. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123241. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123242. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123243. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123244. 10,
  123245. };
  123246. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123247. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123248. };
  123249. static long _vq_quantmap__16c0_s_p5_0[] = {
  123250. 7, 5, 3, 1, 0, 2, 4, 6,
  123251. 8,
  123252. };
  123253. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123254. _vq_quantthresh__16c0_s_p5_0,
  123255. _vq_quantmap__16c0_s_p5_0,
  123256. 9,
  123257. 9
  123258. };
  123259. static static_codebook _16c0_s_p5_0 = {
  123260. 2, 81,
  123261. _vq_lengthlist__16c0_s_p5_0,
  123262. 1, -531628032, 1611661312, 4, 0,
  123263. _vq_quantlist__16c0_s_p5_0,
  123264. NULL,
  123265. &_vq_auxt__16c0_s_p5_0,
  123266. NULL,
  123267. 0
  123268. };
  123269. static long _vq_quantlist__16c0_s_p6_0[] = {
  123270. 8,
  123271. 7,
  123272. 9,
  123273. 6,
  123274. 10,
  123275. 5,
  123276. 11,
  123277. 4,
  123278. 12,
  123279. 3,
  123280. 13,
  123281. 2,
  123282. 14,
  123283. 1,
  123284. 15,
  123285. 0,
  123286. 16,
  123287. };
  123288. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123289. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123290. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123291. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123292. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123293. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123294. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123295. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123296. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123297. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123298. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123299. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123300. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123301. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123302. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123303. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123304. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123305. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123307. 14,
  123308. };
  123309. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123310. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123311. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123312. };
  123313. static long _vq_quantmap__16c0_s_p6_0[] = {
  123314. 15, 13, 11, 9, 7, 5, 3, 1,
  123315. 0, 2, 4, 6, 8, 10, 12, 14,
  123316. 16,
  123317. };
  123318. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123319. _vq_quantthresh__16c0_s_p6_0,
  123320. _vq_quantmap__16c0_s_p6_0,
  123321. 17,
  123322. 17
  123323. };
  123324. static static_codebook _16c0_s_p6_0 = {
  123325. 2, 289,
  123326. _vq_lengthlist__16c0_s_p6_0,
  123327. 1, -529530880, 1611661312, 5, 0,
  123328. _vq_quantlist__16c0_s_p6_0,
  123329. NULL,
  123330. &_vq_auxt__16c0_s_p6_0,
  123331. NULL,
  123332. 0
  123333. };
  123334. static long _vq_quantlist__16c0_s_p7_0[] = {
  123335. 1,
  123336. 0,
  123337. 2,
  123338. };
  123339. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123340. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123341. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123342. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123343. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123344. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123345. 13,
  123346. };
  123347. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123348. -5.5, 5.5,
  123349. };
  123350. static long _vq_quantmap__16c0_s_p7_0[] = {
  123351. 1, 0, 2,
  123352. };
  123353. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123354. _vq_quantthresh__16c0_s_p7_0,
  123355. _vq_quantmap__16c0_s_p7_0,
  123356. 3,
  123357. 3
  123358. };
  123359. static static_codebook _16c0_s_p7_0 = {
  123360. 4, 81,
  123361. _vq_lengthlist__16c0_s_p7_0,
  123362. 1, -529137664, 1618345984, 2, 0,
  123363. _vq_quantlist__16c0_s_p7_0,
  123364. NULL,
  123365. &_vq_auxt__16c0_s_p7_0,
  123366. NULL,
  123367. 0
  123368. };
  123369. static long _vq_quantlist__16c0_s_p7_1[] = {
  123370. 5,
  123371. 4,
  123372. 6,
  123373. 3,
  123374. 7,
  123375. 2,
  123376. 8,
  123377. 1,
  123378. 9,
  123379. 0,
  123380. 10,
  123381. };
  123382. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123383. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123384. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123385. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123386. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123387. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123388. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123389. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123390. 11,11,11, 9, 9, 9, 9,10,10,
  123391. };
  123392. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123393. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123394. 3.5, 4.5,
  123395. };
  123396. static long _vq_quantmap__16c0_s_p7_1[] = {
  123397. 9, 7, 5, 3, 1, 0, 2, 4,
  123398. 6, 8, 10,
  123399. };
  123400. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123401. _vq_quantthresh__16c0_s_p7_1,
  123402. _vq_quantmap__16c0_s_p7_1,
  123403. 11,
  123404. 11
  123405. };
  123406. static static_codebook _16c0_s_p7_1 = {
  123407. 2, 121,
  123408. _vq_lengthlist__16c0_s_p7_1,
  123409. 1, -531365888, 1611661312, 4, 0,
  123410. _vq_quantlist__16c0_s_p7_1,
  123411. NULL,
  123412. &_vq_auxt__16c0_s_p7_1,
  123413. NULL,
  123414. 0
  123415. };
  123416. static long _vq_quantlist__16c0_s_p8_0[] = {
  123417. 6,
  123418. 5,
  123419. 7,
  123420. 4,
  123421. 8,
  123422. 3,
  123423. 9,
  123424. 2,
  123425. 10,
  123426. 1,
  123427. 11,
  123428. 0,
  123429. 12,
  123430. };
  123431. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123432. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123433. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123434. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123435. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123436. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123437. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123438. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123439. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123440. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123441. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123442. 0,12,13,13,12,13,14,14,14,
  123443. };
  123444. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123445. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123446. 12.5, 17.5, 22.5, 27.5,
  123447. };
  123448. static long _vq_quantmap__16c0_s_p8_0[] = {
  123449. 11, 9, 7, 5, 3, 1, 0, 2,
  123450. 4, 6, 8, 10, 12,
  123451. };
  123452. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123453. _vq_quantthresh__16c0_s_p8_0,
  123454. _vq_quantmap__16c0_s_p8_0,
  123455. 13,
  123456. 13
  123457. };
  123458. static static_codebook _16c0_s_p8_0 = {
  123459. 2, 169,
  123460. _vq_lengthlist__16c0_s_p8_0,
  123461. 1, -526516224, 1616117760, 4, 0,
  123462. _vq_quantlist__16c0_s_p8_0,
  123463. NULL,
  123464. &_vq_auxt__16c0_s_p8_0,
  123465. NULL,
  123466. 0
  123467. };
  123468. static long _vq_quantlist__16c0_s_p8_1[] = {
  123469. 2,
  123470. 1,
  123471. 3,
  123472. 0,
  123473. 4,
  123474. };
  123475. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123476. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123477. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123478. };
  123479. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123480. -1.5, -0.5, 0.5, 1.5,
  123481. };
  123482. static long _vq_quantmap__16c0_s_p8_1[] = {
  123483. 3, 1, 0, 2, 4,
  123484. };
  123485. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123486. _vq_quantthresh__16c0_s_p8_1,
  123487. _vq_quantmap__16c0_s_p8_1,
  123488. 5,
  123489. 5
  123490. };
  123491. static static_codebook _16c0_s_p8_1 = {
  123492. 2, 25,
  123493. _vq_lengthlist__16c0_s_p8_1,
  123494. 1, -533725184, 1611661312, 3, 0,
  123495. _vq_quantlist__16c0_s_p8_1,
  123496. NULL,
  123497. &_vq_auxt__16c0_s_p8_1,
  123498. NULL,
  123499. 0
  123500. };
  123501. static long _vq_quantlist__16c0_s_p9_0[] = {
  123502. 1,
  123503. 0,
  123504. 2,
  123505. };
  123506. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123507. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123508. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123509. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123510. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123511. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123512. 7,
  123513. };
  123514. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123515. -157.5, 157.5,
  123516. };
  123517. static long _vq_quantmap__16c0_s_p9_0[] = {
  123518. 1, 0, 2,
  123519. };
  123520. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123521. _vq_quantthresh__16c0_s_p9_0,
  123522. _vq_quantmap__16c0_s_p9_0,
  123523. 3,
  123524. 3
  123525. };
  123526. static static_codebook _16c0_s_p9_0 = {
  123527. 4, 81,
  123528. _vq_lengthlist__16c0_s_p9_0,
  123529. 1, -518803456, 1628680192, 2, 0,
  123530. _vq_quantlist__16c0_s_p9_0,
  123531. NULL,
  123532. &_vq_auxt__16c0_s_p9_0,
  123533. NULL,
  123534. 0
  123535. };
  123536. static long _vq_quantlist__16c0_s_p9_1[] = {
  123537. 7,
  123538. 6,
  123539. 8,
  123540. 5,
  123541. 9,
  123542. 4,
  123543. 10,
  123544. 3,
  123545. 11,
  123546. 2,
  123547. 12,
  123548. 1,
  123549. 13,
  123550. 0,
  123551. 14,
  123552. };
  123553. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123554. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123555. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123556. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123557. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123558. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123559. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123560. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123568. 10,
  123569. };
  123570. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123571. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123572. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123573. };
  123574. static long _vq_quantmap__16c0_s_p9_1[] = {
  123575. 13, 11, 9, 7, 5, 3, 1, 0,
  123576. 2, 4, 6, 8, 10, 12, 14,
  123577. };
  123578. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123579. _vq_quantthresh__16c0_s_p9_1,
  123580. _vq_quantmap__16c0_s_p9_1,
  123581. 15,
  123582. 15
  123583. };
  123584. static static_codebook _16c0_s_p9_1 = {
  123585. 2, 225,
  123586. _vq_lengthlist__16c0_s_p9_1,
  123587. 1, -520986624, 1620377600, 4, 0,
  123588. _vq_quantlist__16c0_s_p9_1,
  123589. NULL,
  123590. &_vq_auxt__16c0_s_p9_1,
  123591. NULL,
  123592. 0
  123593. };
  123594. static long _vq_quantlist__16c0_s_p9_2[] = {
  123595. 10,
  123596. 9,
  123597. 11,
  123598. 8,
  123599. 12,
  123600. 7,
  123601. 13,
  123602. 6,
  123603. 14,
  123604. 5,
  123605. 15,
  123606. 4,
  123607. 16,
  123608. 3,
  123609. 17,
  123610. 2,
  123611. 18,
  123612. 1,
  123613. 19,
  123614. 0,
  123615. 20,
  123616. };
  123617. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123618. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123619. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123620. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123621. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123622. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123623. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123624. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123625. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123626. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123627. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123628. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123629. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123630. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123631. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123632. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123633. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123634. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123635. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123636. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123637. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123638. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123639. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123640. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123641. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123642. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123643. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123644. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123645. 10,11,10,10,11, 9,10,10,10,
  123646. };
  123647. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123648. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123649. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123650. 6.5, 7.5, 8.5, 9.5,
  123651. };
  123652. static long _vq_quantmap__16c0_s_p9_2[] = {
  123653. 19, 17, 15, 13, 11, 9, 7, 5,
  123654. 3, 1, 0, 2, 4, 6, 8, 10,
  123655. 12, 14, 16, 18, 20,
  123656. };
  123657. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123658. _vq_quantthresh__16c0_s_p9_2,
  123659. _vq_quantmap__16c0_s_p9_2,
  123660. 21,
  123661. 21
  123662. };
  123663. static static_codebook _16c0_s_p9_2 = {
  123664. 2, 441,
  123665. _vq_lengthlist__16c0_s_p9_2,
  123666. 1, -529268736, 1611661312, 5, 0,
  123667. _vq_quantlist__16c0_s_p9_2,
  123668. NULL,
  123669. &_vq_auxt__16c0_s_p9_2,
  123670. NULL,
  123671. 0
  123672. };
  123673. static long _huff_lengthlist__16c0_s_single[] = {
  123674. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123675. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123676. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123677. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123678. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123679. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123680. 16,16,18,18,
  123681. };
  123682. static static_codebook _huff_book__16c0_s_single = {
  123683. 2, 100,
  123684. _huff_lengthlist__16c0_s_single,
  123685. 0, 0, 0, 0, 0,
  123686. NULL,
  123687. NULL,
  123688. NULL,
  123689. NULL,
  123690. 0
  123691. };
  123692. static long _huff_lengthlist__16c1_s_long[] = {
  123693. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123694. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123695. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123696. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123697. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123698. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123699. 12,11,11,13,
  123700. };
  123701. static static_codebook _huff_book__16c1_s_long = {
  123702. 2, 100,
  123703. _huff_lengthlist__16c1_s_long,
  123704. 0, 0, 0, 0, 0,
  123705. NULL,
  123706. NULL,
  123707. NULL,
  123708. NULL,
  123709. 0
  123710. };
  123711. static long _vq_quantlist__16c1_s_p1_0[] = {
  123712. 1,
  123713. 0,
  123714. 2,
  123715. };
  123716. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123717. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123718. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123723. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123728. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  123763. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123768. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123773. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123809. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123814. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123819. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 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,
  124128. };
  124129. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124130. -0.5, 0.5,
  124131. };
  124132. static long _vq_quantmap__16c1_s_p1_0[] = {
  124133. 1, 0, 2,
  124134. };
  124135. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124136. _vq_quantthresh__16c1_s_p1_0,
  124137. _vq_quantmap__16c1_s_p1_0,
  124138. 3,
  124139. 3
  124140. };
  124141. static static_codebook _16c1_s_p1_0 = {
  124142. 8, 6561,
  124143. _vq_lengthlist__16c1_s_p1_0,
  124144. 1, -535822336, 1611661312, 2, 0,
  124145. _vq_quantlist__16c1_s_p1_0,
  124146. NULL,
  124147. &_vq_auxt__16c1_s_p1_0,
  124148. NULL,
  124149. 0
  124150. };
  124151. static long _vq_quantlist__16c1_s_p2_0[] = {
  124152. 2,
  124153. 1,
  124154. 3,
  124155. 0,
  124156. 4,
  124157. };
  124158. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0,
  124199. };
  124200. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124201. -1.5, -0.5, 0.5, 1.5,
  124202. };
  124203. static long _vq_quantmap__16c1_s_p2_0[] = {
  124204. 3, 1, 0, 2, 4,
  124205. };
  124206. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124207. _vq_quantthresh__16c1_s_p2_0,
  124208. _vq_quantmap__16c1_s_p2_0,
  124209. 5,
  124210. 5
  124211. };
  124212. static static_codebook _16c1_s_p2_0 = {
  124213. 4, 625,
  124214. _vq_lengthlist__16c1_s_p2_0,
  124215. 1, -533725184, 1611661312, 3, 0,
  124216. _vq_quantlist__16c1_s_p2_0,
  124217. NULL,
  124218. &_vq_auxt__16c1_s_p2_0,
  124219. NULL,
  124220. 0
  124221. };
  124222. static long _vq_quantlist__16c1_s_p3_0[] = {
  124223. 2,
  124224. 1,
  124225. 3,
  124226. 0,
  124227. 4,
  124228. };
  124229. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124230. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0,
  124270. };
  124271. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124272. -1.5, -0.5, 0.5, 1.5,
  124273. };
  124274. static long _vq_quantmap__16c1_s_p3_0[] = {
  124275. 3, 1, 0, 2, 4,
  124276. };
  124277. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124278. _vq_quantthresh__16c1_s_p3_0,
  124279. _vq_quantmap__16c1_s_p3_0,
  124280. 5,
  124281. 5
  124282. };
  124283. static static_codebook _16c1_s_p3_0 = {
  124284. 4, 625,
  124285. _vq_lengthlist__16c1_s_p3_0,
  124286. 1, -533725184, 1611661312, 3, 0,
  124287. _vq_quantlist__16c1_s_p3_0,
  124288. NULL,
  124289. &_vq_auxt__16c1_s_p3_0,
  124290. NULL,
  124291. 0
  124292. };
  124293. static long _vq_quantlist__16c1_s_p4_0[] = {
  124294. 4,
  124295. 3,
  124296. 5,
  124297. 2,
  124298. 6,
  124299. 1,
  124300. 7,
  124301. 0,
  124302. 8,
  124303. };
  124304. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124305. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124306. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124307. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124308. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124309. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0,
  124311. };
  124312. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124313. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124314. };
  124315. static long _vq_quantmap__16c1_s_p4_0[] = {
  124316. 7, 5, 3, 1, 0, 2, 4, 6,
  124317. 8,
  124318. };
  124319. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124320. _vq_quantthresh__16c1_s_p4_0,
  124321. _vq_quantmap__16c1_s_p4_0,
  124322. 9,
  124323. 9
  124324. };
  124325. static static_codebook _16c1_s_p4_0 = {
  124326. 2, 81,
  124327. _vq_lengthlist__16c1_s_p4_0,
  124328. 1, -531628032, 1611661312, 4, 0,
  124329. _vq_quantlist__16c1_s_p4_0,
  124330. NULL,
  124331. &_vq_auxt__16c1_s_p4_0,
  124332. NULL,
  124333. 0
  124334. };
  124335. static long _vq_quantlist__16c1_s_p5_0[] = {
  124336. 4,
  124337. 3,
  124338. 5,
  124339. 2,
  124340. 6,
  124341. 1,
  124342. 7,
  124343. 0,
  124344. 8,
  124345. };
  124346. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124347. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124348. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124349. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124350. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124351. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124352. 10,
  124353. };
  124354. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124355. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124356. };
  124357. static long _vq_quantmap__16c1_s_p5_0[] = {
  124358. 7, 5, 3, 1, 0, 2, 4, 6,
  124359. 8,
  124360. };
  124361. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124362. _vq_quantthresh__16c1_s_p5_0,
  124363. _vq_quantmap__16c1_s_p5_0,
  124364. 9,
  124365. 9
  124366. };
  124367. static static_codebook _16c1_s_p5_0 = {
  124368. 2, 81,
  124369. _vq_lengthlist__16c1_s_p5_0,
  124370. 1, -531628032, 1611661312, 4, 0,
  124371. _vq_quantlist__16c1_s_p5_0,
  124372. NULL,
  124373. &_vq_auxt__16c1_s_p5_0,
  124374. NULL,
  124375. 0
  124376. };
  124377. static long _vq_quantlist__16c1_s_p6_0[] = {
  124378. 8,
  124379. 7,
  124380. 9,
  124381. 6,
  124382. 10,
  124383. 5,
  124384. 11,
  124385. 4,
  124386. 12,
  124387. 3,
  124388. 13,
  124389. 2,
  124390. 14,
  124391. 1,
  124392. 15,
  124393. 0,
  124394. 16,
  124395. };
  124396. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124397. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124398. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124399. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124400. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124401. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124402. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124403. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124404. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124405. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124406. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124407. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124408. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124409. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124410. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124411. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124412. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124413. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124415. 14,
  124416. };
  124417. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124418. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124419. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124420. };
  124421. static long _vq_quantmap__16c1_s_p6_0[] = {
  124422. 15, 13, 11, 9, 7, 5, 3, 1,
  124423. 0, 2, 4, 6, 8, 10, 12, 14,
  124424. 16,
  124425. };
  124426. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124427. _vq_quantthresh__16c1_s_p6_0,
  124428. _vq_quantmap__16c1_s_p6_0,
  124429. 17,
  124430. 17
  124431. };
  124432. static static_codebook _16c1_s_p6_0 = {
  124433. 2, 289,
  124434. _vq_lengthlist__16c1_s_p6_0,
  124435. 1, -529530880, 1611661312, 5, 0,
  124436. _vq_quantlist__16c1_s_p6_0,
  124437. NULL,
  124438. &_vq_auxt__16c1_s_p6_0,
  124439. NULL,
  124440. 0
  124441. };
  124442. static long _vq_quantlist__16c1_s_p7_0[] = {
  124443. 1,
  124444. 0,
  124445. 2,
  124446. };
  124447. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124448. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124449. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124450. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124451. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124452. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124453. 11,
  124454. };
  124455. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124456. -5.5, 5.5,
  124457. };
  124458. static long _vq_quantmap__16c1_s_p7_0[] = {
  124459. 1, 0, 2,
  124460. };
  124461. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124462. _vq_quantthresh__16c1_s_p7_0,
  124463. _vq_quantmap__16c1_s_p7_0,
  124464. 3,
  124465. 3
  124466. };
  124467. static static_codebook _16c1_s_p7_0 = {
  124468. 4, 81,
  124469. _vq_lengthlist__16c1_s_p7_0,
  124470. 1, -529137664, 1618345984, 2, 0,
  124471. _vq_quantlist__16c1_s_p7_0,
  124472. NULL,
  124473. &_vq_auxt__16c1_s_p7_0,
  124474. NULL,
  124475. 0
  124476. };
  124477. static long _vq_quantlist__16c1_s_p7_1[] = {
  124478. 5,
  124479. 4,
  124480. 6,
  124481. 3,
  124482. 7,
  124483. 2,
  124484. 8,
  124485. 1,
  124486. 9,
  124487. 0,
  124488. 10,
  124489. };
  124490. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124491. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124492. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124493. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124494. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124495. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124496. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124497. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124498. 10,10,10, 8, 8, 8, 8, 9, 9,
  124499. };
  124500. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124501. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124502. 3.5, 4.5,
  124503. };
  124504. static long _vq_quantmap__16c1_s_p7_1[] = {
  124505. 9, 7, 5, 3, 1, 0, 2, 4,
  124506. 6, 8, 10,
  124507. };
  124508. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124509. _vq_quantthresh__16c1_s_p7_1,
  124510. _vq_quantmap__16c1_s_p7_1,
  124511. 11,
  124512. 11
  124513. };
  124514. static static_codebook _16c1_s_p7_1 = {
  124515. 2, 121,
  124516. _vq_lengthlist__16c1_s_p7_1,
  124517. 1, -531365888, 1611661312, 4, 0,
  124518. _vq_quantlist__16c1_s_p7_1,
  124519. NULL,
  124520. &_vq_auxt__16c1_s_p7_1,
  124521. NULL,
  124522. 0
  124523. };
  124524. static long _vq_quantlist__16c1_s_p8_0[] = {
  124525. 6,
  124526. 5,
  124527. 7,
  124528. 4,
  124529. 8,
  124530. 3,
  124531. 9,
  124532. 2,
  124533. 10,
  124534. 1,
  124535. 11,
  124536. 0,
  124537. 12,
  124538. };
  124539. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124540. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124541. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124542. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124543. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124544. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124545. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124546. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124547. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124548. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124549. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124550. 0,12,12,12,12,13,13,14,15,
  124551. };
  124552. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124553. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124554. 12.5, 17.5, 22.5, 27.5,
  124555. };
  124556. static long _vq_quantmap__16c1_s_p8_0[] = {
  124557. 11, 9, 7, 5, 3, 1, 0, 2,
  124558. 4, 6, 8, 10, 12,
  124559. };
  124560. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124561. _vq_quantthresh__16c1_s_p8_0,
  124562. _vq_quantmap__16c1_s_p8_0,
  124563. 13,
  124564. 13
  124565. };
  124566. static static_codebook _16c1_s_p8_0 = {
  124567. 2, 169,
  124568. _vq_lengthlist__16c1_s_p8_0,
  124569. 1, -526516224, 1616117760, 4, 0,
  124570. _vq_quantlist__16c1_s_p8_0,
  124571. NULL,
  124572. &_vq_auxt__16c1_s_p8_0,
  124573. NULL,
  124574. 0
  124575. };
  124576. static long _vq_quantlist__16c1_s_p8_1[] = {
  124577. 2,
  124578. 1,
  124579. 3,
  124580. 0,
  124581. 4,
  124582. };
  124583. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124584. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124585. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124586. };
  124587. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124588. -1.5, -0.5, 0.5, 1.5,
  124589. };
  124590. static long _vq_quantmap__16c1_s_p8_1[] = {
  124591. 3, 1, 0, 2, 4,
  124592. };
  124593. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124594. _vq_quantthresh__16c1_s_p8_1,
  124595. _vq_quantmap__16c1_s_p8_1,
  124596. 5,
  124597. 5
  124598. };
  124599. static static_codebook _16c1_s_p8_1 = {
  124600. 2, 25,
  124601. _vq_lengthlist__16c1_s_p8_1,
  124602. 1, -533725184, 1611661312, 3, 0,
  124603. _vq_quantlist__16c1_s_p8_1,
  124604. NULL,
  124605. &_vq_auxt__16c1_s_p8_1,
  124606. NULL,
  124607. 0
  124608. };
  124609. static long _vq_quantlist__16c1_s_p9_0[] = {
  124610. 6,
  124611. 5,
  124612. 7,
  124613. 4,
  124614. 8,
  124615. 3,
  124616. 9,
  124617. 2,
  124618. 10,
  124619. 1,
  124620. 11,
  124621. 0,
  124622. 12,
  124623. };
  124624. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124625. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124626. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124627. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124628. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124629. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124630. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124631. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124632. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124633. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124634. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124635. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124636. };
  124637. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124638. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124639. 787.5, 1102.5, 1417.5, 1732.5,
  124640. };
  124641. static long _vq_quantmap__16c1_s_p9_0[] = {
  124642. 11, 9, 7, 5, 3, 1, 0, 2,
  124643. 4, 6, 8, 10, 12,
  124644. };
  124645. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124646. _vq_quantthresh__16c1_s_p9_0,
  124647. _vq_quantmap__16c1_s_p9_0,
  124648. 13,
  124649. 13
  124650. };
  124651. static static_codebook _16c1_s_p9_0 = {
  124652. 2, 169,
  124653. _vq_lengthlist__16c1_s_p9_0,
  124654. 1, -513964032, 1628680192, 4, 0,
  124655. _vq_quantlist__16c1_s_p9_0,
  124656. NULL,
  124657. &_vq_auxt__16c1_s_p9_0,
  124658. NULL,
  124659. 0
  124660. };
  124661. static long _vq_quantlist__16c1_s_p9_1[] = {
  124662. 7,
  124663. 6,
  124664. 8,
  124665. 5,
  124666. 9,
  124667. 4,
  124668. 10,
  124669. 3,
  124670. 11,
  124671. 2,
  124672. 12,
  124673. 1,
  124674. 13,
  124675. 0,
  124676. 14,
  124677. };
  124678. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124679. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124680. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124681. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124682. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124683. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124684. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124685. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124686. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124687. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124688. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124689. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124690. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124691. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124692. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124693. 13,
  124694. };
  124695. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124696. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124697. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124698. };
  124699. static long _vq_quantmap__16c1_s_p9_1[] = {
  124700. 13, 11, 9, 7, 5, 3, 1, 0,
  124701. 2, 4, 6, 8, 10, 12, 14,
  124702. };
  124703. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124704. _vq_quantthresh__16c1_s_p9_1,
  124705. _vq_quantmap__16c1_s_p9_1,
  124706. 15,
  124707. 15
  124708. };
  124709. static static_codebook _16c1_s_p9_1 = {
  124710. 2, 225,
  124711. _vq_lengthlist__16c1_s_p9_1,
  124712. 1, -520986624, 1620377600, 4, 0,
  124713. _vq_quantlist__16c1_s_p9_1,
  124714. NULL,
  124715. &_vq_auxt__16c1_s_p9_1,
  124716. NULL,
  124717. 0
  124718. };
  124719. static long _vq_quantlist__16c1_s_p9_2[] = {
  124720. 10,
  124721. 9,
  124722. 11,
  124723. 8,
  124724. 12,
  124725. 7,
  124726. 13,
  124727. 6,
  124728. 14,
  124729. 5,
  124730. 15,
  124731. 4,
  124732. 16,
  124733. 3,
  124734. 17,
  124735. 2,
  124736. 18,
  124737. 1,
  124738. 19,
  124739. 0,
  124740. 20,
  124741. };
  124742. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124743. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124744. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124745. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124746. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124747. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124748. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124749. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124750. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124751. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124752. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124753. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124754. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124755. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124756. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124757. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124758. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124759. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124760. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124761. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124762. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124763. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124764. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124765. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124766. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124767. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124768. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124769. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124770. 11,11,11,11,12,11,11,12,11,
  124771. };
  124772. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124773. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124774. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124775. 6.5, 7.5, 8.5, 9.5,
  124776. };
  124777. static long _vq_quantmap__16c1_s_p9_2[] = {
  124778. 19, 17, 15, 13, 11, 9, 7, 5,
  124779. 3, 1, 0, 2, 4, 6, 8, 10,
  124780. 12, 14, 16, 18, 20,
  124781. };
  124782. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124783. _vq_quantthresh__16c1_s_p9_2,
  124784. _vq_quantmap__16c1_s_p9_2,
  124785. 21,
  124786. 21
  124787. };
  124788. static static_codebook _16c1_s_p9_2 = {
  124789. 2, 441,
  124790. _vq_lengthlist__16c1_s_p9_2,
  124791. 1, -529268736, 1611661312, 5, 0,
  124792. _vq_quantlist__16c1_s_p9_2,
  124793. NULL,
  124794. &_vq_auxt__16c1_s_p9_2,
  124795. NULL,
  124796. 0
  124797. };
  124798. static long _huff_lengthlist__16c1_s_short[] = {
  124799. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124800. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124801. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124802. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124803. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124804. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124805. 9, 9,10,13,
  124806. };
  124807. static static_codebook _huff_book__16c1_s_short = {
  124808. 2, 100,
  124809. _huff_lengthlist__16c1_s_short,
  124810. 0, 0, 0, 0, 0,
  124811. NULL,
  124812. NULL,
  124813. NULL,
  124814. NULL,
  124815. 0
  124816. };
  124817. static long _huff_lengthlist__16c2_s_long[] = {
  124818. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124819. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124820. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124821. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124822. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124823. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124824. 14,14,16,18,
  124825. };
  124826. static static_codebook _huff_book__16c2_s_long = {
  124827. 2, 100,
  124828. _huff_lengthlist__16c2_s_long,
  124829. 0, 0, 0, 0, 0,
  124830. NULL,
  124831. NULL,
  124832. NULL,
  124833. NULL,
  124834. 0
  124835. };
  124836. static long _vq_quantlist__16c2_s_p1_0[] = {
  124837. 1,
  124838. 0,
  124839. 2,
  124840. };
  124841. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124842. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124843. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0,
  124848. };
  124849. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124850. -0.5, 0.5,
  124851. };
  124852. static long _vq_quantmap__16c2_s_p1_0[] = {
  124853. 1, 0, 2,
  124854. };
  124855. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124856. _vq_quantthresh__16c2_s_p1_0,
  124857. _vq_quantmap__16c2_s_p1_0,
  124858. 3,
  124859. 3
  124860. };
  124861. static static_codebook _16c2_s_p1_0 = {
  124862. 4, 81,
  124863. _vq_lengthlist__16c2_s_p1_0,
  124864. 1, -535822336, 1611661312, 2, 0,
  124865. _vq_quantlist__16c2_s_p1_0,
  124866. NULL,
  124867. &_vq_auxt__16c2_s_p1_0,
  124868. NULL,
  124869. 0
  124870. };
  124871. static long _vq_quantlist__16c2_s_p2_0[] = {
  124872. 2,
  124873. 1,
  124874. 3,
  124875. 0,
  124876. 4,
  124877. };
  124878. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124879. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124880. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124881. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124882. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124883. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124884. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124885. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124886. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124892. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124893. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124894. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124900. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124901. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124902. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124908. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124909. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124910. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124915. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124916. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124917. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124918. 13,
  124919. };
  124920. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124921. -1.5, -0.5, 0.5, 1.5,
  124922. };
  124923. static long _vq_quantmap__16c2_s_p2_0[] = {
  124924. 3, 1, 0, 2, 4,
  124925. };
  124926. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124927. _vq_quantthresh__16c2_s_p2_0,
  124928. _vq_quantmap__16c2_s_p2_0,
  124929. 5,
  124930. 5
  124931. };
  124932. static static_codebook _16c2_s_p2_0 = {
  124933. 4, 625,
  124934. _vq_lengthlist__16c2_s_p2_0,
  124935. 1, -533725184, 1611661312, 3, 0,
  124936. _vq_quantlist__16c2_s_p2_0,
  124937. NULL,
  124938. &_vq_auxt__16c2_s_p2_0,
  124939. NULL,
  124940. 0
  124941. };
  124942. static long _vq_quantlist__16c2_s_p3_0[] = {
  124943. 4,
  124944. 3,
  124945. 5,
  124946. 2,
  124947. 6,
  124948. 1,
  124949. 7,
  124950. 0,
  124951. 8,
  124952. };
  124953. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124954. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124955. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124956. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124957. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0,
  124960. };
  124961. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124962. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124963. };
  124964. static long _vq_quantmap__16c2_s_p3_0[] = {
  124965. 7, 5, 3, 1, 0, 2, 4, 6,
  124966. 8,
  124967. };
  124968. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124969. _vq_quantthresh__16c2_s_p3_0,
  124970. _vq_quantmap__16c2_s_p3_0,
  124971. 9,
  124972. 9
  124973. };
  124974. static static_codebook _16c2_s_p3_0 = {
  124975. 2, 81,
  124976. _vq_lengthlist__16c2_s_p3_0,
  124977. 1, -531628032, 1611661312, 4, 0,
  124978. _vq_quantlist__16c2_s_p3_0,
  124979. NULL,
  124980. &_vq_auxt__16c2_s_p3_0,
  124981. NULL,
  124982. 0
  124983. };
  124984. static long _vq_quantlist__16c2_s_p4_0[] = {
  124985. 8,
  124986. 7,
  124987. 9,
  124988. 6,
  124989. 10,
  124990. 5,
  124991. 11,
  124992. 4,
  124993. 12,
  124994. 3,
  124995. 13,
  124996. 2,
  124997. 14,
  124998. 1,
  124999. 15,
  125000. 0,
  125001. 16,
  125002. };
  125003. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125004. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125005. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125006. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125007. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125008. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125009. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125010. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125011. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125012. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125013. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0,
  125023. };
  125024. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125025. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125026. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125027. };
  125028. static long _vq_quantmap__16c2_s_p4_0[] = {
  125029. 15, 13, 11, 9, 7, 5, 3, 1,
  125030. 0, 2, 4, 6, 8, 10, 12, 14,
  125031. 16,
  125032. };
  125033. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125034. _vq_quantthresh__16c2_s_p4_0,
  125035. _vq_quantmap__16c2_s_p4_0,
  125036. 17,
  125037. 17
  125038. };
  125039. static static_codebook _16c2_s_p4_0 = {
  125040. 2, 289,
  125041. _vq_lengthlist__16c2_s_p4_0,
  125042. 1, -529530880, 1611661312, 5, 0,
  125043. _vq_quantlist__16c2_s_p4_0,
  125044. NULL,
  125045. &_vq_auxt__16c2_s_p4_0,
  125046. NULL,
  125047. 0
  125048. };
  125049. static long _vq_quantlist__16c2_s_p5_0[] = {
  125050. 1,
  125051. 0,
  125052. 2,
  125053. };
  125054. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125055. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125056. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125057. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125058. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125059. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125060. 12,
  125061. };
  125062. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125063. -5.5, 5.5,
  125064. };
  125065. static long _vq_quantmap__16c2_s_p5_0[] = {
  125066. 1, 0, 2,
  125067. };
  125068. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125069. _vq_quantthresh__16c2_s_p5_0,
  125070. _vq_quantmap__16c2_s_p5_0,
  125071. 3,
  125072. 3
  125073. };
  125074. static static_codebook _16c2_s_p5_0 = {
  125075. 4, 81,
  125076. _vq_lengthlist__16c2_s_p5_0,
  125077. 1, -529137664, 1618345984, 2, 0,
  125078. _vq_quantlist__16c2_s_p5_0,
  125079. NULL,
  125080. &_vq_auxt__16c2_s_p5_0,
  125081. NULL,
  125082. 0
  125083. };
  125084. static long _vq_quantlist__16c2_s_p5_1[] = {
  125085. 5,
  125086. 4,
  125087. 6,
  125088. 3,
  125089. 7,
  125090. 2,
  125091. 8,
  125092. 1,
  125093. 9,
  125094. 0,
  125095. 10,
  125096. };
  125097. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125098. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125099. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125100. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125101. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125102. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125103. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125104. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125105. 11,11,11, 7, 7, 8, 8, 8, 8,
  125106. };
  125107. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125108. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125109. 3.5, 4.5,
  125110. };
  125111. static long _vq_quantmap__16c2_s_p5_1[] = {
  125112. 9, 7, 5, 3, 1, 0, 2, 4,
  125113. 6, 8, 10,
  125114. };
  125115. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125116. _vq_quantthresh__16c2_s_p5_1,
  125117. _vq_quantmap__16c2_s_p5_1,
  125118. 11,
  125119. 11
  125120. };
  125121. static static_codebook _16c2_s_p5_1 = {
  125122. 2, 121,
  125123. _vq_lengthlist__16c2_s_p5_1,
  125124. 1, -531365888, 1611661312, 4, 0,
  125125. _vq_quantlist__16c2_s_p5_1,
  125126. NULL,
  125127. &_vq_auxt__16c2_s_p5_1,
  125128. NULL,
  125129. 0
  125130. };
  125131. static long _vq_quantlist__16c2_s_p6_0[] = {
  125132. 6,
  125133. 5,
  125134. 7,
  125135. 4,
  125136. 8,
  125137. 3,
  125138. 9,
  125139. 2,
  125140. 10,
  125141. 1,
  125142. 11,
  125143. 0,
  125144. 12,
  125145. };
  125146. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125147. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125148. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125149. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125150. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125151. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125152. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. };
  125159. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125160. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125161. 12.5, 17.5, 22.5, 27.5,
  125162. };
  125163. static long _vq_quantmap__16c2_s_p6_0[] = {
  125164. 11, 9, 7, 5, 3, 1, 0, 2,
  125165. 4, 6, 8, 10, 12,
  125166. };
  125167. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125168. _vq_quantthresh__16c2_s_p6_0,
  125169. _vq_quantmap__16c2_s_p6_0,
  125170. 13,
  125171. 13
  125172. };
  125173. static static_codebook _16c2_s_p6_0 = {
  125174. 2, 169,
  125175. _vq_lengthlist__16c2_s_p6_0,
  125176. 1, -526516224, 1616117760, 4, 0,
  125177. _vq_quantlist__16c2_s_p6_0,
  125178. NULL,
  125179. &_vq_auxt__16c2_s_p6_0,
  125180. NULL,
  125181. 0
  125182. };
  125183. static long _vq_quantlist__16c2_s_p6_1[] = {
  125184. 2,
  125185. 1,
  125186. 3,
  125187. 0,
  125188. 4,
  125189. };
  125190. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125191. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125192. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125193. };
  125194. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125195. -1.5, -0.5, 0.5, 1.5,
  125196. };
  125197. static long _vq_quantmap__16c2_s_p6_1[] = {
  125198. 3, 1, 0, 2, 4,
  125199. };
  125200. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125201. _vq_quantthresh__16c2_s_p6_1,
  125202. _vq_quantmap__16c2_s_p6_1,
  125203. 5,
  125204. 5
  125205. };
  125206. static static_codebook _16c2_s_p6_1 = {
  125207. 2, 25,
  125208. _vq_lengthlist__16c2_s_p6_1,
  125209. 1, -533725184, 1611661312, 3, 0,
  125210. _vq_quantlist__16c2_s_p6_1,
  125211. NULL,
  125212. &_vq_auxt__16c2_s_p6_1,
  125213. NULL,
  125214. 0
  125215. };
  125216. static long _vq_quantlist__16c2_s_p7_0[] = {
  125217. 6,
  125218. 5,
  125219. 7,
  125220. 4,
  125221. 8,
  125222. 3,
  125223. 9,
  125224. 2,
  125225. 10,
  125226. 1,
  125227. 11,
  125228. 0,
  125229. 12,
  125230. };
  125231. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125232. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125233. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125234. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125235. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125236. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125237. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125238. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125239. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125240. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125241. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125242. 18,13,14,13,13,14,13,15,14,
  125243. };
  125244. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125245. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125246. 27.5, 38.5, 49.5, 60.5,
  125247. };
  125248. static long _vq_quantmap__16c2_s_p7_0[] = {
  125249. 11, 9, 7, 5, 3, 1, 0, 2,
  125250. 4, 6, 8, 10, 12,
  125251. };
  125252. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125253. _vq_quantthresh__16c2_s_p7_0,
  125254. _vq_quantmap__16c2_s_p7_0,
  125255. 13,
  125256. 13
  125257. };
  125258. static static_codebook _16c2_s_p7_0 = {
  125259. 2, 169,
  125260. _vq_lengthlist__16c2_s_p7_0,
  125261. 1, -523206656, 1618345984, 4, 0,
  125262. _vq_quantlist__16c2_s_p7_0,
  125263. NULL,
  125264. &_vq_auxt__16c2_s_p7_0,
  125265. NULL,
  125266. 0
  125267. };
  125268. static long _vq_quantlist__16c2_s_p7_1[] = {
  125269. 5,
  125270. 4,
  125271. 6,
  125272. 3,
  125273. 7,
  125274. 2,
  125275. 8,
  125276. 1,
  125277. 9,
  125278. 0,
  125279. 10,
  125280. };
  125281. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125282. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125283. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125284. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125285. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125286. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125287. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125288. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125289. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125290. };
  125291. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125292. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125293. 3.5, 4.5,
  125294. };
  125295. static long _vq_quantmap__16c2_s_p7_1[] = {
  125296. 9, 7, 5, 3, 1, 0, 2, 4,
  125297. 6, 8, 10,
  125298. };
  125299. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125300. _vq_quantthresh__16c2_s_p7_1,
  125301. _vq_quantmap__16c2_s_p7_1,
  125302. 11,
  125303. 11
  125304. };
  125305. static static_codebook _16c2_s_p7_1 = {
  125306. 2, 121,
  125307. _vq_lengthlist__16c2_s_p7_1,
  125308. 1, -531365888, 1611661312, 4, 0,
  125309. _vq_quantlist__16c2_s_p7_1,
  125310. NULL,
  125311. &_vq_auxt__16c2_s_p7_1,
  125312. NULL,
  125313. 0
  125314. };
  125315. static long _vq_quantlist__16c2_s_p8_0[] = {
  125316. 7,
  125317. 6,
  125318. 8,
  125319. 5,
  125320. 9,
  125321. 4,
  125322. 10,
  125323. 3,
  125324. 11,
  125325. 2,
  125326. 12,
  125327. 1,
  125328. 13,
  125329. 0,
  125330. 14,
  125331. };
  125332. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125333. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125334. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125335. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125336. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125337. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125338. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125339. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125340. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125341. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125342. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125343. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125344. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125345. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125346. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125347. 13,
  125348. };
  125349. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125350. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125351. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125352. };
  125353. static long _vq_quantmap__16c2_s_p8_0[] = {
  125354. 13, 11, 9, 7, 5, 3, 1, 0,
  125355. 2, 4, 6, 8, 10, 12, 14,
  125356. };
  125357. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125358. _vq_quantthresh__16c2_s_p8_0,
  125359. _vq_quantmap__16c2_s_p8_0,
  125360. 15,
  125361. 15
  125362. };
  125363. static static_codebook _16c2_s_p8_0 = {
  125364. 2, 225,
  125365. _vq_lengthlist__16c2_s_p8_0,
  125366. 1, -520986624, 1620377600, 4, 0,
  125367. _vq_quantlist__16c2_s_p8_0,
  125368. NULL,
  125369. &_vq_auxt__16c2_s_p8_0,
  125370. NULL,
  125371. 0
  125372. };
  125373. static long _vq_quantlist__16c2_s_p8_1[] = {
  125374. 10,
  125375. 9,
  125376. 11,
  125377. 8,
  125378. 12,
  125379. 7,
  125380. 13,
  125381. 6,
  125382. 14,
  125383. 5,
  125384. 15,
  125385. 4,
  125386. 16,
  125387. 3,
  125388. 17,
  125389. 2,
  125390. 18,
  125391. 1,
  125392. 19,
  125393. 0,
  125394. 20,
  125395. };
  125396. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125397. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125398. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125399. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125400. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125401. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125402. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125403. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125404. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125405. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125406. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125407. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125408. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125409. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125410. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125411. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125412. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125413. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125414. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125415. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125416. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125417. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125418. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125419. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125420. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125421. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125422. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125423. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125424. 10,11,10,10,10,10,10,10,10,
  125425. };
  125426. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125427. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125428. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125429. 6.5, 7.5, 8.5, 9.5,
  125430. };
  125431. static long _vq_quantmap__16c2_s_p8_1[] = {
  125432. 19, 17, 15, 13, 11, 9, 7, 5,
  125433. 3, 1, 0, 2, 4, 6, 8, 10,
  125434. 12, 14, 16, 18, 20,
  125435. };
  125436. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125437. _vq_quantthresh__16c2_s_p8_1,
  125438. _vq_quantmap__16c2_s_p8_1,
  125439. 21,
  125440. 21
  125441. };
  125442. static static_codebook _16c2_s_p8_1 = {
  125443. 2, 441,
  125444. _vq_lengthlist__16c2_s_p8_1,
  125445. 1, -529268736, 1611661312, 5, 0,
  125446. _vq_quantlist__16c2_s_p8_1,
  125447. NULL,
  125448. &_vq_auxt__16c2_s_p8_1,
  125449. NULL,
  125450. 0
  125451. };
  125452. static long _vq_quantlist__16c2_s_p9_0[] = {
  125453. 6,
  125454. 5,
  125455. 7,
  125456. 4,
  125457. 8,
  125458. 3,
  125459. 9,
  125460. 2,
  125461. 10,
  125462. 1,
  125463. 11,
  125464. 0,
  125465. 12,
  125466. };
  125467. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125468. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125469. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125470. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125471. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125472. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125473. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125474. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125475. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125476. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125477. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125478. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125479. };
  125480. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125481. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125482. 2327.5, 3258.5, 4189.5, 5120.5,
  125483. };
  125484. static long _vq_quantmap__16c2_s_p9_0[] = {
  125485. 11, 9, 7, 5, 3, 1, 0, 2,
  125486. 4, 6, 8, 10, 12,
  125487. };
  125488. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125489. _vq_quantthresh__16c2_s_p9_0,
  125490. _vq_quantmap__16c2_s_p9_0,
  125491. 13,
  125492. 13
  125493. };
  125494. static static_codebook _16c2_s_p9_0 = {
  125495. 2, 169,
  125496. _vq_lengthlist__16c2_s_p9_0,
  125497. 1, -510275072, 1631393792, 4, 0,
  125498. _vq_quantlist__16c2_s_p9_0,
  125499. NULL,
  125500. &_vq_auxt__16c2_s_p9_0,
  125501. NULL,
  125502. 0
  125503. };
  125504. static long _vq_quantlist__16c2_s_p9_1[] = {
  125505. 8,
  125506. 7,
  125507. 9,
  125508. 6,
  125509. 10,
  125510. 5,
  125511. 11,
  125512. 4,
  125513. 12,
  125514. 3,
  125515. 13,
  125516. 2,
  125517. 14,
  125518. 1,
  125519. 15,
  125520. 0,
  125521. 16,
  125522. };
  125523. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125524. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125525. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125526. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125527. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125528. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125529. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125530. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125531. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125532. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125535. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125537. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125539. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125540. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125542. 10,
  125543. };
  125544. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125545. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125546. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125547. };
  125548. static long _vq_quantmap__16c2_s_p9_1[] = {
  125549. 15, 13, 11, 9, 7, 5, 3, 1,
  125550. 0, 2, 4, 6, 8, 10, 12, 14,
  125551. 16,
  125552. };
  125553. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125554. _vq_quantthresh__16c2_s_p9_1,
  125555. _vq_quantmap__16c2_s_p9_1,
  125556. 17,
  125557. 17
  125558. };
  125559. static static_codebook _16c2_s_p9_1 = {
  125560. 2, 289,
  125561. _vq_lengthlist__16c2_s_p9_1,
  125562. 1, -518488064, 1622704128, 5, 0,
  125563. _vq_quantlist__16c2_s_p9_1,
  125564. NULL,
  125565. &_vq_auxt__16c2_s_p9_1,
  125566. NULL,
  125567. 0
  125568. };
  125569. static long _vq_quantlist__16c2_s_p9_2[] = {
  125570. 13,
  125571. 12,
  125572. 14,
  125573. 11,
  125574. 15,
  125575. 10,
  125576. 16,
  125577. 9,
  125578. 17,
  125579. 8,
  125580. 18,
  125581. 7,
  125582. 19,
  125583. 6,
  125584. 20,
  125585. 5,
  125586. 21,
  125587. 4,
  125588. 22,
  125589. 3,
  125590. 23,
  125591. 2,
  125592. 24,
  125593. 1,
  125594. 25,
  125595. 0,
  125596. 26,
  125597. };
  125598. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125599. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125600. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125601. };
  125602. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125603. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125604. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125605. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125606. 11.5, 12.5,
  125607. };
  125608. static long _vq_quantmap__16c2_s_p9_2[] = {
  125609. 25, 23, 21, 19, 17, 15, 13, 11,
  125610. 9, 7, 5, 3, 1, 0, 2, 4,
  125611. 6, 8, 10, 12, 14, 16, 18, 20,
  125612. 22, 24, 26,
  125613. };
  125614. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125615. _vq_quantthresh__16c2_s_p9_2,
  125616. _vq_quantmap__16c2_s_p9_2,
  125617. 27,
  125618. 27
  125619. };
  125620. static static_codebook _16c2_s_p9_2 = {
  125621. 1, 27,
  125622. _vq_lengthlist__16c2_s_p9_2,
  125623. 1, -528875520, 1611661312, 5, 0,
  125624. _vq_quantlist__16c2_s_p9_2,
  125625. NULL,
  125626. &_vq_auxt__16c2_s_p9_2,
  125627. NULL,
  125628. 0
  125629. };
  125630. static long _huff_lengthlist__16c2_s_short[] = {
  125631. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125632. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125633. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125634. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125635. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125636. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125637. 15,12,14,14,
  125638. };
  125639. static static_codebook _huff_book__16c2_s_short = {
  125640. 2, 100,
  125641. _huff_lengthlist__16c2_s_short,
  125642. 0, 0, 0, 0, 0,
  125643. NULL,
  125644. NULL,
  125645. NULL,
  125646. NULL,
  125647. 0
  125648. };
  125649. static long _vq_quantlist__8c0_s_p1_0[] = {
  125650. 1,
  125651. 0,
  125652. 2,
  125653. };
  125654. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125655. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125656. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125661. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125666. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  125701. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125706. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125711. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125747. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125752. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125757. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 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,
  126066. };
  126067. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126068. -0.5, 0.5,
  126069. };
  126070. static long _vq_quantmap__8c0_s_p1_0[] = {
  126071. 1, 0, 2,
  126072. };
  126073. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126074. _vq_quantthresh__8c0_s_p1_0,
  126075. _vq_quantmap__8c0_s_p1_0,
  126076. 3,
  126077. 3
  126078. };
  126079. static static_codebook _8c0_s_p1_0 = {
  126080. 8, 6561,
  126081. _vq_lengthlist__8c0_s_p1_0,
  126082. 1, -535822336, 1611661312, 2, 0,
  126083. _vq_quantlist__8c0_s_p1_0,
  126084. NULL,
  126085. &_vq_auxt__8c0_s_p1_0,
  126086. NULL,
  126087. 0
  126088. };
  126089. static long _vq_quantlist__8c0_s_p2_0[] = {
  126090. 2,
  126091. 1,
  126092. 3,
  126093. 0,
  126094. 4,
  126095. };
  126096. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0,
  126137. };
  126138. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126139. -1.5, -0.5, 0.5, 1.5,
  126140. };
  126141. static long _vq_quantmap__8c0_s_p2_0[] = {
  126142. 3, 1, 0, 2, 4,
  126143. };
  126144. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126145. _vq_quantthresh__8c0_s_p2_0,
  126146. _vq_quantmap__8c0_s_p2_0,
  126147. 5,
  126148. 5
  126149. };
  126150. static static_codebook _8c0_s_p2_0 = {
  126151. 4, 625,
  126152. _vq_lengthlist__8c0_s_p2_0,
  126153. 1, -533725184, 1611661312, 3, 0,
  126154. _vq_quantlist__8c0_s_p2_0,
  126155. NULL,
  126156. &_vq_auxt__8c0_s_p2_0,
  126157. NULL,
  126158. 0
  126159. };
  126160. static long _vq_quantlist__8c0_s_p3_0[] = {
  126161. 2,
  126162. 1,
  126163. 3,
  126164. 0,
  126165. 4,
  126166. };
  126167. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126168. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0,
  126208. };
  126209. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126210. -1.5, -0.5, 0.5, 1.5,
  126211. };
  126212. static long _vq_quantmap__8c0_s_p3_0[] = {
  126213. 3, 1, 0, 2, 4,
  126214. };
  126215. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126216. _vq_quantthresh__8c0_s_p3_0,
  126217. _vq_quantmap__8c0_s_p3_0,
  126218. 5,
  126219. 5
  126220. };
  126221. static static_codebook _8c0_s_p3_0 = {
  126222. 4, 625,
  126223. _vq_lengthlist__8c0_s_p3_0,
  126224. 1, -533725184, 1611661312, 3, 0,
  126225. _vq_quantlist__8c0_s_p3_0,
  126226. NULL,
  126227. &_vq_auxt__8c0_s_p3_0,
  126228. NULL,
  126229. 0
  126230. };
  126231. static long _vq_quantlist__8c0_s_p4_0[] = {
  126232. 4,
  126233. 3,
  126234. 5,
  126235. 2,
  126236. 6,
  126237. 1,
  126238. 7,
  126239. 0,
  126240. 8,
  126241. };
  126242. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126243. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126244. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126245. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126246. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126247. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0,
  126249. };
  126250. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126251. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126252. };
  126253. static long _vq_quantmap__8c0_s_p4_0[] = {
  126254. 7, 5, 3, 1, 0, 2, 4, 6,
  126255. 8,
  126256. };
  126257. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126258. _vq_quantthresh__8c0_s_p4_0,
  126259. _vq_quantmap__8c0_s_p4_0,
  126260. 9,
  126261. 9
  126262. };
  126263. static static_codebook _8c0_s_p4_0 = {
  126264. 2, 81,
  126265. _vq_lengthlist__8c0_s_p4_0,
  126266. 1, -531628032, 1611661312, 4, 0,
  126267. _vq_quantlist__8c0_s_p4_0,
  126268. NULL,
  126269. &_vq_auxt__8c0_s_p4_0,
  126270. NULL,
  126271. 0
  126272. };
  126273. static long _vq_quantlist__8c0_s_p5_0[] = {
  126274. 4,
  126275. 3,
  126276. 5,
  126277. 2,
  126278. 6,
  126279. 1,
  126280. 7,
  126281. 0,
  126282. 8,
  126283. };
  126284. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126285. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126286. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126287. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126288. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126289. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126290. 10,
  126291. };
  126292. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126293. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126294. };
  126295. static long _vq_quantmap__8c0_s_p5_0[] = {
  126296. 7, 5, 3, 1, 0, 2, 4, 6,
  126297. 8,
  126298. };
  126299. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126300. _vq_quantthresh__8c0_s_p5_0,
  126301. _vq_quantmap__8c0_s_p5_0,
  126302. 9,
  126303. 9
  126304. };
  126305. static static_codebook _8c0_s_p5_0 = {
  126306. 2, 81,
  126307. _vq_lengthlist__8c0_s_p5_0,
  126308. 1, -531628032, 1611661312, 4, 0,
  126309. _vq_quantlist__8c0_s_p5_0,
  126310. NULL,
  126311. &_vq_auxt__8c0_s_p5_0,
  126312. NULL,
  126313. 0
  126314. };
  126315. static long _vq_quantlist__8c0_s_p6_0[] = {
  126316. 8,
  126317. 7,
  126318. 9,
  126319. 6,
  126320. 10,
  126321. 5,
  126322. 11,
  126323. 4,
  126324. 12,
  126325. 3,
  126326. 13,
  126327. 2,
  126328. 14,
  126329. 1,
  126330. 15,
  126331. 0,
  126332. 16,
  126333. };
  126334. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126335. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126336. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126337. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126338. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126339. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126340. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126341. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126342. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126343. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126344. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126345. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126346. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126347. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126348. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126349. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126350. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126351. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126353. 14,
  126354. };
  126355. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126356. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126357. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126358. };
  126359. static long _vq_quantmap__8c0_s_p6_0[] = {
  126360. 15, 13, 11, 9, 7, 5, 3, 1,
  126361. 0, 2, 4, 6, 8, 10, 12, 14,
  126362. 16,
  126363. };
  126364. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126365. _vq_quantthresh__8c0_s_p6_0,
  126366. _vq_quantmap__8c0_s_p6_0,
  126367. 17,
  126368. 17
  126369. };
  126370. static static_codebook _8c0_s_p6_0 = {
  126371. 2, 289,
  126372. _vq_lengthlist__8c0_s_p6_0,
  126373. 1, -529530880, 1611661312, 5, 0,
  126374. _vq_quantlist__8c0_s_p6_0,
  126375. NULL,
  126376. &_vq_auxt__8c0_s_p6_0,
  126377. NULL,
  126378. 0
  126379. };
  126380. static long _vq_quantlist__8c0_s_p7_0[] = {
  126381. 1,
  126382. 0,
  126383. 2,
  126384. };
  126385. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126386. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126387. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126388. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126389. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126390. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126391. 10,
  126392. };
  126393. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126394. -5.5, 5.5,
  126395. };
  126396. static long _vq_quantmap__8c0_s_p7_0[] = {
  126397. 1, 0, 2,
  126398. };
  126399. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126400. _vq_quantthresh__8c0_s_p7_0,
  126401. _vq_quantmap__8c0_s_p7_0,
  126402. 3,
  126403. 3
  126404. };
  126405. static static_codebook _8c0_s_p7_0 = {
  126406. 4, 81,
  126407. _vq_lengthlist__8c0_s_p7_0,
  126408. 1, -529137664, 1618345984, 2, 0,
  126409. _vq_quantlist__8c0_s_p7_0,
  126410. NULL,
  126411. &_vq_auxt__8c0_s_p7_0,
  126412. NULL,
  126413. 0
  126414. };
  126415. static long _vq_quantlist__8c0_s_p7_1[] = {
  126416. 5,
  126417. 4,
  126418. 6,
  126419. 3,
  126420. 7,
  126421. 2,
  126422. 8,
  126423. 1,
  126424. 9,
  126425. 0,
  126426. 10,
  126427. };
  126428. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126429. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126430. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126431. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126432. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126433. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126434. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126435. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126436. 10,10,10, 9, 9, 9,10,10,10,
  126437. };
  126438. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126439. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126440. 3.5, 4.5,
  126441. };
  126442. static long _vq_quantmap__8c0_s_p7_1[] = {
  126443. 9, 7, 5, 3, 1, 0, 2, 4,
  126444. 6, 8, 10,
  126445. };
  126446. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126447. _vq_quantthresh__8c0_s_p7_1,
  126448. _vq_quantmap__8c0_s_p7_1,
  126449. 11,
  126450. 11
  126451. };
  126452. static static_codebook _8c0_s_p7_1 = {
  126453. 2, 121,
  126454. _vq_lengthlist__8c0_s_p7_1,
  126455. 1, -531365888, 1611661312, 4, 0,
  126456. _vq_quantlist__8c0_s_p7_1,
  126457. NULL,
  126458. &_vq_auxt__8c0_s_p7_1,
  126459. NULL,
  126460. 0
  126461. };
  126462. static long _vq_quantlist__8c0_s_p8_0[] = {
  126463. 6,
  126464. 5,
  126465. 7,
  126466. 4,
  126467. 8,
  126468. 3,
  126469. 9,
  126470. 2,
  126471. 10,
  126472. 1,
  126473. 11,
  126474. 0,
  126475. 12,
  126476. };
  126477. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126478. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126479. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126480. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126481. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126482. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126483. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126484. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126485. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126486. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126487. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126488. 0, 0,13,13,11,13,13,11,12,
  126489. };
  126490. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126491. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126492. 12.5, 17.5, 22.5, 27.5,
  126493. };
  126494. static long _vq_quantmap__8c0_s_p8_0[] = {
  126495. 11, 9, 7, 5, 3, 1, 0, 2,
  126496. 4, 6, 8, 10, 12,
  126497. };
  126498. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126499. _vq_quantthresh__8c0_s_p8_0,
  126500. _vq_quantmap__8c0_s_p8_0,
  126501. 13,
  126502. 13
  126503. };
  126504. static static_codebook _8c0_s_p8_0 = {
  126505. 2, 169,
  126506. _vq_lengthlist__8c0_s_p8_0,
  126507. 1, -526516224, 1616117760, 4, 0,
  126508. _vq_quantlist__8c0_s_p8_0,
  126509. NULL,
  126510. &_vq_auxt__8c0_s_p8_0,
  126511. NULL,
  126512. 0
  126513. };
  126514. static long _vq_quantlist__8c0_s_p8_1[] = {
  126515. 2,
  126516. 1,
  126517. 3,
  126518. 0,
  126519. 4,
  126520. };
  126521. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126522. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126523. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126524. };
  126525. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126526. -1.5, -0.5, 0.5, 1.5,
  126527. };
  126528. static long _vq_quantmap__8c0_s_p8_1[] = {
  126529. 3, 1, 0, 2, 4,
  126530. };
  126531. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126532. _vq_quantthresh__8c0_s_p8_1,
  126533. _vq_quantmap__8c0_s_p8_1,
  126534. 5,
  126535. 5
  126536. };
  126537. static static_codebook _8c0_s_p8_1 = {
  126538. 2, 25,
  126539. _vq_lengthlist__8c0_s_p8_1,
  126540. 1, -533725184, 1611661312, 3, 0,
  126541. _vq_quantlist__8c0_s_p8_1,
  126542. NULL,
  126543. &_vq_auxt__8c0_s_p8_1,
  126544. NULL,
  126545. 0
  126546. };
  126547. static long _vq_quantlist__8c0_s_p9_0[] = {
  126548. 1,
  126549. 0,
  126550. 2,
  126551. };
  126552. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126553. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126554. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126555. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126556. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126557. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126558. 7,
  126559. };
  126560. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126561. -157.5, 157.5,
  126562. };
  126563. static long _vq_quantmap__8c0_s_p9_0[] = {
  126564. 1, 0, 2,
  126565. };
  126566. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126567. _vq_quantthresh__8c0_s_p9_0,
  126568. _vq_quantmap__8c0_s_p9_0,
  126569. 3,
  126570. 3
  126571. };
  126572. static static_codebook _8c0_s_p9_0 = {
  126573. 4, 81,
  126574. _vq_lengthlist__8c0_s_p9_0,
  126575. 1, -518803456, 1628680192, 2, 0,
  126576. _vq_quantlist__8c0_s_p9_0,
  126577. NULL,
  126578. &_vq_auxt__8c0_s_p9_0,
  126579. NULL,
  126580. 0
  126581. };
  126582. static long _vq_quantlist__8c0_s_p9_1[] = {
  126583. 7,
  126584. 6,
  126585. 8,
  126586. 5,
  126587. 9,
  126588. 4,
  126589. 10,
  126590. 3,
  126591. 11,
  126592. 2,
  126593. 12,
  126594. 1,
  126595. 13,
  126596. 0,
  126597. 14,
  126598. };
  126599. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126600. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126601. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126602. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126603. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126604. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126605. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126614. 11,
  126615. };
  126616. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126617. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126618. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126619. };
  126620. static long _vq_quantmap__8c0_s_p9_1[] = {
  126621. 13, 11, 9, 7, 5, 3, 1, 0,
  126622. 2, 4, 6, 8, 10, 12, 14,
  126623. };
  126624. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126625. _vq_quantthresh__8c0_s_p9_1,
  126626. _vq_quantmap__8c0_s_p9_1,
  126627. 15,
  126628. 15
  126629. };
  126630. static static_codebook _8c0_s_p9_1 = {
  126631. 2, 225,
  126632. _vq_lengthlist__8c0_s_p9_1,
  126633. 1, -520986624, 1620377600, 4, 0,
  126634. _vq_quantlist__8c0_s_p9_1,
  126635. NULL,
  126636. &_vq_auxt__8c0_s_p9_1,
  126637. NULL,
  126638. 0
  126639. };
  126640. static long _vq_quantlist__8c0_s_p9_2[] = {
  126641. 10,
  126642. 9,
  126643. 11,
  126644. 8,
  126645. 12,
  126646. 7,
  126647. 13,
  126648. 6,
  126649. 14,
  126650. 5,
  126651. 15,
  126652. 4,
  126653. 16,
  126654. 3,
  126655. 17,
  126656. 2,
  126657. 18,
  126658. 1,
  126659. 19,
  126660. 0,
  126661. 20,
  126662. };
  126663. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126664. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126665. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126666. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126667. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126668. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126669. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126670. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126671. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126672. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126673. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126674. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126675. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126676. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126677. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126678. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126679. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126680. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126681. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126682. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126683. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126684. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126685. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126686. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126687. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126688. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126689. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126690. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126691. 10,11, 9,11,10, 9,10, 9,10,
  126692. };
  126693. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126694. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126695. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126696. 6.5, 7.5, 8.5, 9.5,
  126697. };
  126698. static long _vq_quantmap__8c0_s_p9_2[] = {
  126699. 19, 17, 15, 13, 11, 9, 7, 5,
  126700. 3, 1, 0, 2, 4, 6, 8, 10,
  126701. 12, 14, 16, 18, 20,
  126702. };
  126703. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126704. _vq_quantthresh__8c0_s_p9_2,
  126705. _vq_quantmap__8c0_s_p9_2,
  126706. 21,
  126707. 21
  126708. };
  126709. static static_codebook _8c0_s_p9_2 = {
  126710. 2, 441,
  126711. _vq_lengthlist__8c0_s_p9_2,
  126712. 1, -529268736, 1611661312, 5, 0,
  126713. _vq_quantlist__8c0_s_p9_2,
  126714. NULL,
  126715. &_vq_auxt__8c0_s_p9_2,
  126716. NULL,
  126717. 0
  126718. };
  126719. static long _huff_lengthlist__8c0_s_single[] = {
  126720. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126721. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126722. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126723. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126724. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126725. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126726. 17,16,17,17,
  126727. };
  126728. static static_codebook _huff_book__8c0_s_single = {
  126729. 2, 100,
  126730. _huff_lengthlist__8c0_s_single,
  126731. 0, 0, 0, 0, 0,
  126732. NULL,
  126733. NULL,
  126734. NULL,
  126735. NULL,
  126736. 0
  126737. };
  126738. static long _vq_quantlist__8c1_s_p1_0[] = {
  126739. 1,
  126740. 0,
  126741. 2,
  126742. };
  126743. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126744. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126745. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126750. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126755. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  126790. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126795. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126800. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126836. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126841. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126846. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 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,
  127155. };
  127156. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127157. -0.5, 0.5,
  127158. };
  127159. static long _vq_quantmap__8c1_s_p1_0[] = {
  127160. 1, 0, 2,
  127161. };
  127162. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127163. _vq_quantthresh__8c1_s_p1_0,
  127164. _vq_quantmap__8c1_s_p1_0,
  127165. 3,
  127166. 3
  127167. };
  127168. static static_codebook _8c1_s_p1_0 = {
  127169. 8, 6561,
  127170. _vq_lengthlist__8c1_s_p1_0,
  127171. 1, -535822336, 1611661312, 2, 0,
  127172. _vq_quantlist__8c1_s_p1_0,
  127173. NULL,
  127174. &_vq_auxt__8c1_s_p1_0,
  127175. NULL,
  127176. 0
  127177. };
  127178. static long _vq_quantlist__8c1_s_p2_0[] = {
  127179. 2,
  127180. 1,
  127181. 3,
  127182. 0,
  127183. 4,
  127184. };
  127185. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0,
  127226. };
  127227. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127228. -1.5, -0.5, 0.5, 1.5,
  127229. };
  127230. static long _vq_quantmap__8c1_s_p2_0[] = {
  127231. 3, 1, 0, 2, 4,
  127232. };
  127233. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127234. _vq_quantthresh__8c1_s_p2_0,
  127235. _vq_quantmap__8c1_s_p2_0,
  127236. 5,
  127237. 5
  127238. };
  127239. static static_codebook _8c1_s_p2_0 = {
  127240. 4, 625,
  127241. _vq_lengthlist__8c1_s_p2_0,
  127242. 1, -533725184, 1611661312, 3, 0,
  127243. _vq_quantlist__8c1_s_p2_0,
  127244. NULL,
  127245. &_vq_auxt__8c1_s_p2_0,
  127246. NULL,
  127247. 0
  127248. };
  127249. static long _vq_quantlist__8c1_s_p3_0[] = {
  127250. 2,
  127251. 1,
  127252. 3,
  127253. 0,
  127254. 4,
  127255. };
  127256. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127257. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0,
  127297. };
  127298. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127299. -1.5, -0.5, 0.5, 1.5,
  127300. };
  127301. static long _vq_quantmap__8c1_s_p3_0[] = {
  127302. 3, 1, 0, 2, 4,
  127303. };
  127304. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127305. _vq_quantthresh__8c1_s_p3_0,
  127306. _vq_quantmap__8c1_s_p3_0,
  127307. 5,
  127308. 5
  127309. };
  127310. static static_codebook _8c1_s_p3_0 = {
  127311. 4, 625,
  127312. _vq_lengthlist__8c1_s_p3_0,
  127313. 1, -533725184, 1611661312, 3, 0,
  127314. _vq_quantlist__8c1_s_p3_0,
  127315. NULL,
  127316. &_vq_auxt__8c1_s_p3_0,
  127317. NULL,
  127318. 0
  127319. };
  127320. static long _vq_quantlist__8c1_s_p4_0[] = {
  127321. 4,
  127322. 3,
  127323. 5,
  127324. 2,
  127325. 6,
  127326. 1,
  127327. 7,
  127328. 0,
  127329. 8,
  127330. };
  127331. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127332. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127333. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127334. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127335. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127336. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0,
  127338. };
  127339. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127340. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127341. };
  127342. static long _vq_quantmap__8c1_s_p4_0[] = {
  127343. 7, 5, 3, 1, 0, 2, 4, 6,
  127344. 8,
  127345. };
  127346. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127347. _vq_quantthresh__8c1_s_p4_0,
  127348. _vq_quantmap__8c1_s_p4_0,
  127349. 9,
  127350. 9
  127351. };
  127352. static static_codebook _8c1_s_p4_0 = {
  127353. 2, 81,
  127354. _vq_lengthlist__8c1_s_p4_0,
  127355. 1, -531628032, 1611661312, 4, 0,
  127356. _vq_quantlist__8c1_s_p4_0,
  127357. NULL,
  127358. &_vq_auxt__8c1_s_p4_0,
  127359. NULL,
  127360. 0
  127361. };
  127362. static long _vq_quantlist__8c1_s_p5_0[] = {
  127363. 4,
  127364. 3,
  127365. 5,
  127366. 2,
  127367. 6,
  127368. 1,
  127369. 7,
  127370. 0,
  127371. 8,
  127372. };
  127373. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127374. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127375. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127376. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127377. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127378. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127379. 10,
  127380. };
  127381. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127382. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127383. };
  127384. static long _vq_quantmap__8c1_s_p5_0[] = {
  127385. 7, 5, 3, 1, 0, 2, 4, 6,
  127386. 8,
  127387. };
  127388. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127389. _vq_quantthresh__8c1_s_p5_0,
  127390. _vq_quantmap__8c1_s_p5_0,
  127391. 9,
  127392. 9
  127393. };
  127394. static static_codebook _8c1_s_p5_0 = {
  127395. 2, 81,
  127396. _vq_lengthlist__8c1_s_p5_0,
  127397. 1, -531628032, 1611661312, 4, 0,
  127398. _vq_quantlist__8c1_s_p5_0,
  127399. NULL,
  127400. &_vq_auxt__8c1_s_p5_0,
  127401. NULL,
  127402. 0
  127403. };
  127404. static long _vq_quantlist__8c1_s_p6_0[] = {
  127405. 8,
  127406. 7,
  127407. 9,
  127408. 6,
  127409. 10,
  127410. 5,
  127411. 11,
  127412. 4,
  127413. 12,
  127414. 3,
  127415. 13,
  127416. 2,
  127417. 14,
  127418. 1,
  127419. 15,
  127420. 0,
  127421. 16,
  127422. };
  127423. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127424. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127425. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127426. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127427. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127428. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127429. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127430. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127431. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127432. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127433. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127434. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127435. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127436. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127437. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127438. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127439. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127440. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127442. 14,
  127443. };
  127444. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127445. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127446. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127447. };
  127448. static long _vq_quantmap__8c1_s_p6_0[] = {
  127449. 15, 13, 11, 9, 7, 5, 3, 1,
  127450. 0, 2, 4, 6, 8, 10, 12, 14,
  127451. 16,
  127452. };
  127453. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127454. _vq_quantthresh__8c1_s_p6_0,
  127455. _vq_quantmap__8c1_s_p6_0,
  127456. 17,
  127457. 17
  127458. };
  127459. static static_codebook _8c1_s_p6_0 = {
  127460. 2, 289,
  127461. _vq_lengthlist__8c1_s_p6_0,
  127462. 1, -529530880, 1611661312, 5, 0,
  127463. _vq_quantlist__8c1_s_p6_0,
  127464. NULL,
  127465. &_vq_auxt__8c1_s_p6_0,
  127466. NULL,
  127467. 0
  127468. };
  127469. static long _vq_quantlist__8c1_s_p7_0[] = {
  127470. 1,
  127471. 0,
  127472. 2,
  127473. };
  127474. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127475. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127476. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127477. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127478. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127479. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127480. 9,
  127481. };
  127482. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127483. -5.5, 5.5,
  127484. };
  127485. static long _vq_quantmap__8c1_s_p7_0[] = {
  127486. 1, 0, 2,
  127487. };
  127488. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127489. _vq_quantthresh__8c1_s_p7_0,
  127490. _vq_quantmap__8c1_s_p7_0,
  127491. 3,
  127492. 3
  127493. };
  127494. static static_codebook _8c1_s_p7_0 = {
  127495. 4, 81,
  127496. _vq_lengthlist__8c1_s_p7_0,
  127497. 1, -529137664, 1618345984, 2, 0,
  127498. _vq_quantlist__8c1_s_p7_0,
  127499. NULL,
  127500. &_vq_auxt__8c1_s_p7_0,
  127501. NULL,
  127502. 0
  127503. };
  127504. static long _vq_quantlist__8c1_s_p7_1[] = {
  127505. 5,
  127506. 4,
  127507. 6,
  127508. 3,
  127509. 7,
  127510. 2,
  127511. 8,
  127512. 1,
  127513. 9,
  127514. 0,
  127515. 10,
  127516. };
  127517. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127518. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127519. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127520. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127521. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127522. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127523. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127524. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127525. 10,10,10, 8, 8, 8, 8, 8, 8,
  127526. };
  127527. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127528. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127529. 3.5, 4.5,
  127530. };
  127531. static long _vq_quantmap__8c1_s_p7_1[] = {
  127532. 9, 7, 5, 3, 1, 0, 2, 4,
  127533. 6, 8, 10,
  127534. };
  127535. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127536. _vq_quantthresh__8c1_s_p7_1,
  127537. _vq_quantmap__8c1_s_p7_1,
  127538. 11,
  127539. 11
  127540. };
  127541. static static_codebook _8c1_s_p7_1 = {
  127542. 2, 121,
  127543. _vq_lengthlist__8c1_s_p7_1,
  127544. 1, -531365888, 1611661312, 4, 0,
  127545. _vq_quantlist__8c1_s_p7_1,
  127546. NULL,
  127547. &_vq_auxt__8c1_s_p7_1,
  127548. NULL,
  127549. 0
  127550. };
  127551. static long _vq_quantlist__8c1_s_p8_0[] = {
  127552. 6,
  127553. 5,
  127554. 7,
  127555. 4,
  127556. 8,
  127557. 3,
  127558. 9,
  127559. 2,
  127560. 10,
  127561. 1,
  127562. 11,
  127563. 0,
  127564. 12,
  127565. };
  127566. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127567. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127568. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127569. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127570. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127571. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127572. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127573. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127574. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127575. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127576. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127577. 0,12,12,11,10,12,11,13,12,
  127578. };
  127579. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127580. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127581. 12.5, 17.5, 22.5, 27.5,
  127582. };
  127583. static long _vq_quantmap__8c1_s_p8_0[] = {
  127584. 11, 9, 7, 5, 3, 1, 0, 2,
  127585. 4, 6, 8, 10, 12,
  127586. };
  127587. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127588. _vq_quantthresh__8c1_s_p8_0,
  127589. _vq_quantmap__8c1_s_p8_0,
  127590. 13,
  127591. 13
  127592. };
  127593. static static_codebook _8c1_s_p8_0 = {
  127594. 2, 169,
  127595. _vq_lengthlist__8c1_s_p8_0,
  127596. 1, -526516224, 1616117760, 4, 0,
  127597. _vq_quantlist__8c1_s_p8_0,
  127598. NULL,
  127599. &_vq_auxt__8c1_s_p8_0,
  127600. NULL,
  127601. 0
  127602. };
  127603. static long _vq_quantlist__8c1_s_p8_1[] = {
  127604. 2,
  127605. 1,
  127606. 3,
  127607. 0,
  127608. 4,
  127609. };
  127610. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127611. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127612. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127613. };
  127614. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127615. -1.5, -0.5, 0.5, 1.5,
  127616. };
  127617. static long _vq_quantmap__8c1_s_p8_1[] = {
  127618. 3, 1, 0, 2, 4,
  127619. };
  127620. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127621. _vq_quantthresh__8c1_s_p8_1,
  127622. _vq_quantmap__8c1_s_p8_1,
  127623. 5,
  127624. 5
  127625. };
  127626. static static_codebook _8c1_s_p8_1 = {
  127627. 2, 25,
  127628. _vq_lengthlist__8c1_s_p8_1,
  127629. 1, -533725184, 1611661312, 3, 0,
  127630. _vq_quantlist__8c1_s_p8_1,
  127631. NULL,
  127632. &_vq_auxt__8c1_s_p8_1,
  127633. NULL,
  127634. 0
  127635. };
  127636. static long _vq_quantlist__8c1_s_p9_0[] = {
  127637. 6,
  127638. 5,
  127639. 7,
  127640. 4,
  127641. 8,
  127642. 3,
  127643. 9,
  127644. 2,
  127645. 10,
  127646. 1,
  127647. 11,
  127648. 0,
  127649. 12,
  127650. };
  127651. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127652. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127653. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127654. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127655. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127656. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127657. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127658. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127662. 10,10,10,10,10, 9, 9, 9, 9,
  127663. };
  127664. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127665. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127666. 787.5, 1102.5, 1417.5, 1732.5,
  127667. };
  127668. static long _vq_quantmap__8c1_s_p9_0[] = {
  127669. 11, 9, 7, 5, 3, 1, 0, 2,
  127670. 4, 6, 8, 10, 12,
  127671. };
  127672. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127673. _vq_quantthresh__8c1_s_p9_0,
  127674. _vq_quantmap__8c1_s_p9_0,
  127675. 13,
  127676. 13
  127677. };
  127678. static static_codebook _8c1_s_p9_0 = {
  127679. 2, 169,
  127680. _vq_lengthlist__8c1_s_p9_0,
  127681. 1, -513964032, 1628680192, 4, 0,
  127682. _vq_quantlist__8c1_s_p9_0,
  127683. NULL,
  127684. &_vq_auxt__8c1_s_p9_0,
  127685. NULL,
  127686. 0
  127687. };
  127688. static long _vq_quantlist__8c1_s_p9_1[] = {
  127689. 7,
  127690. 6,
  127691. 8,
  127692. 5,
  127693. 9,
  127694. 4,
  127695. 10,
  127696. 3,
  127697. 11,
  127698. 2,
  127699. 12,
  127700. 1,
  127701. 13,
  127702. 0,
  127703. 14,
  127704. };
  127705. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127706. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127707. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127708. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127709. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127710. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127711. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127712. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127713. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127714. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127715. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127716. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127717. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127718. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127719. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127720. 15,
  127721. };
  127722. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127723. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127724. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127725. };
  127726. static long _vq_quantmap__8c1_s_p9_1[] = {
  127727. 13, 11, 9, 7, 5, 3, 1, 0,
  127728. 2, 4, 6, 8, 10, 12, 14,
  127729. };
  127730. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127731. _vq_quantthresh__8c1_s_p9_1,
  127732. _vq_quantmap__8c1_s_p9_1,
  127733. 15,
  127734. 15
  127735. };
  127736. static static_codebook _8c1_s_p9_1 = {
  127737. 2, 225,
  127738. _vq_lengthlist__8c1_s_p9_1,
  127739. 1, -520986624, 1620377600, 4, 0,
  127740. _vq_quantlist__8c1_s_p9_1,
  127741. NULL,
  127742. &_vq_auxt__8c1_s_p9_1,
  127743. NULL,
  127744. 0
  127745. };
  127746. static long _vq_quantlist__8c1_s_p9_2[] = {
  127747. 10,
  127748. 9,
  127749. 11,
  127750. 8,
  127751. 12,
  127752. 7,
  127753. 13,
  127754. 6,
  127755. 14,
  127756. 5,
  127757. 15,
  127758. 4,
  127759. 16,
  127760. 3,
  127761. 17,
  127762. 2,
  127763. 18,
  127764. 1,
  127765. 19,
  127766. 0,
  127767. 20,
  127768. };
  127769. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127770. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127771. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127772. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127773. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127774. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127775. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127776. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127777. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127778. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127779. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127780. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127781. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127782. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127783. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127784. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127785. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127786. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127787. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127788. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127789. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127790. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127791. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127792. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127793. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127794. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127795. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127796. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127797. 10,10,10,10,10,10,10,10,10,
  127798. };
  127799. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127800. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127801. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127802. 6.5, 7.5, 8.5, 9.5,
  127803. };
  127804. static long _vq_quantmap__8c1_s_p9_2[] = {
  127805. 19, 17, 15, 13, 11, 9, 7, 5,
  127806. 3, 1, 0, 2, 4, 6, 8, 10,
  127807. 12, 14, 16, 18, 20,
  127808. };
  127809. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127810. _vq_quantthresh__8c1_s_p9_2,
  127811. _vq_quantmap__8c1_s_p9_2,
  127812. 21,
  127813. 21
  127814. };
  127815. static static_codebook _8c1_s_p9_2 = {
  127816. 2, 441,
  127817. _vq_lengthlist__8c1_s_p9_2,
  127818. 1, -529268736, 1611661312, 5, 0,
  127819. _vq_quantlist__8c1_s_p9_2,
  127820. NULL,
  127821. &_vq_auxt__8c1_s_p9_2,
  127822. NULL,
  127823. 0
  127824. };
  127825. static long _huff_lengthlist__8c1_s_single[] = {
  127826. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127827. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127828. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127829. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127830. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127831. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127832. 9, 7, 7, 8,
  127833. };
  127834. static static_codebook _huff_book__8c1_s_single = {
  127835. 2, 100,
  127836. _huff_lengthlist__8c1_s_single,
  127837. 0, 0, 0, 0, 0,
  127838. NULL,
  127839. NULL,
  127840. NULL,
  127841. NULL,
  127842. 0
  127843. };
  127844. static long _huff_lengthlist__44c2_s_long[] = {
  127845. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127846. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127847. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127848. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127849. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127850. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127851. 10, 8, 8, 9,
  127852. };
  127853. static static_codebook _huff_book__44c2_s_long = {
  127854. 2, 100,
  127855. _huff_lengthlist__44c2_s_long,
  127856. 0, 0, 0, 0, 0,
  127857. NULL,
  127858. NULL,
  127859. NULL,
  127860. NULL,
  127861. 0
  127862. };
  127863. static long _vq_quantlist__44c2_s_p1_0[] = {
  127864. 1,
  127865. 0,
  127866. 2,
  127867. };
  127868. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127869. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127870. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127875. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127880. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  127915. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  127920. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  127925. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127961. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127966. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127971. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 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,
  128280. };
  128281. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128282. -0.5, 0.5,
  128283. };
  128284. static long _vq_quantmap__44c2_s_p1_0[] = {
  128285. 1, 0, 2,
  128286. };
  128287. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128288. _vq_quantthresh__44c2_s_p1_0,
  128289. _vq_quantmap__44c2_s_p1_0,
  128290. 3,
  128291. 3
  128292. };
  128293. static static_codebook _44c2_s_p1_0 = {
  128294. 8, 6561,
  128295. _vq_lengthlist__44c2_s_p1_0,
  128296. 1, -535822336, 1611661312, 2, 0,
  128297. _vq_quantlist__44c2_s_p1_0,
  128298. NULL,
  128299. &_vq_auxt__44c2_s_p1_0,
  128300. NULL,
  128301. 0
  128302. };
  128303. static long _vq_quantlist__44c2_s_p2_0[] = {
  128304. 2,
  128305. 1,
  128306. 3,
  128307. 0,
  128308. 4,
  128309. };
  128310. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128311. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128312. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128313. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128314. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128315. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128321. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128322. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128323. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128329. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128330. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128337. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128338. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0,
  128351. };
  128352. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128353. -1.5, -0.5, 0.5, 1.5,
  128354. };
  128355. static long _vq_quantmap__44c2_s_p2_0[] = {
  128356. 3, 1, 0, 2, 4,
  128357. };
  128358. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128359. _vq_quantthresh__44c2_s_p2_0,
  128360. _vq_quantmap__44c2_s_p2_0,
  128361. 5,
  128362. 5
  128363. };
  128364. static static_codebook _44c2_s_p2_0 = {
  128365. 4, 625,
  128366. _vq_lengthlist__44c2_s_p2_0,
  128367. 1, -533725184, 1611661312, 3, 0,
  128368. _vq_quantlist__44c2_s_p2_0,
  128369. NULL,
  128370. &_vq_auxt__44c2_s_p2_0,
  128371. NULL,
  128372. 0
  128373. };
  128374. static long _vq_quantlist__44c2_s_p3_0[] = {
  128375. 2,
  128376. 1,
  128377. 3,
  128378. 0,
  128379. 4,
  128380. };
  128381. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128382. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0,
  128422. };
  128423. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128424. -1.5, -0.5, 0.5, 1.5,
  128425. };
  128426. static long _vq_quantmap__44c2_s_p3_0[] = {
  128427. 3, 1, 0, 2, 4,
  128428. };
  128429. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128430. _vq_quantthresh__44c2_s_p3_0,
  128431. _vq_quantmap__44c2_s_p3_0,
  128432. 5,
  128433. 5
  128434. };
  128435. static static_codebook _44c2_s_p3_0 = {
  128436. 4, 625,
  128437. _vq_lengthlist__44c2_s_p3_0,
  128438. 1, -533725184, 1611661312, 3, 0,
  128439. _vq_quantlist__44c2_s_p3_0,
  128440. NULL,
  128441. &_vq_auxt__44c2_s_p3_0,
  128442. NULL,
  128443. 0
  128444. };
  128445. static long _vq_quantlist__44c2_s_p4_0[] = {
  128446. 4,
  128447. 3,
  128448. 5,
  128449. 2,
  128450. 6,
  128451. 1,
  128452. 7,
  128453. 0,
  128454. 8,
  128455. };
  128456. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128457. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128458. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128459. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128460. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128461. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0,
  128463. };
  128464. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128466. };
  128467. static long _vq_quantmap__44c2_s_p4_0[] = {
  128468. 7, 5, 3, 1, 0, 2, 4, 6,
  128469. 8,
  128470. };
  128471. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128472. _vq_quantthresh__44c2_s_p4_0,
  128473. _vq_quantmap__44c2_s_p4_0,
  128474. 9,
  128475. 9
  128476. };
  128477. static static_codebook _44c2_s_p4_0 = {
  128478. 2, 81,
  128479. _vq_lengthlist__44c2_s_p4_0,
  128480. 1, -531628032, 1611661312, 4, 0,
  128481. _vq_quantlist__44c2_s_p4_0,
  128482. NULL,
  128483. &_vq_auxt__44c2_s_p4_0,
  128484. NULL,
  128485. 0
  128486. };
  128487. static long _vq_quantlist__44c2_s_p5_0[] = {
  128488. 4,
  128489. 3,
  128490. 5,
  128491. 2,
  128492. 6,
  128493. 1,
  128494. 7,
  128495. 0,
  128496. 8,
  128497. };
  128498. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128499. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128500. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128501. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128502. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128503. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128504. 11,
  128505. };
  128506. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128508. };
  128509. static long _vq_quantmap__44c2_s_p5_0[] = {
  128510. 7, 5, 3, 1, 0, 2, 4, 6,
  128511. 8,
  128512. };
  128513. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128514. _vq_quantthresh__44c2_s_p5_0,
  128515. _vq_quantmap__44c2_s_p5_0,
  128516. 9,
  128517. 9
  128518. };
  128519. static static_codebook _44c2_s_p5_0 = {
  128520. 2, 81,
  128521. _vq_lengthlist__44c2_s_p5_0,
  128522. 1, -531628032, 1611661312, 4, 0,
  128523. _vq_quantlist__44c2_s_p5_0,
  128524. NULL,
  128525. &_vq_auxt__44c2_s_p5_0,
  128526. NULL,
  128527. 0
  128528. };
  128529. static long _vq_quantlist__44c2_s_p6_0[] = {
  128530. 8,
  128531. 7,
  128532. 9,
  128533. 6,
  128534. 10,
  128535. 5,
  128536. 11,
  128537. 4,
  128538. 12,
  128539. 3,
  128540. 13,
  128541. 2,
  128542. 14,
  128543. 1,
  128544. 15,
  128545. 0,
  128546. 16,
  128547. };
  128548. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128549. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128550. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128551. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128552. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128553. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128554. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128555. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128556. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128557. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128558. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128559. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128560. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128561. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128562. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128563. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128564. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128565. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128567. 14,
  128568. };
  128569. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128572. };
  128573. static long _vq_quantmap__44c2_s_p6_0[] = {
  128574. 15, 13, 11, 9, 7, 5, 3, 1,
  128575. 0, 2, 4, 6, 8, 10, 12, 14,
  128576. 16,
  128577. };
  128578. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128579. _vq_quantthresh__44c2_s_p6_0,
  128580. _vq_quantmap__44c2_s_p6_0,
  128581. 17,
  128582. 17
  128583. };
  128584. static static_codebook _44c2_s_p6_0 = {
  128585. 2, 289,
  128586. _vq_lengthlist__44c2_s_p6_0,
  128587. 1, -529530880, 1611661312, 5, 0,
  128588. _vq_quantlist__44c2_s_p6_0,
  128589. NULL,
  128590. &_vq_auxt__44c2_s_p6_0,
  128591. NULL,
  128592. 0
  128593. };
  128594. static long _vq_quantlist__44c2_s_p7_0[] = {
  128595. 1,
  128596. 0,
  128597. 2,
  128598. };
  128599. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128600. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128601. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128602. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128603. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128604. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128605. 11,
  128606. };
  128607. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128608. -5.5, 5.5,
  128609. };
  128610. static long _vq_quantmap__44c2_s_p7_0[] = {
  128611. 1, 0, 2,
  128612. };
  128613. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128614. _vq_quantthresh__44c2_s_p7_0,
  128615. _vq_quantmap__44c2_s_p7_0,
  128616. 3,
  128617. 3
  128618. };
  128619. static static_codebook _44c2_s_p7_0 = {
  128620. 4, 81,
  128621. _vq_lengthlist__44c2_s_p7_0,
  128622. 1, -529137664, 1618345984, 2, 0,
  128623. _vq_quantlist__44c2_s_p7_0,
  128624. NULL,
  128625. &_vq_auxt__44c2_s_p7_0,
  128626. NULL,
  128627. 0
  128628. };
  128629. static long _vq_quantlist__44c2_s_p7_1[] = {
  128630. 5,
  128631. 4,
  128632. 6,
  128633. 3,
  128634. 7,
  128635. 2,
  128636. 8,
  128637. 1,
  128638. 9,
  128639. 0,
  128640. 10,
  128641. };
  128642. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128643. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128644. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128645. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128646. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128647. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128648. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128649. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128650. 10,10,10, 8, 8, 8, 8, 8, 8,
  128651. };
  128652. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128654. 3.5, 4.5,
  128655. };
  128656. static long _vq_quantmap__44c2_s_p7_1[] = {
  128657. 9, 7, 5, 3, 1, 0, 2, 4,
  128658. 6, 8, 10,
  128659. };
  128660. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128661. _vq_quantthresh__44c2_s_p7_1,
  128662. _vq_quantmap__44c2_s_p7_1,
  128663. 11,
  128664. 11
  128665. };
  128666. static static_codebook _44c2_s_p7_1 = {
  128667. 2, 121,
  128668. _vq_lengthlist__44c2_s_p7_1,
  128669. 1, -531365888, 1611661312, 4, 0,
  128670. _vq_quantlist__44c2_s_p7_1,
  128671. NULL,
  128672. &_vq_auxt__44c2_s_p7_1,
  128673. NULL,
  128674. 0
  128675. };
  128676. static long _vq_quantlist__44c2_s_p8_0[] = {
  128677. 6,
  128678. 5,
  128679. 7,
  128680. 4,
  128681. 8,
  128682. 3,
  128683. 9,
  128684. 2,
  128685. 10,
  128686. 1,
  128687. 11,
  128688. 0,
  128689. 12,
  128690. };
  128691. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128692. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128693. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128694. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128695. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128696. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128697. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128698. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128699. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128700. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128701. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128702. 0,12,12,12,12,13,12,14,14,
  128703. };
  128704. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128706. 12.5, 17.5, 22.5, 27.5,
  128707. };
  128708. static long _vq_quantmap__44c2_s_p8_0[] = {
  128709. 11, 9, 7, 5, 3, 1, 0, 2,
  128710. 4, 6, 8, 10, 12,
  128711. };
  128712. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128713. _vq_quantthresh__44c2_s_p8_0,
  128714. _vq_quantmap__44c2_s_p8_0,
  128715. 13,
  128716. 13
  128717. };
  128718. static static_codebook _44c2_s_p8_0 = {
  128719. 2, 169,
  128720. _vq_lengthlist__44c2_s_p8_0,
  128721. 1, -526516224, 1616117760, 4, 0,
  128722. _vq_quantlist__44c2_s_p8_0,
  128723. NULL,
  128724. &_vq_auxt__44c2_s_p8_0,
  128725. NULL,
  128726. 0
  128727. };
  128728. static long _vq_quantlist__44c2_s_p8_1[] = {
  128729. 2,
  128730. 1,
  128731. 3,
  128732. 0,
  128733. 4,
  128734. };
  128735. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128736. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128737. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128738. };
  128739. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128740. -1.5, -0.5, 0.5, 1.5,
  128741. };
  128742. static long _vq_quantmap__44c2_s_p8_1[] = {
  128743. 3, 1, 0, 2, 4,
  128744. };
  128745. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128746. _vq_quantthresh__44c2_s_p8_1,
  128747. _vq_quantmap__44c2_s_p8_1,
  128748. 5,
  128749. 5
  128750. };
  128751. static static_codebook _44c2_s_p8_1 = {
  128752. 2, 25,
  128753. _vq_lengthlist__44c2_s_p8_1,
  128754. 1, -533725184, 1611661312, 3, 0,
  128755. _vq_quantlist__44c2_s_p8_1,
  128756. NULL,
  128757. &_vq_auxt__44c2_s_p8_1,
  128758. NULL,
  128759. 0
  128760. };
  128761. static long _vq_quantlist__44c2_s_p9_0[] = {
  128762. 6,
  128763. 5,
  128764. 7,
  128765. 4,
  128766. 8,
  128767. 3,
  128768. 9,
  128769. 2,
  128770. 10,
  128771. 1,
  128772. 11,
  128773. 0,
  128774. 12,
  128775. };
  128776. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128777. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128778. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128780. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128787. 11,11,11,11,11,11,11,11,11,
  128788. };
  128789. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128790. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128791. 552.5, 773.5, 994.5, 1215.5,
  128792. };
  128793. static long _vq_quantmap__44c2_s_p9_0[] = {
  128794. 11, 9, 7, 5, 3, 1, 0, 2,
  128795. 4, 6, 8, 10, 12,
  128796. };
  128797. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128798. _vq_quantthresh__44c2_s_p9_0,
  128799. _vq_quantmap__44c2_s_p9_0,
  128800. 13,
  128801. 13
  128802. };
  128803. static static_codebook _44c2_s_p9_0 = {
  128804. 2, 169,
  128805. _vq_lengthlist__44c2_s_p9_0,
  128806. 1, -514541568, 1627103232, 4, 0,
  128807. _vq_quantlist__44c2_s_p9_0,
  128808. NULL,
  128809. &_vq_auxt__44c2_s_p9_0,
  128810. NULL,
  128811. 0
  128812. };
  128813. static long _vq_quantlist__44c2_s_p9_1[] = {
  128814. 6,
  128815. 5,
  128816. 7,
  128817. 4,
  128818. 8,
  128819. 3,
  128820. 9,
  128821. 2,
  128822. 10,
  128823. 1,
  128824. 11,
  128825. 0,
  128826. 12,
  128827. };
  128828. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128829. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128830. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128831. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128832. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128833. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128834. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128835. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128836. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128837. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128838. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128839. 17,13,12,12,10,13,11,14,14,
  128840. };
  128841. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128842. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128843. 42.5, 59.5, 76.5, 93.5,
  128844. };
  128845. static long _vq_quantmap__44c2_s_p9_1[] = {
  128846. 11, 9, 7, 5, 3, 1, 0, 2,
  128847. 4, 6, 8, 10, 12,
  128848. };
  128849. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128850. _vq_quantthresh__44c2_s_p9_1,
  128851. _vq_quantmap__44c2_s_p9_1,
  128852. 13,
  128853. 13
  128854. };
  128855. static static_codebook _44c2_s_p9_1 = {
  128856. 2, 169,
  128857. _vq_lengthlist__44c2_s_p9_1,
  128858. 1, -522616832, 1620115456, 4, 0,
  128859. _vq_quantlist__44c2_s_p9_1,
  128860. NULL,
  128861. &_vq_auxt__44c2_s_p9_1,
  128862. NULL,
  128863. 0
  128864. };
  128865. static long _vq_quantlist__44c2_s_p9_2[] = {
  128866. 8,
  128867. 7,
  128868. 9,
  128869. 6,
  128870. 10,
  128871. 5,
  128872. 11,
  128873. 4,
  128874. 12,
  128875. 3,
  128876. 13,
  128877. 2,
  128878. 14,
  128879. 1,
  128880. 15,
  128881. 0,
  128882. 16,
  128883. };
  128884. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128885. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128886. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128887. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128888. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128889. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128890. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128891. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128892. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128893. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128894. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128895. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128896. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128897. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128898. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128899. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128900. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128901. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128902. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128903. 10,
  128904. };
  128905. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128906. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128907. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128908. };
  128909. static long _vq_quantmap__44c2_s_p9_2[] = {
  128910. 15, 13, 11, 9, 7, 5, 3, 1,
  128911. 0, 2, 4, 6, 8, 10, 12, 14,
  128912. 16,
  128913. };
  128914. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128915. _vq_quantthresh__44c2_s_p9_2,
  128916. _vq_quantmap__44c2_s_p9_2,
  128917. 17,
  128918. 17
  128919. };
  128920. static static_codebook _44c2_s_p9_2 = {
  128921. 2, 289,
  128922. _vq_lengthlist__44c2_s_p9_2,
  128923. 1, -529530880, 1611661312, 5, 0,
  128924. _vq_quantlist__44c2_s_p9_2,
  128925. NULL,
  128926. &_vq_auxt__44c2_s_p9_2,
  128927. NULL,
  128928. 0
  128929. };
  128930. static long _huff_lengthlist__44c2_s_short[] = {
  128931. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128932. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128933. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128934. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128935. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128936. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128937. 6, 8, 9,12,
  128938. };
  128939. static static_codebook _huff_book__44c2_s_short = {
  128940. 2, 100,
  128941. _huff_lengthlist__44c2_s_short,
  128942. 0, 0, 0, 0, 0,
  128943. NULL,
  128944. NULL,
  128945. NULL,
  128946. NULL,
  128947. 0
  128948. };
  128949. static long _huff_lengthlist__44c3_s_long[] = {
  128950. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128951. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128952. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128953. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128954. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128955. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128956. 9, 8, 8, 8,
  128957. };
  128958. static static_codebook _huff_book__44c3_s_long = {
  128959. 2, 100,
  128960. _huff_lengthlist__44c3_s_long,
  128961. 0, 0, 0, 0, 0,
  128962. NULL,
  128963. NULL,
  128964. NULL,
  128965. NULL,
  128966. 0
  128967. };
  128968. static long _vq_quantlist__44c3_s_p1_0[] = {
  128969. 1,
  128970. 0,
  128971. 2,
  128972. };
  128973. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128974. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128975. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128980. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128985. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  129020. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129025. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129030. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129066. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129071. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129076. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 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,
  129385. };
  129386. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129387. -0.5, 0.5,
  129388. };
  129389. static long _vq_quantmap__44c3_s_p1_0[] = {
  129390. 1, 0, 2,
  129391. };
  129392. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129393. _vq_quantthresh__44c3_s_p1_0,
  129394. _vq_quantmap__44c3_s_p1_0,
  129395. 3,
  129396. 3
  129397. };
  129398. static static_codebook _44c3_s_p1_0 = {
  129399. 8, 6561,
  129400. _vq_lengthlist__44c3_s_p1_0,
  129401. 1, -535822336, 1611661312, 2, 0,
  129402. _vq_quantlist__44c3_s_p1_0,
  129403. NULL,
  129404. &_vq_auxt__44c3_s_p1_0,
  129405. NULL,
  129406. 0
  129407. };
  129408. static long _vq_quantlist__44c3_s_p2_0[] = {
  129409. 2,
  129410. 1,
  129411. 3,
  129412. 0,
  129413. 4,
  129414. };
  129415. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129416. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129417. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129418. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129419. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129420. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129426. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129427. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129428. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129434. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129435. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129442. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129443. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0,
  129456. };
  129457. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129458. -1.5, -0.5, 0.5, 1.5,
  129459. };
  129460. static long _vq_quantmap__44c3_s_p2_0[] = {
  129461. 3, 1, 0, 2, 4,
  129462. };
  129463. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129464. _vq_quantthresh__44c3_s_p2_0,
  129465. _vq_quantmap__44c3_s_p2_0,
  129466. 5,
  129467. 5
  129468. };
  129469. static static_codebook _44c3_s_p2_0 = {
  129470. 4, 625,
  129471. _vq_lengthlist__44c3_s_p2_0,
  129472. 1, -533725184, 1611661312, 3, 0,
  129473. _vq_quantlist__44c3_s_p2_0,
  129474. NULL,
  129475. &_vq_auxt__44c3_s_p2_0,
  129476. NULL,
  129477. 0
  129478. };
  129479. static long _vq_quantlist__44c3_s_p3_0[] = {
  129480. 2,
  129481. 1,
  129482. 3,
  129483. 0,
  129484. 4,
  129485. };
  129486. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129487. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0,
  129527. };
  129528. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129529. -1.5, -0.5, 0.5, 1.5,
  129530. };
  129531. static long _vq_quantmap__44c3_s_p3_0[] = {
  129532. 3, 1, 0, 2, 4,
  129533. };
  129534. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129535. _vq_quantthresh__44c3_s_p3_0,
  129536. _vq_quantmap__44c3_s_p3_0,
  129537. 5,
  129538. 5
  129539. };
  129540. static static_codebook _44c3_s_p3_0 = {
  129541. 4, 625,
  129542. _vq_lengthlist__44c3_s_p3_0,
  129543. 1, -533725184, 1611661312, 3, 0,
  129544. _vq_quantlist__44c3_s_p3_0,
  129545. NULL,
  129546. &_vq_auxt__44c3_s_p3_0,
  129547. NULL,
  129548. 0
  129549. };
  129550. static long _vq_quantlist__44c3_s_p4_0[] = {
  129551. 4,
  129552. 3,
  129553. 5,
  129554. 2,
  129555. 6,
  129556. 1,
  129557. 7,
  129558. 0,
  129559. 8,
  129560. };
  129561. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129562. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129563. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129564. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129565. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129566. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0,
  129568. };
  129569. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129571. };
  129572. static long _vq_quantmap__44c3_s_p4_0[] = {
  129573. 7, 5, 3, 1, 0, 2, 4, 6,
  129574. 8,
  129575. };
  129576. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129577. _vq_quantthresh__44c3_s_p4_0,
  129578. _vq_quantmap__44c3_s_p4_0,
  129579. 9,
  129580. 9
  129581. };
  129582. static static_codebook _44c3_s_p4_0 = {
  129583. 2, 81,
  129584. _vq_lengthlist__44c3_s_p4_0,
  129585. 1, -531628032, 1611661312, 4, 0,
  129586. _vq_quantlist__44c3_s_p4_0,
  129587. NULL,
  129588. &_vq_auxt__44c3_s_p4_0,
  129589. NULL,
  129590. 0
  129591. };
  129592. static long _vq_quantlist__44c3_s_p5_0[] = {
  129593. 4,
  129594. 3,
  129595. 5,
  129596. 2,
  129597. 6,
  129598. 1,
  129599. 7,
  129600. 0,
  129601. 8,
  129602. };
  129603. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129604. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129605. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129606. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129607. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129608. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129609. 11,
  129610. };
  129611. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129612. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129613. };
  129614. static long _vq_quantmap__44c3_s_p5_0[] = {
  129615. 7, 5, 3, 1, 0, 2, 4, 6,
  129616. 8,
  129617. };
  129618. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129619. _vq_quantthresh__44c3_s_p5_0,
  129620. _vq_quantmap__44c3_s_p5_0,
  129621. 9,
  129622. 9
  129623. };
  129624. static static_codebook _44c3_s_p5_0 = {
  129625. 2, 81,
  129626. _vq_lengthlist__44c3_s_p5_0,
  129627. 1, -531628032, 1611661312, 4, 0,
  129628. _vq_quantlist__44c3_s_p5_0,
  129629. NULL,
  129630. &_vq_auxt__44c3_s_p5_0,
  129631. NULL,
  129632. 0
  129633. };
  129634. static long _vq_quantlist__44c3_s_p6_0[] = {
  129635. 8,
  129636. 7,
  129637. 9,
  129638. 6,
  129639. 10,
  129640. 5,
  129641. 11,
  129642. 4,
  129643. 12,
  129644. 3,
  129645. 13,
  129646. 2,
  129647. 14,
  129648. 1,
  129649. 15,
  129650. 0,
  129651. 16,
  129652. };
  129653. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129654. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129655. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129656. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129657. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129658. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129659. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129660. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129661. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129662. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129663. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129664. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129665. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129666. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129667. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129668. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129669. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129670. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129672. 13,
  129673. };
  129674. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129677. };
  129678. static long _vq_quantmap__44c3_s_p6_0[] = {
  129679. 15, 13, 11, 9, 7, 5, 3, 1,
  129680. 0, 2, 4, 6, 8, 10, 12, 14,
  129681. 16,
  129682. };
  129683. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129684. _vq_quantthresh__44c3_s_p6_0,
  129685. _vq_quantmap__44c3_s_p6_0,
  129686. 17,
  129687. 17
  129688. };
  129689. static static_codebook _44c3_s_p6_0 = {
  129690. 2, 289,
  129691. _vq_lengthlist__44c3_s_p6_0,
  129692. 1, -529530880, 1611661312, 5, 0,
  129693. _vq_quantlist__44c3_s_p6_0,
  129694. NULL,
  129695. &_vq_auxt__44c3_s_p6_0,
  129696. NULL,
  129697. 0
  129698. };
  129699. static long _vq_quantlist__44c3_s_p7_0[] = {
  129700. 1,
  129701. 0,
  129702. 2,
  129703. };
  129704. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129705. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129706. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129707. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129708. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129709. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129710. 10,
  129711. };
  129712. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129713. -5.5, 5.5,
  129714. };
  129715. static long _vq_quantmap__44c3_s_p7_0[] = {
  129716. 1, 0, 2,
  129717. };
  129718. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129719. _vq_quantthresh__44c3_s_p7_0,
  129720. _vq_quantmap__44c3_s_p7_0,
  129721. 3,
  129722. 3
  129723. };
  129724. static static_codebook _44c3_s_p7_0 = {
  129725. 4, 81,
  129726. _vq_lengthlist__44c3_s_p7_0,
  129727. 1, -529137664, 1618345984, 2, 0,
  129728. _vq_quantlist__44c3_s_p7_0,
  129729. NULL,
  129730. &_vq_auxt__44c3_s_p7_0,
  129731. NULL,
  129732. 0
  129733. };
  129734. static long _vq_quantlist__44c3_s_p7_1[] = {
  129735. 5,
  129736. 4,
  129737. 6,
  129738. 3,
  129739. 7,
  129740. 2,
  129741. 8,
  129742. 1,
  129743. 9,
  129744. 0,
  129745. 10,
  129746. };
  129747. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129748. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129749. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129750. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129751. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129752. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129753. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129754. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129755. 10,10,10, 8, 8, 8, 8, 8, 8,
  129756. };
  129757. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129758. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129759. 3.5, 4.5,
  129760. };
  129761. static long _vq_quantmap__44c3_s_p7_1[] = {
  129762. 9, 7, 5, 3, 1, 0, 2, 4,
  129763. 6, 8, 10,
  129764. };
  129765. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129766. _vq_quantthresh__44c3_s_p7_1,
  129767. _vq_quantmap__44c3_s_p7_1,
  129768. 11,
  129769. 11
  129770. };
  129771. static static_codebook _44c3_s_p7_1 = {
  129772. 2, 121,
  129773. _vq_lengthlist__44c3_s_p7_1,
  129774. 1, -531365888, 1611661312, 4, 0,
  129775. _vq_quantlist__44c3_s_p7_1,
  129776. NULL,
  129777. &_vq_auxt__44c3_s_p7_1,
  129778. NULL,
  129779. 0
  129780. };
  129781. static long _vq_quantlist__44c3_s_p8_0[] = {
  129782. 6,
  129783. 5,
  129784. 7,
  129785. 4,
  129786. 8,
  129787. 3,
  129788. 9,
  129789. 2,
  129790. 10,
  129791. 1,
  129792. 11,
  129793. 0,
  129794. 12,
  129795. };
  129796. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129797. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129798. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129799. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129800. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129801. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129802. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129803. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129804. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129805. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129806. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129807. 0,13,13,12,12,13,12,14,13,
  129808. };
  129809. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129810. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129811. 12.5, 17.5, 22.5, 27.5,
  129812. };
  129813. static long _vq_quantmap__44c3_s_p8_0[] = {
  129814. 11, 9, 7, 5, 3, 1, 0, 2,
  129815. 4, 6, 8, 10, 12,
  129816. };
  129817. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129818. _vq_quantthresh__44c3_s_p8_0,
  129819. _vq_quantmap__44c3_s_p8_0,
  129820. 13,
  129821. 13
  129822. };
  129823. static static_codebook _44c3_s_p8_0 = {
  129824. 2, 169,
  129825. _vq_lengthlist__44c3_s_p8_0,
  129826. 1, -526516224, 1616117760, 4, 0,
  129827. _vq_quantlist__44c3_s_p8_0,
  129828. NULL,
  129829. &_vq_auxt__44c3_s_p8_0,
  129830. NULL,
  129831. 0
  129832. };
  129833. static long _vq_quantlist__44c3_s_p8_1[] = {
  129834. 2,
  129835. 1,
  129836. 3,
  129837. 0,
  129838. 4,
  129839. };
  129840. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129841. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129842. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129843. };
  129844. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129845. -1.5, -0.5, 0.5, 1.5,
  129846. };
  129847. static long _vq_quantmap__44c3_s_p8_1[] = {
  129848. 3, 1, 0, 2, 4,
  129849. };
  129850. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129851. _vq_quantthresh__44c3_s_p8_1,
  129852. _vq_quantmap__44c3_s_p8_1,
  129853. 5,
  129854. 5
  129855. };
  129856. static static_codebook _44c3_s_p8_1 = {
  129857. 2, 25,
  129858. _vq_lengthlist__44c3_s_p8_1,
  129859. 1, -533725184, 1611661312, 3, 0,
  129860. _vq_quantlist__44c3_s_p8_1,
  129861. NULL,
  129862. &_vq_auxt__44c3_s_p8_1,
  129863. NULL,
  129864. 0
  129865. };
  129866. static long _vq_quantlist__44c3_s_p9_0[] = {
  129867. 6,
  129868. 5,
  129869. 7,
  129870. 4,
  129871. 8,
  129872. 3,
  129873. 9,
  129874. 2,
  129875. 10,
  129876. 1,
  129877. 11,
  129878. 0,
  129879. 12,
  129880. };
  129881. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129882. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129883. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129884. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129885. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129886. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129887. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129888. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129889. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129890. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129892. 11,11,11,11,11,11,11,11,11,
  129893. };
  129894. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129895. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129896. 637.5, 892.5, 1147.5, 1402.5,
  129897. };
  129898. static long _vq_quantmap__44c3_s_p9_0[] = {
  129899. 11, 9, 7, 5, 3, 1, 0, 2,
  129900. 4, 6, 8, 10, 12,
  129901. };
  129902. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129903. _vq_quantthresh__44c3_s_p9_0,
  129904. _vq_quantmap__44c3_s_p9_0,
  129905. 13,
  129906. 13
  129907. };
  129908. static static_codebook _44c3_s_p9_0 = {
  129909. 2, 169,
  129910. _vq_lengthlist__44c3_s_p9_0,
  129911. 1, -514332672, 1627381760, 4, 0,
  129912. _vq_quantlist__44c3_s_p9_0,
  129913. NULL,
  129914. &_vq_auxt__44c3_s_p9_0,
  129915. NULL,
  129916. 0
  129917. };
  129918. static long _vq_quantlist__44c3_s_p9_1[] = {
  129919. 7,
  129920. 6,
  129921. 8,
  129922. 5,
  129923. 9,
  129924. 4,
  129925. 10,
  129926. 3,
  129927. 11,
  129928. 2,
  129929. 12,
  129930. 1,
  129931. 13,
  129932. 0,
  129933. 14,
  129934. };
  129935. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129936. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129937. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129938. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129939. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129940. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129941. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129942. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129943. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129944. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129945. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129946. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129947. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129948. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129949. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129950. 15,
  129951. };
  129952. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129953. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129954. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129955. };
  129956. static long _vq_quantmap__44c3_s_p9_1[] = {
  129957. 13, 11, 9, 7, 5, 3, 1, 0,
  129958. 2, 4, 6, 8, 10, 12, 14,
  129959. };
  129960. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129961. _vq_quantthresh__44c3_s_p9_1,
  129962. _vq_quantmap__44c3_s_p9_1,
  129963. 15,
  129964. 15
  129965. };
  129966. static static_codebook _44c3_s_p9_1 = {
  129967. 2, 225,
  129968. _vq_lengthlist__44c3_s_p9_1,
  129969. 1, -522338304, 1620115456, 4, 0,
  129970. _vq_quantlist__44c3_s_p9_1,
  129971. NULL,
  129972. &_vq_auxt__44c3_s_p9_1,
  129973. NULL,
  129974. 0
  129975. };
  129976. static long _vq_quantlist__44c3_s_p9_2[] = {
  129977. 8,
  129978. 7,
  129979. 9,
  129980. 6,
  129981. 10,
  129982. 5,
  129983. 11,
  129984. 4,
  129985. 12,
  129986. 3,
  129987. 13,
  129988. 2,
  129989. 14,
  129990. 1,
  129991. 15,
  129992. 0,
  129993. 16,
  129994. };
  129995. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129996. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129997. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129998. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129999. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130000. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130001. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130002. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130003. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130004. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130005. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130006. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130007. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130008. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130009. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130010. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130011. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130012. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130013. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130014. 10,
  130015. };
  130016. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130017. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130018. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130019. };
  130020. static long _vq_quantmap__44c3_s_p9_2[] = {
  130021. 15, 13, 11, 9, 7, 5, 3, 1,
  130022. 0, 2, 4, 6, 8, 10, 12, 14,
  130023. 16,
  130024. };
  130025. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130026. _vq_quantthresh__44c3_s_p9_2,
  130027. _vq_quantmap__44c3_s_p9_2,
  130028. 17,
  130029. 17
  130030. };
  130031. static static_codebook _44c3_s_p9_2 = {
  130032. 2, 289,
  130033. _vq_lengthlist__44c3_s_p9_2,
  130034. 1, -529530880, 1611661312, 5, 0,
  130035. _vq_quantlist__44c3_s_p9_2,
  130036. NULL,
  130037. &_vq_auxt__44c3_s_p9_2,
  130038. NULL,
  130039. 0
  130040. };
  130041. static long _huff_lengthlist__44c3_s_short[] = {
  130042. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130043. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130044. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130045. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130046. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130047. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130048. 6, 8, 9,11,
  130049. };
  130050. static static_codebook _huff_book__44c3_s_short = {
  130051. 2, 100,
  130052. _huff_lengthlist__44c3_s_short,
  130053. 0, 0, 0, 0, 0,
  130054. NULL,
  130055. NULL,
  130056. NULL,
  130057. NULL,
  130058. 0
  130059. };
  130060. static long _huff_lengthlist__44c4_s_long[] = {
  130061. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130062. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130063. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130064. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130065. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130066. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130067. 9, 8, 7, 7,
  130068. };
  130069. static static_codebook _huff_book__44c4_s_long = {
  130070. 2, 100,
  130071. _huff_lengthlist__44c4_s_long,
  130072. 0, 0, 0, 0, 0,
  130073. NULL,
  130074. NULL,
  130075. NULL,
  130076. NULL,
  130077. 0
  130078. };
  130079. static long _vq_quantlist__44c4_s_p1_0[] = {
  130080. 1,
  130081. 0,
  130082. 2,
  130083. };
  130084. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130085. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130086. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130091. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130096. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  130131. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130136. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130141. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130177. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130182. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130187. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 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,
  130496. };
  130497. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130498. -0.5, 0.5,
  130499. };
  130500. static long _vq_quantmap__44c4_s_p1_0[] = {
  130501. 1, 0, 2,
  130502. };
  130503. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130504. _vq_quantthresh__44c4_s_p1_0,
  130505. _vq_quantmap__44c4_s_p1_0,
  130506. 3,
  130507. 3
  130508. };
  130509. static static_codebook _44c4_s_p1_0 = {
  130510. 8, 6561,
  130511. _vq_lengthlist__44c4_s_p1_0,
  130512. 1, -535822336, 1611661312, 2, 0,
  130513. _vq_quantlist__44c4_s_p1_0,
  130514. NULL,
  130515. &_vq_auxt__44c4_s_p1_0,
  130516. NULL,
  130517. 0
  130518. };
  130519. static long _vq_quantlist__44c4_s_p2_0[] = {
  130520. 2,
  130521. 1,
  130522. 3,
  130523. 0,
  130524. 4,
  130525. };
  130526. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130527. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130528. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130529. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130530. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130531. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130537. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130538. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130539. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130545. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130546. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130553. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130554. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0,
  130567. };
  130568. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130569. -1.5, -0.5, 0.5, 1.5,
  130570. };
  130571. static long _vq_quantmap__44c4_s_p2_0[] = {
  130572. 3, 1, 0, 2, 4,
  130573. };
  130574. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130575. _vq_quantthresh__44c4_s_p2_0,
  130576. _vq_quantmap__44c4_s_p2_0,
  130577. 5,
  130578. 5
  130579. };
  130580. static static_codebook _44c4_s_p2_0 = {
  130581. 4, 625,
  130582. _vq_lengthlist__44c4_s_p2_0,
  130583. 1, -533725184, 1611661312, 3, 0,
  130584. _vq_quantlist__44c4_s_p2_0,
  130585. NULL,
  130586. &_vq_auxt__44c4_s_p2_0,
  130587. NULL,
  130588. 0
  130589. };
  130590. static long _vq_quantlist__44c4_s_p3_0[] = {
  130591. 2,
  130592. 1,
  130593. 3,
  130594. 0,
  130595. 4,
  130596. };
  130597. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130598. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0,
  130638. };
  130639. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130640. -1.5, -0.5, 0.5, 1.5,
  130641. };
  130642. static long _vq_quantmap__44c4_s_p3_0[] = {
  130643. 3, 1, 0, 2, 4,
  130644. };
  130645. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130646. _vq_quantthresh__44c4_s_p3_0,
  130647. _vq_quantmap__44c4_s_p3_0,
  130648. 5,
  130649. 5
  130650. };
  130651. static static_codebook _44c4_s_p3_0 = {
  130652. 4, 625,
  130653. _vq_lengthlist__44c4_s_p3_0,
  130654. 1, -533725184, 1611661312, 3, 0,
  130655. _vq_quantlist__44c4_s_p3_0,
  130656. NULL,
  130657. &_vq_auxt__44c4_s_p3_0,
  130658. NULL,
  130659. 0
  130660. };
  130661. static long _vq_quantlist__44c4_s_p4_0[] = {
  130662. 4,
  130663. 3,
  130664. 5,
  130665. 2,
  130666. 6,
  130667. 1,
  130668. 7,
  130669. 0,
  130670. 8,
  130671. };
  130672. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130673. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130674. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130675. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130676. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130677. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0,
  130679. };
  130680. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130681. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130682. };
  130683. static long _vq_quantmap__44c4_s_p4_0[] = {
  130684. 7, 5, 3, 1, 0, 2, 4, 6,
  130685. 8,
  130686. };
  130687. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130688. _vq_quantthresh__44c4_s_p4_0,
  130689. _vq_quantmap__44c4_s_p4_0,
  130690. 9,
  130691. 9
  130692. };
  130693. static static_codebook _44c4_s_p4_0 = {
  130694. 2, 81,
  130695. _vq_lengthlist__44c4_s_p4_0,
  130696. 1, -531628032, 1611661312, 4, 0,
  130697. _vq_quantlist__44c4_s_p4_0,
  130698. NULL,
  130699. &_vq_auxt__44c4_s_p4_0,
  130700. NULL,
  130701. 0
  130702. };
  130703. static long _vq_quantlist__44c4_s_p5_0[] = {
  130704. 4,
  130705. 3,
  130706. 5,
  130707. 2,
  130708. 6,
  130709. 1,
  130710. 7,
  130711. 0,
  130712. 8,
  130713. };
  130714. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130715. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130716. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130717. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130718. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130719. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130720. 10,
  130721. };
  130722. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130723. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130724. };
  130725. static long _vq_quantmap__44c4_s_p5_0[] = {
  130726. 7, 5, 3, 1, 0, 2, 4, 6,
  130727. 8,
  130728. };
  130729. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130730. _vq_quantthresh__44c4_s_p5_0,
  130731. _vq_quantmap__44c4_s_p5_0,
  130732. 9,
  130733. 9
  130734. };
  130735. static static_codebook _44c4_s_p5_0 = {
  130736. 2, 81,
  130737. _vq_lengthlist__44c4_s_p5_0,
  130738. 1, -531628032, 1611661312, 4, 0,
  130739. _vq_quantlist__44c4_s_p5_0,
  130740. NULL,
  130741. &_vq_auxt__44c4_s_p5_0,
  130742. NULL,
  130743. 0
  130744. };
  130745. static long _vq_quantlist__44c4_s_p6_0[] = {
  130746. 8,
  130747. 7,
  130748. 9,
  130749. 6,
  130750. 10,
  130751. 5,
  130752. 11,
  130753. 4,
  130754. 12,
  130755. 3,
  130756. 13,
  130757. 2,
  130758. 14,
  130759. 1,
  130760. 15,
  130761. 0,
  130762. 16,
  130763. };
  130764. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130765. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130766. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130767. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130768. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130769. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130770. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130771. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130772. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130773. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130774. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130775. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130776. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130777. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130778. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130779. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130780. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130781. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130783. 13,
  130784. };
  130785. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130786. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130787. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130788. };
  130789. static long _vq_quantmap__44c4_s_p6_0[] = {
  130790. 15, 13, 11, 9, 7, 5, 3, 1,
  130791. 0, 2, 4, 6, 8, 10, 12, 14,
  130792. 16,
  130793. };
  130794. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130795. _vq_quantthresh__44c4_s_p6_0,
  130796. _vq_quantmap__44c4_s_p6_0,
  130797. 17,
  130798. 17
  130799. };
  130800. static static_codebook _44c4_s_p6_0 = {
  130801. 2, 289,
  130802. _vq_lengthlist__44c4_s_p6_0,
  130803. 1, -529530880, 1611661312, 5, 0,
  130804. _vq_quantlist__44c4_s_p6_0,
  130805. NULL,
  130806. &_vq_auxt__44c4_s_p6_0,
  130807. NULL,
  130808. 0
  130809. };
  130810. static long _vq_quantlist__44c4_s_p7_0[] = {
  130811. 1,
  130812. 0,
  130813. 2,
  130814. };
  130815. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130816. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130817. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130818. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130819. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130820. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130821. 10,
  130822. };
  130823. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130824. -5.5, 5.5,
  130825. };
  130826. static long _vq_quantmap__44c4_s_p7_0[] = {
  130827. 1, 0, 2,
  130828. };
  130829. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130830. _vq_quantthresh__44c4_s_p7_0,
  130831. _vq_quantmap__44c4_s_p7_0,
  130832. 3,
  130833. 3
  130834. };
  130835. static static_codebook _44c4_s_p7_0 = {
  130836. 4, 81,
  130837. _vq_lengthlist__44c4_s_p7_0,
  130838. 1, -529137664, 1618345984, 2, 0,
  130839. _vq_quantlist__44c4_s_p7_0,
  130840. NULL,
  130841. &_vq_auxt__44c4_s_p7_0,
  130842. NULL,
  130843. 0
  130844. };
  130845. static long _vq_quantlist__44c4_s_p7_1[] = {
  130846. 5,
  130847. 4,
  130848. 6,
  130849. 3,
  130850. 7,
  130851. 2,
  130852. 8,
  130853. 1,
  130854. 9,
  130855. 0,
  130856. 10,
  130857. };
  130858. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130859. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130860. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130861. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130862. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130863. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130864. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130865. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130866. 10,10,10, 8, 8, 8, 8, 9, 9,
  130867. };
  130868. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130869. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130870. 3.5, 4.5,
  130871. };
  130872. static long _vq_quantmap__44c4_s_p7_1[] = {
  130873. 9, 7, 5, 3, 1, 0, 2, 4,
  130874. 6, 8, 10,
  130875. };
  130876. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130877. _vq_quantthresh__44c4_s_p7_1,
  130878. _vq_quantmap__44c4_s_p7_1,
  130879. 11,
  130880. 11
  130881. };
  130882. static static_codebook _44c4_s_p7_1 = {
  130883. 2, 121,
  130884. _vq_lengthlist__44c4_s_p7_1,
  130885. 1, -531365888, 1611661312, 4, 0,
  130886. _vq_quantlist__44c4_s_p7_1,
  130887. NULL,
  130888. &_vq_auxt__44c4_s_p7_1,
  130889. NULL,
  130890. 0
  130891. };
  130892. static long _vq_quantlist__44c4_s_p8_0[] = {
  130893. 6,
  130894. 5,
  130895. 7,
  130896. 4,
  130897. 8,
  130898. 3,
  130899. 9,
  130900. 2,
  130901. 10,
  130902. 1,
  130903. 11,
  130904. 0,
  130905. 12,
  130906. };
  130907. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130908. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130909. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130910. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130911. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130912. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130913. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130914. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130915. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130916. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130917. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130918. 0,13,12,12,12,12,12,13,13,
  130919. };
  130920. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130921. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130922. 12.5, 17.5, 22.5, 27.5,
  130923. };
  130924. static long _vq_quantmap__44c4_s_p8_0[] = {
  130925. 11, 9, 7, 5, 3, 1, 0, 2,
  130926. 4, 6, 8, 10, 12,
  130927. };
  130928. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130929. _vq_quantthresh__44c4_s_p8_0,
  130930. _vq_quantmap__44c4_s_p8_0,
  130931. 13,
  130932. 13
  130933. };
  130934. static static_codebook _44c4_s_p8_0 = {
  130935. 2, 169,
  130936. _vq_lengthlist__44c4_s_p8_0,
  130937. 1, -526516224, 1616117760, 4, 0,
  130938. _vq_quantlist__44c4_s_p8_0,
  130939. NULL,
  130940. &_vq_auxt__44c4_s_p8_0,
  130941. NULL,
  130942. 0
  130943. };
  130944. static long _vq_quantlist__44c4_s_p8_1[] = {
  130945. 2,
  130946. 1,
  130947. 3,
  130948. 0,
  130949. 4,
  130950. };
  130951. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130952. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130953. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130954. };
  130955. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130956. -1.5, -0.5, 0.5, 1.5,
  130957. };
  130958. static long _vq_quantmap__44c4_s_p8_1[] = {
  130959. 3, 1, 0, 2, 4,
  130960. };
  130961. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130962. _vq_quantthresh__44c4_s_p8_1,
  130963. _vq_quantmap__44c4_s_p8_1,
  130964. 5,
  130965. 5
  130966. };
  130967. static static_codebook _44c4_s_p8_1 = {
  130968. 2, 25,
  130969. _vq_lengthlist__44c4_s_p8_1,
  130970. 1, -533725184, 1611661312, 3, 0,
  130971. _vq_quantlist__44c4_s_p8_1,
  130972. NULL,
  130973. &_vq_auxt__44c4_s_p8_1,
  130974. NULL,
  130975. 0
  130976. };
  130977. static long _vq_quantlist__44c4_s_p9_0[] = {
  130978. 6,
  130979. 5,
  130980. 7,
  130981. 4,
  130982. 8,
  130983. 3,
  130984. 9,
  130985. 2,
  130986. 10,
  130987. 1,
  130988. 11,
  130989. 0,
  130990. 12,
  130991. };
  130992. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130993. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130994. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130995. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130996. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130997. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130998. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130999. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131003. 12,12,12,12,12,12,12,12,12,
  131004. };
  131005. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131006. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131007. 787.5, 1102.5, 1417.5, 1732.5,
  131008. };
  131009. static long _vq_quantmap__44c4_s_p9_0[] = {
  131010. 11, 9, 7, 5, 3, 1, 0, 2,
  131011. 4, 6, 8, 10, 12,
  131012. };
  131013. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131014. _vq_quantthresh__44c4_s_p9_0,
  131015. _vq_quantmap__44c4_s_p9_0,
  131016. 13,
  131017. 13
  131018. };
  131019. static static_codebook _44c4_s_p9_0 = {
  131020. 2, 169,
  131021. _vq_lengthlist__44c4_s_p9_0,
  131022. 1, -513964032, 1628680192, 4, 0,
  131023. _vq_quantlist__44c4_s_p9_0,
  131024. NULL,
  131025. &_vq_auxt__44c4_s_p9_0,
  131026. NULL,
  131027. 0
  131028. };
  131029. static long _vq_quantlist__44c4_s_p9_1[] = {
  131030. 7,
  131031. 6,
  131032. 8,
  131033. 5,
  131034. 9,
  131035. 4,
  131036. 10,
  131037. 3,
  131038. 11,
  131039. 2,
  131040. 12,
  131041. 1,
  131042. 13,
  131043. 0,
  131044. 14,
  131045. };
  131046. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131047. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131048. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131049. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131050. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131051. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131052. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131053. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131054. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131055. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131056. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131057. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131058. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131059. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131060. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131061. 15,
  131062. };
  131063. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131064. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131065. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131066. };
  131067. static long _vq_quantmap__44c4_s_p9_1[] = {
  131068. 13, 11, 9, 7, 5, 3, 1, 0,
  131069. 2, 4, 6, 8, 10, 12, 14,
  131070. };
  131071. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131072. _vq_quantthresh__44c4_s_p9_1,
  131073. _vq_quantmap__44c4_s_p9_1,
  131074. 15,
  131075. 15
  131076. };
  131077. static static_codebook _44c4_s_p9_1 = {
  131078. 2, 225,
  131079. _vq_lengthlist__44c4_s_p9_1,
  131080. 1, -520986624, 1620377600, 4, 0,
  131081. _vq_quantlist__44c4_s_p9_1,
  131082. NULL,
  131083. &_vq_auxt__44c4_s_p9_1,
  131084. NULL,
  131085. 0
  131086. };
  131087. static long _vq_quantlist__44c4_s_p9_2[] = {
  131088. 10,
  131089. 9,
  131090. 11,
  131091. 8,
  131092. 12,
  131093. 7,
  131094. 13,
  131095. 6,
  131096. 14,
  131097. 5,
  131098. 15,
  131099. 4,
  131100. 16,
  131101. 3,
  131102. 17,
  131103. 2,
  131104. 18,
  131105. 1,
  131106. 19,
  131107. 0,
  131108. 20,
  131109. };
  131110. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131111. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131112. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131113. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131114. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131115. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131116. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131117. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131118. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131119. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131120. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131121. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131122. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131123. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131124. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131125. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131126. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131127. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131128. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131129. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131130. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131131. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131132. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131133. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131134. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131135. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131136. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131137. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131138. 10,10,10,10,10,10,10,10,10,
  131139. };
  131140. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131141. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131142. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131143. 6.5, 7.5, 8.5, 9.5,
  131144. };
  131145. static long _vq_quantmap__44c4_s_p9_2[] = {
  131146. 19, 17, 15, 13, 11, 9, 7, 5,
  131147. 3, 1, 0, 2, 4, 6, 8, 10,
  131148. 12, 14, 16, 18, 20,
  131149. };
  131150. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131151. _vq_quantthresh__44c4_s_p9_2,
  131152. _vq_quantmap__44c4_s_p9_2,
  131153. 21,
  131154. 21
  131155. };
  131156. static static_codebook _44c4_s_p9_2 = {
  131157. 2, 441,
  131158. _vq_lengthlist__44c4_s_p9_2,
  131159. 1, -529268736, 1611661312, 5, 0,
  131160. _vq_quantlist__44c4_s_p9_2,
  131161. NULL,
  131162. &_vq_auxt__44c4_s_p9_2,
  131163. NULL,
  131164. 0
  131165. };
  131166. static long _huff_lengthlist__44c4_s_short[] = {
  131167. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131168. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131169. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131170. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131171. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131172. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131173. 7, 9,12,17,
  131174. };
  131175. static static_codebook _huff_book__44c4_s_short = {
  131176. 2, 100,
  131177. _huff_lengthlist__44c4_s_short,
  131178. 0, 0, 0, 0, 0,
  131179. NULL,
  131180. NULL,
  131181. NULL,
  131182. NULL,
  131183. 0
  131184. };
  131185. static long _huff_lengthlist__44c5_s_long[] = {
  131186. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131187. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131188. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131189. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131190. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131191. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131192. 9, 8, 7, 7,
  131193. };
  131194. static static_codebook _huff_book__44c5_s_long = {
  131195. 2, 100,
  131196. _huff_lengthlist__44c5_s_long,
  131197. 0, 0, 0, 0, 0,
  131198. NULL,
  131199. NULL,
  131200. NULL,
  131201. NULL,
  131202. 0
  131203. };
  131204. static long _vq_quantlist__44c5_s_p1_0[] = {
  131205. 1,
  131206. 0,
  131207. 2,
  131208. };
  131209. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131210. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131211. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131216. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131221. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  131256. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131261. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131266. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131302. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131307. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131312. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 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,
  131621. };
  131622. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131623. -0.5, 0.5,
  131624. };
  131625. static long _vq_quantmap__44c5_s_p1_0[] = {
  131626. 1, 0, 2,
  131627. };
  131628. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131629. _vq_quantthresh__44c5_s_p1_0,
  131630. _vq_quantmap__44c5_s_p1_0,
  131631. 3,
  131632. 3
  131633. };
  131634. static static_codebook _44c5_s_p1_0 = {
  131635. 8, 6561,
  131636. _vq_lengthlist__44c5_s_p1_0,
  131637. 1, -535822336, 1611661312, 2, 0,
  131638. _vq_quantlist__44c5_s_p1_0,
  131639. NULL,
  131640. &_vq_auxt__44c5_s_p1_0,
  131641. NULL,
  131642. 0
  131643. };
  131644. static long _vq_quantlist__44c5_s_p2_0[] = {
  131645. 2,
  131646. 1,
  131647. 3,
  131648. 0,
  131649. 4,
  131650. };
  131651. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131652. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131653. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131654. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131655. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131656. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131662. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131663. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131664. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131670. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131671. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131678. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131679. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0,
  131692. };
  131693. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131694. -1.5, -0.5, 0.5, 1.5,
  131695. };
  131696. static long _vq_quantmap__44c5_s_p2_0[] = {
  131697. 3, 1, 0, 2, 4,
  131698. };
  131699. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131700. _vq_quantthresh__44c5_s_p2_0,
  131701. _vq_quantmap__44c5_s_p2_0,
  131702. 5,
  131703. 5
  131704. };
  131705. static static_codebook _44c5_s_p2_0 = {
  131706. 4, 625,
  131707. _vq_lengthlist__44c5_s_p2_0,
  131708. 1, -533725184, 1611661312, 3, 0,
  131709. _vq_quantlist__44c5_s_p2_0,
  131710. NULL,
  131711. &_vq_auxt__44c5_s_p2_0,
  131712. NULL,
  131713. 0
  131714. };
  131715. static long _vq_quantlist__44c5_s_p3_0[] = {
  131716. 2,
  131717. 1,
  131718. 3,
  131719. 0,
  131720. 4,
  131721. };
  131722. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131723. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0,
  131763. };
  131764. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131765. -1.5, -0.5, 0.5, 1.5,
  131766. };
  131767. static long _vq_quantmap__44c5_s_p3_0[] = {
  131768. 3, 1, 0, 2, 4,
  131769. };
  131770. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131771. _vq_quantthresh__44c5_s_p3_0,
  131772. _vq_quantmap__44c5_s_p3_0,
  131773. 5,
  131774. 5
  131775. };
  131776. static static_codebook _44c5_s_p3_0 = {
  131777. 4, 625,
  131778. _vq_lengthlist__44c5_s_p3_0,
  131779. 1, -533725184, 1611661312, 3, 0,
  131780. _vq_quantlist__44c5_s_p3_0,
  131781. NULL,
  131782. &_vq_auxt__44c5_s_p3_0,
  131783. NULL,
  131784. 0
  131785. };
  131786. static long _vq_quantlist__44c5_s_p4_0[] = {
  131787. 4,
  131788. 3,
  131789. 5,
  131790. 2,
  131791. 6,
  131792. 1,
  131793. 7,
  131794. 0,
  131795. 8,
  131796. };
  131797. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131798. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131799. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131800. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131801. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131802. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0,
  131804. };
  131805. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131806. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131807. };
  131808. static long _vq_quantmap__44c5_s_p4_0[] = {
  131809. 7, 5, 3, 1, 0, 2, 4, 6,
  131810. 8,
  131811. };
  131812. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131813. _vq_quantthresh__44c5_s_p4_0,
  131814. _vq_quantmap__44c5_s_p4_0,
  131815. 9,
  131816. 9
  131817. };
  131818. static static_codebook _44c5_s_p4_0 = {
  131819. 2, 81,
  131820. _vq_lengthlist__44c5_s_p4_0,
  131821. 1, -531628032, 1611661312, 4, 0,
  131822. _vq_quantlist__44c5_s_p4_0,
  131823. NULL,
  131824. &_vq_auxt__44c5_s_p4_0,
  131825. NULL,
  131826. 0
  131827. };
  131828. static long _vq_quantlist__44c5_s_p5_0[] = {
  131829. 4,
  131830. 3,
  131831. 5,
  131832. 2,
  131833. 6,
  131834. 1,
  131835. 7,
  131836. 0,
  131837. 8,
  131838. };
  131839. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131840. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131841. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131842. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131843. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131844. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131845. 10,
  131846. };
  131847. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131849. };
  131850. static long _vq_quantmap__44c5_s_p5_0[] = {
  131851. 7, 5, 3, 1, 0, 2, 4, 6,
  131852. 8,
  131853. };
  131854. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131855. _vq_quantthresh__44c5_s_p5_0,
  131856. _vq_quantmap__44c5_s_p5_0,
  131857. 9,
  131858. 9
  131859. };
  131860. static static_codebook _44c5_s_p5_0 = {
  131861. 2, 81,
  131862. _vq_lengthlist__44c5_s_p5_0,
  131863. 1, -531628032, 1611661312, 4, 0,
  131864. _vq_quantlist__44c5_s_p5_0,
  131865. NULL,
  131866. &_vq_auxt__44c5_s_p5_0,
  131867. NULL,
  131868. 0
  131869. };
  131870. static long _vq_quantlist__44c5_s_p6_0[] = {
  131871. 8,
  131872. 7,
  131873. 9,
  131874. 6,
  131875. 10,
  131876. 5,
  131877. 11,
  131878. 4,
  131879. 12,
  131880. 3,
  131881. 13,
  131882. 2,
  131883. 14,
  131884. 1,
  131885. 15,
  131886. 0,
  131887. 16,
  131888. };
  131889. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131890. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131891. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131892. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131893. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131894. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131895. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131896. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131897. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131898. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131899. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131900. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131901. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131902. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131903. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131904. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131905. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131906. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131908. 13,
  131909. };
  131910. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131911. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131912. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131913. };
  131914. static long _vq_quantmap__44c5_s_p6_0[] = {
  131915. 15, 13, 11, 9, 7, 5, 3, 1,
  131916. 0, 2, 4, 6, 8, 10, 12, 14,
  131917. 16,
  131918. };
  131919. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131920. _vq_quantthresh__44c5_s_p6_0,
  131921. _vq_quantmap__44c5_s_p6_0,
  131922. 17,
  131923. 17
  131924. };
  131925. static static_codebook _44c5_s_p6_0 = {
  131926. 2, 289,
  131927. _vq_lengthlist__44c5_s_p6_0,
  131928. 1, -529530880, 1611661312, 5, 0,
  131929. _vq_quantlist__44c5_s_p6_0,
  131930. NULL,
  131931. &_vq_auxt__44c5_s_p6_0,
  131932. NULL,
  131933. 0
  131934. };
  131935. static long _vq_quantlist__44c5_s_p7_0[] = {
  131936. 1,
  131937. 0,
  131938. 2,
  131939. };
  131940. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131941. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131942. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131943. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131944. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131945. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131946. 10,
  131947. };
  131948. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131949. -5.5, 5.5,
  131950. };
  131951. static long _vq_quantmap__44c5_s_p7_0[] = {
  131952. 1, 0, 2,
  131953. };
  131954. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131955. _vq_quantthresh__44c5_s_p7_0,
  131956. _vq_quantmap__44c5_s_p7_0,
  131957. 3,
  131958. 3
  131959. };
  131960. static static_codebook _44c5_s_p7_0 = {
  131961. 4, 81,
  131962. _vq_lengthlist__44c5_s_p7_0,
  131963. 1, -529137664, 1618345984, 2, 0,
  131964. _vq_quantlist__44c5_s_p7_0,
  131965. NULL,
  131966. &_vq_auxt__44c5_s_p7_0,
  131967. NULL,
  131968. 0
  131969. };
  131970. static long _vq_quantlist__44c5_s_p7_1[] = {
  131971. 5,
  131972. 4,
  131973. 6,
  131974. 3,
  131975. 7,
  131976. 2,
  131977. 8,
  131978. 1,
  131979. 9,
  131980. 0,
  131981. 10,
  131982. };
  131983. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131984. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131985. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131986. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131987. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131988. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131989. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131990. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131991. 10,10,10, 8, 8, 8, 8, 8, 8,
  131992. };
  131993. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131994. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131995. 3.5, 4.5,
  131996. };
  131997. static long _vq_quantmap__44c5_s_p7_1[] = {
  131998. 9, 7, 5, 3, 1, 0, 2, 4,
  131999. 6, 8, 10,
  132000. };
  132001. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132002. _vq_quantthresh__44c5_s_p7_1,
  132003. _vq_quantmap__44c5_s_p7_1,
  132004. 11,
  132005. 11
  132006. };
  132007. static static_codebook _44c5_s_p7_1 = {
  132008. 2, 121,
  132009. _vq_lengthlist__44c5_s_p7_1,
  132010. 1, -531365888, 1611661312, 4, 0,
  132011. _vq_quantlist__44c5_s_p7_1,
  132012. NULL,
  132013. &_vq_auxt__44c5_s_p7_1,
  132014. NULL,
  132015. 0
  132016. };
  132017. static long _vq_quantlist__44c5_s_p8_0[] = {
  132018. 6,
  132019. 5,
  132020. 7,
  132021. 4,
  132022. 8,
  132023. 3,
  132024. 9,
  132025. 2,
  132026. 10,
  132027. 1,
  132028. 11,
  132029. 0,
  132030. 12,
  132031. };
  132032. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132033. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132034. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132035. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132036. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132037. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132038. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132039. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132040. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132041. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132042. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132043. 0,12,12,12,12,12,12,13,13,
  132044. };
  132045. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132046. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132047. 12.5, 17.5, 22.5, 27.5,
  132048. };
  132049. static long _vq_quantmap__44c5_s_p8_0[] = {
  132050. 11, 9, 7, 5, 3, 1, 0, 2,
  132051. 4, 6, 8, 10, 12,
  132052. };
  132053. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132054. _vq_quantthresh__44c5_s_p8_0,
  132055. _vq_quantmap__44c5_s_p8_0,
  132056. 13,
  132057. 13
  132058. };
  132059. static static_codebook _44c5_s_p8_0 = {
  132060. 2, 169,
  132061. _vq_lengthlist__44c5_s_p8_0,
  132062. 1, -526516224, 1616117760, 4, 0,
  132063. _vq_quantlist__44c5_s_p8_0,
  132064. NULL,
  132065. &_vq_auxt__44c5_s_p8_0,
  132066. NULL,
  132067. 0
  132068. };
  132069. static long _vq_quantlist__44c5_s_p8_1[] = {
  132070. 2,
  132071. 1,
  132072. 3,
  132073. 0,
  132074. 4,
  132075. };
  132076. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132077. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132078. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132079. };
  132080. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132081. -1.5, -0.5, 0.5, 1.5,
  132082. };
  132083. static long _vq_quantmap__44c5_s_p8_1[] = {
  132084. 3, 1, 0, 2, 4,
  132085. };
  132086. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132087. _vq_quantthresh__44c5_s_p8_1,
  132088. _vq_quantmap__44c5_s_p8_1,
  132089. 5,
  132090. 5
  132091. };
  132092. static static_codebook _44c5_s_p8_1 = {
  132093. 2, 25,
  132094. _vq_lengthlist__44c5_s_p8_1,
  132095. 1, -533725184, 1611661312, 3, 0,
  132096. _vq_quantlist__44c5_s_p8_1,
  132097. NULL,
  132098. &_vq_auxt__44c5_s_p8_1,
  132099. NULL,
  132100. 0
  132101. };
  132102. static long _vq_quantlist__44c5_s_p9_0[] = {
  132103. 7,
  132104. 6,
  132105. 8,
  132106. 5,
  132107. 9,
  132108. 4,
  132109. 10,
  132110. 3,
  132111. 11,
  132112. 2,
  132113. 12,
  132114. 1,
  132115. 13,
  132116. 0,
  132117. 14,
  132118. };
  132119. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132120. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132121. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132122. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132123. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132124. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132125. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132126. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132127. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132128. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132129. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132130. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132131. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132132. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132133. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132134. 12,
  132135. };
  132136. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132137. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132138. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132139. };
  132140. static long _vq_quantmap__44c5_s_p9_0[] = {
  132141. 13, 11, 9, 7, 5, 3, 1, 0,
  132142. 2, 4, 6, 8, 10, 12, 14,
  132143. };
  132144. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132145. _vq_quantthresh__44c5_s_p9_0,
  132146. _vq_quantmap__44c5_s_p9_0,
  132147. 15,
  132148. 15
  132149. };
  132150. static static_codebook _44c5_s_p9_0 = {
  132151. 2, 225,
  132152. _vq_lengthlist__44c5_s_p9_0,
  132153. 1, -512522752, 1628852224, 4, 0,
  132154. _vq_quantlist__44c5_s_p9_0,
  132155. NULL,
  132156. &_vq_auxt__44c5_s_p9_0,
  132157. NULL,
  132158. 0
  132159. };
  132160. static long _vq_quantlist__44c5_s_p9_1[] = {
  132161. 8,
  132162. 7,
  132163. 9,
  132164. 6,
  132165. 10,
  132166. 5,
  132167. 11,
  132168. 4,
  132169. 12,
  132170. 3,
  132171. 13,
  132172. 2,
  132173. 14,
  132174. 1,
  132175. 15,
  132176. 0,
  132177. 16,
  132178. };
  132179. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132180. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132181. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132182. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132183. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132184. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132185. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132186. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132187. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132188. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132189. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132190. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132191. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132192. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132193. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132194. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132195. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132196. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132197. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132198. 15,
  132199. };
  132200. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132201. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132202. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132203. };
  132204. static long _vq_quantmap__44c5_s_p9_1[] = {
  132205. 15, 13, 11, 9, 7, 5, 3, 1,
  132206. 0, 2, 4, 6, 8, 10, 12, 14,
  132207. 16,
  132208. };
  132209. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132210. _vq_quantthresh__44c5_s_p9_1,
  132211. _vq_quantmap__44c5_s_p9_1,
  132212. 17,
  132213. 17
  132214. };
  132215. static static_codebook _44c5_s_p9_1 = {
  132216. 2, 289,
  132217. _vq_lengthlist__44c5_s_p9_1,
  132218. 1, -520814592, 1620377600, 5, 0,
  132219. _vq_quantlist__44c5_s_p9_1,
  132220. NULL,
  132221. &_vq_auxt__44c5_s_p9_1,
  132222. NULL,
  132223. 0
  132224. };
  132225. static long _vq_quantlist__44c5_s_p9_2[] = {
  132226. 10,
  132227. 9,
  132228. 11,
  132229. 8,
  132230. 12,
  132231. 7,
  132232. 13,
  132233. 6,
  132234. 14,
  132235. 5,
  132236. 15,
  132237. 4,
  132238. 16,
  132239. 3,
  132240. 17,
  132241. 2,
  132242. 18,
  132243. 1,
  132244. 19,
  132245. 0,
  132246. 20,
  132247. };
  132248. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132249. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132250. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132251. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132252. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132253. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132254. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132255. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132256. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132257. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132258. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132259. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132260. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132261. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132262. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132263. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132264. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132265. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132266. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132267. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132268. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132269. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132270. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132271. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132272. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132273. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132274. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132275. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132276. 10,10,10,10,10,10,10,10,10,
  132277. };
  132278. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132279. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132280. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132281. 6.5, 7.5, 8.5, 9.5,
  132282. };
  132283. static long _vq_quantmap__44c5_s_p9_2[] = {
  132284. 19, 17, 15, 13, 11, 9, 7, 5,
  132285. 3, 1, 0, 2, 4, 6, 8, 10,
  132286. 12, 14, 16, 18, 20,
  132287. };
  132288. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132289. _vq_quantthresh__44c5_s_p9_2,
  132290. _vq_quantmap__44c5_s_p9_2,
  132291. 21,
  132292. 21
  132293. };
  132294. static static_codebook _44c5_s_p9_2 = {
  132295. 2, 441,
  132296. _vq_lengthlist__44c5_s_p9_2,
  132297. 1, -529268736, 1611661312, 5, 0,
  132298. _vq_quantlist__44c5_s_p9_2,
  132299. NULL,
  132300. &_vq_auxt__44c5_s_p9_2,
  132301. NULL,
  132302. 0
  132303. };
  132304. static long _huff_lengthlist__44c5_s_short[] = {
  132305. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132306. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132307. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132308. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132309. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132310. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132311. 6, 8,11,16,
  132312. };
  132313. static static_codebook _huff_book__44c5_s_short = {
  132314. 2, 100,
  132315. _huff_lengthlist__44c5_s_short,
  132316. 0, 0, 0, 0, 0,
  132317. NULL,
  132318. NULL,
  132319. NULL,
  132320. NULL,
  132321. 0
  132322. };
  132323. static long _huff_lengthlist__44c6_s_long[] = {
  132324. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132325. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132326. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132327. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132328. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132329. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132330. 11,10,10,12,
  132331. };
  132332. static static_codebook _huff_book__44c6_s_long = {
  132333. 2, 100,
  132334. _huff_lengthlist__44c6_s_long,
  132335. 0, 0, 0, 0, 0,
  132336. NULL,
  132337. NULL,
  132338. NULL,
  132339. NULL,
  132340. 0
  132341. };
  132342. static long _vq_quantlist__44c6_s_p1_0[] = {
  132343. 1,
  132344. 0,
  132345. 2,
  132346. };
  132347. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132348. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132349. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132350. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132351. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132352. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132353. 8,
  132354. };
  132355. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132356. -0.5, 0.5,
  132357. };
  132358. static long _vq_quantmap__44c6_s_p1_0[] = {
  132359. 1, 0, 2,
  132360. };
  132361. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132362. _vq_quantthresh__44c6_s_p1_0,
  132363. _vq_quantmap__44c6_s_p1_0,
  132364. 3,
  132365. 3
  132366. };
  132367. static static_codebook _44c6_s_p1_0 = {
  132368. 4, 81,
  132369. _vq_lengthlist__44c6_s_p1_0,
  132370. 1, -535822336, 1611661312, 2, 0,
  132371. _vq_quantlist__44c6_s_p1_0,
  132372. NULL,
  132373. &_vq_auxt__44c6_s_p1_0,
  132374. NULL,
  132375. 0
  132376. };
  132377. static long _vq_quantlist__44c6_s_p2_0[] = {
  132378. 2,
  132379. 1,
  132380. 3,
  132381. 0,
  132382. 4,
  132383. };
  132384. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132385. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132386. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132387. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132388. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132389. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132390. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132391. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132392. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132395. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132396. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132397. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132398. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132399. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132400. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132402. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132403. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132404. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132405. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132406. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132407. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132408. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132410. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132411. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132412. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132413. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132414. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132415. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132416. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132421. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132422. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132423. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132424. 13,
  132425. };
  132426. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132427. -1.5, -0.5, 0.5, 1.5,
  132428. };
  132429. static long _vq_quantmap__44c6_s_p2_0[] = {
  132430. 3, 1, 0, 2, 4,
  132431. };
  132432. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132433. _vq_quantthresh__44c6_s_p2_0,
  132434. _vq_quantmap__44c6_s_p2_0,
  132435. 5,
  132436. 5
  132437. };
  132438. static static_codebook _44c6_s_p2_0 = {
  132439. 4, 625,
  132440. _vq_lengthlist__44c6_s_p2_0,
  132441. 1, -533725184, 1611661312, 3, 0,
  132442. _vq_quantlist__44c6_s_p2_0,
  132443. NULL,
  132444. &_vq_auxt__44c6_s_p2_0,
  132445. NULL,
  132446. 0
  132447. };
  132448. static long _vq_quantlist__44c6_s_p3_0[] = {
  132449. 4,
  132450. 3,
  132451. 5,
  132452. 2,
  132453. 6,
  132454. 1,
  132455. 7,
  132456. 0,
  132457. 8,
  132458. };
  132459. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132460. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132461. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132462. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132463. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0,
  132466. };
  132467. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132468. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132469. };
  132470. static long _vq_quantmap__44c6_s_p3_0[] = {
  132471. 7, 5, 3, 1, 0, 2, 4, 6,
  132472. 8,
  132473. };
  132474. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132475. _vq_quantthresh__44c6_s_p3_0,
  132476. _vq_quantmap__44c6_s_p3_0,
  132477. 9,
  132478. 9
  132479. };
  132480. static static_codebook _44c6_s_p3_0 = {
  132481. 2, 81,
  132482. _vq_lengthlist__44c6_s_p3_0,
  132483. 1, -531628032, 1611661312, 4, 0,
  132484. _vq_quantlist__44c6_s_p3_0,
  132485. NULL,
  132486. &_vq_auxt__44c6_s_p3_0,
  132487. NULL,
  132488. 0
  132489. };
  132490. static long _vq_quantlist__44c6_s_p4_0[] = {
  132491. 8,
  132492. 7,
  132493. 9,
  132494. 6,
  132495. 10,
  132496. 5,
  132497. 11,
  132498. 4,
  132499. 12,
  132500. 3,
  132501. 13,
  132502. 2,
  132503. 14,
  132504. 1,
  132505. 15,
  132506. 0,
  132507. 16,
  132508. };
  132509. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132510. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132511. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132512. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132513. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132514. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132515. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132516. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132517. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132518. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132519. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132528. 0,
  132529. };
  132530. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132531. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132532. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132533. };
  132534. static long _vq_quantmap__44c6_s_p4_0[] = {
  132535. 15, 13, 11, 9, 7, 5, 3, 1,
  132536. 0, 2, 4, 6, 8, 10, 12, 14,
  132537. 16,
  132538. };
  132539. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132540. _vq_quantthresh__44c6_s_p4_0,
  132541. _vq_quantmap__44c6_s_p4_0,
  132542. 17,
  132543. 17
  132544. };
  132545. static static_codebook _44c6_s_p4_0 = {
  132546. 2, 289,
  132547. _vq_lengthlist__44c6_s_p4_0,
  132548. 1, -529530880, 1611661312, 5, 0,
  132549. _vq_quantlist__44c6_s_p4_0,
  132550. NULL,
  132551. &_vq_auxt__44c6_s_p4_0,
  132552. NULL,
  132553. 0
  132554. };
  132555. static long _vq_quantlist__44c6_s_p5_0[] = {
  132556. 1,
  132557. 0,
  132558. 2,
  132559. };
  132560. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132561. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132562. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132563. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132564. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132565. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132566. 12,
  132567. };
  132568. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132569. -5.5, 5.5,
  132570. };
  132571. static long _vq_quantmap__44c6_s_p5_0[] = {
  132572. 1, 0, 2,
  132573. };
  132574. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132575. _vq_quantthresh__44c6_s_p5_0,
  132576. _vq_quantmap__44c6_s_p5_0,
  132577. 3,
  132578. 3
  132579. };
  132580. static static_codebook _44c6_s_p5_0 = {
  132581. 4, 81,
  132582. _vq_lengthlist__44c6_s_p5_0,
  132583. 1, -529137664, 1618345984, 2, 0,
  132584. _vq_quantlist__44c6_s_p5_0,
  132585. NULL,
  132586. &_vq_auxt__44c6_s_p5_0,
  132587. NULL,
  132588. 0
  132589. };
  132590. static long _vq_quantlist__44c6_s_p5_1[] = {
  132591. 5,
  132592. 4,
  132593. 6,
  132594. 3,
  132595. 7,
  132596. 2,
  132597. 8,
  132598. 1,
  132599. 9,
  132600. 0,
  132601. 10,
  132602. };
  132603. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132604. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132605. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132606. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132607. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132608. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132609. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132610. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132611. 11,10,10, 7, 7, 8, 8, 8, 8,
  132612. };
  132613. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132614. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132615. 3.5, 4.5,
  132616. };
  132617. static long _vq_quantmap__44c6_s_p5_1[] = {
  132618. 9, 7, 5, 3, 1, 0, 2, 4,
  132619. 6, 8, 10,
  132620. };
  132621. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132622. _vq_quantthresh__44c6_s_p5_1,
  132623. _vq_quantmap__44c6_s_p5_1,
  132624. 11,
  132625. 11
  132626. };
  132627. static static_codebook _44c6_s_p5_1 = {
  132628. 2, 121,
  132629. _vq_lengthlist__44c6_s_p5_1,
  132630. 1, -531365888, 1611661312, 4, 0,
  132631. _vq_quantlist__44c6_s_p5_1,
  132632. NULL,
  132633. &_vq_auxt__44c6_s_p5_1,
  132634. NULL,
  132635. 0
  132636. };
  132637. static long _vq_quantlist__44c6_s_p6_0[] = {
  132638. 6,
  132639. 5,
  132640. 7,
  132641. 4,
  132642. 8,
  132643. 3,
  132644. 9,
  132645. 2,
  132646. 10,
  132647. 1,
  132648. 11,
  132649. 0,
  132650. 12,
  132651. };
  132652. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132653. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132654. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132655. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132656. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132657. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132658. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132663. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132664. };
  132665. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132666. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132667. 12.5, 17.5, 22.5, 27.5,
  132668. };
  132669. static long _vq_quantmap__44c6_s_p6_0[] = {
  132670. 11, 9, 7, 5, 3, 1, 0, 2,
  132671. 4, 6, 8, 10, 12,
  132672. };
  132673. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132674. _vq_quantthresh__44c6_s_p6_0,
  132675. _vq_quantmap__44c6_s_p6_0,
  132676. 13,
  132677. 13
  132678. };
  132679. static static_codebook _44c6_s_p6_0 = {
  132680. 2, 169,
  132681. _vq_lengthlist__44c6_s_p6_0,
  132682. 1, -526516224, 1616117760, 4, 0,
  132683. _vq_quantlist__44c6_s_p6_0,
  132684. NULL,
  132685. &_vq_auxt__44c6_s_p6_0,
  132686. NULL,
  132687. 0
  132688. };
  132689. static long _vq_quantlist__44c6_s_p6_1[] = {
  132690. 2,
  132691. 1,
  132692. 3,
  132693. 0,
  132694. 4,
  132695. };
  132696. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132697. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132698. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132699. };
  132700. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132701. -1.5, -0.5, 0.5, 1.5,
  132702. };
  132703. static long _vq_quantmap__44c6_s_p6_1[] = {
  132704. 3, 1, 0, 2, 4,
  132705. };
  132706. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132707. _vq_quantthresh__44c6_s_p6_1,
  132708. _vq_quantmap__44c6_s_p6_1,
  132709. 5,
  132710. 5
  132711. };
  132712. static static_codebook _44c6_s_p6_1 = {
  132713. 2, 25,
  132714. _vq_lengthlist__44c6_s_p6_1,
  132715. 1, -533725184, 1611661312, 3, 0,
  132716. _vq_quantlist__44c6_s_p6_1,
  132717. NULL,
  132718. &_vq_auxt__44c6_s_p6_1,
  132719. NULL,
  132720. 0
  132721. };
  132722. static long _vq_quantlist__44c6_s_p7_0[] = {
  132723. 6,
  132724. 5,
  132725. 7,
  132726. 4,
  132727. 8,
  132728. 3,
  132729. 9,
  132730. 2,
  132731. 10,
  132732. 1,
  132733. 11,
  132734. 0,
  132735. 12,
  132736. };
  132737. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132738. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132739. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132740. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132741. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132742. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132743. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132744. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132745. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132746. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132747. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132748. 20,13,13,13,13,13,13,14,14,
  132749. };
  132750. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132751. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132752. 27.5, 38.5, 49.5, 60.5,
  132753. };
  132754. static long _vq_quantmap__44c6_s_p7_0[] = {
  132755. 11, 9, 7, 5, 3, 1, 0, 2,
  132756. 4, 6, 8, 10, 12,
  132757. };
  132758. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132759. _vq_quantthresh__44c6_s_p7_0,
  132760. _vq_quantmap__44c6_s_p7_0,
  132761. 13,
  132762. 13
  132763. };
  132764. static static_codebook _44c6_s_p7_0 = {
  132765. 2, 169,
  132766. _vq_lengthlist__44c6_s_p7_0,
  132767. 1, -523206656, 1618345984, 4, 0,
  132768. _vq_quantlist__44c6_s_p7_0,
  132769. NULL,
  132770. &_vq_auxt__44c6_s_p7_0,
  132771. NULL,
  132772. 0
  132773. };
  132774. static long _vq_quantlist__44c6_s_p7_1[] = {
  132775. 5,
  132776. 4,
  132777. 6,
  132778. 3,
  132779. 7,
  132780. 2,
  132781. 8,
  132782. 1,
  132783. 9,
  132784. 0,
  132785. 10,
  132786. };
  132787. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132788. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132789. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132790. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132791. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132792. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132793. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132794. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132795. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132796. };
  132797. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132798. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132799. 3.5, 4.5,
  132800. };
  132801. static long _vq_quantmap__44c6_s_p7_1[] = {
  132802. 9, 7, 5, 3, 1, 0, 2, 4,
  132803. 6, 8, 10,
  132804. };
  132805. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132806. _vq_quantthresh__44c6_s_p7_1,
  132807. _vq_quantmap__44c6_s_p7_1,
  132808. 11,
  132809. 11
  132810. };
  132811. static static_codebook _44c6_s_p7_1 = {
  132812. 2, 121,
  132813. _vq_lengthlist__44c6_s_p7_1,
  132814. 1, -531365888, 1611661312, 4, 0,
  132815. _vq_quantlist__44c6_s_p7_1,
  132816. NULL,
  132817. &_vq_auxt__44c6_s_p7_1,
  132818. NULL,
  132819. 0
  132820. };
  132821. static long _vq_quantlist__44c6_s_p8_0[] = {
  132822. 7,
  132823. 6,
  132824. 8,
  132825. 5,
  132826. 9,
  132827. 4,
  132828. 10,
  132829. 3,
  132830. 11,
  132831. 2,
  132832. 12,
  132833. 1,
  132834. 13,
  132835. 0,
  132836. 14,
  132837. };
  132838. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132839. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132840. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132841. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132842. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132843. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132844. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132845. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132846. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132847. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132848. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132849. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132850. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132851. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132852. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132853. 14,
  132854. };
  132855. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132856. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132857. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132858. };
  132859. static long _vq_quantmap__44c6_s_p8_0[] = {
  132860. 13, 11, 9, 7, 5, 3, 1, 0,
  132861. 2, 4, 6, 8, 10, 12, 14,
  132862. };
  132863. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132864. _vq_quantthresh__44c6_s_p8_0,
  132865. _vq_quantmap__44c6_s_p8_0,
  132866. 15,
  132867. 15
  132868. };
  132869. static static_codebook _44c6_s_p8_0 = {
  132870. 2, 225,
  132871. _vq_lengthlist__44c6_s_p8_0,
  132872. 1, -520986624, 1620377600, 4, 0,
  132873. _vq_quantlist__44c6_s_p8_0,
  132874. NULL,
  132875. &_vq_auxt__44c6_s_p8_0,
  132876. NULL,
  132877. 0
  132878. };
  132879. static long _vq_quantlist__44c6_s_p8_1[] = {
  132880. 10,
  132881. 9,
  132882. 11,
  132883. 8,
  132884. 12,
  132885. 7,
  132886. 13,
  132887. 6,
  132888. 14,
  132889. 5,
  132890. 15,
  132891. 4,
  132892. 16,
  132893. 3,
  132894. 17,
  132895. 2,
  132896. 18,
  132897. 1,
  132898. 19,
  132899. 0,
  132900. 20,
  132901. };
  132902. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132903. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132904. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132905. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132906. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132907. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132908. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132909. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132910. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132911. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132912. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132913. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132914. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132915. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132916. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132917. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132918. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132919. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132920. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132921. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132922. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132923. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132924. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132925. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132926. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132927. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132928. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132929. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132930. 10,10,10,10,10,10,10,10,10,
  132931. };
  132932. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132933. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132934. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132935. 6.5, 7.5, 8.5, 9.5,
  132936. };
  132937. static long _vq_quantmap__44c6_s_p8_1[] = {
  132938. 19, 17, 15, 13, 11, 9, 7, 5,
  132939. 3, 1, 0, 2, 4, 6, 8, 10,
  132940. 12, 14, 16, 18, 20,
  132941. };
  132942. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132943. _vq_quantthresh__44c6_s_p8_1,
  132944. _vq_quantmap__44c6_s_p8_1,
  132945. 21,
  132946. 21
  132947. };
  132948. static static_codebook _44c6_s_p8_1 = {
  132949. 2, 441,
  132950. _vq_lengthlist__44c6_s_p8_1,
  132951. 1, -529268736, 1611661312, 5, 0,
  132952. _vq_quantlist__44c6_s_p8_1,
  132953. NULL,
  132954. &_vq_auxt__44c6_s_p8_1,
  132955. NULL,
  132956. 0
  132957. };
  132958. static long _vq_quantlist__44c6_s_p9_0[] = {
  132959. 6,
  132960. 5,
  132961. 7,
  132962. 4,
  132963. 8,
  132964. 3,
  132965. 9,
  132966. 2,
  132967. 10,
  132968. 1,
  132969. 11,
  132970. 0,
  132971. 12,
  132972. };
  132973. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132974. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132975. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132977. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132980. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132981. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132982. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132983. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132984. 10,10,10,10,10,10,10,10,10,
  132985. };
  132986. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132987. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132988. 1592.5, 2229.5, 2866.5, 3503.5,
  132989. };
  132990. static long _vq_quantmap__44c6_s_p9_0[] = {
  132991. 11, 9, 7, 5, 3, 1, 0, 2,
  132992. 4, 6, 8, 10, 12,
  132993. };
  132994. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132995. _vq_quantthresh__44c6_s_p9_0,
  132996. _vq_quantmap__44c6_s_p9_0,
  132997. 13,
  132998. 13
  132999. };
  133000. static static_codebook _44c6_s_p9_0 = {
  133001. 2, 169,
  133002. _vq_lengthlist__44c6_s_p9_0,
  133003. 1, -511845376, 1630791680, 4, 0,
  133004. _vq_quantlist__44c6_s_p9_0,
  133005. NULL,
  133006. &_vq_auxt__44c6_s_p9_0,
  133007. NULL,
  133008. 0
  133009. };
  133010. static long _vq_quantlist__44c6_s_p9_1[] = {
  133011. 6,
  133012. 5,
  133013. 7,
  133014. 4,
  133015. 8,
  133016. 3,
  133017. 9,
  133018. 2,
  133019. 10,
  133020. 1,
  133021. 11,
  133022. 0,
  133023. 12,
  133024. };
  133025. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133026. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133027. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133028. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133029. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133030. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133031. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133032. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133033. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133034. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133035. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133036. 15,12,10,11,11,13,11,12,13,
  133037. };
  133038. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133039. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133040. 122.5, 171.5, 220.5, 269.5,
  133041. };
  133042. static long _vq_quantmap__44c6_s_p9_1[] = {
  133043. 11, 9, 7, 5, 3, 1, 0, 2,
  133044. 4, 6, 8, 10, 12,
  133045. };
  133046. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133047. _vq_quantthresh__44c6_s_p9_1,
  133048. _vq_quantmap__44c6_s_p9_1,
  133049. 13,
  133050. 13
  133051. };
  133052. static static_codebook _44c6_s_p9_1 = {
  133053. 2, 169,
  133054. _vq_lengthlist__44c6_s_p9_1,
  133055. 1, -518889472, 1622704128, 4, 0,
  133056. _vq_quantlist__44c6_s_p9_1,
  133057. NULL,
  133058. &_vq_auxt__44c6_s_p9_1,
  133059. NULL,
  133060. 0
  133061. };
  133062. static long _vq_quantlist__44c6_s_p9_2[] = {
  133063. 24,
  133064. 23,
  133065. 25,
  133066. 22,
  133067. 26,
  133068. 21,
  133069. 27,
  133070. 20,
  133071. 28,
  133072. 19,
  133073. 29,
  133074. 18,
  133075. 30,
  133076. 17,
  133077. 31,
  133078. 16,
  133079. 32,
  133080. 15,
  133081. 33,
  133082. 14,
  133083. 34,
  133084. 13,
  133085. 35,
  133086. 12,
  133087. 36,
  133088. 11,
  133089. 37,
  133090. 10,
  133091. 38,
  133092. 9,
  133093. 39,
  133094. 8,
  133095. 40,
  133096. 7,
  133097. 41,
  133098. 6,
  133099. 42,
  133100. 5,
  133101. 43,
  133102. 4,
  133103. 44,
  133104. 3,
  133105. 45,
  133106. 2,
  133107. 46,
  133108. 1,
  133109. 47,
  133110. 0,
  133111. 48,
  133112. };
  133113. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133114. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133115. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133116. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133117. 7,
  133118. };
  133119. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133120. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133121. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133122. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133123. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133124. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133125. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133126. };
  133127. static long _vq_quantmap__44c6_s_p9_2[] = {
  133128. 47, 45, 43, 41, 39, 37, 35, 33,
  133129. 31, 29, 27, 25, 23, 21, 19, 17,
  133130. 15, 13, 11, 9, 7, 5, 3, 1,
  133131. 0, 2, 4, 6, 8, 10, 12, 14,
  133132. 16, 18, 20, 22, 24, 26, 28, 30,
  133133. 32, 34, 36, 38, 40, 42, 44, 46,
  133134. 48,
  133135. };
  133136. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133137. _vq_quantthresh__44c6_s_p9_2,
  133138. _vq_quantmap__44c6_s_p9_2,
  133139. 49,
  133140. 49
  133141. };
  133142. static static_codebook _44c6_s_p9_2 = {
  133143. 1, 49,
  133144. _vq_lengthlist__44c6_s_p9_2,
  133145. 1, -526909440, 1611661312, 6, 0,
  133146. _vq_quantlist__44c6_s_p9_2,
  133147. NULL,
  133148. &_vq_auxt__44c6_s_p9_2,
  133149. NULL,
  133150. 0
  133151. };
  133152. static long _huff_lengthlist__44c6_s_short[] = {
  133153. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133154. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133155. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133156. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133157. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133158. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133159. 9,10,17,18,
  133160. };
  133161. static static_codebook _huff_book__44c6_s_short = {
  133162. 2, 100,
  133163. _huff_lengthlist__44c6_s_short,
  133164. 0, 0, 0, 0, 0,
  133165. NULL,
  133166. NULL,
  133167. NULL,
  133168. NULL,
  133169. 0
  133170. };
  133171. static long _huff_lengthlist__44c7_s_long[] = {
  133172. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133173. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133174. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133175. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133176. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133177. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133178. 11,10,10,12,
  133179. };
  133180. static static_codebook _huff_book__44c7_s_long = {
  133181. 2, 100,
  133182. _huff_lengthlist__44c7_s_long,
  133183. 0, 0, 0, 0, 0,
  133184. NULL,
  133185. NULL,
  133186. NULL,
  133187. NULL,
  133188. 0
  133189. };
  133190. static long _vq_quantlist__44c7_s_p1_0[] = {
  133191. 1,
  133192. 0,
  133193. 2,
  133194. };
  133195. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133196. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133197. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133198. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133199. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133200. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133201. 8,
  133202. };
  133203. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133204. -0.5, 0.5,
  133205. };
  133206. static long _vq_quantmap__44c7_s_p1_0[] = {
  133207. 1, 0, 2,
  133208. };
  133209. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133210. _vq_quantthresh__44c7_s_p1_0,
  133211. _vq_quantmap__44c7_s_p1_0,
  133212. 3,
  133213. 3
  133214. };
  133215. static static_codebook _44c7_s_p1_0 = {
  133216. 4, 81,
  133217. _vq_lengthlist__44c7_s_p1_0,
  133218. 1, -535822336, 1611661312, 2, 0,
  133219. _vq_quantlist__44c7_s_p1_0,
  133220. NULL,
  133221. &_vq_auxt__44c7_s_p1_0,
  133222. NULL,
  133223. 0
  133224. };
  133225. static long _vq_quantlist__44c7_s_p2_0[] = {
  133226. 2,
  133227. 1,
  133228. 3,
  133229. 0,
  133230. 4,
  133231. };
  133232. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133233. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133234. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133235. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133236. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133237. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133238. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133239. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133240. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133243. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133244. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133245. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133246. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133247. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133248. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133251. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133252. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133253. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133254. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133255. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133256. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133258. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133259. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133260. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133261. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133262. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133263. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133264. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133269. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133270. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133271. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133272. 13,
  133273. };
  133274. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133275. -1.5, -0.5, 0.5, 1.5,
  133276. };
  133277. static long _vq_quantmap__44c7_s_p2_0[] = {
  133278. 3, 1, 0, 2, 4,
  133279. };
  133280. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133281. _vq_quantthresh__44c7_s_p2_0,
  133282. _vq_quantmap__44c7_s_p2_0,
  133283. 5,
  133284. 5
  133285. };
  133286. static static_codebook _44c7_s_p2_0 = {
  133287. 4, 625,
  133288. _vq_lengthlist__44c7_s_p2_0,
  133289. 1, -533725184, 1611661312, 3, 0,
  133290. _vq_quantlist__44c7_s_p2_0,
  133291. NULL,
  133292. &_vq_auxt__44c7_s_p2_0,
  133293. NULL,
  133294. 0
  133295. };
  133296. static long _vq_quantlist__44c7_s_p3_0[] = {
  133297. 4,
  133298. 3,
  133299. 5,
  133300. 2,
  133301. 6,
  133302. 1,
  133303. 7,
  133304. 0,
  133305. 8,
  133306. };
  133307. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133308. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133309. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133310. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133311. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0,
  133314. };
  133315. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133317. };
  133318. static long _vq_quantmap__44c7_s_p3_0[] = {
  133319. 7, 5, 3, 1, 0, 2, 4, 6,
  133320. 8,
  133321. };
  133322. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133323. _vq_quantthresh__44c7_s_p3_0,
  133324. _vq_quantmap__44c7_s_p3_0,
  133325. 9,
  133326. 9
  133327. };
  133328. static static_codebook _44c7_s_p3_0 = {
  133329. 2, 81,
  133330. _vq_lengthlist__44c7_s_p3_0,
  133331. 1, -531628032, 1611661312, 4, 0,
  133332. _vq_quantlist__44c7_s_p3_0,
  133333. NULL,
  133334. &_vq_auxt__44c7_s_p3_0,
  133335. NULL,
  133336. 0
  133337. };
  133338. static long _vq_quantlist__44c7_s_p4_0[] = {
  133339. 8,
  133340. 7,
  133341. 9,
  133342. 6,
  133343. 10,
  133344. 5,
  133345. 11,
  133346. 4,
  133347. 12,
  133348. 3,
  133349. 13,
  133350. 2,
  133351. 14,
  133352. 1,
  133353. 15,
  133354. 0,
  133355. 16,
  133356. };
  133357. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133358. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133359. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133360. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133361. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133362. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133363. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133364. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133365. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133366. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133367. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133376. 0,
  133377. };
  133378. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133379. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133380. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133381. };
  133382. static long _vq_quantmap__44c7_s_p4_0[] = {
  133383. 15, 13, 11, 9, 7, 5, 3, 1,
  133384. 0, 2, 4, 6, 8, 10, 12, 14,
  133385. 16,
  133386. };
  133387. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133388. _vq_quantthresh__44c7_s_p4_0,
  133389. _vq_quantmap__44c7_s_p4_0,
  133390. 17,
  133391. 17
  133392. };
  133393. static static_codebook _44c7_s_p4_0 = {
  133394. 2, 289,
  133395. _vq_lengthlist__44c7_s_p4_0,
  133396. 1, -529530880, 1611661312, 5, 0,
  133397. _vq_quantlist__44c7_s_p4_0,
  133398. NULL,
  133399. &_vq_auxt__44c7_s_p4_0,
  133400. NULL,
  133401. 0
  133402. };
  133403. static long _vq_quantlist__44c7_s_p5_0[] = {
  133404. 1,
  133405. 0,
  133406. 2,
  133407. };
  133408. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133409. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133410. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133411. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133412. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133413. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133414. 12,
  133415. };
  133416. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133417. -5.5, 5.5,
  133418. };
  133419. static long _vq_quantmap__44c7_s_p5_0[] = {
  133420. 1, 0, 2,
  133421. };
  133422. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133423. _vq_quantthresh__44c7_s_p5_0,
  133424. _vq_quantmap__44c7_s_p5_0,
  133425. 3,
  133426. 3
  133427. };
  133428. static static_codebook _44c7_s_p5_0 = {
  133429. 4, 81,
  133430. _vq_lengthlist__44c7_s_p5_0,
  133431. 1, -529137664, 1618345984, 2, 0,
  133432. _vq_quantlist__44c7_s_p5_0,
  133433. NULL,
  133434. &_vq_auxt__44c7_s_p5_0,
  133435. NULL,
  133436. 0
  133437. };
  133438. static long _vq_quantlist__44c7_s_p5_1[] = {
  133439. 5,
  133440. 4,
  133441. 6,
  133442. 3,
  133443. 7,
  133444. 2,
  133445. 8,
  133446. 1,
  133447. 9,
  133448. 0,
  133449. 10,
  133450. };
  133451. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133452. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133453. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133454. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133455. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133456. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133457. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133458. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133459. 11,11,11, 7, 7, 8, 8, 8, 8,
  133460. };
  133461. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133462. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133463. 3.5, 4.5,
  133464. };
  133465. static long _vq_quantmap__44c7_s_p5_1[] = {
  133466. 9, 7, 5, 3, 1, 0, 2, 4,
  133467. 6, 8, 10,
  133468. };
  133469. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133470. _vq_quantthresh__44c7_s_p5_1,
  133471. _vq_quantmap__44c7_s_p5_1,
  133472. 11,
  133473. 11
  133474. };
  133475. static static_codebook _44c7_s_p5_1 = {
  133476. 2, 121,
  133477. _vq_lengthlist__44c7_s_p5_1,
  133478. 1, -531365888, 1611661312, 4, 0,
  133479. _vq_quantlist__44c7_s_p5_1,
  133480. NULL,
  133481. &_vq_auxt__44c7_s_p5_1,
  133482. NULL,
  133483. 0
  133484. };
  133485. static long _vq_quantlist__44c7_s_p6_0[] = {
  133486. 6,
  133487. 5,
  133488. 7,
  133489. 4,
  133490. 8,
  133491. 3,
  133492. 9,
  133493. 2,
  133494. 10,
  133495. 1,
  133496. 11,
  133497. 0,
  133498. 12,
  133499. };
  133500. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133501. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133502. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133503. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133504. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133505. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133506. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133511. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133512. };
  133513. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133514. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133515. 12.5, 17.5, 22.5, 27.5,
  133516. };
  133517. static long _vq_quantmap__44c7_s_p6_0[] = {
  133518. 11, 9, 7, 5, 3, 1, 0, 2,
  133519. 4, 6, 8, 10, 12,
  133520. };
  133521. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133522. _vq_quantthresh__44c7_s_p6_0,
  133523. _vq_quantmap__44c7_s_p6_0,
  133524. 13,
  133525. 13
  133526. };
  133527. static static_codebook _44c7_s_p6_0 = {
  133528. 2, 169,
  133529. _vq_lengthlist__44c7_s_p6_0,
  133530. 1, -526516224, 1616117760, 4, 0,
  133531. _vq_quantlist__44c7_s_p6_0,
  133532. NULL,
  133533. &_vq_auxt__44c7_s_p6_0,
  133534. NULL,
  133535. 0
  133536. };
  133537. static long _vq_quantlist__44c7_s_p6_1[] = {
  133538. 2,
  133539. 1,
  133540. 3,
  133541. 0,
  133542. 4,
  133543. };
  133544. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133545. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133546. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133547. };
  133548. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133549. -1.5, -0.5, 0.5, 1.5,
  133550. };
  133551. static long _vq_quantmap__44c7_s_p6_1[] = {
  133552. 3, 1, 0, 2, 4,
  133553. };
  133554. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133555. _vq_quantthresh__44c7_s_p6_1,
  133556. _vq_quantmap__44c7_s_p6_1,
  133557. 5,
  133558. 5
  133559. };
  133560. static static_codebook _44c7_s_p6_1 = {
  133561. 2, 25,
  133562. _vq_lengthlist__44c7_s_p6_1,
  133563. 1, -533725184, 1611661312, 3, 0,
  133564. _vq_quantlist__44c7_s_p6_1,
  133565. NULL,
  133566. &_vq_auxt__44c7_s_p6_1,
  133567. NULL,
  133568. 0
  133569. };
  133570. static long _vq_quantlist__44c7_s_p7_0[] = {
  133571. 6,
  133572. 5,
  133573. 7,
  133574. 4,
  133575. 8,
  133576. 3,
  133577. 9,
  133578. 2,
  133579. 10,
  133580. 1,
  133581. 11,
  133582. 0,
  133583. 12,
  133584. };
  133585. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133586. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133587. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133588. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133589. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133590. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133591. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133592. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133593. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133594. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133595. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133596. 19,13,13,13,13,14,14,15,15,
  133597. };
  133598. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133599. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133600. 27.5, 38.5, 49.5, 60.5,
  133601. };
  133602. static long _vq_quantmap__44c7_s_p7_0[] = {
  133603. 11, 9, 7, 5, 3, 1, 0, 2,
  133604. 4, 6, 8, 10, 12,
  133605. };
  133606. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133607. _vq_quantthresh__44c7_s_p7_0,
  133608. _vq_quantmap__44c7_s_p7_0,
  133609. 13,
  133610. 13
  133611. };
  133612. static static_codebook _44c7_s_p7_0 = {
  133613. 2, 169,
  133614. _vq_lengthlist__44c7_s_p7_0,
  133615. 1, -523206656, 1618345984, 4, 0,
  133616. _vq_quantlist__44c7_s_p7_0,
  133617. NULL,
  133618. &_vq_auxt__44c7_s_p7_0,
  133619. NULL,
  133620. 0
  133621. };
  133622. static long _vq_quantlist__44c7_s_p7_1[] = {
  133623. 5,
  133624. 4,
  133625. 6,
  133626. 3,
  133627. 7,
  133628. 2,
  133629. 8,
  133630. 1,
  133631. 9,
  133632. 0,
  133633. 10,
  133634. };
  133635. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133636. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133637. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133638. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133639. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133640. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133641. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133642. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133643. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133644. };
  133645. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133646. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133647. 3.5, 4.5,
  133648. };
  133649. static long _vq_quantmap__44c7_s_p7_1[] = {
  133650. 9, 7, 5, 3, 1, 0, 2, 4,
  133651. 6, 8, 10,
  133652. };
  133653. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133654. _vq_quantthresh__44c7_s_p7_1,
  133655. _vq_quantmap__44c7_s_p7_1,
  133656. 11,
  133657. 11
  133658. };
  133659. static static_codebook _44c7_s_p7_1 = {
  133660. 2, 121,
  133661. _vq_lengthlist__44c7_s_p7_1,
  133662. 1, -531365888, 1611661312, 4, 0,
  133663. _vq_quantlist__44c7_s_p7_1,
  133664. NULL,
  133665. &_vq_auxt__44c7_s_p7_1,
  133666. NULL,
  133667. 0
  133668. };
  133669. static long _vq_quantlist__44c7_s_p8_0[] = {
  133670. 7,
  133671. 6,
  133672. 8,
  133673. 5,
  133674. 9,
  133675. 4,
  133676. 10,
  133677. 3,
  133678. 11,
  133679. 2,
  133680. 12,
  133681. 1,
  133682. 13,
  133683. 0,
  133684. 14,
  133685. };
  133686. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133687. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133688. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133689. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133690. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133691. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133692. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133693. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133694. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133695. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133696. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133697. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133698. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133699. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133700. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133701. 14,
  133702. };
  133703. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133704. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133705. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133706. };
  133707. static long _vq_quantmap__44c7_s_p8_0[] = {
  133708. 13, 11, 9, 7, 5, 3, 1, 0,
  133709. 2, 4, 6, 8, 10, 12, 14,
  133710. };
  133711. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133712. _vq_quantthresh__44c7_s_p8_0,
  133713. _vq_quantmap__44c7_s_p8_0,
  133714. 15,
  133715. 15
  133716. };
  133717. static static_codebook _44c7_s_p8_0 = {
  133718. 2, 225,
  133719. _vq_lengthlist__44c7_s_p8_0,
  133720. 1, -520986624, 1620377600, 4, 0,
  133721. _vq_quantlist__44c7_s_p8_0,
  133722. NULL,
  133723. &_vq_auxt__44c7_s_p8_0,
  133724. NULL,
  133725. 0
  133726. };
  133727. static long _vq_quantlist__44c7_s_p8_1[] = {
  133728. 10,
  133729. 9,
  133730. 11,
  133731. 8,
  133732. 12,
  133733. 7,
  133734. 13,
  133735. 6,
  133736. 14,
  133737. 5,
  133738. 15,
  133739. 4,
  133740. 16,
  133741. 3,
  133742. 17,
  133743. 2,
  133744. 18,
  133745. 1,
  133746. 19,
  133747. 0,
  133748. 20,
  133749. };
  133750. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133751. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133752. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133753. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133754. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133755. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133756. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133757. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133758. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133759. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133760. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133761. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133762. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133763. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133764. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133765. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133766. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133767. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133768. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133769. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133770. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133771. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133772. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133773. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133774. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133775. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133776. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133777. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133778. 10,10,10,10,10,10,10,10,10,
  133779. };
  133780. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133781. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133782. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133783. 6.5, 7.5, 8.5, 9.5,
  133784. };
  133785. static long _vq_quantmap__44c7_s_p8_1[] = {
  133786. 19, 17, 15, 13, 11, 9, 7, 5,
  133787. 3, 1, 0, 2, 4, 6, 8, 10,
  133788. 12, 14, 16, 18, 20,
  133789. };
  133790. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133791. _vq_quantthresh__44c7_s_p8_1,
  133792. _vq_quantmap__44c7_s_p8_1,
  133793. 21,
  133794. 21
  133795. };
  133796. static static_codebook _44c7_s_p8_1 = {
  133797. 2, 441,
  133798. _vq_lengthlist__44c7_s_p8_1,
  133799. 1, -529268736, 1611661312, 5, 0,
  133800. _vq_quantlist__44c7_s_p8_1,
  133801. NULL,
  133802. &_vq_auxt__44c7_s_p8_1,
  133803. NULL,
  133804. 0
  133805. };
  133806. static long _vq_quantlist__44c7_s_p9_0[] = {
  133807. 6,
  133808. 5,
  133809. 7,
  133810. 4,
  133811. 8,
  133812. 3,
  133813. 9,
  133814. 2,
  133815. 10,
  133816. 1,
  133817. 11,
  133818. 0,
  133819. 12,
  133820. };
  133821. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133822. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133823. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133832. 11,11,11,11,11,11,11,11,11,
  133833. };
  133834. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133835. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133836. 1592.5, 2229.5, 2866.5, 3503.5,
  133837. };
  133838. static long _vq_quantmap__44c7_s_p9_0[] = {
  133839. 11, 9, 7, 5, 3, 1, 0, 2,
  133840. 4, 6, 8, 10, 12,
  133841. };
  133842. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133843. _vq_quantthresh__44c7_s_p9_0,
  133844. _vq_quantmap__44c7_s_p9_0,
  133845. 13,
  133846. 13
  133847. };
  133848. static static_codebook _44c7_s_p9_0 = {
  133849. 2, 169,
  133850. _vq_lengthlist__44c7_s_p9_0,
  133851. 1, -511845376, 1630791680, 4, 0,
  133852. _vq_quantlist__44c7_s_p9_0,
  133853. NULL,
  133854. &_vq_auxt__44c7_s_p9_0,
  133855. NULL,
  133856. 0
  133857. };
  133858. static long _vq_quantlist__44c7_s_p9_1[] = {
  133859. 6,
  133860. 5,
  133861. 7,
  133862. 4,
  133863. 8,
  133864. 3,
  133865. 9,
  133866. 2,
  133867. 10,
  133868. 1,
  133869. 11,
  133870. 0,
  133871. 12,
  133872. };
  133873. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133874. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133875. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133876. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133877. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133878. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133879. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133880. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133881. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133882. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133883. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133884. 15,11,11,10,10,12,12,12,12,
  133885. };
  133886. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133887. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133888. 122.5, 171.5, 220.5, 269.5,
  133889. };
  133890. static long _vq_quantmap__44c7_s_p9_1[] = {
  133891. 11, 9, 7, 5, 3, 1, 0, 2,
  133892. 4, 6, 8, 10, 12,
  133893. };
  133894. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133895. _vq_quantthresh__44c7_s_p9_1,
  133896. _vq_quantmap__44c7_s_p9_1,
  133897. 13,
  133898. 13
  133899. };
  133900. static static_codebook _44c7_s_p9_1 = {
  133901. 2, 169,
  133902. _vq_lengthlist__44c7_s_p9_1,
  133903. 1, -518889472, 1622704128, 4, 0,
  133904. _vq_quantlist__44c7_s_p9_1,
  133905. NULL,
  133906. &_vq_auxt__44c7_s_p9_1,
  133907. NULL,
  133908. 0
  133909. };
  133910. static long _vq_quantlist__44c7_s_p9_2[] = {
  133911. 24,
  133912. 23,
  133913. 25,
  133914. 22,
  133915. 26,
  133916. 21,
  133917. 27,
  133918. 20,
  133919. 28,
  133920. 19,
  133921. 29,
  133922. 18,
  133923. 30,
  133924. 17,
  133925. 31,
  133926. 16,
  133927. 32,
  133928. 15,
  133929. 33,
  133930. 14,
  133931. 34,
  133932. 13,
  133933. 35,
  133934. 12,
  133935. 36,
  133936. 11,
  133937. 37,
  133938. 10,
  133939. 38,
  133940. 9,
  133941. 39,
  133942. 8,
  133943. 40,
  133944. 7,
  133945. 41,
  133946. 6,
  133947. 42,
  133948. 5,
  133949. 43,
  133950. 4,
  133951. 44,
  133952. 3,
  133953. 45,
  133954. 2,
  133955. 46,
  133956. 1,
  133957. 47,
  133958. 0,
  133959. 48,
  133960. };
  133961. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133962. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133963. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133964. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133965. 7,
  133966. };
  133967. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133968. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133969. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133970. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133971. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133972. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133973. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133974. };
  133975. static long _vq_quantmap__44c7_s_p9_2[] = {
  133976. 47, 45, 43, 41, 39, 37, 35, 33,
  133977. 31, 29, 27, 25, 23, 21, 19, 17,
  133978. 15, 13, 11, 9, 7, 5, 3, 1,
  133979. 0, 2, 4, 6, 8, 10, 12, 14,
  133980. 16, 18, 20, 22, 24, 26, 28, 30,
  133981. 32, 34, 36, 38, 40, 42, 44, 46,
  133982. 48,
  133983. };
  133984. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133985. _vq_quantthresh__44c7_s_p9_2,
  133986. _vq_quantmap__44c7_s_p9_2,
  133987. 49,
  133988. 49
  133989. };
  133990. static static_codebook _44c7_s_p9_2 = {
  133991. 1, 49,
  133992. _vq_lengthlist__44c7_s_p9_2,
  133993. 1, -526909440, 1611661312, 6, 0,
  133994. _vq_quantlist__44c7_s_p9_2,
  133995. NULL,
  133996. &_vq_auxt__44c7_s_p9_2,
  133997. NULL,
  133998. 0
  133999. };
  134000. static long _huff_lengthlist__44c7_s_short[] = {
  134001. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134002. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134003. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134004. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134005. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134006. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134007. 10, 9,11,14,
  134008. };
  134009. static static_codebook _huff_book__44c7_s_short = {
  134010. 2, 100,
  134011. _huff_lengthlist__44c7_s_short,
  134012. 0, 0, 0, 0, 0,
  134013. NULL,
  134014. NULL,
  134015. NULL,
  134016. NULL,
  134017. 0
  134018. };
  134019. static long _huff_lengthlist__44c8_s_long[] = {
  134020. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134021. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134022. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134023. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134024. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134025. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134026. 11, 9, 9,10,
  134027. };
  134028. static static_codebook _huff_book__44c8_s_long = {
  134029. 2, 100,
  134030. _huff_lengthlist__44c8_s_long,
  134031. 0, 0, 0, 0, 0,
  134032. NULL,
  134033. NULL,
  134034. NULL,
  134035. NULL,
  134036. 0
  134037. };
  134038. static long _vq_quantlist__44c8_s_p1_0[] = {
  134039. 1,
  134040. 0,
  134041. 2,
  134042. };
  134043. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134044. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134045. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134047. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134048. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134049. 8,
  134050. };
  134051. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134052. -0.5, 0.5,
  134053. };
  134054. static long _vq_quantmap__44c8_s_p1_0[] = {
  134055. 1, 0, 2,
  134056. };
  134057. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134058. _vq_quantthresh__44c8_s_p1_0,
  134059. _vq_quantmap__44c8_s_p1_0,
  134060. 3,
  134061. 3
  134062. };
  134063. static static_codebook _44c8_s_p1_0 = {
  134064. 4, 81,
  134065. _vq_lengthlist__44c8_s_p1_0,
  134066. 1, -535822336, 1611661312, 2, 0,
  134067. _vq_quantlist__44c8_s_p1_0,
  134068. NULL,
  134069. &_vq_auxt__44c8_s_p1_0,
  134070. NULL,
  134071. 0
  134072. };
  134073. static long _vq_quantlist__44c8_s_p2_0[] = {
  134074. 2,
  134075. 1,
  134076. 3,
  134077. 0,
  134078. 4,
  134079. };
  134080. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134081. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134082. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134083. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134084. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134085. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134086. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134087. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134088. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134091. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134092. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134093. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134094. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134095. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134096. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134099. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134100. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134101. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134102. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134103. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134104. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134107. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134108. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134109. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134110. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134111. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134112. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134117. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134118. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134119. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134120. 13,
  134121. };
  134122. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134123. -1.5, -0.5, 0.5, 1.5,
  134124. };
  134125. static long _vq_quantmap__44c8_s_p2_0[] = {
  134126. 3, 1, 0, 2, 4,
  134127. };
  134128. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134129. _vq_quantthresh__44c8_s_p2_0,
  134130. _vq_quantmap__44c8_s_p2_0,
  134131. 5,
  134132. 5
  134133. };
  134134. static static_codebook _44c8_s_p2_0 = {
  134135. 4, 625,
  134136. _vq_lengthlist__44c8_s_p2_0,
  134137. 1, -533725184, 1611661312, 3, 0,
  134138. _vq_quantlist__44c8_s_p2_0,
  134139. NULL,
  134140. &_vq_auxt__44c8_s_p2_0,
  134141. NULL,
  134142. 0
  134143. };
  134144. static long _vq_quantlist__44c8_s_p3_0[] = {
  134145. 4,
  134146. 3,
  134147. 5,
  134148. 2,
  134149. 6,
  134150. 1,
  134151. 7,
  134152. 0,
  134153. 8,
  134154. };
  134155. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134156. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134157. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134158. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134159. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0,
  134162. };
  134163. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134164. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134165. };
  134166. static long _vq_quantmap__44c8_s_p3_0[] = {
  134167. 7, 5, 3, 1, 0, 2, 4, 6,
  134168. 8,
  134169. };
  134170. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134171. _vq_quantthresh__44c8_s_p3_0,
  134172. _vq_quantmap__44c8_s_p3_0,
  134173. 9,
  134174. 9
  134175. };
  134176. static static_codebook _44c8_s_p3_0 = {
  134177. 2, 81,
  134178. _vq_lengthlist__44c8_s_p3_0,
  134179. 1, -531628032, 1611661312, 4, 0,
  134180. _vq_quantlist__44c8_s_p3_0,
  134181. NULL,
  134182. &_vq_auxt__44c8_s_p3_0,
  134183. NULL,
  134184. 0
  134185. };
  134186. static long _vq_quantlist__44c8_s_p4_0[] = {
  134187. 8,
  134188. 7,
  134189. 9,
  134190. 6,
  134191. 10,
  134192. 5,
  134193. 11,
  134194. 4,
  134195. 12,
  134196. 3,
  134197. 13,
  134198. 2,
  134199. 14,
  134200. 1,
  134201. 15,
  134202. 0,
  134203. 16,
  134204. };
  134205. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134206. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134207. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134208. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134209. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134210. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134211. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134212. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134213. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134214. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134215. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134224. 0,
  134225. };
  134226. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134227. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134228. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134229. };
  134230. static long _vq_quantmap__44c8_s_p4_0[] = {
  134231. 15, 13, 11, 9, 7, 5, 3, 1,
  134232. 0, 2, 4, 6, 8, 10, 12, 14,
  134233. 16,
  134234. };
  134235. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134236. _vq_quantthresh__44c8_s_p4_0,
  134237. _vq_quantmap__44c8_s_p4_0,
  134238. 17,
  134239. 17
  134240. };
  134241. static static_codebook _44c8_s_p4_0 = {
  134242. 2, 289,
  134243. _vq_lengthlist__44c8_s_p4_0,
  134244. 1, -529530880, 1611661312, 5, 0,
  134245. _vq_quantlist__44c8_s_p4_0,
  134246. NULL,
  134247. &_vq_auxt__44c8_s_p4_0,
  134248. NULL,
  134249. 0
  134250. };
  134251. static long _vq_quantlist__44c8_s_p5_0[] = {
  134252. 1,
  134253. 0,
  134254. 2,
  134255. };
  134256. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134257. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134258. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134259. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134260. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134261. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134262. 12,
  134263. };
  134264. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134265. -5.5, 5.5,
  134266. };
  134267. static long _vq_quantmap__44c8_s_p5_0[] = {
  134268. 1, 0, 2,
  134269. };
  134270. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134271. _vq_quantthresh__44c8_s_p5_0,
  134272. _vq_quantmap__44c8_s_p5_0,
  134273. 3,
  134274. 3
  134275. };
  134276. static static_codebook _44c8_s_p5_0 = {
  134277. 4, 81,
  134278. _vq_lengthlist__44c8_s_p5_0,
  134279. 1, -529137664, 1618345984, 2, 0,
  134280. _vq_quantlist__44c8_s_p5_0,
  134281. NULL,
  134282. &_vq_auxt__44c8_s_p5_0,
  134283. NULL,
  134284. 0
  134285. };
  134286. static long _vq_quantlist__44c8_s_p5_1[] = {
  134287. 5,
  134288. 4,
  134289. 6,
  134290. 3,
  134291. 7,
  134292. 2,
  134293. 8,
  134294. 1,
  134295. 9,
  134296. 0,
  134297. 10,
  134298. };
  134299. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134300. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134301. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134302. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134303. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134304. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134305. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134306. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134307. 11,11,11, 7, 7, 7, 7, 8, 8,
  134308. };
  134309. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134310. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134311. 3.5, 4.5,
  134312. };
  134313. static long _vq_quantmap__44c8_s_p5_1[] = {
  134314. 9, 7, 5, 3, 1, 0, 2, 4,
  134315. 6, 8, 10,
  134316. };
  134317. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134318. _vq_quantthresh__44c8_s_p5_1,
  134319. _vq_quantmap__44c8_s_p5_1,
  134320. 11,
  134321. 11
  134322. };
  134323. static static_codebook _44c8_s_p5_1 = {
  134324. 2, 121,
  134325. _vq_lengthlist__44c8_s_p5_1,
  134326. 1, -531365888, 1611661312, 4, 0,
  134327. _vq_quantlist__44c8_s_p5_1,
  134328. NULL,
  134329. &_vq_auxt__44c8_s_p5_1,
  134330. NULL,
  134331. 0
  134332. };
  134333. static long _vq_quantlist__44c8_s_p6_0[] = {
  134334. 6,
  134335. 5,
  134336. 7,
  134337. 4,
  134338. 8,
  134339. 3,
  134340. 9,
  134341. 2,
  134342. 10,
  134343. 1,
  134344. 11,
  134345. 0,
  134346. 12,
  134347. };
  134348. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134349. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134350. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134351. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134352. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134353. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134354. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. };
  134361. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134362. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134363. 12.5, 17.5, 22.5, 27.5,
  134364. };
  134365. static long _vq_quantmap__44c8_s_p6_0[] = {
  134366. 11, 9, 7, 5, 3, 1, 0, 2,
  134367. 4, 6, 8, 10, 12,
  134368. };
  134369. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134370. _vq_quantthresh__44c8_s_p6_0,
  134371. _vq_quantmap__44c8_s_p6_0,
  134372. 13,
  134373. 13
  134374. };
  134375. static static_codebook _44c8_s_p6_0 = {
  134376. 2, 169,
  134377. _vq_lengthlist__44c8_s_p6_0,
  134378. 1, -526516224, 1616117760, 4, 0,
  134379. _vq_quantlist__44c8_s_p6_0,
  134380. NULL,
  134381. &_vq_auxt__44c8_s_p6_0,
  134382. NULL,
  134383. 0
  134384. };
  134385. static long _vq_quantlist__44c8_s_p6_1[] = {
  134386. 2,
  134387. 1,
  134388. 3,
  134389. 0,
  134390. 4,
  134391. };
  134392. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134393. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134394. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134395. };
  134396. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134397. -1.5, -0.5, 0.5, 1.5,
  134398. };
  134399. static long _vq_quantmap__44c8_s_p6_1[] = {
  134400. 3, 1, 0, 2, 4,
  134401. };
  134402. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134403. _vq_quantthresh__44c8_s_p6_1,
  134404. _vq_quantmap__44c8_s_p6_1,
  134405. 5,
  134406. 5
  134407. };
  134408. static static_codebook _44c8_s_p6_1 = {
  134409. 2, 25,
  134410. _vq_lengthlist__44c8_s_p6_1,
  134411. 1, -533725184, 1611661312, 3, 0,
  134412. _vq_quantlist__44c8_s_p6_1,
  134413. NULL,
  134414. &_vq_auxt__44c8_s_p6_1,
  134415. NULL,
  134416. 0
  134417. };
  134418. static long _vq_quantlist__44c8_s_p7_0[] = {
  134419. 6,
  134420. 5,
  134421. 7,
  134422. 4,
  134423. 8,
  134424. 3,
  134425. 9,
  134426. 2,
  134427. 10,
  134428. 1,
  134429. 11,
  134430. 0,
  134431. 12,
  134432. };
  134433. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134434. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134435. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134436. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134437. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134438. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134439. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134440. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134441. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134442. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134443. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134444. 20,13,13,13,13,14,13,15,15,
  134445. };
  134446. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134447. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134448. 27.5, 38.5, 49.5, 60.5,
  134449. };
  134450. static long _vq_quantmap__44c8_s_p7_0[] = {
  134451. 11, 9, 7, 5, 3, 1, 0, 2,
  134452. 4, 6, 8, 10, 12,
  134453. };
  134454. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134455. _vq_quantthresh__44c8_s_p7_0,
  134456. _vq_quantmap__44c8_s_p7_0,
  134457. 13,
  134458. 13
  134459. };
  134460. static static_codebook _44c8_s_p7_0 = {
  134461. 2, 169,
  134462. _vq_lengthlist__44c8_s_p7_0,
  134463. 1, -523206656, 1618345984, 4, 0,
  134464. _vq_quantlist__44c8_s_p7_0,
  134465. NULL,
  134466. &_vq_auxt__44c8_s_p7_0,
  134467. NULL,
  134468. 0
  134469. };
  134470. static long _vq_quantlist__44c8_s_p7_1[] = {
  134471. 5,
  134472. 4,
  134473. 6,
  134474. 3,
  134475. 7,
  134476. 2,
  134477. 8,
  134478. 1,
  134479. 9,
  134480. 0,
  134481. 10,
  134482. };
  134483. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134484. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134485. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134486. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134487. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134488. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134489. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134490. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134491. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134492. };
  134493. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134494. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134495. 3.5, 4.5,
  134496. };
  134497. static long _vq_quantmap__44c8_s_p7_1[] = {
  134498. 9, 7, 5, 3, 1, 0, 2, 4,
  134499. 6, 8, 10,
  134500. };
  134501. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134502. _vq_quantthresh__44c8_s_p7_1,
  134503. _vq_quantmap__44c8_s_p7_1,
  134504. 11,
  134505. 11
  134506. };
  134507. static static_codebook _44c8_s_p7_1 = {
  134508. 2, 121,
  134509. _vq_lengthlist__44c8_s_p7_1,
  134510. 1, -531365888, 1611661312, 4, 0,
  134511. _vq_quantlist__44c8_s_p7_1,
  134512. NULL,
  134513. &_vq_auxt__44c8_s_p7_1,
  134514. NULL,
  134515. 0
  134516. };
  134517. static long _vq_quantlist__44c8_s_p8_0[] = {
  134518. 7,
  134519. 6,
  134520. 8,
  134521. 5,
  134522. 9,
  134523. 4,
  134524. 10,
  134525. 3,
  134526. 11,
  134527. 2,
  134528. 12,
  134529. 1,
  134530. 13,
  134531. 0,
  134532. 14,
  134533. };
  134534. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134535. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134536. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134537. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134538. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134539. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134540. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134541. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134542. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134543. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134544. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134545. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134546. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134547. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134548. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134549. 15,
  134550. };
  134551. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134552. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134553. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134554. };
  134555. static long _vq_quantmap__44c8_s_p8_0[] = {
  134556. 13, 11, 9, 7, 5, 3, 1, 0,
  134557. 2, 4, 6, 8, 10, 12, 14,
  134558. };
  134559. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134560. _vq_quantthresh__44c8_s_p8_0,
  134561. _vq_quantmap__44c8_s_p8_0,
  134562. 15,
  134563. 15
  134564. };
  134565. static static_codebook _44c8_s_p8_0 = {
  134566. 2, 225,
  134567. _vq_lengthlist__44c8_s_p8_0,
  134568. 1, -520986624, 1620377600, 4, 0,
  134569. _vq_quantlist__44c8_s_p8_0,
  134570. NULL,
  134571. &_vq_auxt__44c8_s_p8_0,
  134572. NULL,
  134573. 0
  134574. };
  134575. static long _vq_quantlist__44c8_s_p8_1[] = {
  134576. 10,
  134577. 9,
  134578. 11,
  134579. 8,
  134580. 12,
  134581. 7,
  134582. 13,
  134583. 6,
  134584. 14,
  134585. 5,
  134586. 15,
  134587. 4,
  134588. 16,
  134589. 3,
  134590. 17,
  134591. 2,
  134592. 18,
  134593. 1,
  134594. 19,
  134595. 0,
  134596. 20,
  134597. };
  134598. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134599. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134600. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134602. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134603. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134604. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134605. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134606. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134607. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134608. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134609. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134610. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134611. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134612. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134613. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134614. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134615. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134616. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134617. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134618. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134619. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134621. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134622. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134623. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134624. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134625. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134626. 10, 9, 9,10,10, 9,10, 9, 9,
  134627. };
  134628. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134629. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134630. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134631. 6.5, 7.5, 8.5, 9.5,
  134632. };
  134633. static long _vq_quantmap__44c8_s_p8_1[] = {
  134634. 19, 17, 15, 13, 11, 9, 7, 5,
  134635. 3, 1, 0, 2, 4, 6, 8, 10,
  134636. 12, 14, 16, 18, 20,
  134637. };
  134638. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134639. _vq_quantthresh__44c8_s_p8_1,
  134640. _vq_quantmap__44c8_s_p8_1,
  134641. 21,
  134642. 21
  134643. };
  134644. static static_codebook _44c8_s_p8_1 = {
  134645. 2, 441,
  134646. _vq_lengthlist__44c8_s_p8_1,
  134647. 1, -529268736, 1611661312, 5, 0,
  134648. _vq_quantlist__44c8_s_p8_1,
  134649. NULL,
  134650. &_vq_auxt__44c8_s_p8_1,
  134651. NULL,
  134652. 0
  134653. };
  134654. static long _vq_quantlist__44c8_s_p9_0[] = {
  134655. 8,
  134656. 7,
  134657. 9,
  134658. 6,
  134659. 10,
  134660. 5,
  134661. 11,
  134662. 4,
  134663. 12,
  134664. 3,
  134665. 13,
  134666. 2,
  134667. 14,
  134668. 1,
  134669. 15,
  134670. 0,
  134671. 16,
  134672. };
  134673. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134674. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134675. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134676. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134688. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134692. 10,
  134693. };
  134694. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134695. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134696. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134697. };
  134698. static long _vq_quantmap__44c8_s_p9_0[] = {
  134699. 15, 13, 11, 9, 7, 5, 3, 1,
  134700. 0, 2, 4, 6, 8, 10, 12, 14,
  134701. 16,
  134702. };
  134703. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134704. _vq_quantthresh__44c8_s_p9_0,
  134705. _vq_quantmap__44c8_s_p9_0,
  134706. 17,
  134707. 17
  134708. };
  134709. static static_codebook _44c8_s_p9_0 = {
  134710. 2, 289,
  134711. _vq_lengthlist__44c8_s_p9_0,
  134712. 1, -509798400, 1631393792, 5, 0,
  134713. _vq_quantlist__44c8_s_p9_0,
  134714. NULL,
  134715. &_vq_auxt__44c8_s_p9_0,
  134716. NULL,
  134717. 0
  134718. };
  134719. static long _vq_quantlist__44c8_s_p9_1[] = {
  134720. 9,
  134721. 8,
  134722. 10,
  134723. 7,
  134724. 11,
  134725. 6,
  134726. 12,
  134727. 5,
  134728. 13,
  134729. 4,
  134730. 14,
  134731. 3,
  134732. 15,
  134733. 2,
  134734. 16,
  134735. 1,
  134736. 17,
  134737. 0,
  134738. 18,
  134739. };
  134740. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134741. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134742. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134743. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134744. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134745. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134746. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134747. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134748. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134749. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134750. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134751. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134752. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134753. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134754. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134755. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134756. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134757. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134758. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134759. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134760. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134761. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134762. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134763. 14,13,13,14,14,15,14,15,14,
  134764. };
  134765. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134766. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134767. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134768. 367.5, 416.5,
  134769. };
  134770. static long _vq_quantmap__44c8_s_p9_1[] = {
  134771. 17, 15, 13, 11, 9, 7, 5, 3,
  134772. 1, 0, 2, 4, 6, 8, 10, 12,
  134773. 14, 16, 18,
  134774. };
  134775. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134776. _vq_quantthresh__44c8_s_p9_1,
  134777. _vq_quantmap__44c8_s_p9_1,
  134778. 19,
  134779. 19
  134780. };
  134781. static static_codebook _44c8_s_p9_1 = {
  134782. 2, 361,
  134783. _vq_lengthlist__44c8_s_p9_1,
  134784. 1, -518287360, 1622704128, 5, 0,
  134785. _vq_quantlist__44c8_s_p9_1,
  134786. NULL,
  134787. &_vq_auxt__44c8_s_p9_1,
  134788. NULL,
  134789. 0
  134790. };
  134791. static long _vq_quantlist__44c8_s_p9_2[] = {
  134792. 24,
  134793. 23,
  134794. 25,
  134795. 22,
  134796. 26,
  134797. 21,
  134798. 27,
  134799. 20,
  134800. 28,
  134801. 19,
  134802. 29,
  134803. 18,
  134804. 30,
  134805. 17,
  134806. 31,
  134807. 16,
  134808. 32,
  134809. 15,
  134810. 33,
  134811. 14,
  134812. 34,
  134813. 13,
  134814. 35,
  134815. 12,
  134816. 36,
  134817. 11,
  134818. 37,
  134819. 10,
  134820. 38,
  134821. 9,
  134822. 39,
  134823. 8,
  134824. 40,
  134825. 7,
  134826. 41,
  134827. 6,
  134828. 42,
  134829. 5,
  134830. 43,
  134831. 4,
  134832. 44,
  134833. 3,
  134834. 45,
  134835. 2,
  134836. 46,
  134837. 1,
  134838. 47,
  134839. 0,
  134840. 48,
  134841. };
  134842. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134843. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134844. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134845. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134846. 7,
  134847. };
  134848. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134849. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134850. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134851. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134852. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134853. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134854. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134855. };
  134856. static long _vq_quantmap__44c8_s_p9_2[] = {
  134857. 47, 45, 43, 41, 39, 37, 35, 33,
  134858. 31, 29, 27, 25, 23, 21, 19, 17,
  134859. 15, 13, 11, 9, 7, 5, 3, 1,
  134860. 0, 2, 4, 6, 8, 10, 12, 14,
  134861. 16, 18, 20, 22, 24, 26, 28, 30,
  134862. 32, 34, 36, 38, 40, 42, 44, 46,
  134863. 48,
  134864. };
  134865. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134866. _vq_quantthresh__44c8_s_p9_2,
  134867. _vq_quantmap__44c8_s_p9_2,
  134868. 49,
  134869. 49
  134870. };
  134871. static static_codebook _44c8_s_p9_2 = {
  134872. 1, 49,
  134873. _vq_lengthlist__44c8_s_p9_2,
  134874. 1, -526909440, 1611661312, 6, 0,
  134875. _vq_quantlist__44c8_s_p9_2,
  134876. NULL,
  134877. &_vq_auxt__44c8_s_p9_2,
  134878. NULL,
  134879. 0
  134880. };
  134881. static long _huff_lengthlist__44c8_s_short[] = {
  134882. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134883. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134884. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134885. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134886. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134887. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134888. 10, 9,11,14,
  134889. };
  134890. static static_codebook _huff_book__44c8_s_short = {
  134891. 2, 100,
  134892. _huff_lengthlist__44c8_s_short,
  134893. 0, 0, 0, 0, 0,
  134894. NULL,
  134895. NULL,
  134896. NULL,
  134897. NULL,
  134898. 0
  134899. };
  134900. static long _huff_lengthlist__44c9_s_long[] = {
  134901. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134902. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134903. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134904. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134905. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134906. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134907. 10, 9, 8, 9,
  134908. };
  134909. static static_codebook _huff_book__44c9_s_long = {
  134910. 2, 100,
  134911. _huff_lengthlist__44c9_s_long,
  134912. 0, 0, 0, 0, 0,
  134913. NULL,
  134914. NULL,
  134915. NULL,
  134916. NULL,
  134917. 0
  134918. };
  134919. static long _vq_quantlist__44c9_s_p1_0[] = {
  134920. 1,
  134921. 0,
  134922. 2,
  134923. };
  134924. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134925. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134926. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134928. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134929. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134930. 7,
  134931. };
  134932. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134933. -0.5, 0.5,
  134934. };
  134935. static long _vq_quantmap__44c9_s_p1_0[] = {
  134936. 1, 0, 2,
  134937. };
  134938. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134939. _vq_quantthresh__44c9_s_p1_0,
  134940. _vq_quantmap__44c9_s_p1_0,
  134941. 3,
  134942. 3
  134943. };
  134944. static static_codebook _44c9_s_p1_0 = {
  134945. 4, 81,
  134946. _vq_lengthlist__44c9_s_p1_0,
  134947. 1, -535822336, 1611661312, 2, 0,
  134948. _vq_quantlist__44c9_s_p1_0,
  134949. NULL,
  134950. &_vq_auxt__44c9_s_p1_0,
  134951. NULL,
  134952. 0
  134953. };
  134954. static long _vq_quantlist__44c9_s_p2_0[] = {
  134955. 2,
  134956. 1,
  134957. 3,
  134958. 0,
  134959. 4,
  134960. };
  134961. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134962. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134963. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134964. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134965. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134966. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134967. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134968. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134969. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134972. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134973. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134974. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134975. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134976. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134977. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134980. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134981. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134982. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134983. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134984. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134985. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134988. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134989. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134990. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134991. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134992. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134993. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134998. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134999. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135000. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135001. 12,
  135002. };
  135003. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135004. -1.5, -0.5, 0.5, 1.5,
  135005. };
  135006. static long _vq_quantmap__44c9_s_p2_0[] = {
  135007. 3, 1, 0, 2, 4,
  135008. };
  135009. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135010. _vq_quantthresh__44c9_s_p2_0,
  135011. _vq_quantmap__44c9_s_p2_0,
  135012. 5,
  135013. 5
  135014. };
  135015. static static_codebook _44c9_s_p2_0 = {
  135016. 4, 625,
  135017. _vq_lengthlist__44c9_s_p2_0,
  135018. 1, -533725184, 1611661312, 3, 0,
  135019. _vq_quantlist__44c9_s_p2_0,
  135020. NULL,
  135021. &_vq_auxt__44c9_s_p2_0,
  135022. NULL,
  135023. 0
  135024. };
  135025. static long _vq_quantlist__44c9_s_p3_0[] = {
  135026. 4,
  135027. 3,
  135028. 5,
  135029. 2,
  135030. 6,
  135031. 1,
  135032. 7,
  135033. 0,
  135034. 8,
  135035. };
  135036. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135037. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135038. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135039. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135040. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0,
  135043. };
  135044. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135045. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135046. };
  135047. static long _vq_quantmap__44c9_s_p3_0[] = {
  135048. 7, 5, 3, 1, 0, 2, 4, 6,
  135049. 8,
  135050. };
  135051. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135052. _vq_quantthresh__44c9_s_p3_0,
  135053. _vq_quantmap__44c9_s_p3_0,
  135054. 9,
  135055. 9
  135056. };
  135057. static static_codebook _44c9_s_p3_0 = {
  135058. 2, 81,
  135059. _vq_lengthlist__44c9_s_p3_0,
  135060. 1, -531628032, 1611661312, 4, 0,
  135061. _vq_quantlist__44c9_s_p3_0,
  135062. NULL,
  135063. &_vq_auxt__44c9_s_p3_0,
  135064. NULL,
  135065. 0
  135066. };
  135067. static long _vq_quantlist__44c9_s_p4_0[] = {
  135068. 8,
  135069. 7,
  135070. 9,
  135071. 6,
  135072. 10,
  135073. 5,
  135074. 11,
  135075. 4,
  135076. 12,
  135077. 3,
  135078. 13,
  135079. 2,
  135080. 14,
  135081. 1,
  135082. 15,
  135083. 0,
  135084. 16,
  135085. };
  135086. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135087. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135088. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135089. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135090. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135091. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135092. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135093. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135094. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135095. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135096. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0,
  135106. };
  135107. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135108. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135109. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135110. };
  135111. static long _vq_quantmap__44c9_s_p4_0[] = {
  135112. 15, 13, 11, 9, 7, 5, 3, 1,
  135113. 0, 2, 4, 6, 8, 10, 12, 14,
  135114. 16,
  135115. };
  135116. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135117. _vq_quantthresh__44c9_s_p4_0,
  135118. _vq_quantmap__44c9_s_p4_0,
  135119. 17,
  135120. 17
  135121. };
  135122. static static_codebook _44c9_s_p4_0 = {
  135123. 2, 289,
  135124. _vq_lengthlist__44c9_s_p4_0,
  135125. 1, -529530880, 1611661312, 5, 0,
  135126. _vq_quantlist__44c9_s_p4_0,
  135127. NULL,
  135128. &_vq_auxt__44c9_s_p4_0,
  135129. NULL,
  135130. 0
  135131. };
  135132. static long _vq_quantlist__44c9_s_p5_0[] = {
  135133. 1,
  135134. 0,
  135135. 2,
  135136. };
  135137. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135138. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135139. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135140. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135141. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135142. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135143. 12,
  135144. };
  135145. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135146. -5.5, 5.5,
  135147. };
  135148. static long _vq_quantmap__44c9_s_p5_0[] = {
  135149. 1, 0, 2,
  135150. };
  135151. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135152. _vq_quantthresh__44c9_s_p5_0,
  135153. _vq_quantmap__44c9_s_p5_0,
  135154. 3,
  135155. 3
  135156. };
  135157. static static_codebook _44c9_s_p5_0 = {
  135158. 4, 81,
  135159. _vq_lengthlist__44c9_s_p5_0,
  135160. 1, -529137664, 1618345984, 2, 0,
  135161. _vq_quantlist__44c9_s_p5_0,
  135162. NULL,
  135163. &_vq_auxt__44c9_s_p5_0,
  135164. NULL,
  135165. 0
  135166. };
  135167. static long _vq_quantlist__44c9_s_p5_1[] = {
  135168. 5,
  135169. 4,
  135170. 6,
  135171. 3,
  135172. 7,
  135173. 2,
  135174. 8,
  135175. 1,
  135176. 9,
  135177. 0,
  135178. 10,
  135179. };
  135180. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135181. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135182. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135183. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135184. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135185. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135186. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135187. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135188. 11,11,11, 7, 7, 7, 7, 7, 7,
  135189. };
  135190. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135191. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135192. 3.5, 4.5,
  135193. };
  135194. static long _vq_quantmap__44c9_s_p5_1[] = {
  135195. 9, 7, 5, 3, 1, 0, 2, 4,
  135196. 6, 8, 10,
  135197. };
  135198. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135199. _vq_quantthresh__44c9_s_p5_1,
  135200. _vq_quantmap__44c9_s_p5_1,
  135201. 11,
  135202. 11
  135203. };
  135204. static static_codebook _44c9_s_p5_1 = {
  135205. 2, 121,
  135206. _vq_lengthlist__44c9_s_p5_1,
  135207. 1, -531365888, 1611661312, 4, 0,
  135208. _vq_quantlist__44c9_s_p5_1,
  135209. NULL,
  135210. &_vq_auxt__44c9_s_p5_1,
  135211. NULL,
  135212. 0
  135213. };
  135214. static long _vq_quantlist__44c9_s_p6_0[] = {
  135215. 6,
  135216. 5,
  135217. 7,
  135218. 4,
  135219. 8,
  135220. 3,
  135221. 9,
  135222. 2,
  135223. 10,
  135224. 1,
  135225. 11,
  135226. 0,
  135227. 12,
  135228. };
  135229. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135230. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135231. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135232. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135233. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135234. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135235. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. };
  135242. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135243. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135244. 12.5, 17.5, 22.5, 27.5,
  135245. };
  135246. static long _vq_quantmap__44c9_s_p6_0[] = {
  135247. 11, 9, 7, 5, 3, 1, 0, 2,
  135248. 4, 6, 8, 10, 12,
  135249. };
  135250. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135251. _vq_quantthresh__44c9_s_p6_0,
  135252. _vq_quantmap__44c9_s_p6_0,
  135253. 13,
  135254. 13
  135255. };
  135256. static static_codebook _44c9_s_p6_0 = {
  135257. 2, 169,
  135258. _vq_lengthlist__44c9_s_p6_0,
  135259. 1, -526516224, 1616117760, 4, 0,
  135260. _vq_quantlist__44c9_s_p6_0,
  135261. NULL,
  135262. &_vq_auxt__44c9_s_p6_0,
  135263. NULL,
  135264. 0
  135265. };
  135266. static long _vq_quantlist__44c9_s_p6_1[] = {
  135267. 2,
  135268. 1,
  135269. 3,
  135270. 0,
  135271. 4,
  135272. };
  135273. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135274. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135275. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135276. };
  135277. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135278. -1.5, -0.5, 0.5, 1.5,
  135279. };
  135280. static long _vq_quantmap__44c9_s_p6_1[] = {
  135281. 3, 1, 0, 2, 4,
  135282. };
  135283. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135284. _vq_quantthresh__44c9_s_p6_1,
  135285. _vq_quantmap__44c9_s_p6_1,
  135286. 5,
  135287. 5
  135288. };
  135289. static static_codebook _44c9_s_p6_1 = {
  135290. 2, 25,
  135291. _vq_lengthlist__44c9_s_p6_1,
  135292. 1, -533725184, 1611661312, 3, 0,
  135293. _vq_quantlist__44c9_s_p6_1,
  135294. NULL,
  135295. &_vq_auxt__44c9_s_p6_1,
  135296. NULL,
  135297. 0
  135298. };
  135299. static long _vq_quantlist__44c9_s_p7_0[] = {
  135300. 6,
  135301. 5,
  135302. 7,
  135303. 4,
  135304. 8,
  135305. 3,
  135306. 9,
  135307. 2,
  135308. 10,
  135309. 1,
  135310. 11,
  135311. 0,
  135312. 12,
  135313. };
  135314. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135315. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135316. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135317. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135318. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135319. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135320. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135321. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135322. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135323. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135324. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135325. 19,12,12,12,12,13,13,14,14,
  135326. };
  135327. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135328. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135329. 27.5, 38.5, 49.5, 60.5,
  135330. };
  135331. static long _vq_quantmap__44c9_s_p7_0[] = {
  135332. 11, 9, 7, 5, 3, 1, 0, 2,
  135333. 4, 6, 8, 10, 12,
  135334. };
  135335. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135336. _vq_quantthresh__44c9_s_p7_0,
  135337. _vq_quantmap__44c9_s_p7_0,
  135338. 13,
  135339. 13
  135340. };
  135341. static static_codebook _44c9_s_p7_0 = {
  135342. 2, 169,
  135343. _vq_lengthlist__44c9_s_p7_0,
  135344. 1, -523206656, 1618345984, 4, 0,
  135345. _vq_quantlist__44c9_s_p7_0,
  135346. NULL,
  135347. &_vq_auxt__44c9_s_p7_0,
  135348. NULL,
  135349. 0
  135350. };
  135351. static long _vq_quantlist__44c9_s_p7_1[] = {
  135352. 5,
  135353. 4,
  135354. 6,
  135355. 3,
  135356. 7,
  135357. 2,
  135358. 8,
  135359. 1,
  135360. 9,
  135361. 0,
  135362. 10,
  135363. };
  135364. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135365. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135366. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135367. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135368. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135369. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135370. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135371. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135372. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135373. };
  135374. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135375. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135376. 3.5, 4.5,
  135377. };
  135378. static long _vq_quantmap__44c9_s_p7_1[] = {
  135379. 9, 7, 5, 3, 1, 0, 2, 4,
  135380. 6, 8, 10,
  135381. };
  135382. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135383. _vq_quantthresh__44c9_s_p7_1,
  135384. _vq_quantmap__44c9_s_p7_1,
  135385. 11,
  135386. 11
  135387. };
  135388. static static_codebook _44c9_s_p7_1 = {
  135389. 2, 121,
  135390. _vq_lengthlist__44c9_s_p7_1,
  135391. 1, -531365888, 1611661312, 4, 0,
  135392. _vq_quantlist__44c9_s_p7_1,
  135393. NULL,
  135394. &_vq_auxt__44c9_s_p7_1,
  135395. NULL,
  135396. 0
  135397. };
  135398. static long _vq_quantlist__44c9_s_p8_0[] = {
  135399. 7,
  135400. 6,
  135401. 8,
  135402. 5,
  135403. 9,
  135404. 4,
  135405. 10,
  135406. 3,
  135407. 11,
  135408. 2,
  135409. 12,
  135410. 1,
  135411. 13,
  135412. 0,
  135413. 14,
  135414. };
  135415. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135416. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135417. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135418. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135419. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135420. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135421. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135422. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135423. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135424. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135425. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135426. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135427. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135428. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135429. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135430. 14,
  135431. };
  135432. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135433. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135434. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135435. };
  135436. static long _vq_quantmap__44c9_s_p8_0[] = {
  135437. 13, 11, 9, 7, 5, 3, 1, 0,
  135438. 2, 4, 6, 8, 10, 12, 14,
  135439. };
  135440. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135441. _vq_quantthresh__44c9_s_p8_0,
  135442. _vq_quantmap__44c9_s_p8_0,
  135443. 15,
  135444. 15
  135445. };
  135446. static static_codebook _44c9_s_p8_0 = {
  135447. 2, 225,
  135448. _vq_lengthlist__44c9_s_p8_0,
  135449. 1, -520986624, 1620377600, 4, 0,
  135450. _vq_quantlist__44c9_s_p8_0,
  135451. NULL,
  135452. &_vq_auxt__44c9_s_p8_0,
  135453. NULL,
  135454. 0
  135455. };
  135456. static long _vq_quantlist__44c9_s_p8_1[] = {
  135457. 10,
  135458. 9,
  135459. 11,
  135460. 8,
  135461. 12,
  135462. 7,
  135463. 13,
  135464. 6,
  135465. 14,
  135466. 5,
  135467. 15,
  135468. 4,
  135469. 16,
  135470. 3,
  135471. 17,
  135472. 2,
  135473. 18,
  135474. 1,
  135475. 19,
  135476. 0,
  135477. 20,
  135478. };
  135479. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135480. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135481. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135482. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135483. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135484. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135485. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135486. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135487. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135488. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135489. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135490. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135491. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135492. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135493. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135494. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135495. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135496. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135497. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135498. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135499. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135500. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135501. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135502. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135503. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135504. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135505. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135506. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135507. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135508. };
  135509. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135510. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135511. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135512. 6.5, 7.5, 8.5, 9.5,
  135513. };
  135514. static long _vq_quantmap__44c9_s_p8_1[] = {
  135515. 19, 17, 15, 13, 11, 9, 7, 5,
  135516. 3, 1, 0, 2, 4, 6, 8, 10,
  135517. 12, 14, 16, 18, 20,
  135518. };
  135519. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135520. _vq_quantthresh__44c9_s_p8_1,
  135521. _vq_quantmap__44c9_s_p8_1,
  135522. 21,
  135523. 21
  135524. };
  135525. static static_codebook _44c9_s_p8_1 = {
  135526. 2, 441,
  135527. _vq_lengthlist__44c9_s_p8_1,
  135528. 1, -529268736, 1611661312, 5, 0,
  135529. _vq_quantlist__44c9_s_p8_1,
  135530. NULL,
  135531. &_vq_auxt__44c9_s_p8_1,
  135532. NULL,
  135533. 0
  135534. };
  135535. static long _vq_quantlist__44c9_s_p9_0[] = {
  135536. 9,
  135537. 8,
  135538. 10,
  135539. 7,
  135540. 11,
  135541. 6,
  135542. 12,
  135543. 5,
  135544. 13,
  135545. 4,
  135546. 14,
  135547. 3,
  135548. 15,
  135549. 2,
  135550. 16,
  135551. 1,
  135552. 17,
  135553. 0,
  135554. 18,
  135555. };
  135556. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135557. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135558. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135559. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135560. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135561. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135562. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135563. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135564. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135565. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135566. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135567. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135568. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135569. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135570. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135571. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135572. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135573. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135579. 11,11,11,11,11,11,11,11,11,
  135580. };
  135581. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135582. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135583. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135584. 6982.5, 7913.5,
  135585. };
  135586. static long _vq_quantmap__44c9_s_p9_0[] = {
  135587. 17, 15, 13, 11, 9, 7, 5, 3,
  135588. 1, 0, 2, 4, 6, 8, 10, 12,
  135589. 14, 16, 18,
  135590. };
  135591. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135592. _vq_quantthresh__44c9_s_p9_0,
  135593. _vq_quantmap__44c9_s_p9_0,
  135594. 19,
  135595. 19
  135596. };
  135597. static static_codebook _44c9_s_p9_0 = {
  135598. 2, 361,
  135599. _vq_lengthlist__44c9_s_p9_0,
  135600. 1, -508535424, 1631393792, 5, 0,
  135601. _vq_quantlist__44c9_s_p9_0,
  135602. NULL,
  135603. &_vq_auxt__44c9_s_p9_0,
  135604. NULL,
  135605. 0
  135606. };
  135607. static long _vq_quantlist__44c9_s_p9_1[] = {
  135608. 9,
  135609. 8,
  135610. 10,
  135611. 7,
  135612. 11,
  135613. 6,
  135614. 12,
  135615. 5,
  135616. 13,
  135617. 4,
  135618. 14,
  135619. 3,
  135620. 15,
  135621. 2,
  135622. 16,
  135623. 1,
  135624. 17,
  135625. 0,
  135626. 18,
  135627. };
  135628. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135629. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135630. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135631. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135632. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135633. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135634. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135635. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135636. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135637. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135638. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135639. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135640. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135641. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135642. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135643. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135644. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135645. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135646. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135647. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135648. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135649. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135650. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135651. 13,13,13,14,13,14,15,15,15,
  135652. };
  135653. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135654. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135655. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135656. 367.5, 416.5,
  135657. };
  135658. static long _vq_quantmap__44c9_s_p9_1[] = {
  135659. 17, 15, 13, 11, 9, 7, 5, 3,
  135660. 1, 0, 2, 4, 6, 8, 10, 12,
  135661. 14, 16, 18,
  135662. };
  135663. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135664. _vq_quantthresh__44c9_s_p9_1,
  135665. _vq_quantmap__44c9_s_p9_1,
  135666. 19,
  135667. 19
  135668. };
  135669. static static_codebook _44c9_s_p9_1 = {
  135670. 2, 361,
  135671. _vq_lengthlist__44c9_s_p9_1,
  135672. 1, -518287360, 1622704128, 5, 0,
  135673. _vq_quantlist__44c9_s_p9_1,
  135674. NULL,
  135675. &_vq_auxt__44c9_s_p9_1,
  135676. NULL,
  135677. 0
  135678. };
  135679. static long _vq_quantlist__44c9_s_p9_2[] = {
  135680. 24,
  135681. 23,
  135682. 25,
  135683. 22,
  135684. 26,
  135685. 21,
  135686. 27,
  135687. 20,
  135688. 28,
  135689. 19,
  135690. 29,
  135691. 18,
  135692. 30,
  135693. 17,
  135694. 31,
  135695. 16,
  135696. 32,
  135697. 15,
  135698. 33,
  135699. 14,
  135700. 34,
  135701. 13,
  135702. 35,
  135703. 12,
  135704. 36,
  135705. 11,
  135706. 37,
  135707. 10,
  135708. 38,
  135709. 9,
  135710. 39,
  135711. 8,
  135712. 40,
  135713. 7,
  135714. 41,
  135715. 6,
  135716. 42,
  135717. 5,
  135718. 43,
  135719. 4,
  135720. 44,
  135721. 3,
  135722. 45,
  135723. 2,
  135724. 46,
  135725. 1,
  135726. 47,
  135727. 0,
  135728. 48,
  135729. };
  135730. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135731. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135732. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135733. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135734. 7,
  135735. };
  135736. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135737. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135738. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135739. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135740. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135741. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135742. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135743. };
  135744. static long _vq_quantmap__44c9_s_p9_2[] = {
  135745. 47, 45, 43, 41, 39, 37, 35, 33,
  135746. 31, 29, 27, 25, 23, 21, 19, 17,
  135747. 15, 13, 11, 9, 7, 5, 3, 1,
  135748. 0, 2, 4, 6, 8, 10, 12, 14,
  135749. 16, 18, 20, 22, 24, 26, 28, 30,
  135750. 32, 34, 36, 38, 40, 42, 44, 46,
  135751. 48,
  135752. };
  135753. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135754. _vq_quantthresh__44c9_s_p9_2,
  135755. _vq_quantmap__44c9_s_p9_2,
  135756. 49,
  135757. 49
  135758. };
  135759. static static_codebook _44c9_s_p9_2 = {
  135760. 1, 49,
  135761. _vq_lengthlist__44c9_s_p9_2,
  135762. 1, -526909440, 1611661312, 6, 0,
  135763. _vq_quantlist__44c9_s_p9_2,
  135764. NULL,
  135765. &_vq_auxt__44c9_s_p9_2,
  135766. NULL,
  135767. 0
  135768. };
  135769. static long _huff_lengthlist__44c9_s_short[] = {
  135770. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135771. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135772. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135773. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135774. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135775. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135776. 9, 8,10,13,
  135777. };
  135778. static static_codebook _huff_book__44c9_s_short = {
  135779. 2, 100,
  135780. _huff_lengthlist__44c9_s_short,
  135781. 0, 0, 0, 0, 0,
  135782. NULL,
  135783. NULL,
  135784. NULL,
  135785. NULL,
  135786. 0
  135787. };
  135788. static long _huff_lengthlist__44c0_s_long[] = {
  135789. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135790. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135791. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135792. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135793. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135794. 12,
  135795. };
  135796. static static_codebook _huff_book__44c0_s_long = {
  135797. 2, 81,
  135798. _huff_lengthlist__44c0_s_long,
  135799. 0, 0, 0, 0, 0,
  135800. NULL,
  135801. NULL,
  135802. NULL,
  135803. NULL,
  135804. 0
  135805. };
  135806. static long _vq_quantlist__44c0_s_p1_0[] = {
  135807. 1,
  135808. 0,
  135809. 2,
  135810. };
  135811. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135812. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135813. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135818. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135823. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  135858. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135863. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  135868. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135904. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135909. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135914. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 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,
  136223. };
  136224. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136225. -0.5, 0.5,
  136226. };
  136227. static long _vq_quantmap__44c0_s_p1_0[] = {
  136228. 1, 0, 2,
  136229. };
  136230. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136231. _vq_quantthresh__44c0_s_p1_0,
  136232. _vq_quantmap__44c0_s_p1_0,
  136233. 3,
  136234. 3
  136235. };
  136236. static static_codebook _44c0_s_p1_0 = {
  136237. 8, 6561,
  136238. _vq_lengthlist__44c0_s_p1_0,
  136239. 1, -535822336, 1611661312, 2, 0,
  136240. _vq_quantlist__44c0_s_p1_0,
  136241. NULL,
  136242. &_vq_auxt__44c0_s_p1_0,
  136243. NULL,
  136244. 0
  136245. };
  136246. static long _vq_quantlist__44c0_s_p2_0[] = {
  136247. 2,
  136248. 1,
  136249. 3,
  136250. 0,
  136251. 4,
  136252. };
  136253. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136254. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0,
  136294. };
  136295. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136296. -1.5, -0.5, 0.5, 1.5,
  136297. };
  136298. static long _vq_quantmap__44c0_s_p2_0[] = {
  136299. 3, 1, 0, 2, 4,
  136300. };
  136301. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136302. _vq_quantthresh__44c0_s_p2_0,
  136303. _vq_quantmap__44c0_s_p2_0,
  136304. 5,
  136305. 5
  136306. };
  136307. static static_codebook _44c0_s_p2_0 = {
  136308. 4, 625,
  136309. _vq_lengthlist__44c0_s_p2_0,
  136310. 1, -533725184, 1611661312, 3, 0,
  136311. _vq_quantlist__44c0_s_p2_0,
  136312. NULL,
  136313. &_vq_auxt__44c0_s_p2_0,
  136314. NULL,
  136315. 0
  136316. };
  136317. static long _vq_quantlist__44c0_s_p3_0[] = {
  136318. 4,
  136319. 3,
  136320. 5,
  136321. 2,
  136322. 6,
  136323. 1,
  136324. 7,
  136325. 0,
  136326. 8,
  136327. };
  136328. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136329. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136330. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136331. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136332. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136333. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0,
  136335. };
  136336. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136337. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136338. };
  136339. static long _vq_quantmap__44c0_s_p3_0[] = {
  136340. 7, 5, 3, 1, 0, 2, 4, 6,
  136341. 8,
  136342. };
  136343. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136344. _vq_quantthresh__44c0_s_p3_0,
  136345. _vq_quantmap__44c0_s_p3_0,
  136346. 9,
  136347. 9
  136348. };
  136349. static static_codebook _44c0_s_p3_0 = {
  136350. 2, 81,
  136351. _vq_lengthlist__44c0_s_p3_0,
  136352. 1, -531628032, 1611661312, 4, 0,
  136353. _vq_quantlist__44c0_s_p3_0,
  136354. NULL,
  136355. &_vq_auxt__44c0_s_p3_0,
  136356. NULL,
  136357. 0
  136358. };
  136359. static long _vq_quantlist__44c0_s_p4_0[] = {
  136360. 4,
  136361. 3,
  136362. 5,
  136363. 2,
  136364. 6,
  136365. 1,
  136366. 7,
  136367. 0,
  136368. 8,
  136369. };
  136370. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136371. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136372. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136373. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136374. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136375. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136376. 10,
  136377. };
  136378. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136379. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136380. };
  136381. static long _vq_quantmap__44c0_s_p4_0[] = {
  136382. 7, 5, 3, 1, 0, 2, 4, 6,
  136383. 8,
  136384. };
  136385. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136386. _vq_quantthresh__44c0_s_p4_0,
  136387. _vq_quantmap__44c0_s_p4_0,
  136388. 9,
  136389. 9
  136390. };
  136391. static static_codebook _44c0_s_p4_0 = {
  136392. 2, 81,
  136393. _vq_lengthlist__44c0_s_p4_0,
  136394. 1, -531628032, 1611661312, 4, 0,
  136395. _vq_quantlist__44c0_s_p4_0,
  136396. NULL,
  136397. &_vq_auxt__44c0_s_p4_0,
  136398. NULL,
  136399. 0
  136400. };
  136401. static long _vq_quantlist__44c0_s_p5_0[] = {
  136402. 8,
  136403. 7,
  136404. 9,
  136405. 6,
  136406. 10,
  136407. 5,
  136408. 11,
  136409. 4,
  136410. 12,
  136411. 3,
  136412. 13,
  136413. 2,
  136414. 14,
  136415. 1,
  136416. 15,
  136417. 0,
  136418. 16,
  136419. };
  136420. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136421. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136422. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136423. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136424. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136425. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136426. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136427. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136428. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136429. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136430. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136431. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136432. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136433. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136434. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136435. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136436. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136437. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136439. 14,
  136440. };
  136441. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136442. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136443. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136444. };
  136445. static long _vq_quantmap__44c0_s_p5_0[] = {
  136446. 15, 13, 11, 9, 7, 5, 3, 1,
  136447. 0, 2, 4, 6, 8, 10, 12, 14,
  136448. 16,
  136449. };
  136450. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136451. _vq_quantthresh__44c0_s_p5_0,
  136452. _vq_quantmap__44c0_s_p5_0,
  136453. 17,
  136454. 17
  136455. };
  136456. static static_codebook _44c0_s_p5_0 = {
  136457. 2, 289,
  136458. _vq_lengthlist__44c0_s_p5_0,
  136459. 1, -529530880, 1611661312, 5, 0,
  136460. _vq_quantlist__44c0_s_p5_0,
  136461. NULL,
  136462. &_vq_auxt__44c0_s_p5_0,
  136463. NULL,
  136464. 0
  136465. };
  136466. static long _vq_quantlist__44c0_s_p6_0[] = {
  136467. 1,
  136468. 0,
  136469. 2,
  136470. };
  136471. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136472. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136473. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136474. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136475. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136476. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136477. 10,
  136478. };
  136479. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136480. -5.5, 5.5,
  136481. };
  136482. static long _vq_quantmap__44c0_s_p6_0[] = {
  136483. 1, 0, 2,
  136484. };
  136485. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136486. _vq_quantthresh__44c0_s_p6_0,
  136487. _vq_quantmap__44c0_s_p6_0,
  136488. 3,
  136489. 3
  136490. };
  136491. static static_codebook _44c0_s_p6_0 = {
  136492. 4, 81,
  136493. _vq_lengthlist__44c0_s_p6_0,
  136494. 1, -529137664, 1618345984, 2, 0,
  136495. _vq_quantlist__44c0_s_p6_0,
  136496. NULL,
  136497. &_vq_auxt__44c0_s_p6_0,
  136498. NULL,
  136499. 0
  136500. };
  136501. static long _vq_quantlist__44c0_s_p6_1[] = {
  136502. 5,
  136503. 4,
  136504. 6,
  136505. 3,
  136506. 7,
  136507. 2,
  136508. 8,
  136509. 1,
  136510. 9,
  136511. 0,
  136512. 10,
  136513. };
  136514. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136515. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136516. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136517. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136518. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136519. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136520. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136521. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136522. 10,10,10, 8, 8, 8, 8, 8, 8,
  136523. };
  136524. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136525. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136526. 3.5, 4.5,
  136527. };
  136528. static long _vq_quantmap__44c0_s_p6_1[] = {
  136529. 9, 7, 5, 3, 1, 0, 2, 4,
  136530. 6, 8, 10,
  136531. };
  136532. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136533. _vq_quantthresh__44c0_s_p6_1,
  136534. _vq_quantmap__44c0_s_p6_1,
  136535. 11,
  136536. 11
  136537. };
  136538. static static_codebook _44c0_s_p6_1 = {
  136539. 2, 121,
  136540. _vq_lengthlist__44c0_s_p6_1,
  136541. 1, -531365888, 1611661312, 4, 0,
  136542. _vq_quantlist__44c0_s_p6_1,
  136543. NULL,
  136544. &_vq_auxt__44c0_s_p6_1,
  136545. NULL,
  136546. 0
  136547. };
  136548. static long _vq_quantlist__44c0_s_p7_0[] = {
  136549. 6,
  136550. 5,
  136551. 7,
  136552. 4,
  136553. 8,
  136554. 3,
  136555. 9,
  136556. 2,
  136557. 10,
  136558. 1,
  136559. 11,
  136560. 0,
  136561. 12,
  136562. };
  136563. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136564. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136565. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136566. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136567. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136568. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136569. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136570. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136571. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136572. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136573. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136574. 0,12,12,11,11,12,12,13,13,
  136575. };
  136576. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136577. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136578. 12.5, 17.5, 22.5, 27.5,
  136579. };
  136580. static long _vq_quantmap__44c0_s_p7_0[] = {
  136581. 11, 9, 7, 5, 3, 1, 0, 2,
  136582. 4, 6, 8, 10, 12,
  136583. };
  136584. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136585. _vq_quantthresh__44c0_s_p7_0,
  136586. _vq_quantmap__44c0_s_p7_0,
  136587. 13,
  136588. 13
  136589. };
  136590. static static_codebook _44c0_s_p7_0 = {
  136591. 2, 169,
  136592. _vq_lengthlist__44c0_s_p7_0,
  136593. 1, -526516224, 1616117760, 4, 0,
  136594. _vq_quantlist__44c0_s_p7_0,
  136595. NULL,
  136596. &_vq_auxt__44c0_s_p7_0,
  136597. NULL,
  136598. 0
  136599. };
  136600. static long _vq_quantlist__44c0_s_p7_1[] = {
  136601. 2,
  136602. 1,
  136603. 3,
  136604. 0,
  136605. 4,
  136606. };
  136607. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136608. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136609. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136610. };
  136611. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136612. -1.5, -0.5, 0.5, 1.5,
  136613. };
  136614. static long _vq_quantmap__44c0_s_p7_1[] = {
  136615. 3, 1, 0, 2, 4,
  136616. };
  136617. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136618. _vq_quantthresh__44c0_s_p7_1,
  136619. _vq_quantmap__44c0_s_p7_1,
  136620. 5,
  136621. 5
  136622. };
  136623. static static_codebook _44c0_s_p7_1 = {
  136624. 2, 25,
  136625. _vq_lengthlist__44c0_s_p7_1,
  136626. 1, -533725184, 1611661312, 3, 0,
  136627. _vq_quantlist__44c0_s_p7_1,
  136628. NULL,
  136629. &_vq_auxt__44c0_s_p7_1,
  136630. NULL,
  136631. 0
  136632. };
  136633. static long _vq_quantlist__44c0_s_p8_0[] = {
  136634. 2,
  136635. 1,
  136636. 3,
  136637. 0,
  136638. 4,
  136639. };
  136640. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136641. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136642. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136643. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136646. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136648. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136650. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136651. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136652. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136653. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136656. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136670. 11,11,11,11,11,11,11,11,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,11,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,
  136681. };
  136682. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136683. -331.5, -110.5, 110.5, 331.5,
  136684. };
  136685. static long _vq_quantmap__44c0_s_p8_0[] = {
  136686. 3, 1, 0, 2, 4,
  136687. };
  136688. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136689. _vq_quantthresh__44c0_s_p8_0,
  136690. _vq_quantmap__44c0_s_p8_0,
  136691. 5,
  136692. 5
  136693. };
  136694. static static_codebook _44c0_s_p8_0 = {
  136695. 4, 625,
  136696. _vq_lengthlist__44c0_s_p8_0,
  136697. 1, -518283264, 1627103232, 3, 0,
  136698. _vq_quantlist__44c0_s_p8_0,
  136699. NULL,
  136700. &_vq_auxt__44c0_s_p8_0,
  136701. NULL,
  136702. 0
  136703. };
  136704. static long _vq_quantlist__44c0_s_p8_1[] = {
  136705. 6,
  136706. 5,
  136707. 7,
  136708. 4,
  136709. 8,
  136710. 3,
  136711. 9,
  136712. 2,
  136713. 10,
  136714. 1,
  136715. 11,
  136716. 0,
  136717. 12,
  136718. };
  136719. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136720. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136721. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136722. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136723. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136724. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136725. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136726. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136727. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136728. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136729. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136730. 16,13,13,12,12,14,14,15,13,
  136731. };
  136732. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136733. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136734. 42.5, 59.5, 76.5, 93.5,
  136735. };
  136736. static long _vq_quantmap__44c0_s_p8_1[] = {
  136737. 11, 9, 7, 5, 3, 1, 0, 2,
  136738. 4, 6, 8, 10, 12,
  136739. };
  136740. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136741. _vq_quantthresh__44c0_s_p8_1,
  136742. _vq_quantmap__44c0_s_p8_1,
  136743. 13,
  136744. 13
  136745. };
  136746. static static_codebook _44c0_s_p8_1 = {
  136747. 2, 169,
  136748. _vq_lengthlist__44c0_s_p8_1,
  136749. 1, -522616832, 1620115456, 4, 0,
  136750. _vq_quantlist__44c0_s_p8_1,
  136751. NULL,
  136752. &_vq_auxt__44c0_s_p8_1,
  136753. NULL,
  136754. 0
  136755. };
  136756. static long _vq_quantlist__44c0_s_p8_2[] = {
  136757. 8,
  136758. 7,
  136759. 9,
  136760. 6,
  136761. 10,
  136762. 5,
  136763. 11,
  136764. 4,
  136765. 12,
  136766. 3,
  136767. 13,
  136768. 2,
  136769. 14,
  136770. 1,
  136771. 15,
  136772. 0,
  136773. 16,
  136774. };
  136775. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136776. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136777. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136778. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136779. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136780. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136781. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136782. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136783. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136784. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136785. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136786. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136787. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136788. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136789. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136790. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136791. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136792. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136793. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136794. 10,
  136795. };
  136796. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136797. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136798. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136799. };
  136800. static long _vq_quantmap__44c0_s_p8_2[] = {
  136801. 15, 13, 11, 9, 7, 5, 3, 1,
  136802. 0, 2, 4, 6, 8, 10, 12, 14,
  136803. 16,
  136804. };
  136805. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136806. _vq_quantthresh__44c0_s_p8_2,
  136807. _vq_quantmap__44c0_s_p8_2,
  136808. 17,
  136809. 17
  136810. };
  136811. static static_codebook _44c0_s_p8_2 = {
  136812. 2, 289,
  136813. _vq_lengthlist__44c0_s_p8_2,
  136814. 1, -529530880, 1611661312, 5, 0,
  136815. _vq_quantlist__44c0_s_p8_2,
  136816. NULL,
  136817. &_vq_auxt__44c0_s_p8_2,
  136818. NULL,
  136819. 0
  136820. };
  136821. static long _huff_lengthlist__44c0_s_short[] = {
  136822. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136823. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136824. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136825. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136826. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136827. 12,
  136828. };
  136829. static static_codebook _huff_book__44c0_s_short = {
  136830. 2, 81,
  136831. _huff_lengthlist__44c0_s_short,
  136832. 0, 0, 0, 0, 0,
  136833. NULL,
  136834. NULL,
  136835. NULL,
  136836. NULL,
  136837. 0
  136838. };
  136839. static long _huff_lengthlist__44c0_sm_long[] = {
  136840. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136841. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136842. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136843. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136844. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136845. 13,
  136846. };
  136847. static static_codebook _huff_book__44c0_sm_long = {
  136848. 2, 81,
  136849. _huff_lengthlist__44c0_sm_long,
  136850. 0, 0, 0, 0, 0,
  136851. NULL,
  136852. NULL,
  136853. NULL,
  136854. NULL,
  136855. 0
  136856. };
  136857. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136858. 1,
  136859. 0,
  136860. 2,
  136861. };
  136862. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136863. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136864. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136869. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136874. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  136909. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136914. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136919. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136955. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136960. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136965. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 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,
  137274. };
  137275. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137276. -0.5, 0.5,
  137277. };
  137278. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137279. 1, 0, 2,
  137280. };
  137281. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137282. _vq_quantthresh__44c0_sm_p1_0,
  137283. _vq_quantmap__44c0_sm_p1_0,
  137284. 3,
  137285. 3
  137286. };
  137287. static static_codebook _44c0_sm_p1_0 = {
  137288. 8, 6561,
  137289. _vq_lengthlist__44c0_sm_p1_0,
  137290. 1, -535822336, 1611661312, 2, 0,
  137291. _vq_quantlist__44c0_sm_p1_0,
  137292. NULL,
  137293. &_vq_auxt__44c0_sm_p1_0,
  137294. NULL,
  137295. 0
  137296. };
  137297. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137298. 2,
  137299. 1,
  137300. 3,
  137301. 0,
  137302. 4,
  137303. };
  137304. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137305. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0,
  137345. };
  137346. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137347. -1.5, -0.5, 0.5, 1.5,
  137348. };
  137349. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137350. 3, 1, 0, 2, 4,
  137351. };
  137352. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137353. _vq_quantthresh__44c0_sm_p2_0,
  137354. _vq_quantmap__44c0_sm_p2_0,
  137355. 5,
  137356. 5
  137357. };
  137358. static static_codebook _44c0_sm_p2_0 = {
  137359. 4, 625,
  137360. _vq_lengthlist__44c0_sm_p2_0,
  137361. 1, -533725184, 1611661312, 3, 0,
  137362. _vq_quantlist__44c0_sm_p2_0,
  137363. NULL,
  137364. &_vq_auxt__44c0_sm_p2_0,
  137365. NULL,
  137366. 0
  137367. };
  137368. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137369. 4,
  137370. 3,
  137371. 5,
  137372. 2,
  137373. 6,
  137374. 1,
  137375. 7,
  137376. 0,
  137377. 8,
  137378. };
  137379. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137380. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137381. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137382. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137383. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137384. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0,
  137386. };
  137387. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137388. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137389. };
  137390. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137391. 7, 5, 3, 1, 0, 2, 4, 6,
  137392. 8,
  137393. };
  137394. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137395. _vq_quantthresh__44c0_sm_p3_0,
  137396. _vq_quantmap__44c0_sm_p3_0,
  137397. 9,
  137398. 9
  137399. };
  137400. static static_codebook _44c0_sm_p3_0 = {
  137401. 2, 81,
  137402. _vq_lengthlist__44c0_sm_p3_0,
  137403. 1, -531628032, 1611661312, 4, 0,
  137404. _vq_quantlist__44c0_sm_p3_0,
  137405. NULL,
  137406. &_vq_auxt__44c0_sm_p3_0,
  137407. NULL,
  137408. 0
  137409. };
  137410. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137411. 4,
  137412. 3,
  137413. 5,
  137414. 2,
  137415. 6,
  137416. 1,
  137417. 7,
  137418. 0,
  137419. 8,
  137420. };
  137421. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137422. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137423. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137424. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137425. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137426. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137427. 11,
  137428. };
  137429. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137431. };
  137432. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137433. 7, 5, 3, 1, 0, 2, 4, 6,
  137434. 8,
  137435. };
  137436. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137437. _vq_quantthresh__44c0_sm_p4_0,
  137438. _vq_quantmap__44c0_sm_p4_0,
  137439. 9,
  137440. 9
  137441. };
  137442. static static_codebook _44c0_sm_p4_0 = {
  137443. 2, 81,
  137444. _vq_lengthlist__44c0_sm_p4_0,
  137445. 1, -531628032, 1611661312, 4, 0,
  137446. _vq_quantlist__44c0_sm_p4_0,
  137447. NULL,
  137448. &_vq_auxt__44c0_sm_p4_0,
  137449. NULL,
  137450. 0
  137451. };
  137452. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137453. 8,
  137454. 7,
  137455. 9,
  137456. 6,
  137457. 10,
  137458. 5,
  137459. 11,
  137460. 4,
  137461. 12,
  137462. 3,
  137463. 13,
  137464. 2,
  137465. 14,
  137466. 1,
  137467. 15,
  137468. 0,
  137469. 16,
  137470. };
  137471. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137472. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137473. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137474. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137475. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137476. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137477. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137478. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137479. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137480. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137481. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137482. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137483. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137484. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137485. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137486. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137487. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137488. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137490. 14,
  137491. };
  137492. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137493. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137494. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137495. };
  137496. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137497. 15, 13, 11, 9, 7, 5, 3, 1,
  137498. 0, 2, 4, 6, 8, 10, 12, 14,
  137499. 16,
  137500. };
  137501. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137502. _vq_quantthresh__44c0_sm_p5_0,
  137503. _vq_quantmap__44c0_sm_p5_0,
  137504. 17,
  137505. 17
  137506. };
  137507. static static_codebook _44c0_sm_p5_0 = {
  137508. 2, 289,
  137509. _vq_lengthlist__44c0_sm_p5_0,
  137510. 1, -529530880, 1611661312, 5, 0,
  137511. _vq_quantlist__44c0_sm_p5_0,
  137512. NULL,
  137513. &_vq_auxt__44c0_sm_p5_0,
  137514. NULL,
  137515. 0
  137516. };
  137517. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137518. 1,
  137519. 0,
  137520. 2,
  137521. };
  137522. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137523. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137524. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137525. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137526. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137527. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137528. 11,
  137529. };
  137530. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137531. -5.5, 5.5,
  137532. };
  137533. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137534. 1, 0, 2,
  137535. };
  137536. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137537. _vq_quantthresh__44c0_sm_p6_0,
  137538. _vq_quantmap__44c0_sm_p6_0,
  137539. 3,
  137540. 3
  137541. };
  137542. static static_codebook _44c0_sm_p6_0 = {
  137543. 4, 81,
  137544. _vq_lengthlist__44c0_sm_p6_0,
  137545. 1, -529137664, 1618345984, 2, 0,
  137546. _vq_quantlist__44c0_sm_p6_0,
  137547. NULL,
  137548. &_vq_auxt__44c0_sm_p6_0,
  137549. NULL,
  137550. 0
  137551. };
  137552. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137553. 5,
  137554. 4,
  137555. 6,
  137556. 3,
  137557. 7,
  137558. 2,
  137559. 8,
  137560. 1,
  137561. 9,
  137562. 0,
  137563. 10,
  137564. };
  137565. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137566. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137567. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137568. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137569. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137570. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137571. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137572. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137573. 10,10,10, 8, 8, 8, 8, 8, 8,
  137574. };
  137575. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137576. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137577. 3.5, 4.5,
  137578. };
  137579. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137580. 9, 7, 5, 3, 1, 0, 2, 4,
  137581. 6, 8, 10,
  137582. };
  137583. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137584. _vq_quantthresh__44c0_sm_p6_1,
  137585. _vq_quantmap__44c0_sm_p6_1,
  137586. 11,
  137587. 11
  137588. };
  137589. static static_codebook _44c0_sm_p6_1 = {
  137590. 2, 121,
  137591. _vq_lengthlist__44c0_sm_p6_1,
  137592. 1, -531365888, 1611661312, 4, 0,
  137593. _vq_quantlist__44c0_sm_p6_1,
  137594. NULL,
  137595. &_vq_auxt__44c0_sm_p6_1,
  137596. NULL,
  137597. 0
  137598. };
  137599. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137600. 6,
  137601. 5,
  137602. 7,
  137603. 4,
  137604. 8,
  137605. 3,
  137606. 9,
  137607. 2,
  137608. 10,
  137609. 1,
  137610. 11,
  137611. 0,
  137612. 12,
  137613. };
  137614. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137615. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137616. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137617. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137618. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137619. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137620. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137621. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137622. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137623. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137624. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137625. 0,12,12,11,11,13,12,14,14,
  137626. };
  137627. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137629. 12.5, 17.5, 22.5, 27.5,
  137630. };
  137631. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137632. 11, 9, 7, 5, 3, 1, 0, 2,
  137633. 4, 6, 8, 10, 12,
  137634. };
  137635. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137636. _vq_quantthresh__44c0_sm_p7_0,
  137637. _vq_quantmap__44c0_sm_p7_0,
  137638. 13,
  137639. 13
  137640. };
  137641. static static_codebook _44c0_sm_p7_0 = {
  137642. 2, 169,
  137643. _vq_lengthlist__44c0_sm_p7_0,
  137644. 1, -526516224, 1616117760, 4, 0,
  137645. _vq_quantlist__44c0_sm_p7_0,
  137646. NULL,
  137647. &_vq_auxt__44c0_sm_p7_0,
  137648. NULL,
  137649. 0
  137650. };
  137651. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137652. 2,
  137653. 1,
  137654. 3,
  137655. 0,
  137656. 4,
  137657. };
  137658. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137659. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137660. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137661. };
  137662. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137663. -1.5, -0.5, 0.5, 1.5,
  137664. };
  137665. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137666. 3, 1, 0, 2, 4,
  137667. };
  137668. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137669. _vq_quantthresh__44c0_sm_p7_1,
  137670. _vq_quantmap__44c0_sm_p7_1,
  137671. 5,
  137672. 5
  137673. };
  137674. static static_codebook _44c0_sm_p7_1 = {
  137675. 2, 25,
  137676. _vq_lengthlist__44c0_sm_p7_1,
  137677. 1, -533725184, 1611661312, 3, 0,
  137678. _vq_quantlist__44c0_sm_p7_1,
  137679. NULL,
  137680. &_vq_auxt__44c0_sm_p7_1,
  137681. NULL,
  137682. 0
  137683. };
  137684. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137685. 4,
  137686. 3,
  137687. 5,
  137688. 2,
  137689. 6,
  137690. 1,
  137691. 7,
  137692. 0,
  137693. 8,
  137694. };
  137695. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137696. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137697. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137699. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137700. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137701. 12,
  137702. };
  137703. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137704. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137705. };
  137706. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137707. 7, 5, 3, 1, 0, 2, 4, 6,
  137708. 8,
  137709. };
  137710. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137711. _vq_quantthresh__44c0_sm_p8_0,
  137712. _vq_quantmap__44c0_sm_p8_0,
  137713. 9,
  137714. 9
  137715. };
  137716. static static_codebook _44c0_sm_p8_0 = {
  137717. 2, 81,
  137718. _vq_lengthlist__44c0_sm_p8_0,
  137719. 1, -516186112, 1627103232, 4, 0,
  137720. _vq_quantlist__44c0_sm_p8_0,
  137721. NULL,
  137722. &_vq_auxt__44c0_sm_p8_0,
  137723. NULL,
  137724. 0
  137725. };
  137726. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137727. 6,
  137728. 5,
  137729. 7,
  137730. 4,
  137731. 8,
  137732. 3,
  137733. 9,
  137734. 2,
  137735. 10,
  137736. 1,
  137737. 11,
  137738. 0,
  137739. 12,
  137740. };
  137741. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137742. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137743. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137744. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137745. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137746. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137747. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137748. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137749. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137750. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137751. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137752. 20,13,13,12,12,16,13,15,13,
  137753. };
  137754. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137755. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137756. 42.5, 59.5, 76.5, 93.5,
  137757. };
  137758. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137759. 11, 9, 7, 5, 3, 1, 0, 2,
  137760. 4, 6, 8, 10, 12,
  137761. };
  137762. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137763. _vq_quantthresh__44c0_sm_p8_1,
  137764. _vq_quantmap__44c0_sm_p8_1,
  137765. 13,
  137766. 13
  137767. };
  137768. static static_codebook _44c0_sm_p8_1 = {
  137769. 2, 169,
  137770. _vq_lengthlist__44c0_sm_p8_1,
  137771. 1, -522616832, 1620115456, 4, 0,
  137772. _vq_quantlist__44c0_sm_p8_1,
  137773. NULL,
  137774. &_vq_auxt__44c0_sm_p8_1,
  137775. NULL,
  137776. 0
  137777. };
  137778. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137779. 8,
  137780. 7,
  137781. 9,
  137782. 6,
  137783. 10,
  137784. 5,
  137785. 11,
  137786. 4,
  137787. 12,
  137788. 3,
  137789. 13,
  137790. 2,
  137791. 14,
  137792. 1,
  137793. 15,
  137794. 0,
  137795. 16,
  137796. };
  137797. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137798. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137799. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137800. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137801. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137802. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137803. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137804. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137805. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137806. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137807. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137808. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137809. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137810. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137811. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137812. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137813. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137814. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137815. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137816. 9,
  137817. };
  137818. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137819. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137820. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137821. };
  137822. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137823. 15, 13, 11, 9, 7, 5, 3, 1,
  137824. 0, 2, 4, 6, 8, 10, 12, 14,
  137825. 16,
  137826. };
  137827. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137828. _vq_quantthresh__44c0_sm_p8_2,
  137829. _vq_quantmap__44c0_sm_p8_2,
  137830. 17,
  137831. 17
  137832. };
  137833. static static_codebook _44c0_sm_p8_2 = {
  137834. 2, 289,
  137835. _vq_lengthlist__44c0_sm_p8_2,
  137836. 1, -529530880, 1611661312, 5, 0,
  137837. _vq_quantlist__44c0_sm_p8_2,
  137838. NULL,
  137839. &_vq_auxt__44c0_sm_p8_2,
  137840. NULL,
  137841. 0
  137842. };
  137843. static long _huff_lengthlist__44c0_sm_short[] = {
  137844. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137845. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137846. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137847. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137848. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137849. 12,
  137850. };
  137851. static static_codebook _huff_book__44c0_sm_short = {
  137852. 2, 81,
  137853. _huff_lengthlist__44c0_sm_short,
  137854. 0, 0, 0, 0, 0,
  137855. NULL,
  137856. NULL,
  137857. NULL,
  137858. NULL,
  137859. 0
  137860. };
  137861. static long _huff_lengthlist__44c1_s_long[] = {
  137862. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137863. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137864. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137865. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137866. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137867. 11,
  137868. };
  137869. static static_codebook _huff_book__44c1_s_long = {
  137870. 2, 81,
  137871. _huff_lengthlist__44c1_s_long,
  137872. 0, 0, 0, 0, 0,
  137873. NULL,
  137874. NULL,
  137875. NULL,
  137876. NULL,
  137877. 0
  137878. };
  137879. static long _vq_quantlist__44c1_s_p1_0[] = {
  137880. 1,
  137881. 0,
  137882. 2,
  137883. };
  137884. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137885. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137886. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137891. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137896. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  137931. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  137936. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  137941. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137977. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137982. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137987. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 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,
  138296. };
  138297. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138298. -0.5, 0.5,
  138299. };
  138300. static long _vq_quantmap__44c1_s_p1_0[] = {
  138301. 1, 0, 2,
  138302. };
  138303. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138304. _vq_quantthresh__44c1_s_p1_0,
  138305. _vq_quantmap__44c1_s_p1_0,
  138306. 3,
  138307. 3
  138308. };
  138309. static static_codebook _44c1_s_p1_0 = {
  138310. 8, 6561,
  138311. _vq_lengthlist__44c1_s_p1_0,
  138312. 1, -535822336, 1611661312, 2, 0,
  138313. _vq_quantlist__44c1_s_p1_0,
  138314. NULL,
  138315. &_vq_auxt__44c1_s_p1_0,
  138316. NULL,
  138317. 0
  138318. };
  138319. static long _vq_quantlist__44c1_s_p2_0[] = {
  138320. 2,
  138321. 1,
  138322. 3,
  138323. 0,
  138324. 4,
  138325. };
  138326. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138327. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0,
  138367. };
  138368. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138369. -1.5, -0.5, 0.5, 1.5,
  138370. };
  138371. static long _vq_quantmap__44c1_s_p2_0[] = {
  138372. 3, 1, 0, 2, 4,
  138373. };
  138374. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138375. _vq_quantthresh__44c1_s_p2_0,
  138376. _vq_quantmap__44c1_s_p2_0,
  138377. 5,
  138378. 5
  138379. };
  138380. static static_codebook _44c1_s_p2_0 = {
  138381. 4, 625,
  138382. _vq_lengthlist__44c1_s_p2_0,
  138383. 1, -533725184, 1611661312, 3, 0,
  138384. _vq_quantlist__44c1_s_p2_0,
  138385. NULL,
  138386. &_vq_auxt__44c1_s_p2_0,
  138387. NULL,
  138388. 0
  138389. };
  138390. static long _vq_quantlist__44c1_s_p3_0[] = {
  138391. 4,
  138392. 3,
  138393. 5,
  138394. 2,
  138395. 6,
  138396. 1,
  138397. 7,
  138398. 0,
  138399. 8,
  138400. };
  138401. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138402. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138403. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138404. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138405. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138406. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0,
  138408. };
  138409. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138410. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138411. };
  138412. static long _vq_quantmap__44c1_s_p3_0[] = {
  138413. 7, 5, 3, 1, 0, 2, 4, 6,
  138414. 8,
  138415. };
  138416. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138417. _vq_quantthresh__44c1_s_p3_0,
  138418. _vq_quantmap__44c1_s_p3_0,
  138419. 9,
  138420. 9
  138421. };
  138422. static static_codebook _44c1_s_p3_0 = {
  138423. 2, 81,
  138424. _vq_lengthlist__44c1_s_p3_0,
  138425. 1, -531628032, 1611661312, 4, 0,
  138426. _vq_quantlist__44c1_s_p3_0,
  138427. NULL,
  138428. &_vq_auxt__44c1_s_p3_0,
  138429. NULL,
  138430. 0
  138431. };
  138432. static long _vq_quantlist__44c1_s_p4_0[] = {
  138433. 4,
  138434. 3,
  138435. 5,
  138436. 2,
  138437. 6,
  138438. 1,
  138439. 7,
  138440. 0,
  138441. 8,
  138442. };
  138443. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138444. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138445. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138446. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138447. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138448. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138449. 11,
  138450. };
  138451. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138452. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138453. };
  138454. static long _vq_quantmap__44c1_s_p4_0[] = {
  138455. 7, 5, 3, 1, 0, 2, 4, 6,
  138456. 8,
  138457. };
  138458. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138459. _vq_quantthresh__44c1_s_p4_0,
  138460. _vq_quantmap__44c1_s_p4_0,
  138461. 9,
  138462. 9
  138463. };
  138464. static static_codebook _44c1_s_p4_0 = {
  138465. 2, 81,
  138466. _vq_lengthlist__44c1_s_p4_0,
  138467. 1, -531628032, 1611661312, 4, 0,
  138468. _vq_quantlist__44c1_s_p4_0,
  138469. NULL,
  138470. &_vq_auxt__44c1_s_p4_0,
  138471. NULL,
  138472. 0
  138473. };
  138474. static long _vq_quantlist__44c1_s_p5_0[] = {
  138475. 8,
  138476. 7,
  138477. 9,
  138478. 6,
  138479. 10,
  138480. 5,
  138481. 11,
  138482. 4,
  138483. 12,
  138484. 3,
  138485. 13,
  138486. 2,
  138487. 14,
  138488. 1,
  138489. 15,
  138490. 0,
  138491. 16,
  138492. };
  138493. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138494. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138495. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138496. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138497. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138498. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138499. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138500. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138501. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138502. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138503. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138504. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138505. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138506. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138507. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138508. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138509. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138510. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138512. 14,
  138513. };
  138514. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138515. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138516. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138517. };
  138518. static long _vq_quantmap__44c1_s_p5_0[] = {
  138519. 15, 13, 11, 9, 7, 5, 3, 1,
  138520. 0, 2, 4, 6, 8, 10, 12, 14,
  138521. 16,
  138522. };
  138523. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138524. _vq_quantthresh__44c1_s_p5_0,
  138525. _vq_quantmap__44c1_s_p5_0,
  138526. 17,
  138527. 17
  138528. };
  138529. static static_codebook _44c1_s_p5_0 = {
  138530. 2, 289,
  138531. _vq_lengthlist__44c1_s_p5_0,
  138532. 1, -529530880, 1611661312, 5, 0,
  138533. _vq_quantlist__44c1_s_p5_0,
  138534. NULL,
  138535. &_vq_auxt__44c1_s_p5_0,
  138536. NULL,
  138537. 0
  138538. };
  138539. static long _vq_quantlist__44c1_s_p6_0[] = {
  138540. 1,
  138541. 0,
  138542. 2,
  138543. };
  138544. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138545. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138546. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138547. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138548. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138549. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138550. 11,
  138551. };
  138552. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138553. -5.5, 5.5,
  138554. };
  138555. static long _vq_quantmap__44c1_s_p6_0[] = {
  138556. 1, 0, 2,
  138557. };
  138558. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138559. _vq_quantthresh__44c1_s_p6_0,
  138560. _vq_quantmap__44c1_s_p6_0,
  138561. 3,
  138562. 3
  138563. };
  138564. static static_codebook _44c1_s_p6_0 = {
  138565. 4, 81,
  138566. _vq_lengthlist__44c1_s_p6_0,
  138567. 1, -529137664, 1618345984, 2, 0,
  138568. _vq_quantlist__44c1_s_p6_0,
  138569. NULL,
  138570. &_vq_auxt__44c1_s_p6_0,
  138571. NULL,
  138572. 0
  138573. };
  138574. static long _vq_quantlist__44c1_s_p6_1[] = {
  138575. 5,
  138576. 4,
  138577. 6,
  138578. 3,
  138579. 7,
  138580. 2,
  138581. 8,
  138582. 1,
  138583. 9,
  138584. 0,
  138585. 10,
  138586. };
  138587. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138588. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138589. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138590. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138591. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138592. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138593. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138594. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138595. 10,10,10, 8, 8, 8, 8, 8, 8,
  138596. };
  138597. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138598. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138599. 3.5, 4.5,
  138600. };
  138601. static long _vq_quantmap__44c1_s_p6_1[] = {
  138602. 9, 7, 5, 3, 1, 0, 2, 4,
  138603. 6, 8, 10,
  138604. };
  138605. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138606. _vq_quantthresh__44c1_s_p6_1,
  138607. _vq_quantmap__44c1_s_p6_1,
  138608. 11,
  138609. 11
  138610. };
  138611. static static_codebook _44c1_s_p6_1 = {
  138612. 2, 121,
  138613. _vq_lengthlist__44c1_s_p6_1,
  138614. 1, -531365888, 1611661312, 4, 0,
  138615. _vq_quantlist__44c1_s_p6_1,
  138616. NULL,
  138617. &_vq_auxt__44c1_s_p6_1,
  138618. NULL,
  138619. 0
  138620. };
  138621. static long _vq_quantlist__44c1_s_p7_0[] = {
  138622. 6,
  138623. 5,
  138624. 7,
  138625. 4,
  138626. 8,
  138627. 3,
  138628. 9,
  138629. 2,
  138630. 10,
  138631. 1,
  138632. 11,
  138633. 0,
  138634. 12,
  138635. };
  138636. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138637. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138638. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138639. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138640. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138641. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138642. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138643. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138644. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138645. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138646. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138647. 0,12,11,11,11,13,10,14,13,
  138648. };
  138649. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138650. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138651. 12.5, 17.5, 22.5, 27.5,
  138652. };
  138653. static long _vq_quantmap__44c1_s_p7_0[] = {
  138654. 11, 9, 7, 5, 3, 1, 0, 2,
  138655. 4, 6, 8, 10, 12,
  138656. };
  138657. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138658. _vq_quantthresh__44c1_s_p7_0,
  138659. _vq_quantmap__44c1_s_p7_0,
  138660. 13,
  138661. 13
  138662. };
  138663. static static_codebook _44c1_s_p7_0 = {
  138664. 2, 169,
  138665. _vq_lengthlist__44c1_s_p7_0,
  138666. 1, -526516224, 1616117760, 4, 0,
  138667. _vq_quantlist__44c1_s_p7_0,
  138668. NULL,
  138669. &_vq_auxt__44c1_s_p7_0,
  138670. NULL,
  138671. 0
  138672. };
  138673. static long _vq_quantlist__44c1_s_p7_1[] = {
  138674. 2,
  138675. 1,
  138676. 3,
  138677. 0,
  138678. 4,
  138679. };
  138680. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138681. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138682. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138683. };
  138684. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138685. -1.5, -0.5, 0.5, 1.5,
  138686. };
  138687. static long _vq_quantmap__44c1_s_p7_1[] = {
  138688. 3, 1, 0, 2, 4,
  138689. };
  138690. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138691. _vq_quantthresh__44c1_s_p7_1,
  138692. _vq_quantmap__44c1_s_p7_1,
  138693. 5,
  138694. 5
  138695. };
  138696. static static_codebook _44c1_s_p7_1 = {
  138697. 2, 25,
  138698. _vq_lengthlist__44c1_s_p7_1,
  138699. 1, -533725184, 1611661312, 3, 0,
  138700. _vq_quantlist__44c1_s_p7_1,
  138701. NULL,
  138702. &_vq_auxt__44c1_s_p7_1,
  138703. NULL,
  138704. 0
  138705. };
  138706. static long _vq_quantlist__44c1_s_p8_0[] = {
  138707. 6,
  138708. 5,
  138709. 7,
  138710. 4,
  138711. 8,
  138712. 3,
  138713. 9,
  138714. 2,
  138715. 10,
  138716. 1,
  138717. 11,
  138718. 0,
  138719. 12,
  138720. };
  138721. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138722. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138723. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138728. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138731. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138732. 10,10,10,10,10,10,10,10,10,
  138733. };
  138734. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138735. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138736. 552.5, 773.5, 994.5, 1215.5,
  138737. };
  138738. static long _vq_quantmap__44c1_s_p8_0[] = {
  138739. 11, 9, 7, 5, 3, 1, 0, 2,
  138740. 4, 6, 8, 10, 12,
  138741. };
  138742. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138743. _vq_quantthresh__44c1_s_p8_0,
  138744. _vq_quantmap__44c1_s_p8_0,
  138745. 13,
  138746. 13
  138747. };
  138748. static static_codebook _44c1_s_p8_0 = {
  138749. 2, 169,
  138750. _vq_lengthlist__44c1_s_p8_0,
  138751. 1, -514541568, 1627103232, 4, 0,
  138752. _vq_quantlist__44c1_s_p8_0,
  138753. NULL,
  138754. &_vq_auxt__44c1_s_p8_0,
  138755. NULL,
  138756. 0
  138757. };
  138758. static long _vq_quantlist__44c1_s_p8_1[] = {
  138759. 6,
  138760. 5,
  138761. 7,
  138762. 4,
  138763. 8,
  138764. 3,
  138765. 9,
  138766. 2,
  138767. 10,
  138768. 1,
  138769. 11,
  138770. 0,
  138771. 12,
  138772. };
  138773. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138774. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138775. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138776. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138777. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138778. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138779. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138780. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138781. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138782. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138783. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138784. 16,13,12,12,11,14,12,15,13,
  138785. };
  138786. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138787. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138788. 42.5, 59.5, 76.5, 93.5,
  138789. };
  138790. static long _vq_quantmap__44c1_s_p8_1[] = {
  138791. 11, 9, 7, 5, 3, 1, 0, 2,
  138792. 4, 6, 8, 10, 12,
  138793. };
  138794. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138795. _vq_quantthresh__44c1_s_p8_1,
  138796. _vq_quantmap__44c1_s_p8_1,
  138797. 13,
  138798. 13
  138799. };
  138800. static static_codebook _44c1_s_p8_1 = {
  138801. 2, 169,
  138802. _vq_lengthlist__44c1_s_p8_1,
  138803. 1, -522616832, 1620115456, 4, 0,
  138804. _vq_quantlist__44c1_s_p8_1,
  138805. NULL,
  138806. &_vq_auxt__44c1_s_p8_1,
  138807. NULL,
  138808. 0
  138809. };
  138810. static long _vq_quantlist__44c1_s_p8_2[] = {
  138811. 8,
  138812. 7,
  138813. 9,
  138814. 6,
  138815. 10,
  138816. 5,
  138817. 11,
  138818. 4,
  138819. 12,
  138820. 3,
  138821. 13,
  138822. 2,
  138823. 14,
  138824. 1,
  138825. 15,
  138826. 0,
  138827. 16,
  138828. };
  138829. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138830. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138831. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138832. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138833. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138834. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138835. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138836. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138837. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138838. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138839. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138840. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138841. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138842. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138843. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138844. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138845. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138846. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138847. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138848. 9,
  138849. };
  138850. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138851. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138852. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138853. };
  138854. static long _vq_quantmap__44c1_s_p8_2[] = {
  138855. 15, 13, 11, 9, 7, 5, 3, 1,
  138856. 0, 2, 4, 6, 8, 10, 12, 14,
  138857. 16,
  138858. };
  138859. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138860. _vq_quantthresh__44c1_s_p8_2,
  138861. _vq_quantmap__44c1_s_p8_2,
  138862. 17,
  138863. 17
  138864. };
  138865. static static_codebook _44c1_s_p8_2 = {
  138866. 2, 289,
  138867. _vq_lengthlist__44c1_s_p8_2,
  138868. 1, -529530880, 1611661312, 5, 0,
  138869. _vq_quantlist__44c1_s_p8_2,
  138870. NULL,
  138871. &_vq_auxt__44c1_s_p8_2,
  138872. NULL,
  138873. 0
  138874. };
  138875. static long _huff_lengthlist__44c1_s_short[] = {
  138876. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138877. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138878. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138879. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138880. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138881. 11,
  138882. };
  138883. static static_codebook _huff_book__44c1_s_short = {
  138884. 2, 81,
  138885. _huff_lengthlist__44c1_s_short,
  138886. 0, 0, 0, 0, 0,
  138887. NULL,
  138888. NULL,
  138889. NULL,
  138890. NULL,
  138891. 0
  138892. };
  138893. static long _huff_lengthlist__44c1_sm_long[] = {
  138894. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138895. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138896. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138897. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138898. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138899. 11,
  138900. };
  138901. static static_codebook _huff_book__44c1_sm_long = {
  138902. 2, 81,
  138903. _huff_lengthlist__44c1_sm_long,
  138904. 0, 0, 0, 0, 0,
  138905. NULL,
  138906. NULL,
  138907. NULL,
  138908. NULL,
  138909. 0
  138910. };
  138911. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138912. 1,
  138913. 0,
  138914. 2,
  138915. };
  138916. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138917. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138918. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138923. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138928. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  138963. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  138968. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138973. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139009. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139014. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139019. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 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,
  139328. };
  139329. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139330. -0.5, 0.5,
  139331. };
  139332. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139333. 1, 0, 2,
  139334. };
  139335. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139336. _vq_quantthresh__44c1_sm_p1_0,
  139337. _vq_quantmap__44c1_sm_p1_0,
  139338. 3,
  139339. 3
  139340. };
  139341. static static_codebook _44c1_sm_p1_0 = {
  139342. 8, 6561,
  139343. _vq_lengthlist__44c1_sm_p1_0,
  139344. 1, -535822336, 1611661312, 2, 0,
  139345. _vq_quantlist__44c1_sm_p1_0,
  139346. NULL,
  139347. &_vq_auxt__44c1_sm_p1_0,
  139348. NULL,
  139349. 0
  139350. };
  139351. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139352. 2,
  139353. 1,
  139354. 3,
  139355. 0,
  139356. 4,
  139357. };
  139358. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139359. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0,
  139399. };
  139400. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139401. -1.5, -0.5, 0.5, 1.5,
  139402. };
  139403. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139404. 3, 1, 0, 2, 4,
  139405. };
  139406. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139407. _vq_quantthresh__44c1_sm_p2_0,
  139408. _vq_quantmap__44c1_sm_p2_0,
  139409. 5,
  139410. 5
  139411. };
  139412. static static_codebook _44c1_sm_p2_0 = {
  139413. 4, 625,
  139414. _vq_lengthlist__44c1_sm_p2_0,
  139415. 1, -533725184, 1611661312, 3, 0,
  139416. _vq_quantlist__44c1_sm_p2_0,
  139417. NULL,
  139418. &_vq_auxt__44c1_sm_p2_0,
  139419. NULL,
  139420. 0
  139421. };
  139422. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139423. 4,
  139424. 3,
  139425. 5,
  139426. 2,
  139427. 6,
  139428. 1,
  139429. 7,
  139430. 0,
  139431. 8,
  139432. };
  139433. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139434. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139435. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139436. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139437. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139438. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0,
  139440. };
  139441. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139442. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139443. };
  139444. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139445. 7, 5, 3, 1, 0, 2, 4, 6,
  139446. 8,
  139447. };
  139448. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139449. _vq_quantthresh__44c1_sm_p3_0,
  139450. _vq_quantmap__44c1_sm_p3_0,
  139451. 9,
  139452. 9
  139453. };
  139454. static static_codebook _44c1_sm_p3_0 = {
  139455. 2, 81,
  139456. _vq_lengthlist__44c1_sm_p3_0,
  139457. 1, -531628032, 1611661312, 4, 0,
  139458. _vq_quantlist__44c1_sm_p3_0,
  139459. NULL,
  139460. &_vq_auxt__44c1_sm_p3_0,
  139461. NULL,
  139462. 0
  139463. };
  139464. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139465. 4,
  139466. 3,
  139467. 5,
  139468. 2,
  139469. 6,
  139470. 1,
  139471. 7,
  139472. 0,
  139473. 8,
  139474. };
  139475. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139476. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139477. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139478. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139479. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139480. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139481. 11,
  139482. };
  139483. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139484. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139485. };
  139486. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139487. 7, 5, 3, 1, 0, 2, 4, 6,
  139488. 8,
  139489. };
  139490. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139491. _vq_quantthresh__44c1_sm_p4_0,
  139492. _vq_quantmap__44c1_sm_p4_0,
  139493. 9,
  139494. 9
  139495. };
  139496. static static_codebook _44c1_sm_p4_0 = {
  139497. 2, 81,
  139498. _vq_lengthlist__44c1_sm_p4_0,
  139499. 1, -531628032, 1611661312, 4, 0,
  139500. _vq_quantlist__44c1_sm_p4_0,
  139501. NULL,
  139502. &_vq_auxt__44c1_sm_p4_0,
  139503. NULL,
  139504. 0
  139505. };
  139506. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139507. 8,
  139508. 7,
  139509. 9,
  139510. 6,
  139511. 10,
  139512. 5,
  139513. 11,
  139514. 4,
  139515. 12,
  139516. 3,
  139517. 13,
  139518. 2,
  139519. 14,
  139520. 1,
  139521. 15,
  139522. 0,
  139523. 16,
  139524. };
  139525. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139526. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139527. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139528. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139529. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139530. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139531. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139532. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139533. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139534. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139535. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139536. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139537. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139538. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139539. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139540. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139541. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139542. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139544. 14,
  139545. };
  139546. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139547. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139548. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139549. };
  139550. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139551. 15, 13, 11, 9, 7, 5, 3, 1,
  139552. 0, 2, 4, 6, 8, 10, 12, 14,
  139553. 16,
  139554. };
  139555. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139556. _vq_quantthresh__44c1_sm_p5_0,
  139557. _vq_quantmap__44c1_sm_p5_0,
  139558. 17,
  139559. 17
  139560. };
  139561. static static_codebook _44c1_sm_p5_0 = {
  139562. 2, 289,
  139563. _vq_lengthlist__44c1_sm_p5_0,
  139564. 1, -529530880, 1611661312, 5, 0,
  139565. _vq_quantlist__44c1_sm_p5_0,
  139566. NULL,
  139567. &_vq_auxt__44c1_sm_p5_0,
  139568. NULL,
  139569. 0
  139570. };
  139571. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139572. 1,
  139573. 0,
  139574. 2,
  139575. };
  139576. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139577. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139578. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139579. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139580. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139581. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139582. 11,
  139583. };
  139584. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139585. -5.5, 5.5,
  139586. };
  139587. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139588. 1, 0, 2,
  139589. };
  139590. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139591. _vq_quantthresh__44c1_sm_p6_0,
  139592. _vq_quantmap__44c1_sm_p6_0,
  139593. 3,
  139594. 3
  139595. };
  139596. static static_codebook _44c1_sm_p6_0 = {
  139597. 4, 81,
  139598. _vq_lengthlist__44c1_sm_p6_0,
  139599. 1, -529137664, 1618345984, 2, 0,
  139600. _vq_quantlist__44c1_sm_p6_0,
  139601. NULL,
  139602. &_vq_auxt__44c1_sm_p6_0,
  139603. NULL,
  139604. 0
  139605. };
  139606. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139607. 5,
  139608. 4,
  139609. 6,
  139610. 3,
  139611. 7,
  139612. 2,
  139613. 8,
  139614. 1,
  139615. 9,
  139616. 0,
  139617. 10,
  139618. };
  139619. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139620. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139621. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139622. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139623. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139624. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139625. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139626. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139627. 10,10,10, 8, 8, 8, 8, 8, 8,
  139628. };
  139629. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139630. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139631. 3.5, 4.5,
  139632. };
  139633. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139634. 9, 7, 5, 3, 1, 0, 2, 4,
  139635. 6, 8, 10,
  139636. };
  139637. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139638. _vq_quantthresh__44c1_sm_p6_1,
  139639. _vq_quantmap__44c1_sm_p6_1,
  139640. 11,
  139641. 11
  139642. };
  139643. static static_codebook _44c1_sm_p6_1 = {
  139644. 2, 121,
  139645. _vq_lengthlist__44c1_sm_p6_1,
  139646. 1, -531365888, 1611661312, 4, 0,
  139647. _vq_quantlist__44c1_sm_p6_1,
  139648. NULL,
  139649. &_vq_auxt__44c1_sm_p6_1,
  139650. NULL,
  139651. 0
  139652. };
  139653. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139654. 6,
  139655. 5,
  139656. 7,
  139657. 4,
  139658. 8,
  139659. 3,
  139660. 9,
  139661. 2,
  139662. 10,
  139663. 1,
  139664. 11,
  139665. 0,
  139666. 12,
  139667. };
  139668. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139669. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139670. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139671. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139672. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139673. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139674. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139675. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139676. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139677. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139678. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139679. 0,12,12,11,11,13,12,14,13,
  139680. };
  139681. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139682. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139683. 12.5, 17.5, 22.5, 27.5,
  139684. };
  139685. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139686. 11, 9, 7, 5, 3, 1, 0, 2,
  139687. 4, 6, 8, 10, 12,
  139688. };
  139689. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139690. _vq_quantthresh__44c1_sm_p7_0,
  139691. _vq_quantmap__44c1_sm_p7_0,
  139692. 13,
  139693. 13
  139694. };
  139695. static static_codebook _44c1_sm_p7_0 = {
  139696. 2, 169,
  139697. _vq_lengthlist__44c1_sm_p7_0,
  139698. 1, -526516224, 1616117760, 4, 0,
  139699. _vq_quantlist__44c1_sm_p7_0,
  139700. NULL,
  139701. &_vq_auxt__44c1_sm_p7_0,
  139702. NULL,
  139703. 0
  139704. };
  139705. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139706. 2,
  139707. 1,
  139708. 3,
  139709. 0,
  139710. 4,
  139711. };
  139712. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139713. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139714. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139715. };
  139716. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139717. -1.5, -0.5, 0.5, 1.5,
  139718. };
  139719. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139720. 3, 1, 0, 2, 4,
  139721. };
  139722. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139723. _vq_quantthresh__44c1_sm_p7_1,
  139724. _vq_quantmap__44c1_sm_p7_1,
  139725. 5,
  139726. 5
  139727. };
  139728. static static_codebook _44c1_sm_p7_1 = {
  139729. 2, 25,
  139730. _vq_lengthlist__44c1_sm_p7_1,
  139731. 1, -533725184, 1611661312, 3, 0,
  139732. _vq_quantlist__44c1_sm_p7_1,
  139733. NULL,
  139734. &_vq_auxt__44c1_sm_p7_1,
  139735. NULL,
  139736. 0
  139737. };
  139738. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139739. 6,
  139740. 5,
  139741. 7,
  139742. 4,
  139743. 8,
  139744. 3,
  139745. 9,
  139746. 2,
  139747. 10,
  139748. 1,
  139749. 11,
  139750. 0,
  139751. 12,
  139752. };
  139753. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139754. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139755. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139756. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139757. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139758. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139759. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139760. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139761. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139762. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139763. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139764. 13,13,13,13,13,13,13,13,13,
  139765. };
  139766. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139767. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139768. 552.5, 773.5, 994.5, 1215.5,
  139769. };
  139770. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139771. 11, 9, 7, 5, 3, 1, 0, 2,
  139772. 4, 6, 8, 10, 12,
  139773. };
  139774. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139775. _vq_quantthresh__44c1_sm_p8_0,
  139776. _vq_quantmap__44c1_sm_p8_0,
  139777. 13,
  139778. 13
  139779. };
  139780. static static_codebook _44c1_sm_p8_0 = {
  139781. 2, 169,
  139782. _vq_lengthlist__44c1_sm_p8_0,
  139783. 1, -514541568, 1627103232, 4, 0,
  139784. _vq_quantlist__44c1_sm_p8_0,
  139785. NULL,
  139786. &_vq_auxt__44c1_sm_p8_0,
  139787. NULL,
  139788. 0
  139789. };
  139790. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139791. 6,
  139792. 5,
  139793. 7,
  139794. 4,
  139795. 8,
  139796. 3,
  139797. 9,
  139798. 2,
  139799. 10,
  139800. 1,
  139801. 11,
  139802. 0,
  139803. 12,
  139804. };
  139805. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139806. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139807. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139808. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139809. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139810. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139811. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139812. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139813. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139814. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139815. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139816. 20,13,12,12,12,14,12,14,13,
  139817. };
  139818. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139819. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139820. 42.5, 59.5, 76.5, 93.5,
  139821. };
  139822. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139823. 11, 9, 7, 5, 3, 1, 0, 2,
  139824. 4, 6, 8, 10, 12,
  139825. };
  139826. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139827. _vq_quantthresh__44c1_sm_p8_1,
  139828. _vq_quantmap__44c1_sm_p8_1,
  139829. 13,
  139830. 13
  139831. };
  139832. static static_codebook _44c1_sm_p8_1 = {
  139833. 2, 169,
  139834. _vq_lengthlist__44c1_sm_p8_1,
  139835. 1, -522616832, 1620115456, 4, 0,
  139836. _vq_quantlist__44c1_sm_p8_1,
  139837. NULL,
  139838. &_vq_auxt__44c1_sm_p8_1,
  139839. NULL,
  139840. 0
  139841. };
  139842. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139843. 8,
  139844. 7,
  139845. 9,
  139846. 6,
  139847. 10,
  139848. 5,
  139849. 11,
  139850. 4,
  139851. 12,
  139852. 3,
  139853. 13,
  139854. 2,
  139855. 14,
  139856. 1,
  139857. 15,
  139858. 0,
  139859. 16,
  139860. };
  139861. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139862. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139863. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139864. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139865. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139866. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139867. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139868. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139869. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139870. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139871. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139872. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139873. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139874. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139875. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139876. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139877. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139878. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139879. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139880. 9,
  139881. };
  139882. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139883. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139884. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139885. };
  139886. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139887. 15, 13, 11, 9, 7, 5, 3, 1,
  139888. 0, 2, 4, 6, 8, 10, 12, 14,
  139889. 16,
  139890. };
  139891. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139892. _vq_quantthresh__44c1_sm_p8_2,
  139893. _vq_quantmap__44c1_sm_p8_2,
  139894. 17,
  139895. 17
  139896. };
  139897. static static_codebook _44c1_sm_p8_2 = {
  139898. 2, 289,
  139899. _vq_lengthlist__44c1_sm_p8_2,
  139900. 1, -529530880, 1611661312, 5, 0,
  139901. _vq_quantlist__44c1_sm_p8_2,
  139902. NULL,
  139903. &_vq_auxt__44c1_sm_p8_2,
  139904. NULL,
  139905. 0
  139906. };
  139907. static long _huff_lengthlist__44c1_sm_short[] = {
  139908. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139909. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139910. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139911. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139912. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139913. 11,
  139914. };
  139915. static static_codebook _huff_book__44c1_sm_short = {
  139916. 2, 81,
  139917. _huff_lengthlist__44c1_sm_short,
  139918. 0, 0, 0, 0, 0,
  139919. NULL,
  139920. NULL,
  139921. NULL,
  139922. NULL,
  139923. 0
  139924. };
  139925. static long _huff_lengthlist__44cn1_s_long[] = {
  139926. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139927. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139928. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139929. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139930. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139931. 20,
  139932. };
  139933. static static_codebook _huff_book__44cn1_s_long = {
  139934. 2, 81,
  139935. _huff_lengthlist__44cn1_s_long,
  139936. 0, 0, 0, 0, 0,
  139937. NULL,
  139938. NULL,
  139939. NULL,
  139940. NULL,
  139941. 0
  139942. };
  139943. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139944. 1,
  139945. 0,
  139946. 2,
  139947. };
  139948. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139949. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139950. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139955. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139960. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  139995. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140000. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140005. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140041. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140046. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140051. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 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,
  140360. };
  140361. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140362. -0.5, 0.5,
  140363. };
  140364. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140365. 1, 0, 2,
  140366. };
  140367. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140368. _vq_quantthresh__44cn1_s_p1_0,
  140369. _vq_quantmap__44cn1_s_p1_0,
  140370. 3,
  140371. 3
  140372. };
  140373. static static_codebook _44cn1_s_p1_0 = {
  140374. 8, 6561,
  140375. _vq_lengthlist__44cn1_s_p1_0,
  140376. 1, -535822336, 1611661312, 2, 0,
  140377. _vq_quantlist__44cn1_s_p1_0,
  140378. NULL,
  140379. &_vq_auxt__44cn1_s_p1_0,
  140380. NULL,
  140381. 0
  140382. };
  140383. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140384. 2,
  140385. 1,
  140386. 3,
  140387. 0,
  140388. 4,
  140389. };
  140390. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140391. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0,
  140431. };
  140432. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140433. -1.5, -0.5, 0.5, 1.5,
  140434. };
  140435. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140436. 3, 1, 0, 2, 4,
  140437. };
  140438. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140439. _vq_quantthresh__44cn1_s_p2_0,
  140440. _vq_quantmap__44cn1_s_p2_0,
  140441. 5,
  140442. 5
  140443. };
  140444. static static_codebook _44cn1_s_p2_0 = {
  140445. 4, 625,
  140446. _vq_lengthlist__44cn1_s_p2_0,
  140447. 1, -533725184, 1611661312, 3, 0,
  140448. _vq_quantlist__44cn1_s_p2_0,
  140449. NULL,
  140450. &_vq_auxt__44cn1_s_p2_0,
  140451. NULL,
  140452. 0
  140453. };
  140454. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140455. 4,
  140456. 3,
  140457. 5,
  140458. 2,
  140459. 6,
  140460. 1,
  140461. 7,
  140462. 0,
  140463. 8,
  140464. };
  140465. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140466. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140467. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140468. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140469. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140470. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0,
  140472. };
  140473. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140474. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140475. };
  140476. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140477. 7, 5, 3, 1, 0, 2, 4, 6,
  140478. 8,
  140479. };
  140480. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140481. _vq_quantthresh__44cn1_s_p3_0,
  140482. _vq_quantmap__44cn1_s_p3_0,
  140483. 9,
  140484. 9
  140485. };
  140486. static static_codebook _44cn1_s_p3_0 = {
  140487. 2, 81,
  140488. _vq_lengthlist__44cn1_s_p3_0,
  140489. 1, -531628032, 1611661312, 4, 0,
  140490. _vq_quantlist__44cn1_s_p3_0,
  140491. NULL,
  140492. &_vq_auxt__44cn1_s_p3_0,
  140493. NULL,
  140494. 0
  140495. };
  140496. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140497. 4,
  140498. 3,
  140499. 5,
  140500. 2,
  140501. 6,
  140502. 1,
  140503. 7,
  140504. 0,
  140505. 8,
  140506. };
  140507. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140508. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140509. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140510. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140511. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140512. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140513. 11,
  140514. };
  140515. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140516. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140517. };
  140518. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140519. 7, 5, 3, 1, 0, 2, 4, 6,
  140520. 8,
  140521. };
  140522. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140523. _vq_quantthresh__44cn1_s_p4_0,
  140524. _vq_quantmap__44cn1_s_p4_0,
  140525. 9,
  140526. 9
  140527. };
  140528. static static_codebook _44cn1_s_p4_0 = {
  140529. 2, 81,
  140530. _vq_lengthlist__44cn1_s_p4_0,
  140531. 1, -531628032, 1611661312, 4, 0,
  140532. _vq_quantlist__44cn1_s_p4_0,
  140533. NULL,
  140534. &_vq_auxt__44cn1_s_p4_0,
  140535. NULL,
  140536. 0
  140537. };
  140538. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140539. 8,
  140540. 7,
  140541. 9,
  140542. 6,
  140543. 10,
  140544. 5,
  140545. 11,
  140546. 4,
  140547. 12,
  140548. 3,
  140549. 13,
  140550. 2,
  140551. 14,
  140552. 1,
  140553. 15,
  140554. 0,
  140555. 16,
  140556. };
  140557. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140558. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140559. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140560. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140561. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140562. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140563. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140564. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140565. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140566. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140567. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140568. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140569. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140570. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140571. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140572. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140573. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140574. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140576. 14,
  140577. };
  140578. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140579. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140580. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140581. };
  140582. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140583. 15, 13, 11, 9, 7, 5, 3, 1,
  140584. 0, 2, 4, 6, 8, 10, 12, 14,
  140585. 16,
  140586. };
  140587. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140588. _vq_quantthresh__44cn1_s_p5_0,
  140589. _vq_quantmap__44cn1_s_p5_0,
  140590. 17,
  140591. 17
  140592. };
  140593. static static_codebook _44cn1_s_p5_0 = {
  140594. 2, 289,
  140595. _vq_lengthlist__44cn1_s_p5_0,
  140596. 1, -529530880, 1611661312, 5, 0,
  140597. _vq_quantlist__44cn1_s_p5_0,
  140598. NULL,
  140599. &_vq_auxt__44cn1_s_p5_0,
  140600. NULL,
  140601. 0
  140602. };
  140603. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140604. 1,
  140605. 0,
  140606. 2,
  140607. };
  140608. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140609. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140610. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140611. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140612. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140613. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140614. 10,
  140615. };
  140616. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140617. -5.5, 5.5,
  140618. };
  140619. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140620. 1, 0, 2,
  140621. };
  140622. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140623. _vq_quantthresh__44cn1_s_p6_0,
  140624. _vq_quantmap__44cn1_s_p6_0,
  140625. 3,
  140626. 3
  140627. };
  140628. static static_codebook _44cn1_s_p6_0 = {
  140629. 4, 81,
  140630. _vq_lengthlist__44cn1_s_p6_0,
  140631. 1, -529137664, 1618345984, 2, 0,
  140632. _vq_quantlist__44cn1_s_p6_0,
  140633. NULL,
  140634. &_vq_auxt__44cn1_s_p6_0,
  140635. NULL,
  140636. 0
  140637. };
  140638. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140639. 5,
  140640. 4,
  140641. 6,
  140642. 3,
  140643. 7,
  140644. 2,
  140645. 8,
  140646. 1,
  140647. 9,
  140648. 0,
  140649. 10,
  140650. };
  140651. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140652. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140653. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140654. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140655. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140656. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140657. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140658. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140659. 10,10,10, 9, 9, 9, 9, 9, 9,
  140660. };
  140661. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140662. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140663. 3.5, 4.5,
  140664. };
  140665. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140666. 9, 7, 5, 3, 1, 0, 2, 4,
  140667. 6, 8, 10,
  140668. };
  140669. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140670. _vq_quantthresh__44cn1_s_p6_1,
  140671. _vq_quantmap__44cn1_s_p6_1,
  140672. 11,
  140673. 11
  140674. };
  140675. static static_codebook _44cn1_s_p6_1 = {
  140676. 2, 121,
  140677. _vq_lengthlist__44cn1_s_p6_1,
  140678. 1, -531365888, 1611661312, 4, 0,
  140679. _vq_quantlist__44cn1_s_p6_1,
  140680. NULL,
  140681. &_vq_auxt__44cn1_s_p6_1,
  140682. NULL,
  140683. 0
  140684. };
  140685. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140686. 6,
  140687. 5,
  140688. 7,
  140689. 4,
  140690. 8,
  140691. 3,
  140692. 9,
  140693. 2,
  140694. 10,
  140695. 1,
  140696. 11,
  140697. 0,
  140698. 12,
  140699. };
  140700. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140701. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140702. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140703. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140704. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140705. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140706. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140707. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140708. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140709. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140710. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140711. 0,13,13,12,12,13,13,13,14,
  140712. };
  140713. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140714. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140715. 12.5, 17.5, 22.5, 27.5,
  140716. };
  140717. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140718. 11, 9, 7, 5, 3, 1, 0, 2,
  140719. 4, 6, 8, 10, 12,
  140720. };
  140721. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140722. _vq_quantthresh__44cn1_s_p7_0,
  140723. _vq_quantmap__44cn1_s_p7_0,
  140724. 13,
  140725. 13
  140726. };
  140727. static static_codebook _44cn1_s_p7_0 = {
  140728. 2, 169,
  140729. _vq_lengthlist__44cn1_s_p7_0,
  140730. 1, -526516224, 1616117760, 4, 0,
  140731. _vq_quantlist__44cn1_s_p7_0,
  140732. NULL,
  140733. &_vq_auxt__44cn1_s_p7_0,
  140734. NULL,
  140735. 0
  140736. };
  140737. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140738. 2,
  140739. 1,
  140740. 3,
  140741. 0,
  140742. 4,
  140743. };
  140744. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140745. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140746. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140747. };
  140748. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140749. -1.5, -0.5, 0.5, 1.5,
  140750. };
  140751. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140752. 3, 1, 0, 2, 4,
  140753. };
  140754. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140755. _vq_quantthresh__44cn1_s_p7_1,
  140756. _vq_quantmap__44cn1_s_p7_1,
  140757. 5,
  140758. 5
  140759. };
  140760. static static_codebook _44cn1_s_p7_1 = {
  140761. 2, 25,
  140762. _vq_lengthlist__44cn1_s_p7_1,
  140763. 1, -533725184, 1611661312, 3, 0,
  140764. _vq_quantlist__44cn1_s_p7_1,
  140765. NULL,
  140766. &_vq_auxt__44cn1_s_p7_1,
  140767. NULL,
  140768. 0
  140769. };
  140770. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140771. 2,
  140772. 1,
  140773. 3,
  140774. 0,
  140775. 4,
  140776. };
  140777. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140778. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140779. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140781. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140785. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140787. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140793. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140796. 11,11,11,11,11,11,11,11,11,11,11,11,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,11,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,11,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,11,11,11,11,11,11,11,11,11,11,
  140805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140808. 11,11,11,11,11,11,11,11,11,11,11,11,11,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,11,11,11,11,11,11,
  140811. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140812. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140813. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140817. 12,
  140818. };
  140819. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140820. -331.5, -110.5, 110.5, 331.5,
  140821. };
  140822. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140823. 3, 1, 0, 2, 4,
  140824. };
  140825. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140826. _vq_quantthresh__44cn1_s_p8_0,
  140827. _vq_quantmap__44cn1_s_p8_0,
  140828. 5,
  140829. 5
  140830. };
  140831. static static_codebook _44cn1_s_p8_0 = {
  140832. 4, 625,
  140833. _vq_lengthlist__44cn1_s_p8_0,
  140834. 1, -518283264, 1627103232, 3, 0,
  140835. _vq_quantlist__44cn1_s_p8_0,
  140836. NULL,
  140837. &_vq_auxt__44cn1_s_p8_0,
  140838. NULL,
  140839. 0
  140840. };
  140841. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140842. 6,
  140843. 5,
  140844. 7,
  140845. 4,
  140846. 8,
  140847. 3,
  140848. 9,
  140849. 2,
  140850. 10,
  140851. 1,
  140852. 11,
  140853. 0,
  140854. 12,
  140855. };
  140856. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140857. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140858. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140859. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140860. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140861. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140862. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140863. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140864. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140865. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140866. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140867. 15,12,12,11,11,14,12,13,14,
  140868. };
  140869. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140870. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140871. 42.5, 59.5, 76.5, 93.5,
  140872. };
  140873. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140874. 11, 9, 7, 5, 3, 1, 0, 2,
  140875. 4, 6, 8, 10, 12,
  140876. };
  140877. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140878. _vq_quantthresh__44cn1_s_p8_1,
  140879. _vq_quantmap__44cn1_s_p8_1,
  140880. 13,
  140881. 13
  140882. };
  140883. static static_codebook _44cn1_s_p8_1 = {
  140884. 2, 169,
  140885. _vq_lengthlist__44cn1_s_p8_1,
  140886. 1, -522616832, 1620115456, 4, 0,
  140887. _vq_quantlist__44cn1_s_p8_1,
  140888. NULL,
  140889. &_vq_auxt__44cn1_s_p8_1,
  140890. NULL,
  140891. 0
  140892. };
  140893. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140894. 8,
  140895. 7,
  140896. 9,
  140897. 6,
  140898. 10,
  140899. 5,
  140900. 11,
  140901. 4,
  140902. 12,
  140903. 3,
  140904. 13,
  140905. 2,
  140906. 14,
  140907. 1,
  140908. 15,
  140909. 0,
  140910. 16,
  140911. };
  140912. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140913. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140914. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140915. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140916. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140917. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140918. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140919. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140920. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140921. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140922. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140923. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140924. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140925. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140926. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140927. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140928. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140929. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140930. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140931. 9,
  140932. };
  140933. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140934. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140935. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140936. };
  140937. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140938. 15, 13, 11, 9, 7, 5, 3, 1,
  140939. 0, 2, 4, 6, 8, 10, 12, 14,
  140940. 16,
  140941. };
  140942. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140943. _vq_quantthresh__44cn1_s_p8_2,
  140944. _vq_quantmap__44cn1_s_p8_2,
  140945. 17,
  140946. 17
  140947. };
  140948. static static_codebook _44cn1_s_p8_2 = {
  140949. 2, 289,
  140950. _vq_lengthlist__44cn1_s_p8_2,
  140951. 1, -529530880, 1611661312, 5, 0,
  140952. _vq_quantlist__44cn1_s_p8_2,
  140953. NULL,
  140954. &_vq_auxt__44cn1_s_p8_2,
  140955. NULL,
  140956. 0
  140957. };
  140958. static long _huff_lengthlist__44cn1_s_short[] = {
  140959. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140960. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140961. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140962. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140963. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140964. 10,
  140965. };
  140966. static static_codebook _huff_book__44cn1_s_short = {
  140967. 2, 81,
  140968. _huff_lengthlist__44cn1_s_short,
  140969. 0, 0, 0, 0, 0,
  140970. NULL,
  140971. NULL,
  140972. NULL,
  140973. NULL,
  140974. 0
  140975. };
  140976. static long _huff_lengthlist__44cn1_sm_long[] = {
  140977. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140978. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140979. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140980. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140981. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140982. 17,
  140983. };
  140984. static static_codebook _huff_book__44cn1_sm_long = {
  140985. 2, 81,
  140986. _huff_lengthlist__44cn1_sm_long,
  140987. 0, 0, 0, 0, 0,
  140988. NULL,
  140989. NULL,
  140990. NULL,
  140991. NULL,
  140992. 0
  140993. };
  140994. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140995. 1,
  140996. 0,
  140997. 2,
  140998. };
  140999. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141000. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141001. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141006. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141011. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  141046. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141051. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141056. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141092. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141097. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141102. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 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,
  141411. };
  141412. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141413. -0.5, 0.5,
  141414. };
  141415. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141416. 1, 0, 2,
  141417. };
  141418. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141419. _vq_quantthresh__44cn1_sm_p1_0,
  141420. _vq_quantmap__44cn1_sm_p1_0,
  141421. 3,
  141422. 3
  141423. };
  141424. static static_codebook _44cn1_sm_p1_0 = {
  141425. 8, 6561,
  141426. _vq_lengthlist__44cn1_sm_p1_0,
  141427. 1, -535822336, 1611661312, 2, 0,
  141428. _vq_quantlist__44cn1_sm_p1_0,
  141429. NULL,
  141430. &_vq_auxt__44cn1_sm_p1_0,
  141431. NULL,
  141432. 0
  141433. };
  141434. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141435. 2,
  141436. 1,
  141437. 3,
  141438. 0,
  141439. 4,
  141440. };
  141441. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141442. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0,
  141482. };
  141483. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141484. -1.5, -0.5, 0.5, 1.5,
  141485. };
  141486. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141487. 3, 1, 0, 2, 4,
  141488. };
  141489. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141490. _vq_quantthresh__44cn1_sm_p2_0,
  141491. _vq_quantmap__44cn1_sm_p2_0,
  141492. 5,
  141493. 5
  141494. };
  141495. static static_codebook _44cn1_sm_p2_0 = {
  141496. 4, 625,
  141497. _vq_lengthlist__44cn1_sm_p2_0,
  141498. 1, -533725184, 1611661312, 3, 0,
  141499. _vq_quantlist__44cn1_sm_p2_0,
  141500. NULL,
  141501. &_vq_auxt__44cn1_sm_p2_0,
  141502. NULL,
  141503. 0
  141504. };
  141505. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141506. 4,
  141507. 3,
  141508. 5,
  141509. 2,
  141510. 6,
  141511. 1,
  141512. 7,
  141513. 0,
  141514. 8,
  141515. };
  141516. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141517. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141518. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141519. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141520. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141521. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0,
  141523. };
  141524. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141525. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141526. };
  141527. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141528. 7, 5, 3, 1, 0, 2, 4, 6,
  141529. 8,
  141530. };
  141531. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141532. _vq_quantthresh__44cn1_sm_p3_0,
  141533. _vq_quantmap__44cn1_sm_p3_0,
  141534. 9,
  141535. 9
  141536. };
  141537. static static_codebook _44cn1_sm_p3_0 = {
  141538. 2, 81,
  141539. _vq_lengthlist__44cn1_sm_p3_0,
  141540. 1, -531628032, 1611661312, 4, 0,
  141541. _vq_quantlist__44cn1_sm_p3_0,
  141542. NULL,
  141543. &_vq_auxt__44cn1_sm_p3_0,
  141544. NULL,
  141545. 0
  141546. };
  141547. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141548. 4,
  141549. 3,
  141550. 5,
  141551. 2,
  141552. 6,
  141553. 1,
  141554. 7,
  141555. 0,
  141556. 8,
  141557. };
  141558. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141559. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141560. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141561. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141562. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141563. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141564. 11,
  141565. };
  141566. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141567. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141568. };
  141569. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141570. 7, 5, 3, 1, 0, 2, 4, 6,
  141571. 8,
  141572. };
  141573. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141574. _vq_quantthresh__44cn1_sm_p4_0,
  141575. _vq_quantmap__44cn1_sm_p4_0,
  141576. 9,
  141577. 9
  141578. };
  141579. static static_codebook _44cn1_sm_p4_0 = {
  141580. 2, 81,
  141581. _vq_lengthlist__44cn1_sm_p4_0,
  141582. 1, -531628032, 1611661312, 4, 0,
  141583. _vq_quantlist__44cn1_sm_p4_0,
  141584. NULL,
  141585. &_vq_auxt__44cn1_sm_p4_0,
  141586. NULL,
  141587. 0
  141588. };
  141589. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141590. 8,
  141591. 7,
  141592. 9,
  141593. 6,
  141594. 10,
  141595. 5,
  141596. 11,
  141597. 4,
  141598. 12,
  141599. 3,
  141600. 13,
  141601. 2,
  141602. 14,
  141603. 1,
  141604. 15,
  141605. 0,
  141606. 16,
  141607. };
  141608. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141609. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141610. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141611. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141612. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141613. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141614. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141615. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141616. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141617. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141618. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141619. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141620. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141621. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141622. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141623. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141624. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141625. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141626. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141627. 14,
  141628. };
  141629. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141630. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141631. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141632. };
  141633. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141634. 15, 13, 11, 9, 7, 5, 3, 1,
  141635. 0, 2, 4, 6, 8, 10, 12, 14,
  141636. 16,
  141637. };
  141638. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141639. _vq_quantthresh__44cn1_sm_p5_0,
  141640. _vq_quantmap__44cn1_sm_p5_0,
  141641. 17,
  141642. 17
  141643. };
  141644. static static_codebook _44cn1_sm_p5_0 = {
  141645. 2, 289,
  141646. _vq_lengthlist__44cn1_sm_p5_0,
  141647. 1, -529530880, 1611661312, 5, 0,
  141648. _vq_quantlist__44cn1_sm_p5_0,
  141649. NULL,
  141650. &_vq_auxt__44cn1_sm_p5_0,
  141651. NULL,
  141652. 0
  141653. };
  141654. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141655. 1,
  141656. 0,
  141657. 2,
  141658. };
  141659. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141660. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141661. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141662. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141663. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141664. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141665. 10,
  141666. };
  141667. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141668. -5.5, 5.5,
  141669. };
  141670. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141671. 1, 0, 2,
  141672. };
  141673. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141674. _vq_quantthresh__44cn1_sm_p6_0,
  141675. _vq_quantmap__44cn1_sm_p6_0,
  141676. 3,
  141677. 3
  141678. };
  141679. static static_codebook _44cn1_sm_p6_0 = {
  141680. 4, 81,
  141681. _vq_lengthlist__44cn1_sm_p6_0,
  141682. 1, -529137664, 1618345984, 2, 0,
  141683. _vq_quantlist__44cn1_sm_p6_0,
  141684. NULL,
  141685. &_vq_auxt__44cn1_sm_p6_0,
  141686. NULL,
  141687. 0
  141688. };
  141689. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141690. 5,
  141691. 4,
  141692. 6,
  141693. 3,
  141694. 7,
  141695. 2,
  141696. 8,
  141697. 1,
  141698. 9,
  141699. 0,
  141700. 10,
  141701. };
  141702. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141703. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141704. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141705. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141706. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141707. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141708. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141709. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141710. 10,10,10, 8, 9, 8, 8, 9, 8,
  141711. };
  141712. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141713. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141714. 3.5, 4.5,
  141715. };
  141716. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141717. 9, 7, 5, 3, 1, 0, 2, 4,
  141718. 6, 8, 10,
  141719. };
  141720. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141721. _vq_quantthresh__44cn1_sm_p6_1,
  141722. _vq_quantmap__44cn1_sm_p6_1,
  141723. 11,
  141724. 11
  141725. };
  141726. static static_codebook _44cn1_sm_p6_1 = {
  141727. 2, 121,
  141728. _vq_lengthlist__44cn1_sm_p6_1,
  141729. 1, -531365888, 1611661312, 4, 0,
  141730. _vq_quantlist__44cn1_sm_p6_1,
  141731. NULL,
  141732. &_vq_auxt__44cn1_sm_p6_1,
  141733. NULL,
  141734. 0
  141735. };
  141736. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141737. 6,
  141738. 5,
  141739. 7,
  141740. 4,
  141741. 8,
  141742. 3,
  141743. 9,
  141744. 2,
  141745. 10,
  141746. 1,
  141747. 11,
  141748. 0,
  141749. 12,
  141750. };
  141751. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141752. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141753. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141754. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141755. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141756. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141757. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141758. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141759. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141760. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141761. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141762. 0,13,12,12,12,13,13,13,14,
  141763. };
  141764. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141765. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141766. 12.5, 17.5, 22.5, 27.5,
  141767. };
  141768. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141769. 11, 9, 7, 5, 3, 1, 0, 2,
  141770. 4, 6, 8, 10, 12,
  141771. };
  141772. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141773. _vq_quantthresh__44cn1_sm_p7_0,
  141774. _vq_quantmap__44cn1_sm_p7_0,
  141775. 13,
  141776. 13
  141777. };
  141778. static static_codebook _44cn1_sm_p7_0 = {
  141779. 2, 169,
  141780. _vq_lengthlist__44cn1_sm_p7_0,
  141781. 1, -526516224, 1616117760, 4, 0,
  141782. _vq_quantlist__44cn1_sm_p7_0,
  141783. NULL,
  141784. &_vq_auxt__44cn1_sm_p7_0,
  141785. NULL,
  141786. 0
  141787. };
  141788. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141789. 2,
  141790. 1,
  141791. 3,
  141792. 0,
  141793. 4,
  141794. };
  141795. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141796. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141797. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141798. };
  141799. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141800. -1.5, -0.5, 0.5, 1.5,
  141801. };
  141802. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141803. 3, 1, 0, 2, 4,
  141804. };
  141805. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141806. _vq_quantthresh__44cn1_sm_p7_1,
  141807. _vq_quantmap__44cn1_sm_p7_1,
  141808. 5,
  141809. 5
  141810. };
  141811. static static_codebook _44cn1_sm_p7_1 = {
  141812. 2, 25,
  141813. _vq_lengthlist__44cn1_sm_p7_1,
  141814. 1, -533725184, 1611661312, 3, 0,
  141815. _vq_quantlist__44cn1_sm_p7_1,
  141816. NULL,
  141817. &_vq_auxt__44cn1_sm_p7_1,
  141818. NULL,
  141819. 0
  141820. };
  141821. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141822. 4,
  141823. 3,
  141824. 5,
  141825. 2,
  141826. 6,
  141827. 1,
  141828. 7,
  141829. 0,
  141830. 8,
  141831. };
  141832. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141833. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141834. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141835. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141836. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141837. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141838. 14,
  141839. };
  141840. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141841. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141842. };
  141843. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141844. 7, 5, 3, 1, 0, 2, 4, 6,
  141845. 8,
  141846. };
  141847. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141848. _vq_quantthresh__44cn1_sm_p8_0,
  141849. _vq_quantmap__44cn1_sm_p8_0,
  141850. 9,
  141851. 9
  141852. };
  141853. static static_codebook _44cn1_sm_p8_0 = {
  141854. 2, 81,
  141855. _vq_lengthlist__44cn1_sm_p8_0,
  141856. 1, -516186112, 1627103232, 4, 0,
  141857. _vq_quantlist__44cn1_sm_p8_0,
  141858. NULL,
  141859. &_vq_auxt__44cn1_sm_p8_0,
  141860. NULL,
  141861. 0
  141862. };
  141863. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141864. 6,
  141865. 5,
  141866. 7,
  141867. 4,
  141868. 8,
  141869. 3,
  141870. 9,
  141871. 2,
  141872. 10,
  141873. 1,
  141874. 11,
  141875. 0,
  141876. 12,
  141877. };
  141878. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141879. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141880. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141881. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141882. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141883. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141884. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141885. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141886. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141887. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141888. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141889. 17,12,12,11,10,13,11,13,13,
  141890. };
  141891. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141892. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141893. 42.5, 59.5, 76.5, 93.5,
  141894. };
  141895. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141896. 11, 9, 7, 5, 3, 1, 0, 2,
  141897. 4, 6, 8, 10, 12,
  141898. };
  141899. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141900. _vq_quantthresh__44cn1_sm_p8_1,
  141901. _vq_quantmap__44cn1_sm_p8_1,
  141902. 13,
  141903. 13
  141904. };
  141905. static static_codebook _44cn1_sm_p8_1 = {
  141906. 2, 169,
  141907. _vq_lengthlist__44cn1_sm_p8_1,
  141908. 1, -522616832, 1620115456, 4, 0,
  141909. _vq_quantlist__44cn1_sm_p8_1,
  141910. NULL,
  141911. &_vq_auxt__44cn1_sm_p8_1,
  141912. NULL,
  141913. 0
  141914. };
  141915. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141916. 8,
  141917. 7,
  141918. 9,
  141919. 6,
  141920. 10,
  141921. 5,
  141922. 11,
  141923. 4,
  141924. 12,
  141925. 3,
  141926. 13,
  141927. 2,
  141928. 14,
  141929. 1,
  141930. 15,
  141931. 0,
  141932. 16,
  141933. };
  141934. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141935. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141936. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141937. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141938. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141939. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141940. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141941. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141942. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141943. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141944. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141945. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141946. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141947. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141948. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141949. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141950. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141951. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141952. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141953. 9,
  141954. };
  141955. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141956. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141957. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141958. };
  141959. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141960. 15, 13, 11, 9, 7, 5, 3, 1,
  141961. 0, 2, 4, 6, 8, 10, 12, 14,
  141962. 16,
  141963. };
  141964. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141965. _vq_quantthresh__44cn1_sm_p8_2,
  141966. _vq_quantmap__44cn1_sm_p8_2,
  141967. 17,
  141968. 17
  141969. };
  141970. static static_codebook _44cn1_sm_p8_2 = {
  141971. 2, 289,
  141972. _vq_lengthlist__44cn1_sm_p8_2,
  141973. 1, -529530880, 1611661312, 5, 0,
  141974. _vq_quantlist__44cn1_sm_p8_2,
  141975. NULL,
  141976. &_vq_auxt__44cn1_sm_p8_2,
  141977. NULL,
  141978. 0
  141979. };
  141980. static long _huff_lengthlist__44cn1_sm_short[] = {
  141981. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141982. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141983. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141984. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141985. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141986. 9,
  141987. };
  141988. static static_codebook _huff_book__44cn1_sm_short = {
  141989. 2, 81,
  141990. _huff_lengthlist__44cn1_sm_short,
  141991. 0, 0, 0, 0, 0,
  141992. NULL,
  141993. NULL,
  141994. NULL,
  141995. NULL,
  141996. 0
  141997. };
  141998. /*** End of inlined file: res_books_stereo.h ***/
  141999. /***** residue backends *********************************************/
  142000. static vorbis_info_residue0 _residue_44_low={
  142001. 0,-1, -1, 9,-1,
  142002. /* 0 1 2 3 4 5 6 7 */
  142003. {0},
  142004. {-1},
  142005. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142006. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142007. };
  142008. static vorbis_info_residue0 _residue_44_mid={
  142009. 0,-1, -1, 10,-1,
  142010. /* 0 1 2 3 4 5 6 7 8 */
  142011. {0},
  142012. {-1},
  142013. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142014. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142015. };
  142016. static vorbis_info_residue0 _residue_44_high={
  142017. 0,-1, -1, 10,-1,
  142018. /* 0 1 2 3 4 5 6 7 8 */
  142019. {0},
  142020. {-1},
  142021. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142022. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142023. };
  142024. static static_bookblock _resbook_44s_n1={
  142025. {
  142026. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142027. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142028. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142029. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142030. }
  142031. };
  142032. static static_bookblock _resbook_44sm_n1={
  142033. {
  142034. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142035. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142036. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142037. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142038. }
  142039. };
  142040. static static_bookblock _resbook_44s_0={
  142041. {
  142042. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142043. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142044. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142045. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142046. }
  142047. };
  142048. static static_bookblock _resbook_44sm_0={
  142049. {
  142050. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142051. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142052. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142053. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142054. }
  142055. };
  142056. static static_bookblock _resbook_44s_1={
  142057. {
  142058. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142059. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142060. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142061. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142062. }
  142063. };
  142064. static static_bookblock _resbook_44sm_1={
  142065. {
  142066. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142067. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142068. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142069. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142070. }
  142071. };
  142072. static static_bookblock _resbook_44s_2={
  142073. {
  142074. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142075. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142076. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142077. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142078. }
  142079. };
  142080. static static_bookblock _resbook_44s_3={
  142081. {
  142082. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142083. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142084. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142085. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142086. }
  142087. };
  142088. static static_bookblock _resbook_44s_4={
  142089. {
  142090. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142091. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142092. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142093. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142094. }
  142095. };
  142096. static static_bookblock _resbook_44s_5={
  142097. {
  142098. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142099. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142100. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142101. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142102. }
  142103. };
  142104. static static_bookblock _resbook_44s_6={
  142105. {
  142106. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142107. {0,0,&_44c6_s_p4_0},
  142108. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142109. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142110. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142111. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142112. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142113. }
  142114. };
  142115. static static_bookblock _resbook_44s_7={
  142116. {
  142117. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142118. {0,0,&_44c7_s_p4_0},
  142119. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142120. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142121. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142122. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142123. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142124. }
  142125. };
  142126. static static_bookblock _resbook_44s_8={
  142127. {
  142128. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142129. {0,0,&_44c8_s_p4_0},
  142130. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142131. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142132. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142133. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142134. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142135. }
  142136. };
  142137. static static_bookblock _resbook_44s_9={
  142138. {
  142139. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142140. {0,0,&_44c9_s_p4_0},
  142141. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142142. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142143. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142144. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142145. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142146. }
  142147. };
  142148. static vorbis_residue_template _res_44s_n1[]={
  142149. {2,0, &_residue_44_low,
  142150. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142151. &_resbook_44s_n1,&_resbook_44sm_n1},
  142152. {2,0, &_residue_44_low,
  142153. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142154. &_resbook_44s_n1,&_resbook_44sm_n1}
  142155. };
  142156. static vorbis_residue_template _res_44s_0[]={
  142157. {2,0, &_residue_44_low,
  142158. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142159. &_resbook_44s_0,&_resbook_44sm_0},
  142160. {2,0, &_residue_44_low,
  142161. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142162. &_resbook_44s_0,&_resbook_44sm_0}
  142163. };
  142164. static vorbis_residue_template _res_44s_1[]={
  142165. {2,0, &_residue_44_low,
  142166. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142167. &_resbook_44s_1,&_resbook_44sm_1},
  142168. {2,0, &_residue_44_low,
  142169. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142170. &_resbook_44s_1,&_resbook_44sm_1}
  142171. };
  142172. static vorbis_residue_template _res_44s_2[]={
  142173. {2,0, &_residue_44_mid,
  142174. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142175. &_resbook_44s_2,&_resbook_44s_2},
  142176. {2,0, &_residue_44_mid,
  142177. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142178. &_resbook_44s_2,&_resbook_44s_2}
  142179. };
  142180. static vorbis_residue_template _res_44s_3[]={
  142181. {2,0, &_residue_44_mid,
  142182. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142183. &_resbook_44s_3,&_resbook_44s_3},
  142184. {2,0, &_residue_44_mid,
  142185. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142186. &_resbook_44s_3,&_resbook_44s_3}
  142187. };
  142188. static vorbis_residue_template _res_44s_4[]={
  142189. {2,0, &_residue_44_mid,
  142190. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142191. &_resbook_44s_4,&_resbook_44s_4},
  142192. {2,0, &_residue_44_mid,
  142193. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142194. &_resbook_44s_4,&_resbook_44s_4}
  142195. };
  142196. static vorbis_residue_template _res_44s_5[]={
  142197. {2,0, &_residue_44_mid,
  142198. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142199. &_resbook_44s_5,&_resbook_44s_5},
  142200. {2,0, &_residue_44_mid,
  142201. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142202. &_resbook_44s_5,&_resbook_44s_5}
  142203. };
  142204. static vorbis_residue_template _res_44s_6[]={
  142205. {2,0, &_residue_44_high,
  142206. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142207. &_resbook_44s_6,&_resbook_44s_6},
  142208. {2,0, &_residue_44_high,
  142209. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142210. &_resbook_44s_6,&_resbook_44s_6}
  142211. };
  142212. static vorbis_residue_template _res_44s_7[]={
  142213. {2,0, &_residue_44_high,
  142214. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142215. &_resbook_44s_7,&_resbook_44s_7},
  142216. {2,0, &_residue_44_high,
  142217. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142218. &_resbook_44s_7,&_resbook_44s_7}
  142219. };
  142220. static vorbis_residue_template _res_44s_8[]={
  142221. {2,0, &_residue_44_high,
  142222. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142223. &_resbook_44s_8,&_resbook_44s_8},
  142224. {2,0, &_residue_44_high,
  142225. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142226. &_resbook_44s_8,&_resbook_44s_8}
  142227. };
  142228. static vorbis_residue_template _res_44s_9[]={
  142229. {2,0, &_residue_44_high,
  142230. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142231. &_resbook_44s_9,&_resbook_44s_9},
  142232. {2,0, &_residue_44_high,
  142233. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142234. &_resbook_44s_9,&_resbook_44s_9}
  142235. };
  142236. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142237. { _map_nominal, _res_44s_n1 }, /* -1 */
  142238. { _map_nominal, _res_44s_0 }, /* 0 */
  142239. { _map_nominal, _res_44s_1 }, /* 1 */
  142240. { _map_nominal, _res_44s_2 }, /* 2 */
  142241. { _map_nominal, _res_44s_3 }, /* 3 */
  142242. { _map_nominal, _res_44s_4 }, /* 4 */
  142243. { _map_nominal, _res_44s_5 }, /* 5 */
  142244. { _map_nominal, _res_44s_6 }, /* 6 */
  142245. { _map_nominal, _res_44s_7 }, /* 7 */
  142246. { _map_nominal, _res_44s_8 }, /* 8 */
  142247. { _map_nominal, _res_44s_9 }, /* 9 */
  142248. };
  142249. /*** End of inlined file: residue_44.h ***/
  142250. /*** Start of inlined file: psych_44.h ***/
  142251. /* preecho trigger settings *****************************************/
  142252. static vorbis_info_psy_global _psy_global_44[5]={
  142253. {8, /* lines per eighth octave */
  142254. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142255. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142256. -6.f,
  142257. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142258. },
  142259. {8, /* lines per eighth octave */
  142260. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142261. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142262. -6.f,
  142263. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142264. },
  142265. {8, /* lines per eighth octave */
  142266. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142267. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142268. -6.f,
  142269. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142270. },
  142271. {8, /* lines per eighth octave */
  142272. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142273. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142274. -6.f,
  142275. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142276. },
  142277. {8, /* lines per eighth octave */
  142278. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142279. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142280. -6.f,
  142281. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142282. },
  142283. };
  142284. /* noise compander lookups * low, mid, high quality ****************/
  142285. static compandblock _psy_compand_44[6]={
  142286. /* sub-mode Z short */
  142287. {{
  142288. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142289. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142290. 16,17,18,19,20,21,22, 23, /* 23dB */
  142291. 24,25,26,27,28,29,30, 31, /* 31dB */
  142292. 32,33,34,35,36,37,38, 39, /* 39dB */
  142293. }},
  142294. /* mode_Z nominal short */
  142295. {{
  142296. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142297. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142298. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142299. 15,16,17,17,17,18,18, 19, /* 31dB */
  142300. 19,19,20,21,22,23,24, 25, /* 39dB */
  142301. }},
  142302. /* mode A short */
  142303. {{
  142304. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142305. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142306. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142307. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142308. 11,12,13,14,15,16,17, 18, /* 39dB */
  142309. }},
  142310. /* sub-mode Z long */
  142311. {{
  142312. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142313. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142314. 16,17,18,19,20,21,22, 23, /* 23dB */
  142315. 24,25,26,27,28,29,30, 31, /* 31dB */
  142316. 32,33,34,35,36,37,38, 39, /* 39dB */
  142317. }},
  142318. /* mode_Z nominal long */
  142319. {{
  142320. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142321. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142322. 13,14,14,14,15,15,15, 15, /* 23dB */
  142323. 16,16,17,17,17,18,18, 19, /* 31dB */
  142324. 19,19,20,21,22,23,24, 25, /* 39dB */
  142325. }},
  142326. /* mode A long */
  142327. {{
  142328. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142329. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142330. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142331. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142332. 11,12,13,14,15,16,17, 18, /* 39dB */
  142333. }}
  142334. };
  142335. /* tonal masking curve level adjustments *************************/
  142336. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142337. /* 63 125 250 500 1 2 4 8 16 */
  142338. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142339. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142340. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142341. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142342. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142343. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142344. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142345. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142346. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142347. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142348. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142349. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142350. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142351. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142352. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142353. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142354. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142355. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142356. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142357. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142358. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142359. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142360. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142361. };
  142362. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142363. /* 63 125 250 500 1 2 4 8 16 */
  142364. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142365. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142366. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142367. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142368. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142369. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142370. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142371. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142372. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142373. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142374. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142375. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142376. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142377. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142378. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142379. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142380. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142381. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142382. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142383. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142384. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142385. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142386. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142387. };
  142388. /* noise bias (transition block) */
  142389. static noise3 _psy_noisebias_trans[12]={
  142390. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142391. /* -1 */
  142392. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142393. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142394. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142395. /* 0
  142396. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142397. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142398. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142399. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142400. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142401. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142402. /* 1
  142403. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142404. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142405. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142406. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142407. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142408. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142409. /* 2
  142410. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142411. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142412. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142413. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142414. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142415. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142416. /* 3
  142417. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142418. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142419. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142420. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142421. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142422. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142423. /* 4
  142424. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142425. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142426. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142427. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142428. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142429. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142430. /* 5
  142431. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142432. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142433. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142434. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142435. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142436. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142437. /* 6
  142438. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142439. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142440. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142441. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142442. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142443. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142444. /* 7
  142445. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142446. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142447. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  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,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142450. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142451. /* 8
  142452. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142453. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142454. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142455. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142456. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142457. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142458. /* 9
  142459. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142460. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142461. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142462. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142463. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142464. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142465. /* 10 */
  142466. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142467. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142468. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142469. };
  142470. /* noise bias (long block) */
  142471. static noise3 _psy_noisebias_long[12]={
  142472. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142473. /* -1 */
  142474. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142475. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142476. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142477. /* 0 */
  142478. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142479. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142480. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142481. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142482. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142483. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142484. /* 1 */
  142485. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142486. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142487. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142488. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142489. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142490. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142491. /* 2 */
  142492. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142493. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142494. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142495. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142496. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142497. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142498. /* 3 */
  142499. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142500. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142501. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142502. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142503. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142504. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142505. /* 4 */
  142506. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142507. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142508. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142509. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142510. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142511. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142512. /* 5 */
  142513. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142514. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142515. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142516. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142517. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142518. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142519. /* 6 */
  142520. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142521. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142522. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142523. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142524. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142525. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142526. /* 7 */
  142527. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142528. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142529. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142530. /* 8 */
  142531. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142532. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142533. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142534. /* 9 */
  142535. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142536. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142537. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142538. /* 10 */
  142539. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142540. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142541. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142542. };
  142543. /* noise bias (impulse block) */
  142544. static noise3 _psy_noisebias_impulse[12]={
  142545. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142546. /* -1 */
  142547. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142548. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142549. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142550. /* 0 */
  142551. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142552. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142553. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142554. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142555. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142556. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142557. /* 1 */
  142558. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142559. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142560. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142561. /* 2 */
  142562. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142563. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142564. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142565. /* 3 */
  142566. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142567. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142568. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142569. /* 4 */
  142570. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142571. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142572. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142573. /* 5 */
  142574. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142575. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142576. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142577. /* 6
  142578. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142579. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142580. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142581. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142582. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142583. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142584. /* 7 */
  142585. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142586. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142587. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142588. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142589. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142590. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142591. /* 8 */
  142592. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142593. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142594. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142595. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142596. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142597. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142598. /* 9 */
  142599. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142600. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142601. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142602. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142603. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142604. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142605. /* 10 */
  142606. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142607. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142608. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142609. };
  142610. /* noise bias (padding block) */
  142611. static noise3 _psy_noisebias_padding[12]={
  142612. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142613. /* -1 */
  142614. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142615. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142616. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142617. /* 0 */
  142618. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142619. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142621. /* 1 */
  142622. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142624. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142625. /* 2 */
  142626. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142627. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142628. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142629. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142630. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142631. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142632. /* 3 */
  142633. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142634. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142635. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142636. /* 4 */
  142637. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142638. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142639. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142640. /* 5 */
  142641. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142642. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142643. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142644. /* 6 */
  142645. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142646. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142647. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142648. /* 7 */
  142649. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142650. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142651. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142652. /* 8 */
  142653. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142654. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142655. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142656. /* 9 */
  142657. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142658. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142659. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142660. /* 10 */
  142661. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142662. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142663. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142664. };
  142665. static noiseguard _psy_noiseguards_44[4]={
  142666. {3,3,15},
  142667. {3,3,15},
  142668. {10,10,100},
  142669. {10,10,100},
  142670. };
  142671. static int _psy_tone_suppress[12]={
  142672. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142673. };
  142674. static int _psy_tone_0dB[12]={
  142675. 90,90,95,95,95,95,105,105,105,105,105,105,
  142676. };
  142677. static int _psy_noise_suppress[12]={
  142678. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142679. };
  142680. static vorbis_info_psy _psy_info_template={
  142681. /* blockflag */
  142682. -1,
  142683. /* ath_adjatt, ath_maxatt */
  142684. -140.,-140.,
  142685. /* tonemask att boost/decay,suppr,curves */
  142686. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142687. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142688. 1, -0.f, .5f, .5f, 0,0,0,
  142689. /* noiseoffset*3, noisecompand, max_curve_dB */
  142690. {{-1},{-1},{-1}},{-1},105.f,
  142691. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142692. 0,0,-1,-1,0.,
  142693. };
  142694. /* ath ****************/
  142695. static int _psy_ath_floater[12]={
  142696. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142697. };
  142698. static int _psy_ath_abs[12]={
  142699. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142700. };
  142701. /* stereo setup. These don't map directly to quality level, there's
  142702. an additional indirection as several of the below may be used in a
  142703. single bitmanaged stream
  142704. ****************/
  142705. /* various stereo possibilities */
  142706. /* stereo mode by base quality level */
  142707. static adj_stereo _psy_stereo_modes_44[12]={
  142708. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142709. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142710. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142711. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142712. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142713. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142714. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142715. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142716. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142717. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142718. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142719. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142720. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142721. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142722. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142723. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142724. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142725. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142726. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142727. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142728. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142729. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142730. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142731. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142732. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142733. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142734. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142735. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142736. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142737. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142738. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142739. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142740. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142741. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142742. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142743. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142744. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142745. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142746. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142747. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142748. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142749. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142750. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142751. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142752. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142753. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142754. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142755. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142756. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142757. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142758. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142759. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142760. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142761. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142762. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142763. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142764. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142765. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142766. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142767. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142768. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142769. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142770. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142771. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142772. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142773. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142774. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142775. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142776. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142777. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142778. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142779. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142780. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142781. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142782. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142783. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142784. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142785. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142786. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142787. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142788. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142789. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142790. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142791. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142792. };
  142793. /* tone master attenuation by base quality mode and bitrate tweak */
  142794. static att3 _psy_tone_masteratt_44[12]={
  142795. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142796. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142797. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142798. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142799. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142800. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142801. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142802. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142803. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142804. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142805. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142806. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142807. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142808. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142809. };
  142810. /* lowpass by mode **************/
  142811. static double _psy_lowpass_44[12]={
  142812. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142813. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142814. };
  142815. /* noise normalization **********/
  142816. static int _noise_start_short_44[11]={
  142817. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142818. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142819. };
  142820. static int _noise_start_long_44[11]={
  142821. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142822. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142823. };
  142824. static int _noise_part_short_44[11]={
  142825. 8,8,8,8,8,8,8,8,8,8,8
  142826. };
  142827. static int _noise_part_long_44[11]={
  142828. 32,32,32,32,32,32,32,32,32,32,32
  142829. };
  142830. static double _noise_thresh_44[11]={
  142831. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142832. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142833. };
  142834. static double _noise_thresh_5only[2]={
  142835. .5,.5,
  142836. };
  142837. /*** End of inlined file: psych_44.h ***/
  142838. static double rate_mapping_44_stereo[12]={
  142839. 22500.,32000.,40000.,48000.,56000.,64000.,
  142840. 80000.,96000.,112000.,128000.,160000.,250001.
  142841. };
  142842. static double quality_mapping_44[12]={
  142843. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142844. };
  142845. static int blocksize_short_44[11]={
  142846. 512,256,256,256,256,256,256,256,256,256,256
  142847. };
  142848. static int blocksize_long_44[11]={
  142849. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142850. };
  142851. static double _psy_compand_short_mapping[12]={
  142852. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142853. };
  142854. static double _psy_compand_long_mapping[12]={
  142855. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142856. };
  142857. static double _global_mapping_44[12]={
  142858. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142859. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142860. };
  142861. static int _floor_short_mapping_44[11]={
  142862. 1,0,0,2,2,4,5,5,5,5,5
  142863. };
  142864. static int _floor_long_mapping_44[11]={
  142865. 8,7,7,7,7,7,7,7,7,7,7
  142866. };
  142867. ve_setup_data_template ve_setup_44_stereo={
  142868. 11,
  142869. rate_mapping_44_stereo,
  142870. quality_mapping_44,
  142871. 2,
  142872. 40000,
  142873. 50000,
  142874. blocksize_short_44,
  142875. blocksize_long_44,
  142876. _psy_tone_masteratt_44,
  142877. _psy_tone_0dB,
  142878. _psy_tone_suppress,
  142879. _vp_tonemask_adj_otherblock,
  142880. _vp_tonemask_adj_longblock,
  142881. _vp_tonemask_adj_otherblock,
  142882. _psy_noiseguards_44,
  142883. _psy_noisebias_impulse,
  142884. _psy_noisebias_padding,
  142885. _psy_noisebias_trans,
  142886. _psy_noisebias_long,
  142887. _psy_noise_suppress,
  142888. _psy_compand_44,
  142889. _psy_compand_short_mapping,
  142890. _psy_compand_long_mapping,
  142891. {_noise_start_short_44,_noise_start_long_44},
  142892. {_noise_part_short_44,_noise_part_long_44},
  142893. _noise_thresh_44,
  142894. _psy_ath_floater,
  142895. _psy_ath_abs,
  142896. _psy_lowpass_44,
  142897. _psy_global_44,
  142898. _global_mapping_44,
  142899. _psy_stereo_modes_44,
  142900. _floor_books,
  142901. _floor,
  142902. _floor_short_mapping_44,
  142903. _floor_long_mapping_44,
  142904. _mapres_template_44_stereo
  142905. };
  142906. /*** End of inlined file: setup_44.h ***/
  142907. /*** Start of inlined file: setup_44u.h ***/
  142908. /*** Start of inlined file: residue_44u.h ***/
  142909. /*** Start of inlined file: res_books_uncoupled.h ***/
  142910. static long _vq_quantlist__16u0__p1_0[] = {
  142911. 1,
  142912. 0,
  142913. 2,
  142914. };
  142915. static long _vq_lengthlist__16u0__p1_0[] = {
  142916. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142917. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142918. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142919. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142920. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142921. 12,
  142922. };
  142923. static float _vq_quantthresh__16u0__p1_0[] = {
  142924. -0.5, 0.5,
  142925. };
  142926. static long _vq_quantmap__16u0__p1_0[] = {
  142927. 1, 0, 2,
  142928. };
  142929. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142930. _vq_quantthresh__16u0__p1_0,
  142931. _vq_quantmap__16u0__p1_0,
  142932. 3,
  142933. 3
  142934. };
  142935. static static_codebook _16u0__p1_0 = {
  142936. 4, 81,
  142937. _vq_lengthlist__16u0__p1_0,
  142938. 1, -535822336, 1611661312, 2, 0,
  142939. _vq_quantlist__16u0__p1_0,
  142940. NULL,
  142941. &_vq_auxt__16u0__p1_0,
  142942. NULL,
  142943. 0
  142944. };
  142945. static long _vq_quantlist__16u0__p2_0[] = {
  142946. 1,
  142947. 0,
  142948. 2,
  142949. };
  142950. static long _vq_lengthlist__16u0__p2_0[] = {
  142951. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142952. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142953. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142954. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142955. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142956. 8,
  142957. };
  142958. static float _vq_quantthresh__16u0__p2_0[] = {
  142959. -0.5, 0.5,
  142960. };
  142961. static long _vq_quantmap__16u0__p2_0[] = {
  142962. 1, 0, 2,
  142963. };
  142964. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142965. _vq_quantthresh__16u0__p2_0,
  142966. _vq_quantmap__16u0__p2_0,
  142967. 3,
  142968. 3
  142969. };
  142970. static static_codebook _16u0__p2_0 = {
  142971. 4, 81,
  142972. _vq_lengthlist__16u0__p2_0,
  142973. 1, -535822336, 1611661312, 2, 0,
  142974. _vq_quantlist__16u0__p2_0,
  142975. NULL,
  142976. &_vq_auxt__16u0__p2_0,
  142977. NULL,
  142978. 0
  142979. };
  142980. static long _vq_quantlist__16u0__p3_0[] = {
  142981. 2,
  142982. 1,
  142983. 3,
  142984. 0,
  142985. 4,
  142986. };
  142987. static long _vq_lengthlist__16u0__p3_0[] = {
  142988. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142989. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142990. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142991. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142992. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142993. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142994. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142995. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142996. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142997. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142998. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142999. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143000. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143001. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143002. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143003. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143004. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143005. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143006. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143007. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143008. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143009. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143010. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143011. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143012. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143013. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143014. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143015. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143016. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143017. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143018. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143019. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143020. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143021. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143022. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143023. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143024. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143025. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143026. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143027. 18,
  143028. };
  143029. static float _vq_quantthresh__16u0__p3_0[] = {
  143030. -1.5, -0.5, 0.5, 1.5,
  143031. };
  143032. static long _vq_quantmap__16u0__p3_0[] = {
  143033. 3, 1, 0, 2, 4,
  143034. };
  143035. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143036. _vq_quantthresh__16u0__p3_0,
  143037. _vq_quantmap__16u0__p3_0,
  143038. 5,
  143039. 5
  143040. };
  143041. static static_codebook _16u0__p3_0 = {
  143042. 4, 625,
  143043. _vq_lengthlist__16u0__p3_0,
  143044. 1, -533725184, 1611661312, 3, 0,
  143045. _vq_quantlist__16u0__p3_0,
  143046. NULL,
  143047. &_vq_auxt__16u0__p3_0,
  143048. NULL,
  143049. 0
  143050. };
  143051. static long _vq_quantlist__16u0__p4_0[] = {
  143052. 2,
  143053. 1,
  143054. 3,
  143055. 0,
  143056. 4,
  143057. };
  143058. static long _vq_lengthlist__16u0__p4_0[] = {
  143059. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143060. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143061. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143062. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143063. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143064. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143065. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143066. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143067. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143068. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143069. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143070. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143071. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143072. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143073. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143074. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143075. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143076. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143077. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143078. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143079. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143080. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143081. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143082. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143083. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143084. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143085. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143086. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143087. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143088. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143089. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143090. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143091. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143092. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143093. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143094. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143095. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143096. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143097. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143098. 11,
  143099. };
  143100. static float _vq_quantthresh__16u0__p4_0[] = {
  143101. -1.5, -0.5, 0.5, 1.5,
  143102. };
  143103. static long _vq_quantmap__16u0__p4_0[] = {
  143104. 3, 1, 0, 2, 4,
  143105. };
  143106. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143107. _vq_quantthresh__16u0__p4_0,
  143108. _vq_quantmap__16u0__p4_0,
  143109. 5,
  143110. 5
  143111. };
  143112. static static_codebook _16u0__p4_0 = {
  143113. 4, 625,
  143114. _vq_lengthlist__16u0__p4_0,
  143115. 1, -533725184, 1611661312, 3, 0,
  143116. _vq_quantlist__16u0__p4_0,
  143117. NULL,
  143118. &_vq_auxt__16u0__p4_0,
  143119. NULL,
  143120. 0
  143121. };
  143122. static long _vq_quantlist__16u0__p5_0[] = {
  143123. 4,
  143124. 3,
  143125. 5,
  143126. 2,
  143127. 6,
  143128. 1,
  143129. 7,
  143130. 0,
  143131. 8,
  143132. };
  143133. static long _vq_lengthlist__16u0__p5_0[] = {
  143134. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143135. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143136. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143137. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143138. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143139. 12,
  143140. };
  143141. static float _vq_quantthresh__16u0__p5_0[] = {
  143142. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143143. };
  143144. static long _vq_quantmap__16u0__p5_0[] = {
  143145. 7, 5, 3, 1, 0, 2, 4, 6,
  143146. 8,
  143147. };
  143148. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143149. _vq_quantthresh__16u0__p5_0,
  143150. _vq_quantmap__16u0__p5_0,
  143151. 9,
  143152. 9
  143153. };
  143154. static static_codebook _16u0__p5_0 = {
  143155. 2, 81,
  143156. _vq_lengthlist__16u0__p5_0,
  143157. 1, -531628032, 1611661312, 4, 0,
  143158. _vq_quantlist__16u0__p5_0,
  143159. NULL,
  143160. &_vq_auxt__16u0__p5_0,
  143161. NULL,
  143162. 0
  143163. };
  143164. static long _vq_quantlist__16u0__p6_0[] = {
  143165. 6,
  143166. 5,
  143167. 7,
  143168. 4,
  143169. 8,
  143170. 3,
  143171. 9,
  143172. 2,
  143173. 10,
  143174. 1,
  143175. 11,
  143176. 0,
  143177. 12,
  143178. };
  143179. static long _vq_lengthlist__16u0__p6_0[] = {
  143180. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143181. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143182. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143183. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143184. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143185. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143186. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143187. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143188. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143189. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143190. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143191. };
  143192. static float _vq_quantthresh__16u0__p6_0[] = {
  143193. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143194. 12.5, 17.5, 22.5, 27.5,
  143195. };
  143196. static long _vq_quantmap__16u0__p6_0[] = {
  143197. 11, 9, 7, 5, 3, 1, 0, 2,
  143198. 4, 6, 8, 10, 12,
  143199. };
  143200. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143201. _vq_quantthresh__16u0__p6_0,
  143202. _vq_quantmap__16u0__p6_0,
  143203. 13,
  143204. 13
  143205. };
  143206. static static_codebook _16u0__p6_0 = {
  143207. 2, 169,
  143208. _vq_lengthlist__16u0__p6_0,
  143209. 1, -526516224, 1616117760, 4, 0,
  143210. _vq_quantlist__16u0__p6_0,
  143211. NULL,
  143212. &_vq_auxt__16u0__p6_0,
  143213. NULL,
  143214. 0
  143215. };
  143216. static long _vq_quantlist__16u0__p6_1[] = {
  143217. 2,
  143218. 1,
  143219. 3,
  143220. 0,
  143221. 4,
  143222. };
  143223. static long _vq_lengthlist__16u0__p6_1[] = {
  143224. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143225. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143226. };
  143227. static float _vq_quantthresh__16u0__p6_1[] = {
  143228. -1.5, -0.5, 0.5, 1.5,
  143229. };
  143230. static long _vq_quantmap__16u0__p6_1[] = {
  143231. 3, 1, 0, 2, 4,
  143232. };
  143233. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143234. _vq_quantthresh__16u0__p6_1,
  143235. _vq_quantmap__16u0__p6_1,
  143236. 5,
  143237. 5
  143238. };
  143239. static static_codebook _16u0__p6_1 = {
  143240. 2, 25,
  143241. _vq_lengthlist__16u0__p6_1,
  143242. 1, -533725184, 1611661312, 3, 0,
  143243. _vq_quantlist__16u0__p6_1,
  143244. NULL,
  143245. &_vq_auxt__16u0__p6_1,
  143246. NULL,
  143247. 0
  143248. };
  143249. static long _vq_quantlist__16u0__p7_0[] = {
  143250. 1,
  143251. 0,
  143252. 2,
  143253. };
  143254. static long _vq_lengthlist__16u0__p7_0[] = {
  143255. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143256. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143257. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143258. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143259. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143260. 7,
  143261. };
  143262. static float _vq_quantthresh__16u0__p7_0[] = {
  143263. -157.5, 157.5,
  143264. };
  143265. static long _vq_quantmap__16u0__p7_0[] = {
  143266. 1, 0, 2,
  143267. };
  143268. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143269. _vq_quantthresh__16u0__p7_0,
  143270. _vq_quantmap__16u0__p7_0,
  143271. 3,
  143272. 3
  143273. };
  143274. static static_codebook _16u0__p7_0 = {
  143275. 4, 81,
  143276. _vq_lengthlist__16u0__p7_0,
  143277. 1, -518803456, 1628680192, 2, 0,
  143278. _vq_quantlist__16u0__p7_0,
  143279. NULL,
  143280. &_vq_auxt__16u0__p7_0,
  143281. NULL,
  143282. 0
  143283. };
  143284. static long _vq_quantlist__16u0__p7_1[] = {
  143285. 7,
  143286. 6,
  143287. 8,
  143288. 5,
  143289. 9,
  143290. 4,
  143291. 10,
  143292. 3,
  143293. 11,
  143294. 2,
  143295. 12,
  143296. 1,
  143297. 13,
  143298. 0,
  143299. 14,
  143300. };
  143301. static long _vq_lengthlist__16u0__p7_1[] = {
  143302. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143303. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143304. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143305. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143306. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143307. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143308. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143309. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143310. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143311. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143312. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143313. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143314. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143316. 10,
  143317. };
  143318. static float _vq_quantthresh__16u0__p7_1[] = {
  143319. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143320. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143321. };
  143322. static long _vq_quantmap__16u0__p7_1[] = {
  143323. 13, 11, 9, 7, 5, 3, 1, 0,
  143324. 2, 4, 6, 8, 10, 12, 14,
  143325. };
  143326. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143327. _vq_quantthresh__16u0__p7_1,
  143328. _vq_quantmap__16u0__p7_1,
  143329. 15,
  143330. 15
  143331. };
  143332. static static_codebook _16u0__p7_1 = {
  143333. 2, 225,
  143334. _vq_lengthlist__16u0__p7_1,
  143335. 1, -520986624, 1620377600, 4, 0,
  143336. _vq_quantlist__16u0__p7_1,
  143337. NULL,
  143338. &_vq_auxt__16u0__p7_1,
  143339. NULL,
  143340. 0
  143341. };
  143342. static long _vq_quantlist__16u0__p7_2[] = {
  143343. 10,
  143344. 9,
  143345. 11,
  143346. 8,
  143347. 12,
  143348. 7,
  143349. 13,
  143350. 6,
  143351. 14,
  143352. 5,
  143353. 15,
  143354. 4,
  143355. 16,
  143356. 3,
  143357. 17,
  143358. 2,
  143359. 18,
  143360. 1,
  143361. 19,
  143362. 0,
  143363. 20,
  143364. };
  143365. static long _vq_lengthlist__16u0__p7_2[] = {
  143366. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143367. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143368. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143369. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143370. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143371. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143372. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143373. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143374. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143375. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143376. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143377. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143378. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143379. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143380. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143381. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143382. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143383. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143384. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143385. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143386. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143387. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143388. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143389. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143390. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143391. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143392. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143393. 10,10,12,11,10,11,11,11,10,
  143394. };
  143395. static float _vq_quantthresh__16u0__p7_2[] = {
  143396. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143397. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143398. 6.5, 7.5, 8.5, 9.5,
  143399. };
  143400. static long _vq_quantmap__16u0__p7_2[] = {
  143401. 19, 17, 15, 13, 11, 9, 7, 5,
  143402. 3, 1, 0, 2, 4, 6, 8, 10,
  143403. 12, 14, 16, 18, 20,
  143404. };
  143405. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143406. _vq_quantthresh__16u0__p7_2,
  143407. _vq_quantmap__16u0__p7_2,
  143408. 21,
  143409. 21
  143410. };
  143411. static static_codebook _16u0__p7_2 = {
  143412. 2, 441,
  143413. _vq_lengthlist__16u0__p7_2,
  143414. 1, -529268736, 1611661312, 5, 0,
  143415. _vq_quantlist__16u0__p7_2,
  143416. NULL,
  143417. &_vq_auxt__16u0__p7_2,
  143418. NULL,
  143419. 0
  143420. };
  143421. static long _huff_lengthlist__16u0__single[] = {
  143422. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143423. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143424. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143425. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143426. };
  143427. static static_codebook _huff_book__16u0__single = {
  143428. 2, 64,
  143429. _huff_lengthlist__16u0__single,
  143430. 0, 0, 0, 0, 0,
  143431. NULL,
  143432. NULL,
  143433. NULL,
  143434. NULL,
  143435. 0
  143436. };
  143437. static long _huff_lengthlist__16u1__long[] = {
  143438. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143439. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143440. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143441. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143442. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143443. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143444. 16,13,16,18,
  143445. };
  143446. static static_codebook _huff_book__16u1__long = {
  143447. 2, 100,
  143448. _huff_lengthlist__16u1__long,
  143449. 0, 0, 0, 0, 0,
  143450. NULL,
  143451. NULL,
  143452. NULL,
  143453. NULL,
  143454. 0
  143455. };
  143456. static long _vq_quantlist__16u1__p1_0[] = {
  143457. 1,
  143458. 0,
  143459. 2,
  143460. };
  143461. static long _vq_lengthlist__16u1__p1_0[] = {
  143462. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143463. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143464. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143465. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143466. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143467. 11,
  143468. };
  143469. static float _vq_quantthresh__16u1__p1_0[] = {
  143470. -0.5, 0.5,
  143471. };
  143472. static long _vq_quantmap__16u1__p1_0[] = {
  143473. 1, 0, 2,
  143474. };
  143475. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143476. _vq_quantthresh__16u1__p1_0,
  143477. _vq_quantmap__16u1__p1_0,
  143478. 3,
  143479. 3
  143480. };
  143481. static static_codebook _16u1__p1_0 = {
  143482. 4, 81,
  143483. _vq_lengthlist__16u1__p1_0,
  143484. 1, -535822336, 1611661312, 2, 0,
  143485. _vq_quantlist__16u1__p1_0,
  143486. NULL,
  143487. &_vq_auxt__16u1__p1_0,
  143488. NULL,
  143489. 0
  143490. };
  143491. static long _vq_quantlist__16u1__p2_0[] = {
  143492. 1,
  143493. 0,
  143494. 2,
  143495. };
  143496. static long _vq_lengthlist__16u1__p2_0[] = {
  143497. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143498. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143499. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143500. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143501. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143502. 8,
  143503. };
  143504. static float _vq_quantthresh__16u1__p2_0[] = {
  143505. -0.5, 0.5,
  143506. };
  143507. static long _vq_quantmap__16u1__p2_0[] = {
  143508. 1, 0, 2,
  143509. };
  143510. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143511. _vq_quantthresh__16u1__p2_0,
  143512. _vq_quantmap__16u1__p2_0,
  143513. 3,
  143514. 3
  143515. };
  143516. static static_codebook _16u1__p2_0 = {
  143517. 4, 81,
  143518. _vq_lengthlist__16u1__p2_0,
  143519. 1, -535822336, 1611661312, 2, 0,
  143520. _vq_quantlist__16u1__p2_0,
  143521. NULL,
  143522. &_vq_auxt__16u1__p2_0,
  143523. NULL,
  143524. 0
  143525. };
  143526. static long _vq_quantlist__16u1__p3_0[] = {
  143527. 2,
  143528. 1,
  143529. 3,
  143530. 0,
  143531. 4,
  143532. };
  143533. static long _vq_lengthlist__16u1__p3_0[] = {
  143534. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143535. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143536. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143537. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143538. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143539. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143540. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143541. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143542. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143543. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143544. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143545. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143546. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143547. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143548. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143549. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143550. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143551. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143552. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143553. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143554. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143555. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143556. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143557. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143558. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143559. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143560. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143561. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143562. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143563. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143564. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143565. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143566. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143567. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143568. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143569. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143570. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143571. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143572. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143573. 16,
  143574. };
  143575. static float _vq_quantthresh__16u1__p3_0[] = {
  143576. -1.5, -0.5, 0.5, 1.5,
  143577. };
  143578. static long _vq_quantmap__16u1__p3_0[] = {
  143579. 3, 1, 0, 2, 4,
  143580. };
  143581. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143582. _vq_quantthresh__16u1__p3_0,
  143583. _vq_quantmap__16u1__p3_0,
  143584. 5,
  143585. 5
  143586. };
  143587. static static_codebook _16u1__p3_0 = {
  143588. 4, 625,
  143589. _vq_lengthlist__16u1__p3_0,
  143590. 1, -533725184, 1611661312, 3, 0,
  143591. _vq_quantlist__16u1__p3_0,
  143592. NULL,
  143593. &_vq_auxt__16u1__p3_0,
  143594. NULL,
  143595. 0
  143596. };
  143597. static long _vq_quantlist__16u1__p4_0[] = {
  143598. 2,
  143599. 1,
  143600. 3,
  143601. 0,
  143602. 4,
  143603. };
  143604. static long _vq_lengthlist__16u1__p4_0[] = {
  143605. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143606. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143607. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143608. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143609. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143610. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143611. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143612. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143613. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143614. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143615. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143616. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143617. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143618. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143619. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143620. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143621. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143622. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143623. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143624. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143625. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143626. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143627. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143628. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143629. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143630. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143631. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143632. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143633. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143634. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143635. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143636. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143637. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143638. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143639. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143640. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143641. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143642. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143643. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143644. 11,
  143645. };
  143646. static float _vq_quantthresh__16u1__p4_0[] = {
  143647. -1.5, -0.5, 0.5, 1.5,
  143648. };
  143649. static long _vq_quantmap__16u1__p4_0[] = {
  143650. 3, 1, 0, 2, 4,
  143651. };
  143652. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143653. _vq_quantthresh__16u1__p4_0,
  143654. _vq_quantmap__16u1__p4_0,
  143655. 5,
  143656. 5
  143657. };
  143658. static static_codebook _16u1__p4_0 = {
  143659. 4, 625,
  143660. _vq_lengthlist__16u1__p4_0,
  143661. 1, -533725184, 1611661312, 3, 0,
  143662. _vq_quantlist__16u1__p4_0,
  143663. NULL,
  143664. &_vq_auxt__16u1__p4_0,
  143665. NULL,
  143666. 0
  143667. };
  143668. static long _vq_quantlist__16u1__p5_0[] = {
  143669. 4,
  143670. 3,
  143671. 5,
  143672. 2,
  143673. 6,
  143674. 1,
  143675. 7,
  143676. 0,
  143677. 8,
  143678. };
  143679. static long _vq_lengthlist__16u1__p5_0[] = {
  143680. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143681. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143682. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143683. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143684. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143685. 13,
  143686. };
  143687. static float _vq_quantthresh__16u1__p5_0[] = {
  143688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143689. };
  143690. static long _vq_quantmap__16u1__p5_0[] = {
  143691. 7, 5, 3, 1, 0, 2, 4, 6,
  143692. 8,
  143693. };
  143694. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143695. _vq_quantthresh__16u1__p5_0,
  143696. _vq_quantmap__16u1__p5_0,
  143697. 9,
  143698. 9
  143699. };
  143700. static static_codebook _16u1__p5_0 = {
  143701. 2, 81,
  143702. _vq_lengthlist__16u1__p5_0,
  143703. 1, -531628032, 1611661312, 4, 0,
  143704. _vq_quantlist__16u1__p5_0,
  143705. NULL,
  143706. &_vq_auxt__16u1__p5_0,
  143707. NULL,
  143708. 0
  143709. };
  143710. static long _vq_quantlist__16u1__p6_0[] = {
  143711. 4,
  143712. 3,
  143713. 5,
  143714. 2,
  143715. 6,
  143716. 1,
  143717. 7,
  143718. 0,
  143719. 8,
  143720. };
  143721. static long _vq_lengthlist__16u1__p6_0[] = {
  143722. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143723. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143724. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143725. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143726. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143727. 11,
  143728. };
  143729. static float _vq_quantthresh__16u1__p6_0[] = {
  143730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143731. };
  143732. static long _vq_quantmap__16u1__p6_0[] = {
  143733. 7, 5, 3, 1, 0, 2, 4, 6,
  143734. 8,
  143735. };
  143736. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143737. _vq_quantthresh__16u1__p6_0,
  143738. _vq_quantmap__16u1__p6_0,
  143739. 9,
  143740. 9
  143741. };
  143742. static static_codebook _16u1__p6_0 = {
  143743. 2, 81,
  143744. _vq_lengthlist__16u1__p6_0,
  143745. 1, -531628032, 1611661312, 4, 0,
  143746. _vq_quantlist__16u1__p6_0,
  143747. NULL,
  143748. &_vq_auxt__16u1__p6_0,
  143749. NULL,
  143750. 0
  143751. };
  143752. static long _vq_quantlist__16u1__p7_0[] = {
  143753. 1,
  143754. 0,
  143755. 2,
  143756. };
  143757. static long _vq_lengthlist__16u1__p7_0[] = {
  143758. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143759. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143760. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143761. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143762. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143763. 13,
  143764. };
  143765. static float _vq_quantthresh__16u1__p7_0[] = {
  143766. -5.5, 5.5,
  143767. };
  143768. static long _vq_quantmap__16u1__p7_0[] = {
  143769. 1, 0, 2,
  143770. };
  143771. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143772. _vq_quantthresh__16u1__p7_0,
  143773. _vq_quantmap__16u1__p7_0,
  143774. 3,
  143775. 3
  143776. };
  143777. static static_codebook _16u1__p7_0 = {
  143778. 4, 81,
  143779. _vq_lengthlist__16u1__p7_0,
  143780. 1, -529137664, 1618345984, 2, 0,
  143781. _vq_quantlist__16u1__p7_0,
  143782. NULL,
  143783. &_vq_auxt__16u1__p7_0,
  143784. NULL,
  143785. 0
  143786. };
  143787. static long _vq_quantlist__16u1__p7_1[] = {
  143788. 5,
  143789. 4,
  143790. 6,
  143791. 3,
  143792. 7,
  143793. 2,
  143794. 8,
  143795. 1,
  143796. 9,
  143797. 0,
  143798. 10,
  143799. };
  143800. static long _vq_lengthlist__16u1__p7_1[] = {
  143801. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143802. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143803. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143804. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143805. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143806. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143807. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143808. 8, 9, 9,10,10,10,10,10,10,
  143809. };
  143810. static float _vq_quantthresh__16u1__p7_1[] = {
  143811. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143812. 3.5, 4.5,
  143813. };
  143814. static long _vq_quantmap__16u1__p7_1[] = {
  143815. 9, 7, 5, 3, 1, 0, 2, 4,
  143816. 6, 8, 10,
  143817. };
  143818. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143819. _vq_quantthresh__16u1__p7_1,
  143820. _vq_quantmap__16u1__p7_1,
  143821. 11,
  143822. 11
  143823. };
  143824. static static_codebook _16u1__p7_1 = {
  143825. 2, 121,
  143826. _vq_lengthlist__16u1__p7_1,
  143827. 1, -531365888, 1611661312, 4, 0,
  143828. _vq_quantlist__16u1__p7_1,
  143829. NULL,
  143830. &_vq_auxt__16u1__p7_1,
  143831. NULL,
  143832. 0
  143833. };
  143834. static long _vq_quantlist__16u1__p8_0[] = {
  143835. 5,
  143836. 4,
  143837. 6,
  143838. 3,
  143839. 7,
  143840. 2,
  143841. 8,
  143842. 1,
  143843. 9,
  143844. 0,
  143845. 10,
  143846. };
  143847. static long _vq_lengthlist__16u1__p8_0[] = {
  143848. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143849. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143850. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143851. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143852. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143853. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143854. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143855. 13,14,14,15,15,16,16,15,16,
  143856. };
  143857. static float _vq_quantthresh__16u1__p8_0[] = {
  143858. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143859. 38.5, 49.5,
  143860. };
  143861. static long _vq_quantmap__16u1__p8_0[] = {
  143862. 9, 7, 5, 3, 1, 0, 2, 4,
  143863. 6, 8, 10,
  143864. };
  143865. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143866. _vq_quantthresh__16u1__p8_0,
  143867. _vq_quantmap__16u1__p8_0,
  143868. 11,
  143869. 11
  143870. };
  143871. static static_codebook _16u1__p8_0 = {
  143872. 2, 121,
  143873. _vq_lengthlist__16u1__p8_0,
  143874. 1, -524582912, 1618345984, 4, 0,
  143875. _vq_quantlist__16u1__p8_0,
  143876. NULL,
  143877. &_vq_auxt__16u1__p8_0,
  143878. NULL,
  143879. 0
  143880. };
  143881. static long _vq_quantlist__16u1__p8_1[] = {
  143882. 5,
  143883. 4,
  143884. 6,
  143885. 3,
  143886. 7,
  143887. 2,
  143888. 8,
  143889. 1,
  143890. 9,
  143891. 0,
  143892. 10,
  143893. };
  143894. static long _vq_lengthlist__16u1__p8_1[] = {
  143895. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143896. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143897. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143898. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143899. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143900. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143901. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143902. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143903. };
  143904. static float _vq_quantthresh__16u1__p8_1[] = {
  143905. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143906. 3.5, 4.5,
  143907. };
  143908. static long _vq_quantmap__16u1__p8_1[] = {
  143909. 9, 7, 5, 3, 1, 0, 2, 4,
  143910. 6, 8, 10,
  143911. };
  143912. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143913. _vq_quantthresh__16u1__p8_1,
  143914. _vq_quantmap__16u1__p8_1,
  143915. 11,
  143916. 11
  143917. };
  143918. static static_codebook _16u1__p8_1 = {
  143919. 2, 121,
  143920. _vq_lengthlist__16u1__p8_1,
  143921. 1, -531365888, 1611661312, 4, 0,
  143922. _vq_quantlist__16u1__p8_1,
  143923. NULL,
  143924. &_vq_auxt__16u1__p8_1,
  143925. NULL,
  143926. 0
  143927. };
  143928. static long _vq_quantlist__16u1__p9_0[] = {
  143929. 7,
  143930. 6,
  143931. 8,
  143932. 5,
  143933. 9,
  143934. 4,
  143935. 10,
  143936. 3,
  143937. 11,
  143938. 2,
  143939. 12,
  143940. 1,
  143941. 13,
  143942. 0,
  143943. 14,
  143944. };
  143945. static long _vq_lengthlist__16u1__p9_0[] = {
  143946. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143947. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143948. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143949. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143950. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143951. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143952. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143953. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143954. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143955. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143956. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143957. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143958. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143959. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143960. 8,
  143961. };
  143962. static float _vq_quantthresh__16u1__p9_0[] = {
  143963. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143964. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143965. };
  143966. static long _vq_quantmap__16u1__p9_0[] = {
  143967. 13, 11, 9, 7, 5, 3, 1, 0,
  143968. 2, 4, 6, 8, 10, 12, 14,
  143969. };
  143970. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143971. _vq_quantthresh__16u1__p9_0,
  143972. _vq_quantmap__16u1__p9_0,
  143973. 15,
  143974. 15
  143975. };
  143976. static static_codebook _16u1__p9_0 = {
  143977. 2, 225,
  143978. _vq_lengthlist__16u1__p9_0,
  143979. 1, -514071552, 1627381760, 4, 0,
  143980. _vq_quantlist__16u1__p9_0,
  143981. NULL,
  143982. &_vq_auxt__16u1__p9_0,
  143983. NULL,
  143984. 0
  143985. };
  143986. static long _vq_quantlist__16u1__p9_1[] = {
  143987. 7,
  143988. 6,
  143989. 8,
  143990. 5,
  143991. 9,
  143992. 4,
  143993. 10,
  143994. 3,
  143995. 11,
  143996. 2,
  143997. 12,
  143998. 1,
  143999. 13,
  144000. 0,
  144001. 14,
  144002. };
  144003. static long _vq_lengthlist__16u1__p9_1[] = {
  144004. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144005. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144006. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144007. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144008. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144009. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144010. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144011. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144012. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144014. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144015. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144017. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144018. 9,
  144019. };
  144020. static float _vq_quantthresh__16u1__p9_1[] = {
  144021. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144022. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144023. };
  144024. static long _vq_quantmap__16u1__p9_1[] = {
  144025. 13, 11, 9, 7, 5, 3, 1, 0,
  144026. 2, 4, 6, 8, 10, 12, 14,
  144027. };
  144028. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144029. _vq_quantthresh__16u1__p9_1,
  144030. _vq_quantmap__16u1__p9_1,
  144031. 15,
  144032. 15
  144033. };
  144034. static static_codebook _16u1__p9_1 = {
  144035. 2, 225,
  144036. _vq_lengthlist__16u1__p9_1,
  144037. 1, -522338304, 1620115456, 4, 0,
  144038. _vq_quantlist__16u1__p9_1,
  144039. NULL,
  144040. &_vq_auxt__16u1__p9_1,
  144041. NULL,
  144042. 0
  144043. };
  144044. static long _vq_quantlist__16u1__p9_2[] = {
  144045. 8,
  144046. 7,
  144047. 9,
  144048. 6,
  144049. 10,
  144050. 5,
  144051. 11,
  144052. 4,
  144053. 12,
  144054. 3,
  144055. 13,
  144056. 2,
  144057. 14,
  144058. 1,
  144059. 15,
  144060. 0,
  144061. 16,
  144062. };
  144063. static long _vq_lengthlist__16u1__p9_2[] = {
  144064. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144065. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144066. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144067. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144068. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144069. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144070. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144071. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144072. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144073. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144074. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144075. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144076. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144077. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144078. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144079. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144080. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144081. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144082. 10,
  144083. };
  144084. static float _vq_quantthresh__16u1__p9_2[] = {
  144085. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144086. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144087. };
  144088. static long _vq_quantmap__16u1__p9_2[] = {
  144089. 15, 13, 11, 9, 7, 5, 3, 1,
  144090. 0, 2, 4, 6, 8, 10, 12, 14,
  144091. 16,
  144092. };
  144093. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144094. _vq_quantthresh__16u1__p9_2,
  144095. _vq_quantmap__16u1__p9_2,
  144096. 17,
  144097. 17
  144098. };
  144099. static static_codebook _16u1__p9_2 = {
  144100. 2, 289,
  144101. _vq_lengthlist__16u1__p9_2,
  144102. 1, -529530880, 1611661312, 5, 0,
  144103. _vq_quantlist__16u1__p9_2,
  144104. NULL,
  144105. &_vq_auxt__16u1__p9_2,
  144106. NULL,
  144107. 0
  144108. };
  144109. static long _huff_lengthlist__16u1__short[] = {
  144110. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144111. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144112. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144113. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144114. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144115. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144116. 16,16,16,16,
  144117. };
  144118. static static_codebook _huff_book__16u1__short = {
  144119. 2, 100,
  144120. _huff_lengthlist__16u1__short,
  144121. 0, 0, 0, 0, 0,
  144122. NULL,
  144123. NULL,
  144124. NULL,
  144125. NULL,
  144126. 0
  144127. };
  144128. static long _huff_lengthlist__16u2__long[] = {
  144129. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144130. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144131. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144132. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144133. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144134. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144135. 13,14,18,18,
  144136. };
  144137. static static_codebook _huff_book__16u2__long = {
  144138. 2, 100,
  144139. _huff_lengthlist__16u2__long,
  144140. 0, 0, 0, 0, 0,
  144141. NULL,
  144142. NULL,
  144143. NULL,
  144144. NULL,
  144145. 0
  144146. };
  144147. static long _huff_lengthlist__16u2__short[] = {
  144148. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144149. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144150. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144151. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144152. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144153. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144154. 16,16,16,16,
  144155. };
  144156. static static_codebook _huff_book__16u2__short = {
  144157. 2, 100,
  144158. _huff_lengthlist__16u2__short,
  144159. 0, 0, 0, 0, 0,
  144160. NULL,
  144161. NULL,
  144162. NULL,
  144163. NULL,
  144164. 0
  144165. };
  144166. static long _vq_quantlist__16u2_p1_0[] = {
  144167. 1,
  144168. 0,
  144169. 2,
  144170. };
  144171. static long _vq_lengthlist__16u2_p1_0[] = {
  144172. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144173. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144174. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144175. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144176. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144177. 10,
  144178. };
  144179. static float _vq_quantthresh__16u2_p1_0[] = {
  144180. -0.5, 0.5,
  144181. };
  144182. static long _vq_quantmap__16u2_p1_0[] = {
  144183. 1, 0, 2,
  144184. };
  144185. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144186. _vq_quantthresh__16u2_p1_0,
  144187. _vq_quantmap__16u2_p1_0,
  144188. 3,
  144189. 3
  144190. };
  144191. static static_codebook _16u2_p1_0 = {
  144192. 4, 81,
  144193. _vq_lengthlist__16u2_p1_0,
  144194. 1, -535822336, 1611661312, 2, 0,
  144195. _vq_quantlist__16u2_p1_0,
  144196. NULL,
  144197. &_vq_auxt__16u2_p1_0,
  144198. NULL,
  144199. 0
  144200. };
  144201. static long _vq_quantlist__16u2_p2_0[] = {
  144202. 2,
  144203. 1,
  144204. 3,
  144205. 0,
  144206. 4,
  144207. };
  144208. static long _vq_lengthlist__16u2_p2_0[] = {
  144209. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144210. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144211. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144212. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144213. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144214. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144215. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144216. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144217. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144218. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144219. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144220. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144221. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144222. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144223. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144224. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144225. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144226. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144227. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144228. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144229. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144230. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144231. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144232. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144233. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144234. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144235. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144236. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144237. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144238. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144239. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144240. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144241. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144242. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144243. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144244. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144245. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144246. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144247. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144248. 13,
  144249. };
  144250. static float _vq_quantthresh__16u2_p2_0[] = {
  144251. -1.5, -0.5, 0.5, 1.5,
  144252. };
  144253. static long _vq_quantmap__16u2_p2_0[] = {
  144254. 3, 1, 0, 2, 4,
  144255. };
  144256. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144257. _vq_quantthresh__16u2_p2_0,
  144258. _vq_quantmap__16u2_p2_0,
  144259. 5,
  144260. 5
  144261. };
  144262. static static_codebook _16u2_p2_0 = {
  144263. 4, 625,
  144264. _vq_lengthlist__16u2_p2_0,
  144265. 1, -533725184, 1611661312, 3, 0,
  144266. _vq_quantlist__16u2_p2_0,
  144267. NULL,
  144268. &_vq_auxt__16u2_p2_0,
  144269. NULL,
  144270. 0
  144271. };
  144272. static long _vq_quantlist__16u2_p3_0[] = {
  144273. 4,
  144274. 3,
  144275. 5,
  144276. 2,
  144277. 6,
  144278. 1,
  144279. 7,
  144280. 0,
  144281. 8,
  144282. };
  144283. static long _vq_lengthlist__16u2_p3_0[] = {
  144284. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144285. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144286. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144287. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144288. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144289. 11,
  144290. };
  144291. static float _vq_quantthresh__16u2_p3_0[] = {
  144292. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144293. };
  144294. static long _vq_quantmap__16u2_p3_0[] = {
  144295. 7, 5, 3, 1, 0, 2, 4, 6,
  144296. 8,
  144297. };
  144298. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144299. _vq_quantthresh__16u2_p3_0,
  144300. _vq_quantmap__16u2_p3_0,
  144301. 9,
  144302. 9
  144303. };
  144304. static static_codebook _16u2_p3_0 = {
  144305. 2, 81,
  144306. _vq_lengthlist__16u2_p3_0,
  144307. 1, -531628032, 1611661312, 4, 0,
  144308. _vq_quantlist__16u2_p3_0,
  144309. NULL,
  144310. &_vq_auxt__16u2_p3_0,
  144311. NULL,
  144312. 0
  144313. };
  144314. static long _vq_quantlist__16u2_p4_0[] = {
  144315. 8,
  144316. 7,
  144317. 9,
  144318. 6,
  144319. 10,
  144320. 5,
  144321. 11,
  144322. 4,
  144323. 12,
  144324. 3,
  144325. 13,
  144326. 2,
  144327. 14,
  144328. 1,
  144329. 15,
  144330. 0,
  144331. 16,
  144332. };
  144333. static long _vq_lengthlist__16u2_p4_0[] = {
  144334. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144335. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144336. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144337. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144338. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144339. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144340. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144341. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144342. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144343. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144344. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144345. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144346. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144347. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144348. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144349. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144350. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144351. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144352. 14,
  144353. };
  144354. static float _vq_quantthresh__16u2_p4_0[] = {
  144355. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144356. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144357. };
  144358. static long _vq_quantmap__16u2_p4_0[] = {
  144359. 15, 13, 11, 9, 7, 5, 3, 1,
  144360. 0, 2, 4, 6, 8, 10, 12, 14,
  144361. 16,
  144362. };
  144363. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144364. _vq_quantthresh__16u2_p4_0,
  144365. _vq_quantmap__16u2_p4_0,
  144366. 17,
  144367. 17
  144368. };
  144369. static static_codebook _16u2_p4_0 = {
  144370. 2, 289,
  144371. _vq_lengthlist__16u2_p4_0,
  144372. 1, -529530880, 1611661312, 5, 0,
  144373. _vq_quantlist__16u2_p4_0,
  144374. NULL,
  144375. &_vq_auxt__16u2_p4_0,
  144376. NULL,
  144377. 0
  144378. };
  144379. static long _vq_quantlist__16u2_p5_0[] = {
  144380. 1,
  144381. 0,
  144382. 2,
  144383. };
  144384. static long _vq_lengthlist__16u2_p5_0[] = {
  144385. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144386. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144387. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144388. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144389. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144390. 10,
  144391. };
  144392. static float _vq_quantthresh__16u2_p5_0[] = {
  144393. -5.5, 5.5,
  144394. };
  144395. static long _vq_quantmap__16u2_p5_0[] = {
  144396. 1, 0, 2,
  144397. };
  144398. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144399. _vq_quantthresh__16u2_p5_0,
  144400. _vq_quantmap__16u2_p5_0,
  144401. 3,
  144402. 3
  144403. };
  144404. static static_codebook _16u2_p5_0 = {
  144405. 4, 81,
  144406. _vq_lengthlist__16u2_p5_0,
  144407. 1, -529137664, 1618345984, 2, 0,
  144408. _vq_quantlist__16u2_p5_0,
  144409. NULL,
  144410. &_vq_auxt__16u2_p5_0,
  144411. NULL,
  144412. 0
  144413. };
  144414. static long _vq_quantlist__16u2_p5_1[] = {
  144415. 5,
  144416. 4,
  144417. 6,
  144418. 3,
  144419. 7,
  144420. 2,
  144421. 8,
  144422. 1,
  144423. 9,
  144424. 0,
  144425. 10,
  144426. };
  144427. static long _vq_lengthlist__16u2_p5_1[] = {
  144428. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144429. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144430. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144431. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144432. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144433. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144434. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144435. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144436. };
  144437. static float _vq_quantthresh__16u2_p5_1[] = {
  144438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144439. 3.5, 4.5,
  144440. };
  144441. static long _vq_quantmap__16u2_p5_1[] = {
  144442. 9, 7, 5, 3, 1, 0, 2, 4,
  144443. 6, 8, 10,
  144444. };
  144445. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144446. _vq_quantthresh__16u2_p5_1,
  144447. _vq_quantmap__16u2_p5_1,
  144448. 11,
  144449. 11
  144450. };
  144451. static static_codebook _16u2_p5_1 = {
  144452. 2, 121,
  144453. _vq_lengthlist__16u2_p5_1,
  144454. 1, -531365888, 1611661312, 4, 0,
  144455. _vq_quantlist__16u2_p5_1,
  144456. NULL,
  144457. &_vq_auxt__16u2_p5_1,
  144458. NULL,
  144459. 0
  144460. };
  144461. static long _vq_quantlist__16u2_p6_0[] = {
  144462. 6,
  144463. 5,
  144464. 7,
  144465. 4,
  144466. 8,
  144467. 3,
  144468. 9,
  144469. 2,
  144470. 10,
  144471. 1,
  144472. 11,
  144473. 0,
  144474. 12,
  144475. };
  144476. static long _vq_lengthlist__16u2_p6_0[] = {
  144477. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144478. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144479. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144480. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144481. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144482. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144483. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144484. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144485. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144486. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144487. 12,13,13,14,14,14,14,15,15,
  144488. };
  144489. static float _vq_quantthresh__16u2_p6_0[] = {
  144490. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144491. 12.5, 17.5, 22.5, 27.5,
  144492. };
  144493. static long _vq_quantmap__16u2_p6_0[] = {
  144494. 11, 9, 7, 5, 3, 1, 0, 2,
  144495. 4, 6, 8, 10, 12,
  144496. };
  144497. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144498. _vq_quantthresh__16u2_p6_0,
  144499. _vq_quantmap__16u2_p6_0,
  144500. 13,
  144501. 13
  144502. };
  144503. static static_codebook _16u2_p6_0 = {
  144504. 2, 169,
  144505. _vq_lengthlist__16u2_p6_0,
  144506. 1, -526516224, 1616117760, 4, 0,
  144507. _vq_quantlist__16u2_p6_0,
  144508. NULL,
  144509. &_vq_auxt__16u2_p6_0,
  144510. NULL,
  144511. 0
  144512. };
  144513. static long _vq_quantlist__16u2_p6_1[] = {
  144514. 2,
  144515. 1,
  144516. 3,
  144517. 0,
  144518. 4,
  144519. };
  144520. static long _vq_lengthlist__16u2_p6_1[] = {
  144521. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144522. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144523. };
  144524. static float _vq_quantthresh__16u2_p6_1[] = {
  144525. -1.5, -0.5, 0.5, 1.5,
  144526. };
  144527. static long _vq_quantmap__16u2_p6_1[] = {
  144528. 3, 1, 0, 2, 4,
  144529. };
  144530. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144531. _vq_quantthresh__16u2_p6_1,
  144532. _vq_quantmap__16u2_p6_1,
  144533. 5,
  144534. 5
  144535. };
  144536. static static_codebook _16u2_p6_1 = {
  144537. 2, 25,
  144538. _vq_lengthlist__16u2_p6_1,
  144539. 1, -533725184, 1611661312, 3, 0,
  144540. _vq_quantlist__16u2_p6_1,
  144541. NULL,
  144542. &_vq_auxt__16u2_p6_1,
  144543. NULL,
  144544. 0
  144545. };
  144546. static long _vq_quantlist__16u2_p7_0[] = {
  144547. 6,
  144548. 5,
  144549. 7,
  144550. 4,
  144551. 8,
  144552. 3,
  144553. 9,
  144554. 2,
  144555. 10,
  144556. 1,
  144557. 11,
  144558. 0,
  144559. 12,
  144560. };
  144561. static long _vq_lengthlist__16u2_p7_0[] = {
  144562. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144563. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144564. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144565. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144566. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144567. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144568. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144569. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144570. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144571. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144572. 12,13,13,13,14,14,14,15,14,
  144573. };
  144574. static float _vq_quantthresh__16u2_p7_0[] = {
  144575. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144576. 27.5, 38.5, 49.5, 60.5,
  144577. };
  144578. static long _vq_quantmap__16u2_p7_0[] = {
  144579. 11, 9, 7, 5, 3, 1, 0, 2,
  144580. 4, 6, 8, 10, 12,
  144581. };
  144582. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144583. _vq_quantthresh__16u2_p7_0,
  144584. _vq_quantmap__16u2_p7_0,
  144585. 13,
  144586. 13
  144587. };
  144588. static static_codebook _16u2_p7_0 = {
  144589. 2, 169,
  144590. _vq_lengthlist__16u2_p7_0,
  144591. 1, -523206656, 1618345984, 4, 0,
  144592. _vq_quantlist__16u2_p7_0,
  144593. NULL,
  144594. &_vq_auxt__16u2_p7_0,
  144595. NULL,
  144596. 0
  144597. };
  144598. static long _vq_quantlist__16u2_p7_1[] = {
  144599. 5,
  144600. 4,
  144601. 6,
  144602. 3,
  144603. 7,
  144604. 2,
  144605. 8,
  144606. 1,
  144607. 9,
  144608. 0,
  144609. 10,
  144610. };
  144611. static long _vq_lengthlist__16u2_p7_1[] = {
  144612. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144613. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144614. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144615. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144616. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144617. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144618. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144619. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144620. };
  144621. static float _vq_quantthresh__16u2_p7_1[] = {
  144622. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144623. 3.5, 4.5,
  144624. };
  144625. static long _vq_quantmap__16u2_p7_1[] = {
  144626. 9, 7, 5, 3, 1, 0, 2, 4,
  144627. 6, 8, 10,
  144628. };
  144629. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144630. _vq_quantthresh__16u2_p7_1,
  144631. _vq_quantmap__16u2_p7_1,
  144632. 11,
  144633. 11
  144634. };
  144635. static static_codebook _16u2_p7_1 = {
  144636. 2, 121,
  144637. _vq_lengthlist__16u2_p7_1,
  144638. 1, -531365888, 1611661312, 4, 0,
  144639. _vq_quantlist__16u2_p7_1,
  144640. NULL,
  144641. &_vq_auxt__16u2_p7_1,
  144642. NULL,
  144643. 0
  144644. };
  144645. static long _vq_quantlist__16u2_p8_0[] = {
  144646. 7,
  144647. 6,
  144648. 8,
  144649. 5,
  144650. 9,
  144651. 4,
  144652. 10,
  144653. 3,
  144654. 11,
  144655. 2,
  144656. 12,
  144657. 1,
  144658. 13,
  144659. 0,
  144660. 14,
  144661. };
  144662. static long _vq_lengthlist__16u2_p8_0[] = {
  144663. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144664. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144665. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144666. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144667. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144668. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144669. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144670. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144671. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144672. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144673. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144674. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144675. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144676. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144677. 14,
  144678. };
  144679. static float _vq_quantthresh__16u2_p8_0[] = {
  144680. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144681. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144682. };
  144683. static long _vq_quantmap__16u2_p8_0[] = {
  144684. 13, 11, 9, 7, 5, 3, 1, 0,
  144685. 2, 4, 6, 8, 10, 12, 14,
  144686. };
  144687. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144688. _vq_quantthresh__16u2_p8_0,
  144689. _vq_quantmap__16u2_p8_0,
  144690. 15,
  144691. 15
  144692. };
  144693. static static_codebook _16u2_p8_0 = {
  144694. 2, 225,
  144695. _vq_lengthlist__16u2_p8_0,
  144696. 1, -520986624, 1620377600, 4, 0,
  144697. _vq_quantlist__16u2_p8_0,
  144698. NULL,
  144699. &_vq_auxt__16u2_p8_0,
  144700. NULL,
  144701. 0
  144702. };
  144703. static long _vq_quantlist__16u2_p8_1[] = {
  144704. 10,
  144705. 9,
  144706. 11,
  144707. 8,
  144708. 12,
  144709. 7,
  144710. 13,
  144711. 6,
  144712. 14,
  144713. 5,
  144714. 15,
  144715. 4,
  144716. 16,
  144717. 3,
  144718. 17,
  144719. 2,
  144720. 18,
  144721. 1,
  144722. 19,
  144723. 0,
  144724. 20,
  144725. };
  144726. static long _vq_lengthlist__16u2_p8_1[] = {
  144727. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144728. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144729. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144730. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144731. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144732. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144733. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144734. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144735. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144736. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144737. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144738. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144739. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144740. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144741. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144742. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144743. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144744. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144745. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144746. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144747. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144748. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144749. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144750. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144752. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144753. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144754. 11,11,10,11,11,11,10,11,11,
  144755. };
  144756. static float _vq_quantthresh__16u2_p8_1[] = {
  144757. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144758. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144759. 6.5, 7.5, 8.5, 9.5,
  144760. };
  144761. static long _vq_quantmap__16u2_p8_1[] = {
  144762. 19, 17, 15, 13, 11, 9, 7, 5,
  144763. 3, 1, 0, 2, 4, 6, 8, 10,
  144764. 12, 14, 16, 18, 20,
  144765. };
  144766. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144767. _vq_quantthresh__16u2_p8_1,
  144768. _vq_quantmap__16u2_p8_1,
  144769. 21,
  144770. 21
  144771. };
  144772. static static_codebook _16u2_p8_1 = {
  144773. 2, 441,
  144774. _vq_lengthlist__16u2_p8_1,
  144775. 1, -529268736, 1611661312, 5, 0,
  144776. _vq_quantlist__16u2_p8_1,
  144777. NULL,
  144778. &_vq_auxt__16u2_p8_1,
  144779. NULL,
  144780. 0
  144781. };
  144782. static long _vq_quantlist__16u2_p9_0[] = {
  144783. 5586,
  144784. 4655,
  144785. 6517,
  144786. 3724,
  144787. 7448,
  144788. 2793,
  144789. 8379,
  144790. 1862,
  144791. 9310,
  144792. 931,
  144793. 10241,
  144794. 0,
  144795. 11172,
  144796. 5521,
  144797. 5651,
  144798. };
  144799. static long _vq_lengthlist__16u2_p9_0[] = {
  144800. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144802. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144803. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144804. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144805. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144806. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144807. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144808. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144809. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144810. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144812. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144813. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144814. 5,
  144815. };
  144816. static float _vq_quantthresh__16u2_p9_0[] = {
  144817. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144818. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144819. };
  144820. static long _vq_quantmap__16u2_p9_0[] = {
  144821. 11, 9, 7, 5, 3, 1, 13, 0,
  144822. 14, 2, 4, 6, 8, 10, 12,
  144823. };
  144824. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144825. _vq_quantthresh__16u2_p9_0,
  144826. _vq_quantmap__16u2_p9_0,
  144827. 15,
  144828. 15
  144829. };
  144830. static static_codebook _16u2_p9_0 = {
  144831. 2, 225,
  144832. _vq_lengthlist__16u2_p9_0,
  144833. 1, -510275072, 1611661312, 14, 0,
  144834. _vq_quantlist__16u2_p9_0,
  144835. NULL,
  144836. &_vq_auxt__16u2_p9_0,
  144837. NULL,
  144838. 0
  144839. };
  144840. static long _vq_quantlist__16u2_p9_1[] = {
  144841. 392,
  144842. 343,
  144843. 441,
  144844. 294,
  144845. 490,
  144846. 245,
  144847. 539,
  144848. 196,
  144849. 588,
  144850. 147,
  144851. 637,
  144852. 98,
  144853. 686,
  144854. 49,
  144855. 735,
  144856. 0,
  144857. 784,
  144858. 388,
  144859. 396,
  144860. };
  144861. static long _vq_lengthlist__16u2_p9_1[] = {
  144862. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144863. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144864. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144865. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144866. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144867. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144868. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144869. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144870. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144871. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144872. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144873. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144874. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144875. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144876. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144882. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144883. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144884. 11,11,11,11,11,11,11, 5, 4,
  144885. };
  144886. static float _vq_quantthresh__16u2_p9_1[] = {
  144887. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144888. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144889. 318.5, 367.5,
  144890. };
  144891. static long _vq_quantmap__16u2_p9_1[] = {
  144892. 15, 13, 11, 9, 7, 5, 3, 1,
  144893. 17, 0, 18, 2, 4, 6, 8, 10,
  144894. 12, 14, 16,
  144895. };
  144896. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144897. _vq_quantthresh__16u2_p9_1,
  144898. _vq_quantmap__16u2_p9_1,
  144899. 19,
  144900. 19
  144901. };
  144902. static static_codebook _16u2_p9_1 = {
  144903. 2, 361,
  144904. _vq_lengthlist__16u2_p9_1,
  144905. 1, -518488064, 1611661312, 10, 0,
  144906. _vq_quantlist__16u2_p9_1,
  144907. NULL,
  144908. &_vq_auxt__16u2_p9_1,
  144909. NULL,
  144910. 0
  144911. };
  144912. static long _vq_quantlist__16u2_p9_2[] = {
  144913. 24,
  144914. 23,
  144915. 25,
  144916. 22,
  144917. 26,
  144918. 21,
  144919. 27,
  144920. 20,
  144921. 28,
  144922. 19,
  144923. 29,
  144924. 18,
  144925. 30,
  144926. 17,
  144927. 31,
  144928. 16,
  144929. 32,
  144930. 15,
  144931. 33,
  144932. 14,
  144933. 34,
  144934. 13,
  144935. 35,
  144936. 12,
  144937. 36,
  144938. 11,
  144939. 37,
  144940. 10,
  144941. 38,
  144942. 9,
  144943. 39,
  144944. 8,
  144945. 40,
  144946. 7,
  144947. 41,
  144948. 6,
  144949. 42,
  144950. 5,
  144951. 43,
  144952. 4,
  144953. 44,
  144954. 3,
  144955. 45,
  144956. 2,
  144957. 46,
  144958. 1,
  144959. 47,
  144960. 0,
  144961. 48,
  144962. };
  144963. static long _vq_lengthlist__16u2_p9_2[] = {
  144964. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144965. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144966. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144967. 11,
  144968. };
  144969. static float _vq_quantthresh__16u2_p9_2[] = {
  144970. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144971. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144972. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144973. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144974. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144975. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144976. };
  144977. static long _vq_quantmap__16u2_p9_2[] = {
  144978. 47, 45, 43, 41, 39, 37, 35, 33,
  144979. 31, 29, 27, 25, 23, 21, 19, 17,
  144980. 15, 13, 11, 9, 7, 5, 3, 1,
  144981. 0, 2, 4, 6, 8, 10, 12, 14,
  144982. 16, 18, 20, 22, 24, 26, 28, 30,
  144983. 32, 34, 36, 38, 40, 42, 44, 46,
  144984. 48,
  144985. };
  144986. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144987. _vq_quantthresh__16u2_p9_2,
  144988. _vq_quantmap__16u2_p9_2,
  144989. 49,
  144990. 49
  144991. };
  144992. static static_codebook _16u2_p9_2 = {
  144993. 1, 49,
  144994. _vq_lengthlist__16u2_p9_2,
  144995. 1, -526909440, 1611661312, 6, 0,
  144996. _vq_quantlist__16u2_p9_2,
  144997. NULL,
  144998. &_vq_auxt__16u2_p9_2,
  144999. NULL,
  145000. 0
  145001. };
  145002. static long _vq_quantlist__8u0__p1_0[] = {
  145003. 1,
  145004. 0,
  145005. 2,
  145006. };
  145007. static long _vq_lengthlist__8u0__p1_0[] = {
  145008. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145009. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145010. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145011. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145012. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145013. 11,
  145014. };
  145015. static float _vq_quantthresh__8u0__p1_0[] = {
  145016. -0.5, 0.5,
  145017. };
  145018. static long _vq_quantmap__8u0__p1_0[] = {
  145019. 1, 0, 2,
  145020. };
  145021. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145022. _vq_quantthresh__8u0__p1_0,
  145023. _vq_quantmap__8u0__p1_0,
  145024. 3,
  145025. 3
  145026. };
  145027. static static_codebook _8u0__p1_0 = {
  145028. 4, 81,
  145029. _vq_lengthlist__8u0__p1_0,
  145030. 1, -535822336, 1611661312, 2, 0,
  145031. _vq_quantlist__8u0__p1_0,
  145032. NULL,
  145033. &_vq_auxt__8u0__p1_0,
  145034. NULL,
  145035. 0
  145036. };
  145037. static long _vq_quantlist__8u0__p2_0[] = {
  145038. 1,
  145039. 0,
  145040. 2,
  145041. };
  145042. static long _vq_lengthlist__8u0__p2_0[] = {
  145043. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145044. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145045. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145046. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145047. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145048. 8,
  145049. };
  145050. static float _vq_quantthresh__8u0__p2_0[] = {
  145051. -0.5, 0.5,
  145052. };
  145053. static long _vq_quantmap__8u0__p2_0[] = {
  145054. 1, 0, 2,
  145055. };
  145056. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145057. _vq_quantthresh__8u0__p2_0,
  145058. _vq_quantmap__8u0__p2_0,
  145059. 3,
  145060. 3
  145061. };
  145062. static static_codebook _8u0__p2_0 = {
  145063. 4, 81,
  145064. _vq_lengthlist__8u0__p2_0,
  145065. 1, -535822336, 1611661312, 2, 0,
  145066. _vq_quantlist__8u0__p2_0,
  145067. NULL,
  145068. &_vq_auxt__8u0__p2_0,
  145069. NULL,
  145070. 0
  145071. };
  145072. static long _vq_quantlist__8u0__p3_0[] = {
  145073. 2,
  145074. 1,
  145075. 3,
  145076. 0,
  145077. 4,
  145078. };
  145079. static long _vq_lengthlist__8u0__p3_0[] = {
  145080. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145081. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145082. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145083. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145084. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145085. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145086. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145087. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145088. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145089. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145090. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145091. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145092. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145093. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145094. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145095. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145096. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145097. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145098. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145099. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145100. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145101. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145102. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145103. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145104. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145105. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145106. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145107. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145108. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145109. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145110. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145111. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145112. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145113. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145114. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145115. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145116. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145117. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145118. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145119. 16,
  145120. };
  145121. static float _vq_quantthresh__8u0__p3_0[] = {
  145122. -1.5, -0.5, 0.5, 1.5,
  145123. };
  145124. static long _vq_quantmap__8u0__p3_0[] = {
  145125. 3, 1, 0, 2, 4,
  145126. };
  145127. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145128. _vq_quantthresh__8u0__p3_0,
  145129. _vq_quantmap__8u0__p3_0,
  145130. 5,
  145131. 5
  145132. };
  145133. static static_codebook _8u0__p3_0 = {
  145134. 4, 625,
  145135. _vq_lengthlist__8u0__p3_0,
  145136. 1, -533725184, 1611661312, 3, 0,
  145137. _vq_quantlist__8u0__p3_0,
  145138. NULL,
  145139. &_vq_auxt__8u0__p3_0,
  145140. NULL,
  145141. 0
  145142. };
  145143. static long _vq_quantlist__8u0__p4_0[] = {
  145144. 2,
  145145. 1,
  145146. 3,
  145147. 0,
  145148. 4,
  145149. };
  145150. static long _vq_lengthlist__8u0__p4_0[] = {
  145151. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145152. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145153. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145154. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145155. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145156. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145157. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145158. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145159. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145160. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145161. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145162. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145163. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145164. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145165. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145166. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145167. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145168. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145169. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145170. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145171. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145172. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145173. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145174. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145175. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145176. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145177. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145178. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145179. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145180. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145181. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145182. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145183. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145184. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145185. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145186. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145187. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145188. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145189. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145190. 12,
  145191. };
  145192. static float _vq_quantthresh__8u0__p4_0[] = {
  145193. -1.5, -0.5, 0.5, 1.5,
  145194. };
  145195. static long _vq_quantmap__8u0__p4_0[] = {
  145196. 3, 1, 0, 2, 4,
  145197. };
  145198. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145199. _vq_quantthresh__8u0__p4_0,
  145200. _vq_quantmap__8u0__p4_0,
  145201. 5,
  145202. 5
  145203. };
  145204. static static_codebook _8u0__p4_0 = {
  145205. 4, 625,
  145206. _vq_lengthlist__8u0__p4_0,
  145207. 1, -533725184, 1611661312, 3, 0,
  145208. _vq_quantlist__8u0__p4_0,
  145209. NULL,
  145210. &_vq_auxt__8u0__p4_0,
  145211. NULL,
  145212. 0
  145213. };
  145214. static long _vq_quantlist__8u0__p5_0[] = {
  145215. 4,
  145216. 3,
  145217. 5,
  145218. 2,
  145219. 6,
  145220. 1,
  145221. 7,
  145222. 0,
  145223. 8,
  145224. };
  145225. static long _vq_lengthlist__8u0__p5_0[] = {
  145226. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145227. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145228. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145229. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145230. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145231. 12,
  145232. };
  145233. static float _vq_quantthresh__8u0__p5_0[] = {
  145234. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145235. };
  145236. static long _vq_quantmap__8u0__p5_0[] = {
  145237. 7, 5, 3, 1, 0, 2, 4, 6,
  145238. 8,
  145239. };
  145240. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145241. _vq_quantthresh__8u0__p5_0,
  145242. _vq_quantmap__8u0__p5_0,
  145243. 9,
  145244. 9
  145245. };
  145246. static static_codebook _8u0__p5_0 = {
  145247. 2, 81,
  145248. _vq_lengthlist__8u0__p5_0,
  145249. 1, -531628032, 1611661312, 4, 0,
  145250. _vq_quantlist__8u0__p5_0,
  145251. NULL,
  145252. &_vq_auxt__8u0__p5_0,
  145253. NULL,
  145254. 0
  145255. };
  145256. static long _vq_quantlist__8u0__p6_0[] = {
  145257. 6,
  145258. 5,
  145259. 7,
  145260. 4,
  145261. 8,
  145262. 3,
  145263. 9,
  145264. 2,
  145265. 10,
  145266. 1,
  145267. 11,
  145268. 0,
  145269. 12,
  145270. };
  145271. static long _vq_lengthlist__8u0__p6_0[] = {
  145272. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145273. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145274. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145275. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145276. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145277. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145278. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145279. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145280. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145281. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145282. 16, 0,15, 0,17, 0, 0, 0, 0,
  145283. };
  145284. static float _vq_quantthresh__8u0__p6_0[] = {
  145285. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145286. 12.5, 17.5, 22.5, 27.5,
  145287. };
  145288. static long _vq_quantmap__8u0__p6_0[] = {
  145289. 11, 9, 7, 5, 3, 1, 0, 2,
  145290. 4, 6, 8, 10, 12,
  145291. };
  145292. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145293. _vq_quantthresh__8u0__p6_0,
  145294. _vq_quantmap__8u0__p6_0,
  145295. 13,
  145296. 13
  145297. };
  145298. static static_codebook _8u0__p6_0 = {
  145299. 2, 169,
  145300. _vq_lengthlist__8u0__p6_0,
  145301. 1, -526516224, 1616117760, 4, 0,
  145302. _vq_quantlist__8u0__p6_0,
  145303. NULL,
  145304. &_vq_auxt__8u0__p6_0,
  145305. NULL,
  145306. 0
  145307. };
  145308. static long _vq_quantlist__8u0__p6_1[] = {
  145309. 2,
  145310. 1,
  145311. 3,
  145312. 0,
  145313. 4,
  145314. };
  145315. static long _vq_lengthlist__8u0__p6_1[] = {
  145316. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145317. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145318. };
  145319. static float _vq_quantthresh__8u0__p6_1[] = {
  145320. -1.5, -0.5, 0.5, 1.5,
  145321. };
  145322. static long _vq_quantmap__8u0__p6_1[] = {
  145323. 3, 1, 0, 2, 4,
  145324. };
  145325. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145326. _vq_quantthresh__8u0__p6_1,
  145327. _vq_quantmap__8u0__p6_1,
  145328. 5,
  145329. 5
  145330. };
  145331. static static_codebook _8u0__p6_1 = {
  145332. 2, 25,
  145333. _vq_lengthlist__8u0__p6_1,
  145334. 1, -533725184, 1611661312, 3, 0,
  145335. _vq_quantlist__8u0__p6_1,
  145336. NULL,
  145337. &_vq_auxt__8u0__p6_1,
  145338. NULL,
  145339. 0
  145340. };
  145341. static long _vq_quantlist__8u0__p7_0[] = {
  145342. 1,
  145343. 0,
  145344. 2,
  145345. };
  145346. static long _vq_lengthlist__8u0__p7_0[] = {
  145347. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145348. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145349. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145350. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145351. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145352. 7,
  145353. };
  145354. static float _vq_quantthresh__8u0__p7_0[] = {
  145355. -157.5, 157.5,
  145356. };
  145357. static long _vq_quantmap__8u0__p7_0[] = {
  145358. 1, 0, 2,
  145359. };
  145360. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145361. _vq_quantthresh__8u0__p7_0,
  145362. _vq_quantmap__8u0__p7_0,
  145363. 3,
  145364. 3
  145365. };
  145366. static static_codebook _8u0__p7_0 = {
  145367. 4, 81,
  145368. _vq_lengthlist__8u0__p7_0,
  145369. 1, -518803456, 1628680192, 2, 0,
  145370. _vq_quantlist__8u0__p7_0,
  145371. NULL,
  145372. &_vq_auxt__8u0__p7_0,
  145373. NULL,
  145374. 0
  145375. };
  145376. static long _vq_quantlist__8u0__p7_1[] = {
  145377. 7,
  145378. 6,
  145379. 8,
  145380. 5,
  145381. 9,
  145382. 4,
  145383. 10,
  145384. 3,
  145385. 11,
  145386. 2,
  145387. 12,
  145388. 1,
  145389. 13,
  145390. 0,
  145391. 14,
  145392. };
  145393. static long _vq_lengthlist__8u0__p7_1[] = {
  145394. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145395. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145396. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145397. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145398. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145399. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145402. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145405. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145406. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145407. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145408. 10,
  145409. };
  145410. static float _vq_quantthresh__8u0__p7_1[] = {
  145411. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145412. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145413. };
  145414. static long _vq_quantmap__8u0__p7_1[] = {
  145415. 13, 11, 9, 7, 5, 3, 1, 0,
  145416. 2, 4, 6, 8, 10, 12, 14,
  145417. };
  145418. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145419. _vq_quantthresh__8u0__p7_1,
  145420. _vq_quantmap__8u0__p7_1,
  145421. 15,
  145422. 15
  145423. };
  145424. static static_codebook _8u0__p7_1 = {
  145425. 2, 225,
  145426. _vq_lengthlist__8u0__p7_1,
  145427. 1, -520986624, 1620377600, 4, 0,
  145428. _vq_quantlist__8u0__p7_1,
  145429. NULL,
  145430. &_vq_auxt__8u0__p7_1,
  145431. NULL,
  145432. 0
  145433. };
  145434. static long _vq_quantlist__8u0__p7_2[] = {
  145435. 10,
  145436. 9,
  145437. 11,
  145438. 8,
  145439. 12,
  145440. 7,
  145441. 13,
  145442. 6,
  145443. 14,
  145444. 5,
  145445. 15,
  145446. 4,
  145447. 16,
  145448. 3,
  145449. 17,
  145450. 2,
  145451. 18,
  145452. 1,
  145453. 19,
  145454. 0,
  145455. 20,
  145456. };
  145457. static long _vq_lengthlist__8u0__p7_2[] = {
  145458. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145459. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145460. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145461. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145462. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145463. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145464. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145465. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145466. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145467. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145468. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145469. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145470. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145471. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145472. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145473. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145474. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145475. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145476. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145477. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145478. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145479. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145480. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145481. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145482. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145483. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145484. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145485. 11,12,11,11,11,10,10,11,11,
  145486. };
  145487. static float _vq_quantthresh__8u0__p7_2[] = {
  145488. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145489. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145490. 6.5, 7.5, 8.5, 9.5,
  145491. };
  145492. static long _vq_quantmap__8u0__p7_2[] = {
  145493. 19, 17, 15, 13, 11, 9, 7, 5,
  145494. 3, 1, 0, 2, 4, 6, 8, 10,
  145495. 12, 14, 16, 18, 20,
  145496. };
  145497. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145498. _vq_quantthresh__8u0__p7_2,
  145499. _vq_quantmap__8u0__p7_2,
  145500. 21,
  145501. 21
  145502. };
  145503. static static_codebook _8u0__p7_2 = {
  145504. 2, 441,
  145505. _vq_lengthlist__8u0__p7_2,
  145506. 1, -529268736, 1611661312, 5, 0,
  145507. _vq_quantlist__8u0__p7_2,
  145508. NULL,
  145509. &_vq_auxt__8u0__p7_2,
  145510. NULL,
  145511. 0
  145512. };
  145513. static long _huff_lengthlist__8u0__single[] = {
  145514. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145515. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145516. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145517. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145518. };
  145519. static static_codebook _huff_book__8u0__single = {
  145520. 2, 64,
  145521. _huff_lengthlist__8u0__single,
  145522. 0, 0, 0, 0, 0,
  145523. NULL,
  145524. NULL,
  145525. NULL,
  145526. NULL,
  145527. 0
  145528. };
  145529. static long _vq_quantlist__8u1__p1_0[] = {
  145530. 1,
  145531. 0,
  145532. 2,
  145533. };
  145534. static long _vq_lengthlist__8u1__p1_0[] = {
  145535. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145536. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145537. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145538. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145539. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145540. 10,
  145541. };
  145542. static float _vq_quantthresh__8u1__p1_0[] = {
  145543. -0.5, 0.5,
  145544. };
  145545. static long _vq_quantmap__8u1__p1_0[] = {
  145546. 1, 0, 2,
  145547. };
  145548. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145549. _vq_quantthresh__8u1__p1_0,
  145550. _vq_quantmap__8u1__p1_0,
  145551. 3,
  145552. 3
  145553. };
  145554. static static_codebook _8u1__p1_0 = {
  145555. 4, 81,
  145556. _vq_lengthlist__8u1__p1_0,
  145557. 1, -535822336, 1611661312, 2, 0,
  145558. _vq_quantlist__8u1__p1_0,
  145559. NULL,
  145560. &_vq_auxt__8u1__p1_0,
  145561. NULL,
  145562. 0
  145563. };
  145564. static long _vq_quantlist__8u1__p2_0[] = {
  145565. 1,
  145566. 0,
  145567. 2,
  145568. };
  145569. static long _vq_lengthlist__8u1__p2_0[] = {
  145570. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145571. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145572. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145573. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145574. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145575. 7,
  145576. };
  145577. static float _vq_quantthresh__8u1__p2_0[] = {
  145578. -0.5, 0.5,
  145579. };
  145580. static long _vq_quantmap__8u1__p2_0[] = {
  145581. 1, 0, 2,
  145582. };
  145583. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145584. _vq_quantthresh__8u1__p2_0,
  145585. _vq_quantmap__8u1__p2_0,
  145586. 3,
  145587. 3
  145588. };
  145589. static static_codebook _8u1__p2_0 = {
  145590. 4, 81,
  145591. _vq_lengthlist__8u1__p2_0,
  145592. 1, -535822336, 1611661312, 2, 0,
  145593. _vq_quantlist__8u1__p2_0,
  145594. NULL,
  145595. &_vq_auxt__8u1__p2_0,
  145596. NULL,
  145597. 0
  145598. };
  145599. static long _vq_quantlist__8u1__p3_0[] = {
  145600. 2,
  145601. 1,
  145602. 3,
  145603. 0,
  145604. 4,
  145605. };
  145606. static long _vq_lengthlist__8u1__p3_0[] = {
  145607. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145608. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145609. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145610. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145611. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145612. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145613. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145614. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145615. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145616. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145617. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145618. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145619. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145620. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145621. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145622. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145623. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145624. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145625. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145626. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145627. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145628. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145629. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145630. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145631. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145632. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145633. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145634. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145635. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145636. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145637. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145638. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145639. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145640. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145641. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145642. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145643. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145644. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145645. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145646. 16,
  145647. };
  145648. static float _vq_quantthresh__8u1__p3_0[] = {
  145649. -1.5, -0.5, 0.5, 1.5,
  145650. };
  145651. static long _vq_quantmap__8u1__p3_0[] = {
  145652. 3, 1, 0, 2, 4,
  145653. };
  145654. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145655. _vq_quantthresh__8u1__p3_0,
  145656. _vq_quantmap__8u1__p3_0,
  145657. 5,
  145658. 5
  145659. };
  145660. static static_codebook _8u1__p3_0 = {
  145661. 4, 625,
  145662. _vq_lengthlist__8u1__p3_0,
  145663. 1, -533725184, 1611661312, 3, 0,
  145664. _vq_quantlist__8u1__p3_0,
  145665. NULL,
  145666. &_vq_auxt__8u1__p3_0,
  145667. NULL,
  145668. 0
  145669. };
  145670. static long _vq_quantlist__8u1__p4_0[] = {
  145671. 2,
  145672. 1,
  145673. 3,
  145674. 0,
  145675. 4,
  145676. };
  145677. static long _vq_lengthlist__8u1__p4_0[] = {
  145678. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145679. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145680. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145681. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145682. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145683. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145684. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145685. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145686. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145687. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145688. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145689. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145690. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145691. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145692. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145693. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145694. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145695. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145696. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145697. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145698. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145699. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145700. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145701. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145702. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145703. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145704. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145705. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145706. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145707. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145708. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145709. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145710. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145711. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145712. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145713. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145714. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145715. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145716. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145717. 10,
  145718. };
  145719. static float _vq_quantthresh__8u1__p4_0[] = {
  145720. -1.5, -0.5, 0.5, 1.5,
  145721. };
  145722. static long _vq_quantmap__8u1__p4_0[] = {
  145723. 3, 1, 0, 2, 4,
  145724. };
  145725. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145726. _vq_quantthresh__8u1__p4_0,
  145727. _vq_quantmap__8u1__p4_0,
  145728. 5,
  145729. 5
  145730. };
  145731. static static_codebook _8u1__p4_0 = {
  145732. 4, 625,
  145733. _vq_lengthlist__8u1__p4_0,
  145734. 1, -533725184, 1611661312, 3, 0,
  145735. _vq_quantlist__8u1__p4_0,
  145736. NULL,
  145737. &_vq_auxt__8u1__p4_0,
  145738. NULL,
  145739. 0
  145740. };
  145741. static long _vq_quantlist__8u1__p5_0[] = {
  145742. 4,
  145743. 3,
  145744. 5,
  145745. 2,
  145746. 6,
  145747. 1,
  145748. 7,
  145749. 0,
  145750. 8,
  145751. };
  145752. static long _vq_lengthlist__8u1__p5_0[] = {
  145753. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145754. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145755. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145756. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145757. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145758. 13,
  145759. };
  145760. static float _vq_quantthresh__8u1__p5_0[] = {
  145761. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145762. };
  145763. static long _vq_quantmap__8u1__p5_0[] = {
  145764. 7, 5, 3, 1, 0, 2, 4, 6,
  145765. 8,
  145766. };
  145767. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145768. _vq_quantthresh__8u1__p5_0,
  145769. _vq_quantmap__8u1__p5_0,
  145770. 9,
  145771. 9
  145772. };
  145773. static static_codebook _8u1__p5_0 = {
  145774. 2, 81,
  145775. _vq_lengthlist__8u1__p5_0,
  145776. 1, -531628032, 1611661312, 4, 0,
  145777. _vq_quantlist__8u1__p5_0,
  145778. NULL,
  145779. &_vq_auxt__8u1__p5_0,
  145780. NULL,
  145781. 0
  145782. };
  145783. static long _vq_quantlist__8u1__p6_0[] = {
  145784. 4,
  145785. 3,
  145786. 5,
  145787. 2,
  145788. 6,
  145789. 1,
  145790. 7,
  145791. 0,
  145792. 8,
  145793. };
  145794. static long _vq_lengthlist__8u1__p6_0[] = {
  145795. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145796. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145797. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145798. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145799. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145800. 10,
  145801. };
  145802. static float _vq_quantthresh__8u1__p6_0[] = {
  145803. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145804. };
  145805. static long _vq_quantmap__8u1__p6_0[] = {
  145806. 7, 5, 3, 1, 0, 2, 4, 6,
  145807. 8,
  145808. };
  145809. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145810. _vq_quantthresh__8u1__p6_0,
  145811. _vq_quantmap__8u1__p6_0,
  145812. 9,
  145813. 9
  145814. };
  145815. static static_codebook _8u1__p6_0 = {
  145816. 2, 81,
  145817. _vq_lengthlist__8u1__p6_0,
  145818. 1, -531628032, 1611661312, 4, 0,
  145819. _vq_quantlist__8u1__p6_0,
  145820. NULL,
  145821. &_vq_auxt__8u1__p6_0,
  145822. NULL,
  145823. 0
  145824. };
  145825. static long _vq_quantlist__8u1__p7_0[] = {
  145826. 1,
  145827. 0,
  145828. 2,
  145829. };
  145830. static long _vq_lengthlist__8u1__p7_0[] = {
  145831. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145832. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145833. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145834. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145835. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145836. 11,
  145837. };
  145838. static float _vq_quantthresh__8u1__p7_0[] = {
  145839. -5.5, 5.5,
  145840. };
  145841. static long _vq_quantmap__8u1__p7_0[] = {
  145842. 1, 0, 2,
  145843. };
  145844. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145845. _vq_quantthresh__8u1__p7_0,
  145846. _vq_quantmap__8u1__p7_0,
  145847. 3,
  145848. 3
  145849. };
  145850. static static_codebook _8u1__p7_0 = {
  145851. 4, 81,
  145852. _vq_lengthlist__8u1__p7_0,
  145853. 1, -529137664, 1618345984, 2, 0,
  145854. _vq_quantlist__8u1__p7_0,
  145855. NULL,
  145856. &_vq_auxt__8u1__p7_0,
  145857. NULL,
  145858. 0
  145859. };
  145860. static long _vq_quantlist__8u1__p7_1[] = {
  145861. 5,
  145862. 4,
  145863. 6,
  145864. 3,
  145865. 7,
  145866. 2,
  145867. 8,
  145868. 1,
  145869. 9,
  145870. 0,
  145871. 10,
  145872. };
  145873. static long _vq_lengthlist__8u1__p7_1[] = {
  145874. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145875. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145876. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145877. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145878. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145879. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145880. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145881. 9, 9, 9, 9, 9,10,10,10,10,
  145882. };
  145883. static float _vq_quantthresh__8u1__p7_1[] = {
  145884. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145885. 3.5, 4.5,
  145886. };
  145887. static long _vq_quantmap__8u1__p7_1[] = {
  145888. 9, 7, 5, 3, 1, 0, 2, 4,
  145889. 6, 8, 10,
  145890. };
  145891. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145892. _vq_quantthresh__8u1__p7_1,
  145893. _vq_quantmap__8u1__p7_1,
  145894. 11,
  145895. 11
  145896. };
  145897. static static_codebook _8u1__p7_1 = {
  145898. 2, 121,
  145899. _vq_lengthlist__8u1__p7_1,
  145900. 1, -531365888, 1611661312, 4, 0,
  145901. _vq_quantlist__8u1__p7_1,
  145902. NULL,
  145903. &_vq_auxt__8u1__p7_1,
  145904. NULL,
  145905. 0
  145906. };
  145907. static long _vq_quantlist__8u1__p8_0[] = {
  145908. 5,
  145909. 4,
  145910. 6,
  145911. 3,
  145912. 7,
  145913. 2,
  145914. 8,
  145915. 1,
  145916. 9,
  145917. 0,
  145918. 10,
  145919. };
  145920. static long _vq_lengthlist__8u1__p8_0[] = {
  145921. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145922. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145923. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145924. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145925. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145926. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145927. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145928. 12,13,13,14,14,15,15,15,15,
  145929. };
  145930. static float _vq_quantthresh__8u1__p8_0[] = {
  145931. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145932. 38.5, 49.5,
  145933. };
  145934. static long _vq_quantmap__8u1__p8_0[] = {
  145935. 9, 7, 5, 3, 1, 0, 2, 4,
  145936. 6, 8, 10,
  145937. };
  145938. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145939. _vq_quantthresh__8u1__p8_0,
  145940. _vq_quantmap__8u1__p8_0,
  145941. 11,
  145942. 11
  145943. };
  145944. static static_codebook _8u1__p8_0 = {
  145945. 2, 121,
  145946. _vq_lengthlist__8u1__p8_0,
  145947. 1, -524582912, 1618345984, 4, 0,
  145948. _vq_quantlist__8u1__p8_0,
  145949. NULL,
  145950. &_vq_auxt__8u1__p8_0,
  145951. NULL,
  145952. 0
  145953. };
  145954. static long _vq_quantlist__8u1__p8_1[] = {
  145955. 5,
  145956. 4,
  145957. 6,
  145958. 3,
  145959. 7,
  145960. 2,
  145961. 8,
  145962. 1,
  145963. 9,
  145964. 0,
  145965. 10,
  145966. };
  145967. static long _vq_lengthlist__8u1__p8_1[] = {
  145968. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145969. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145970. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145971. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145972. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145973. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145974. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145975. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145976. };
  145977. static float _vq_quantthresh__8u1__p8_1[] = {
  145978. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145979. 3.5, 4.5,
  145980. };
  145981. static long _vq_quantmap__8u1__p8_1[] = {
  145982. 9, 7, 5, 3, 1, 0, 2, 4,
  145983. 6, 8, 10,
  145984. };
  145985. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145986. _vq_quantthresh__8u1__p8_1,
  145987. _vq_quantmap__8u1__p8_1,
  145988. 11,
  145989. 11
  145990. };
  145991. static static_codebook _8u1__p8_1 = {
  145992. 2, 121,
  145993. _vq_lengthlist__8u1__p8_1,
  145994. 1, -531365888, 1611661312, 4, 0,
  145995. _vq_quantlist__8u1__p8_1,
  145996. NULL,
  145997. &_vq_auxt__8u1__p8_1,
  145998. NULL,
  145999. 0
  146000. };
  146001. static long _vq_quantlist__8u1__p9_0[] = {
  146002. 7,
  146003. 6,
  146004. 8,
  146005. 5,
  146006. 9,
  146007. 4,
  146008. 10,
  146009. 3,
  146010. 11,
  146011. 2,
  146012. 12,
  146013. 1,
  146014. 13,
  146015. 0,
  146016. 14,
  146017. };
  146018. static long _vq_lengthlist__8u1__p9_0[] = {
  146019. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146020. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146021. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146031. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146033. 10,
  146034. };
  146035. static float _vq_quantthresh__8u1__p9_0[] = {
  146036. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146037. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146038. };
  146039. static long _vq_quantmap__8u1__p9_0[] = {
  146040. 13, 11, 9, 7, 5, 3, 1, 0,
  146041. 2, 4, 6, 8, 10, 12, 14,
  146042. };
  146043. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146044. _vq_quantthresh__8u1__p9_0,
  146045. _vq_quantmap__8u1__p9_0,
  146046. 15,
  146047. 15
  146048. };
  146049. static static_codebook _8u1__p9_0 = {
  146050. 2, 225,
  146051. _vq_lengthlist__8u1__p9_0,
  146052. 1, -514071552, 1627381760, 4, 0,
  146053. _vq_quantlist__8u1__p9_0,
  146054. NULL,
  146055. &_vq_auxt__8u1__p9_0,
  146056. NULL,
  146057. 0
  146058. };
  146059. static long _vq_quantlist__8u1__p9_1[] = {
  146060. 7,
  146061. 6,
  146062. 8,
  146063. 5,
  146064. 9,
  146065. 4,
  146066. 10,
  146067. 3,
  146068. 11,
  146069. 2,
  146070. 12,
  146071. 1,
  146072. 13,
  146073. 0,
  146074. 14,
  146075. };
  146076. static long _vq_lengthlist__8u1__p9_1[] = {
  146077. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146078. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146079. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146080. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146081. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146082. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146083. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146084. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146085. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146086. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146087. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146088. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146089. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146090. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146091. 13,
  146092. };
  146093. static float _vq_quantthresh__8u1__p9_1[] = {
  146094. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146095. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146096. };
  146097. static long _vq_quantmap__8u1__p9_1[] = {
  146098. 13, 11, 9, 7, 5, 3, 1, 0,
  146099. 2, 4, 6, 8, 10, 12, 14,
  146100. };
  146101. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146102. _vq_quantthresh__8u1__p9_1,
  146103. _vq_quantmap__8u1__p9_1,
  146104. 15,
  146105. 15
  146106. };
  146107. static static_codebook _8u1__p9_1 = {
  146108. 2, 225,
  146109. _vq_lengthlist__8u1__p9_1,
  146110. 1, -522338304, 1620115456, 4, 0,
  146111. _vq_quantlist__8u1__p9_1,
  146112. NULL,
  146113. &_vq_auxt__8u1__p9_1,
  146114. NULL,
  146115. 0
  146116. };
  146117. static long _vq_quantlist__8u1__p9_2[] = {
  146118. 8,
  146119. 7,
  146120. 9,
  146121. 6,
  146122. 10,
  146123. 5,
  146124. 11,
  146125. 4,
  146126. 12,
  146127. 3,
  146128. 13,
  146129. 2,
  146130. 14,
  146131. 1,
  146132. 15,
  146133. 0,
  146134. 16,
  146135. };
  146136. static long _vq_lengthlist__8u1__p9_2[] = {
  146137. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146138. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146139. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146140. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146141. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146142. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146143. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146144. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146145. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146146. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146147. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146148. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146149. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146150. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146151. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146152. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146153. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146154. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146155. 10,
  146156. };
  146157. static float _vq_quantthresh__8u1__p9_2[] = {
  146158. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146159. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146160. };
  146161. static long _vq_quantmap__8u1__p9_2[] = {
  146162. 15, 13, 11, 9, 7, 5, 3, 1,
  146163. 0, 2, 4, 6, 8, 10, 12, 14,
  146164. 16,
  146165. };
  146166. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146167. _vq_quantthresh__8u1__p9_2,
  146168. _vq_quantmap__8u1__p9_2,
  146169. 17,
  146170. 17
  146171. };
  146172. static static_codebook _8u1__p9_2 = {
  146173. 2, 289,
  146174. _vq_lengthlist__8u1__p9_2,
  146175. 1, -529530880, 1611661312, 5, 0,
  146176. _vq_quantlist__8u1__p9_2,
  146177. NULL,
  146178. &_vq_auxt__8u1__p9_2,
  146179. NULL,
  146180. 0
  146181. };
  146182. static long _huff_lengthlist__8u1__single[] = {
  146183. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146184. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146185. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146186. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146187. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146188. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146189. 13, 8, 8,15,
  146190. };
  146191. static static_codebook _huff_book__8u1__single = {
  146192. 2, 100,
  146193. _huff_lengthlist__8u1__single,
  146194. 0, 0, 0, 0, 0,
  146195. NULL,
  146196. NULL,
  146197. NULL,
  146198. NULL,
  146199. 0
  146200. };
  146201. static long _huff_lengthlist__44u0__long[] = {
  146202. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146203. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146204. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146205. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146206. };
  146207. static static_codebook _huff_book__44u0__long = {
  146208. 2, 64,
  146209. _huff_lengthlist__44u0__long,
  146210. 0, 0, 0, 0, 0,
  146211. NULL,
  146212. NULL,
  146213. NULL,
  146214. NULL,
  146215. 0
  146216. };
  146217. static long _vq_quantlist__44u0__p1_0[] = {
  146218. 1,
  146219. 0,
  146220. 2,
  146221. };
  146222. static long _vq_lengthlist__44u0__p1_0[] = {
  146223. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146224. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146225. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146226. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146227. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146228. 13,
  146229. };
  146230. static float _vq_quantthresh__44u0__p1_0[] = {
  146231. -0.5, 0.5,
  146232. };
  146233. static long _vq_quantmap__44u0__p1_0[] = {
  146234. 1, 0, 2,
  146235. };
  146236. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146237. _vq_quantthresh__44u0__p1_0,
  146238. _vq_quantmap__44u0__p1_0,
  146239. 3,
  146240. 3
  146241. };
  146242. static static_codebook _44u0__p1_0 = {
  146243. 4, 81,
  146244. _vq_lengthlist__44u0__p1_0,
  146245. 1, -535822336, 1611661312, 2, 0,
  146246. _vq_quantlist__44u0__p1_0,
  146247. NULL,
  146248. &_vq_auxt__44u0__p1_0,
  146249. NULL,
  146250. 0
  146251. };
  146252. static long _vq_quantlist__44u0__p2_0[] = {
  146253. 1,
  146254. 0,
  146255. 2,
  146256. };
  146257. static long _vq_lengthlist__44u0__p2_0[] = {
  146258. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146259. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146260. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146261. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146262. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146263. 9,
  146264. };
  146265. static float _vq_quantthresh__44u0__p2_0[] = {
  146266. -0.5, 0.5,
  146267. };
  146268. static long _vq_quantmap__44u0__p2_0[] = {
  146269. 1, 0, 2,
  146270. };
  146271. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146272. _vq_quantthresh__44u0__p2_0,
  146273. _vq_quantmap__44u0__p2_0,
  146274. 3,
  146275. 3
  146276. };
  146277. static static_codebook _44u0__p2_0 = {
  146278. 4, 81,
  146279. _vq_lengthlist__44u0__p2_0,
  146280. 1, -535822336, 1611661312, 2, 0,
  146281. _vq_quantlist__44u0__p2_0,
  146282. NULL,
  146283. &_vq_auxt__44u0__p2_0,
  146284. NULL,
  146285. 0
  146286. };
  146287. static long _vq_quantlist__44u0__p3_0[] = {
  146288. 2,
  146289. 1,
  146290. 3,
  146291. 0,
  146292. 4,
  146293. };
  146294. static long _vq_lengthlist__44u0__p3_0[] = {
  146295. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146296. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146297. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146298. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146299. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146300. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146301. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146302. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146303. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146304. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146305. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146306. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146307. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146308. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146309. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146310. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146311. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146312. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146313. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146314. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146315. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146316. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146317. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146318. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146319. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146320. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146321. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146322. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146323. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146324. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146325. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146326. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146327. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146328. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146329. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146330. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146331. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146332. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146333. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146334. 19,
  146335. };
  146336. static float _vq_quantthresh__44u0__p3_0[] = {
  146337. -1.5, -0.5, 0.5, 1.5,
  146338. };
  146339. static long _vq_quantmap__44u0__p3_0[] = {
  146340. 3, 1, 0, 2, 4,
  146341. };
  146342. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146343. _vq_quantthresh__44u0__p3_0,
  146344. _vq_quantmap__44u0__p3_0,
  146345. 5,
  146346. 5
  146347. };
  146348. static static_codebook _44u0__p3_0 = {
  146349. 4, 625,
  146350. _vq_lengthlist__44u0__p3_0,
  146351. 1, -533725184, 1611661312, 3, 0,
  146352. _vq_quantlist__44u0__p3_0,
  146353. NULL,
  146354. &_vq_auxt__44u0__p3_0,
  146355. NULL,
  146356. 0
  146357. };
  146358. static long _vq_quantlist__44u0__p4_0[] = {
  146359. 2,
  146360. 1,
  146361. 3,
  146362. 0,
  146363. 4,
  146364. };
  146365. static long _vq_lengthlist__44u0__p4_0[] = {
  146366. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146367. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146368. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146369. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146370. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146371. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146372. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146373. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146374. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146375. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146376. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146377. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146378. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146379. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146380. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146381. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146382. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146383. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146384. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146385. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146386. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146387. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146388. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146389. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146390. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146391. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146392. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146393. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146394. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146395. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146396. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146397. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146398. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146399. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146400. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146401. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146402. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146403. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146404. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146405. 12,
  146406. };
  146407. static float _vq_quantthresh__44u0__p4_0[] = {
  146408. -1.5, -0.5, 0.5, 1.5,
  146409. };
  146410. static long _vq_quantmap__44u0__p4_0[] = {
  146411. 3, 1, 0, 2, 4,
  146412. };
  146413. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146414. _vq_quantthresh__44u0__p4_0,
  146415. _vq_quantmap__44u0__p4_0,
  146416. 5,
  146417. 5
  146418. };
  146419. static static_codebook _44u0__p4_0 = {
  146420. 4, 625,
  146421. _vq_lengthlist__44u0__p4_0,
  146422. 1, -533725184, 1611661312, 3, 0,
  146423. _vq_quantlist__44u0__p4_0,
  146424. NULL,
  146425. &_vq_auxt__44u0__p4_0,
  146426. NULL,
  146427. 0
  146428. };
  146429. static long _vq_quantlist__44u0__p5_0[] = {
  146430. 4,
  146431. 3,
  146432. 5,
  146433. 2,
  146434. 6,
  146435. 1,
  146436. 7,
  146437. 0,
  146438. 8,
  146439. };
  146440. static long _vq_lengthlist__44u0__p5_0[] = {
  146441. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146442. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146443. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146444. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146445. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146446. 12,
  146447. };
  146448. static float _vq_quantthresh__44u0__p5_0[] = {
  146449. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146450. };
  146451. static long _vq_quantmap__44u0__p5_0[] = {
  146452. 7, 5, 3, 1, 0, 2, 4, 6,
  146453. 8,
  146454. };
  146455. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146456. _vq_quantthresh__44u0__p5_0,
  146457. _vq_quantmap__44u0__p5_0,
  146458. 9,
  146459. 9
  146460. };
  146461. static static_codebook _44u0__p5_0 = {
  146462. 2, 81,
  146463. _vq_lengthlist__44u0__p5_0,
  146464. 1, -531628032, 1611661312, 4, 0,
  146465. _vq_quantlist__44u0__p5_0,
  146466. NULL,
  146467. &_vq_auxt__44u0__p5_0,
  146468. NULL,
  146469. 0
  146470. };
  146471. static long _vq_quantlist__44u0__p6_0[] = {
  146472. 6,
  146473. 5,
  146474. 7,
  146475. 4,
  146476. 8,
  146477. 3,
  146478. 9,
  146479. 2,
  146480. 10,
  146481. 1,
  146482. 11,
  146483. 0,
  146484. 12,
  146485. };
  146486. static long _vq_lengthlist__44u0__p6_0[] = {
  146487. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146488. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146489. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146490. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146491. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146492. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146493. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146494. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146495. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146496. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146497. 15,17,16,17,18,17,17,18, 0,
  146498. };
  146499. static float _vq_quantthresh__44u0__p6_0[] = {
  146500. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146501. 12.5, 17.5, 22.5, 27.5,
  146502. };
  146503. static long _vq_quantmap__44u0__p6_0[] = {
  146504. 11, 9, 7, 5, 3, 1, 0, 2,
  146505. 4, 6, 8, 10, 12,
  146506. };
  146507. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146508. _vq_quantthresh__44u0__p6_0,
  146509. _vq_quantmap__44u0__p6_0,
  146510. 13,
  146511. 13
  146512. };
  146513. static static_codebook _44u0__p6_0 = {
  146514. 2, 169,
  146515. _vq_lengthlist__44u0__p6_0,
  146516. 1, -526516224, 1616117760, 4, 0,
  146517. _vq_quantlist__44u0__p6_0,
  146518. NULL,
  146519. &_vq_auxt__44u0__p6_0,
  146520. NULL,
  146521. 0
  146522. };
  146523. static long _vq_quantlist__44u0__p6_1[] = {
  146524. 2,
  146525. 1,
  146526. 3,
  146527. 0,
  146528. 4,
  146529. };
  146530. static long _vq_lengthlist__44u0__p6_1[] = {
  146531. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146532. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146533. };
  146534. static float _vq_quantthresh__44u0__p6_1[] = {
  146535. -1.5, -0.5, 0.5, 1.5,
  146536. };
  146537. static long _vq_quantmap__44u0__p6_1[] = {
  146538. 3, 1, 0, 2, 4,
  146539. };
  146540. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146541. _vq_quantthresh__44u0__p6_1,
  146542. _vq_quantmap__44u0__p6_1,
  146543. 5,
  146544. 5
  146545. };
  146546. static static_codebook _44u0__p6_1 = {
  146547. 2, 25,
  146548. _vq_lengthlist__44u0__p6_1,
  146549. 1, -533725184, 1611661312, 3, 0,
  146550. _vq_quantlist__44u0__p6_1,
  146551. NULL,
  146552. &_vq_auxt__44u0__p6_1,
  146553. NULL,
  146554. 0
  146555. };
  146556. static long _vq_quantlist__44u0__p7_0[] = {
  146557. 2,
  146558. 1,
  146559. 3,
  146560. 0,
  146561. 4,
  146562. };
  146563. static long _vq_lengthlist__44u0__p7_0[] = {
  146564. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146567. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146568. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146569. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146570. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146571. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146579. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146581. 11,11,11,11,11,11,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,11,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,11,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,10,10,10,10,10,10,10,10,10,10,
  146595. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146597. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146598. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146600. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146603. 10,
  146604. };
  146605. static float _vq_quantthresh__44u0__p7_0[] = {
  146606. -253.5, -84.5, 84.5, 253.5,
  146607. };
  146608. static long _vq_quantmap__44u0__p7_0[] = {
  146609. 3, 1, 0, 2, 4,
  146610. };
  146611. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146612. _vq_quantthresh__44u0__p7_0,
  146613. _vq_quantmap__44u0__p7_0,
  146614. 5,
  146615. 5
  146616. };
  146617. static static_codebook _44u0__p7_0 = {
  146618. 4, 625,
  146619. _vq_lengthlist__44u0__p7_0,
  146620. 1, -518709248, 1626677248, 3, 0,
  146621. _vq_quantlist__44u0__p7_0,
  146622. NULL,
  146623. &_vq_auxt__44u0__p7_0,
  146624. NULL,
  146625. 0
  146626. };
  146627. static long _vq_quantlist__44u0__p7_1[] = {
  146628. 6,
  146629. 5,
  146630. 7,
  146631. 4,
  146632. 8,
  146633. 3,
  146634. 9,
  146635. 2,
  146636. 10,
  146637. 1,
  146638. 11,
  146639. 0,
  146640. 12,
  146641. };
  146642. static long _vq_lengthlist__44u0__p7_1[] = {
  146643. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146644. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146645. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146646. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146647. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146648. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146649. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146650. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146651. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146652. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146653. 15,15,15,15,15,15,15,15,15,
  146654. };
  146655. static float _vq_quantthresh__44u0__p7_1[] = {
  146656. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146657. 32.5, 45.5, 58.5, 71.5,
  146658. };
  146659. static long _vq_quantmap__44u0__p7_1[] = {
  146660. 11, 9, 7, 5, 3, 1, 0, 2,
  146661. 4, 6, 8, 10, 12,
  146662. };
  146663. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146664. _vq_quantthresh__44u0__p7_1,
  146665. _vq_quantmap__44u0__p7_1,
  146666. 13,
  146667. 13
  146668. };
  146669. static static_codebook _44u0__p7_1 = {
  146670. 2, 169,
  146671. _vq_lengthlist__44u0__p7_1,
  146672. 1, -523010048, 1618608128, 4, 0,
  146673. _vq_quantlist__44u0__p7_1,
  146674. NULL,
  146675. &_vq_auxt__44u0__p7_1,
  146676. NULL,
  146677. 0
  146678. };
  146679. static long _vq_quantlist__44u0__p7_2[] = {
  146680. 6,
  146681. 5,
  146682. 7,
  146683. 4,
  146684. 8,
  146685. 3,
  146686. 9,
  146687. 2,
  146688. 10,
  146689. 1,
  146690. 11,
  146691. 0,
  146692. 12,
  146693. };
  146694. static long _vq_lengthlist__44u0__p7_2[] = {
  146695. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146696. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146697. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146698. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146699. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146700. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146701. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146702. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146703. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146704. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146705. 9, 9, 9,10, 9, 9,10,10, 9,
  146706. };
  146707. static float _vq_quantthresh__44u0__p7_2[] = {
  146708. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146709. 2.5, 3.5, 4.5, 5.5,
  146710. };
  146711. static long _vq_quantmap__44u0__p7_2[] = {
  146712. 11, 9, 7, 5, 3, 1, 0, 2,
  146713. 4, 6, 8, 10, 12,
  146714. };
  146715. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146716. _vq_quantthresh__44u0__p7_2,
  146717. _vq_quantmap__44u0__p7_2,
  146718. 13,
  146719. 13
  146720. };
  146721. static static_codebook _44u0__p7_2 = {
  146722. 2, 169,
  146723. _vq_lengthlist__44u0__p7_2,
  146724. 1, -531103744, 1611661312, 4, 0,
  146725. _vq_quantlist__44u0__p7_2,
  146726. NULL,
  146727. &_vq_auxt__44u0__p7_2,
  146728. NULL,
  146729. 0
  146730. };
  146731. static long _huff_lengthlist__44u0__short[] = {
  146732. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146733. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146734. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146735. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146736. };
  146737. static static_codebook _huff_book__44u0__short = {
  146738. 2, 64,
  146739. _huff_lengthlist__44u0__short,
  146740. 0, 0, 0, 0, 0,
  146741. NULL,
  146742. NULL,
  146743. NULL,
  146744. NULL,
  146745. 0
  146746. };
  146747. static long _huff_lengthlist__44u1__long[] = {
  146748. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146749. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146750. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146751. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146752. };
  146753. static static_codebook _huff_book__44u1__long = {
  146754. 2, 64,
  146755. _huff_lengthlist__44u1__long,
  146756. 0, 0, 0, 0, 0,
  146757. NULL,
  146758. NULL,
  146759. NULL,
  146760. NULL,
  146761. 0
  146762. };
  146763. static long _vq_quantlist__44u1__p1_0[] = {
  146764. 1,
  146765. 0,
  146766. 2,
  146767. };
  146768. static long _vq_lengthlist__44u1__p1_0[] = {
  146769. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146770. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146771. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146772. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146773. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146774. 13,
  146775. };
  146776. static float _vq_quantthresh__44u1__p1_0[] = {
  146777. -0.5, 0.5,
  146778. };
  146779. static long _vq_quantmap__44u1__p1_0[] = {
  146780. 1, 0, 2,
  146781. };
  146782. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146783. _vq_quantthresh__44u1__p1_0,
  146784. _vq_quantmap__44u1__p1_0,
  146785. 3,
  146786. 3
  146787. };
  146788. static static_codebook _44u1__p1_0 = {
  146789. 4, 81,
  146790. _vq_lengthlist__44u1__p1_0,
  146791. 1, -535822336, 1611661312, 2, 0,
  146792. _vq_quantlist__44u1__p1_0,
  146793. NULL,
  146794. &_vq_auxt__44u1__p1_0,
  146795. NULL,
  146796. 0
  146797. };
  146798. static long _vq_quantlist__44u1__p2_0[] = {
  146799. 1,
  146800. 0,
  146801. 2,
  146802. };
  146803. static long _vq_lengthlist__44u1__p2_0[] = {
  146804. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146805. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146806. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146807. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146808. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146809. 9,
  146810. };
  146811. static float _vq_quantthresh__44u1__p2_0[] = {
  146812. -0.5, 0.5,
  146813. };
  146814. static long _vq_quantmap__44u1__p2_0[] = {
  146815. 1, 0, 2,
  146816. };
  146817. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146818. _vq_quantthresh__44u1__p2_0,
  146819. _vq_quantmap__44u1__p2_0,
  146820. 3,
  146821. 3
  146822. };
  146823. static static_codebook _44u1__p2_0 = {
  146824. 4, 81,
  146825. _vq_lengthlist__44u1__p2_0,
  146826. 1, -535822336, 1611661312, 2, 0,
  146827. _vq_quantlist__44u1__p2_0,
  146828. NULL,
  146829. &_vq_auxt__44u1__p2_0,
  146830. NULL,
  146831. 0
  146832. };
  146833. static long _vq_quantlist__44u1__p3_0[] = {
  146834. 2,
  146835. 1,
  146836. 3,
  146837. 0,
  146838. 4,
  146839. };
  146840. static long _vq_lengthlist__44u1__p3_0[] = {
  146841. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146842. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146843. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146844. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146845. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146846. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146847. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146848. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146849. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146850. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146851. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146852. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146853. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146854. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146855. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146856. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146857. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146858. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146859. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146860. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146861. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146862. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146863. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146864. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146865. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146866. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146867. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146868. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146869. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146870. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146871. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146872. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146873. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146874. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146875. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146876. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146877. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146878. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146879. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146880. 19,
  146881. };
  146882. static float _vq_quantthresh__44u1__p3_0[] = {
  146883. -1.5, -0.5, 0.5, 1.5,
  146884. };
  146885. static long _vq_quantmap__44u1__p3_0[] = {
  146886. 3, 1, 0, 2, 4,
  146887. };
  146888. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146889. _vq_quantthresh__44u1__p3_0,
  146890. _vq_quantmap__44u1__p3_0,
  146891. 5,
  146892. 5
  146893. };
  146894. static static_codebook _44u1__p3_0 = {
  146895. 4, 625,
  146896. _vq_lengthlist__44u1__p3_0,
  146897. 1, -533725184, 1611661312, 3, 0,
  146898. _vq_quantlist__44u1__p3_0,
  146899. NULL,
  146900. &_vq_auxt__44u1__p3_0,
  146901. NULL,
  146902. 0
  146903. };
  146904. static long _vq_quantlist__44u1__p4_0[] = {
  146905. 2,
  146906. 1,
  146907. 3,
  146908. 0,
  146909. 4,
  146910. };
  146911. static long _vq_lengthlist__44u1__p4_0[] = {
  146912. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146913. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146914. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146915. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146916. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146917. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146918. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146919. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146920. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146921. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146922. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146923. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146924. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146925. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146926. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146927. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146928. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146929. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146930. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146931. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146932. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146933. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146934. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146935. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146936. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146937. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146938. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146939. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146940. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146941. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146942. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146943. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146944. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146945. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146946. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146947. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146948. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146949. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146950. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146951. 12,
  146952. };
  146953. static float _vq_quantthresh__44u1__p4_0[] = {
  146954. -1.5, -0.5, 0.5, 1.5,
  146955. };
  146956. static long _vq_quantmap__44u1__p4_0[] = {
  146957. 3, 1, 0, 2, 4,
  146958. };
  146959. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146960. _vq_quantthresh__44u1__p4_0,
  146961. _vq_quantmap__44u1__p4_0,
  146962. 5,
  146963. 5
  146964. };
  146965. static static_codebook _44u1__p4_0 = {
  146966. 4, 625,
  146967. _vq_lengthlist__44u1__p4_0,
  146968. 1, -533725184, 1611661312, 3, 0,
  146969. _vq_quantlist__44u1__p4_0,
  146970. NULL,
  146971. &_vq_auxt__44u1__p4_0,
  146972. NULL,
  146973. 0
  146974. };
  146975. static long _vq_quantlist__44u1__p5_0[] = {
  146976. 4,
  146977. 3,
  146978. 5,
  146979. 2,
  146980. 6,
  146981. 1,
  146982. 7,
  146983. 0,
  146984. 8,
  146985. };
  146986. static long _vq_lengthlist__44u1__p5_0[] = {
  146987. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146988. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146989. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146990. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146991. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146992. 12,
  146993. };
  146994. static float _vq_quantthresh__44u1__p5_0[] = {
  146995. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146996. };
  146997. static long _vq_quantmap__44u1__p5_0[] = {
  146998. 7, 5, 3, 1, 0, 2, 4, 6,
  146999. 8,
  147000. };
  147001. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147002. _vq_quantthresh__44u1__p5_0,
  147003. _vq_quantmap__44u1__p5_0,
  147004. 9,
  147005. 9
  147006. };
  147007. static static_codebook _44u1__p5_0 = {
  147008. 2, 81,
  147009. _vq_lengthlist__44u1__p5_0,
  147010. 1, -531628032, 1611661312, 4, 0,
  147011. _vq_quantlist__44u1__p5_0,
  147012. NULL,
  147013. &_vq_auxt__44u1__p5_0,
  147014. NULL,
  147015. 0
  147016. };
  147017. static long _vq_quantlist__44u1__p6_0[] = {
  147018. 6,
  147019. 5,
  147020. 7,
  147021. 4,
  147022. 8,
  147023. 3,
  147024. 9,
  147025. 2,
  147026. 10,
  147027. 1,
  147028. 11,
  147029. 0,
  147030. 12,
  147031. };
  147032. static long _vq_lengthlist__44u1__p6_0[] = {
  147033. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147034. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147035. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147036. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147037. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147038. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147039. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147040. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147041. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147042. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147043. 15,17,16,17,18,17,17,18, 0,
  147044. };
  147045. static float _vq_quantthresh__44u1__p6_0[] = {
  147046. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147047. 12.5, 17.5, 22.5, 27.5,
  147048. };
  147049. static long _vq_quantmap__44u1__p6_0[] = {
  147050. 11, 9, 7, 5, 3, 1, 0, 2,
  147051. 4, 6, 8, 10, 12,
  147052. };
  147053. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147054. _vq_quantthresh__44u1__p6_0,
  147055. _vq_quantmap__44u1__p6_0,
  147056. 13,
  147057. 13
  147058. };
  147059. static static_codebook _44u1__p6_0 = {
  147060. 2, 169,
  147061. _vq_lengthlist__44u1__p6_0,
  147062. 1, -526516224, 1616117760, 4, 0,
  147063. _vq_quantlist__44u1__p6_0,
  147064. NULL,
  147065. &_vq_auxt__44u1__p6_0,
  147066. NULL,
  147067. 0
  147068. };
  147069. static long _vq_quantlist__44u1__p6_1[] = {
  147070. 2,
  147071. 1,
  147072. 3,
  147073. 0,
  147074. 4,
  147075. };
  147076. static long _vq_lengthlist__44u1__p6_1[] = {
  147077. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147078. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147079. };
  147080. static float _vq_quantthresh__44u1__p6_1[] = {
  147081. -1.5, -0.5, 0.5, 1.5,
  147082. };
  147083. static long _vq_quantmap__44u1__p6_1[] = {
  147084. 3, 1, 0, 2, 4,
  147085. };
  147086. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147087. _vq_quantthresh__44u1__p6_1,
  147088. _vq_quantmap__44u1__p6_1,
  147089. 5,
  147090. 5
  147091. };
  147092. static static_codebook _44u1__p6_1 = {
  147093. 2, 25,
  147094. _vq_lengthlist__44u1__p6_1,
  147095. 1, -533725184, 1611661312, 3, 0,
  147096. _vq_quantlist__44u1__p6_1,
  147097. NULL,
  147098. &_vq_auxt__44u1__p6_1,
  147099. NULL,
  147100. 0
  147101. };
  147102. static long _vq_quantlist__44u1__p7_0[] = {
  147103. 3,
  147104. 2,
  147105. 4,
  147106. 1,
  147107. 5,
  147108. 0,
  147109. 6,
  147110. };
  147111. static long _vq_lengthlist__44u1__p7_0[] = {
  147112. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147113. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147114. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147115. 8,
  147116. };
  147117. static float _vq_quantthresh__44u1__p7_0[] = {
  147118. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147119. };
  147120. static long _vq_quantmap__44u1__p7_0[] = {
  147121. 5, 3, 1, 0, 2, 4, 6,
  147122. };
  147123. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147124. _vq_quantthresh__44u1__p7_0,
  147125. _vq_quantmap__44u1__p7_0,
  147126. 7,
  147127. 7
  147128. };
  147129. static static_codebook _44u1__p7_0 = {
  147130. 2, 49,
  147131. _vq_lengthlist__44u1__p7_0,
  147132. 1, -518017024, 1626677248, 3, 0,
  147133. _vq_quantlist__44u1__p7_0,
  147134. NULL,
  147135. &_vq_auxt__44u1__p7_0,
  147136. NULL,
  147137. 0
  147138. };
  147139. static long _vq_quantlist__44u1__p7_1[] = {
  147140. 6,
  147141. 5,
  147142. 7,
  147143. 4,
  147144. 8,
  147145. 3,
  147146. 9,
  147147. 2,
  147148. 10,
  147149. 1,
  147150. 11,
  147151. 0,
  147152. 12,
  147153. };
  147154. static long _vq_lengthlist__44u1__p7_1[] = {
  147155. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147156. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147157. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147158. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147159. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147160. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147161. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147162. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147163. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147164. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147165. 15,15,15,15,15,15,15,15,15,
  147166. };
  147167. static float _vq_quantthresh__44u1__p7_1[] = {
  147168. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147169. 32.5, 45.5, 58.5, 71.5,
  147170. };
  147171. static long _vq_quantmap__44u1__p7_1[] = {
  147172. 11, 9, 7, 5, 3, 1, 0, 2,
  147173. 4, 6, 8, 10, 12,
  147174. };
  147175. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147176. _vq_quantthresh__44u1__p7_1,
  147177. _vq_quantmap__44u1__p7_1,
  147178. 13,
  147179. 13
  147180. };
  147181. static static_codebook _44u1__p7_1 = {
  147182. 2, 169,
  147183. _vq_lengthlist__44u1__p7_1,
  147184. 1, -523010048, 1618608128, 4, 0,
  147185. _vq_quantlist__44u1__p7_1,
  147186. NULL,
  147187. &_vq_auxt__44u1__p7_1,
  147188. NULL,
  147189. 0
  147190. };
  147191. static long _vq_quantlist__44u1__p7_2[] = {
  147192. 6,
  147193. 5,
  147194. 7,
  147195. 4,
  147196. 8,
  147197. 3,
  147198. 9,
  147199. 2,
  147200. 10,
  147201. 1,
  147202. 11,
  147203. 0,
  147204. 12,
  147205. };
  147206. static long _vq_lengthlist__44u1__p7_2[] = {
  147207. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147208. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147209. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147210. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147211. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147212. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147213. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147214. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147215. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147216. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147217. 9, 9, 9,10, 9, 9,10,10, 9,
  147218. };
  147219. static float _vq_quantthresh__44u1__p7_2[] = {
  147220. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147221. 2.5, 3.5, 4.5, 5.5,
  147222. };
  147223. static long _vq_quantmap__44u1__p7_2[] = {
  147224. 11, 9, 7, 5, 3, 1, 0, 2,
  147225. 4, 6, 8, 10, 12,
  147226. };
  147227. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147228. _vq_quantthresh__44u1__p7_2,
  147229. _vq_quantmap__44u1__p7_2,
  147230. 13,
  147231. 13
  147232. };
  147233. static static_codebook _44u1__p7_2 = {
  147234. 2, 169,
  147235. _vq_lengthlist__44u1__p7_2,
  147236. 1, -531103744, 1611661312, 4, 0,
  147237. _vq_quantlist__44u1__p7_2,
  147238. NULL,
  147239. &_vq_auxt__44u1__p7_2,
  147240. NULL,
  147241. 0
  147242. };
  147243. static long _huff_lengthlist__44u1__short[] = {
  147244. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147245. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147246. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147247. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147248. };
  147249. static static_codebook _huff_book__44u1__short = {
  147250. 2, 64,
  147251. _huff_lengthlist__44u1__short,
  147252. 0, 0, 0, 0, 0,
  147253. NULL,
  147254. NULL,
  147255. NULL,
  147256. NULL,
  147257. 0
  147258. };
  147259. static long _huff_lengthlist__44u2__long[] = {
  147260. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147261. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147262. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147263. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147264. };
  147265. static static_codebook _huff_book__44u2__long = {
  147266. 2, 64,
  147267. _huff_lengthlist__44u2__long,
  147268. 0, 0, 0, 0, 0,
  147269. NULL,
  147270. NULL,
  147271. NULL,
  147272. NULL,
  147273. 0
  147274. };
  147275. static long _vq_quantlist__44u2__p1_0[] = {
  147276. 1,
  147277. 0,
  147278. 2,
  147279. };
  147280. static long _vq_lengthlist__44u2__p1_0[] = {
  147281. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147282. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147283. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147284. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147285. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147286. 13,
  147287. };
  147288. static float _vq_quantthresh__44u2__p1_0[] = {
  147289. -0.5, 0.5,
  147290. };
  147291. static long _vq_quantmap__44u2__p1_0[] = {
  147292. 1, 0, 2,
  147293. };
  147294. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147295. _vq_quantthresh__44u2__p1_0,
  147296. _vq_quantmap__44u2__p1_0,
  147297. 3,
  147298. 3
  147299. };
  147300. static static_codebook _44u2__p1_0 = {
  147301. 4, 81,
  147302. _vq_lengthlist__44u2__p1_0,
  147303. 1, -535822336, 1611661312, 2, 0,
  147304. _vq_quantlist__44u2__p1_0,
  147305. NULL,
  147306. &_vq_auxt__44u2__p1_0,
  147307. NULL,
  147308. 0
  147309. };
  147310. static long _vq_quantlist__44u2__p2_0[] = {
  147311. 1,
  147312. 0,
  147313. 2,
  147314. };
  147315. static long _vq_lengthlist__44u2__p2_0[] = {
  147316. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147317. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147318. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147319. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147320. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147321. 9,
  147322. };
  147323. static float _vq_quantthresh__44u2__p2_0[] = {
  147324. -0.5, 0.5,
  147325. };
  147326. static long _vq_quantmap__44u2__p2_0[] = {
  147327. 1, 0, 2,
  147328. };
  147329. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147330. _vq_quantthresh__44u2__p2_0,
  147331. _vq_quantmap__44u2__p2_0,
  147332. 3,
  147333. 3
  147334. };
  147335. static static_codebook _44u2__p2_0 = {
  147336. 4, 81,
  147337. _vq_lengthlist__44u2__p2_0,
  147338. 1, -535822336, 1611661312, 2, 0,
  147339. _vq_quantlist__44u2__p2_0,
  147340. NULL,
  147341. &_vq_auxt__44u2__p2_0,
  147342. NULL,
  147343. 0
  147344. };
  147345. static long _vq_quantlist__44u2__p3_0[] = {
  147346. 2,
  147347. 1,
  147348. 3,
  147349. 0,
  147350. 4,
  147351. };
  147352. static long _vq_lengthlist__44u2__p3_0[] = {
  147353. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147354. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147355. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147356. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147357. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147358. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147359. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147360. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147361. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147362. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147363. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147364. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147365. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147366. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147367. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147368. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147369. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147370. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147371. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147372. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147373. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147374. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147375. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147376. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147377. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147378. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147379. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147380. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147381. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147382. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147383. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147384. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147385. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147386. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147387. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147388. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147389. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147390. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147391. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147392. 0,
  147393. };
  147394. static float _vq_quantthresh__44u2__p3_0[] = {
  147395. -1.5, -0.5, 0.5, 1.5,
  147396. };
  147397. static long _vq_quantmap__44u2__p3_0[] = {
  147398. 3, 1, 0, 2, 4,
  147399. };
  147400. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147401. _vq_quantthresh__44u2__p3_0,
  147402. _vq_quantmap__44u2__p3_0,
  147403. 5,
  147404. 5
  147405. };
  147406. static static_codebook _44u2__p3_0 = {
  147407. 4, 625,
  147408. _vq_lengthlist__44u2__p3_0,
  147409. 1, -533725184, 1611661312, 3, 0,
  147410. _vq_quantlist__44u2__p3_0,
  147411. NULL,
  147412. &_vq_auxt__44u2__p3_0,
  147413. NULL,
  147414. 0
  147415. };
  147416. static long _vq_quantlist__44u2__p4_0[] = {
  147417. 2,
  147418. 1,
  147419. 3,
  147420. 0,
  147421. 4,
  147422. };
  147423. static long _vq_lengthlist__44u2__p4_0[] = {
  147424. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147425. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147426. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147427. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147428. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147429. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147430. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147431. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147432. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147433. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147434. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147435. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147436. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147437. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147438. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147439. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147440. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147441. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147442. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147443. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147444. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147445. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147446. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147447. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147448. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147449. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147450. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147451. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147452. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147453. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147454. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147455. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147456. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147457. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147458. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147459. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147460. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147461. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147462. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147463. 13,
  147464. };
  147465. static float _vq_quantthresh__44u2__p4_0[] = {
  147466. -1.5, -0.5, 0.5, 1.5,
  147467. };
  147468. static long _vq_quantmap__44u2__p4_0[] = {
  147469. 3, 1, 0, 2, 4,
  147470. };
  147471. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147472. _vq_quantthresh__44u2__p4_0,
  147473. _vq_quantmap__44u2__p4_0,
  147474. 5,
  147475. 5
  147476. };
  147477. static static_codebook _44u2__p4_0 = {
  147478. 4, 625,
  147479. _vq_lengthlist__44u2__p4_0,
  147480. 1, -533725184, 1611661312, 3, 0,
  147481. _vq_quantlist__44u2__p4_0,
  147482. NULL,
  147483. &_vq_auxt__44u2__p4_0,
  147484. NULL,
  147485. 0
  147486. };
  147487. static long _vq_quantlist__44u2__p5_0[] = {
  147488. 4,
  147489. 3,
  147490. 5,
  147491. 2,
  147492. 6,
  147493. 1,
  147494. 7,
  147495. 0,
  147496. 8,
  147497. };
  147498. static long _vq_lengthlist__44u2__p5_0[] = {
  147499. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147500. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147501. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147502. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147503. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147504. 13,
  147505. };
  147506. static float _vq_quantthresh__44u2__p5_0[] = {
  147507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147508. };
  147509. static long _vq_quantmap__44u2__p5_0[] = {
  147510. 7, 5, 3, 1, 0, 2, 4, 6,
  147511. 8,
  147512. };
  147513. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147514. _vq_quantthresh__44u2__p5_0,
  147515. _vq_quantmap__44u2__p5_0,
  147516. 9,
  147517. 9
  147518. };
  147519. static static_codebook _44u2__p5_0 = {
  147520. 2, 81,
  147521. _vq_lengthlist__44u2__p5_0,
  147522. 1, -531628032, 1611661312, 4, 0,
  147523. _vq_quantlist__44u2__p5_0,
  147524. NULL,
  147525. &_vq_auxt__44u2__p5_0,
  147526. NULL,
  147527. 0
  147528. };
  147529. static long _vq_quantlist__44u2__p6_0[] = {
  147530. 6,
  147531. 5,
  147532. 7,
  147533. 4,
  147534. 8,
  147535. 3,
  147536. 9,
  147537. 2,
  147538. 10,
  147539. 1,
  147540. 11,
  147541. 0,
  147542. 12,
  147543. };
  147544. static long _vq_lengthlist__44u2__p6_0[] = {
  147545. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147546. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147547. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147548. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147549. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147550. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147551. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147552. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147553. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147554. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147555. 15,17,17,16,18,17,18, 0, 0,
  147556. };
  147557. static float _vq_quantthresh__44u2__p6_0[] = {
  147558. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147559. 12.5, 17.5, 22.5, 27.5,
  147560. };
  147561. static long _vq_quantmap__44u2__p6_0[] = {
  147562. 11, 9, 7, 5, 3, 1, 0, 2,
  147563. 4, 6, 8, 10, 12,
  147564. };
  147565. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147566. _vq_quantthresh__44u2__p6_0,
  147567. _vq_quantmap__44u2__p6_0,
  147568. 13,
  147569. 13
  147570. };
  147571. static static_codebook _44u2__p6_0 = {
  147572. 2, 169,
  147573. _vq_lengthlist__44u2__p6_0,
  147574. 1, -526516224, 1616117760, 4, 0,
  147575. _vq_quantlist__44u2__p6_0,
  147576. NULL,
  147577. &_vq_auxt__44u2__p6_0,
  147578. NULL,
  147579. 0
  147580. };
  147581. static long _vq_quantlist__44u2__p6_1[] = {
  147582. 2,
  147583. 1,
  147584. 3,
  147585. 0,
  147586. 4,
  147587. };
  147588. static long _vq_lengthlist__44u2__p6_1[] = {
  147589. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147590. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147591. };
  147592. static float _vq_quantthresh__44u2__p6_1[] = {
  147593. -1.5, -0.5, 0.5, 1.5,
  147594. };
  147595. static long _vq_quantmap__44u2__p6_1[] = {
  147596. 3, 1, 0, 2, 4,
  147597. };
  147598. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147599. _vq_quantthresh__44u2__p6_1,
  147600. _vq_quantmap__44u2__p6_1,
  147601. 5,
  147602. 5
  147603. };
  147604. static static_codebook _44u2__p6_1 = {
  147605. 2, 25,
  147606. _vq_lengthlist__44u2__p6_1,
  147607. 1, -533725184, 1611661312, 3, 0,
  147608. _vq_quantlist__44u2__p6_1,
  147609. NULL,
  147610. &_vq_auxt__44u2__p6_1,
  147611. NULL,
  147612. 0
  147613. };
  147614. static long _vq_quantlist__44u2__p7_0[] = {
  147615. 4,
  147616. 3,
  147617. 5,
  147618. 2,
  147619. 6,
  147620. 1,
  147621. 7,
  147622. 0,
  147623. 8,
  147624. };
  147625. static long _vq_lengthlist__44u2__p7_0[] = {
  147626. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147627. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147631. 11,
  147632. };
  147633. static float _vq_quantthresh__44u2__p7_0[] = {
  147634. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147635. };
  147636. static long _vq_quantmap__44u2__p7_0[] = {
  147637. 7, 5, 3, 1, 0, 2, 4, 6,
  147638. 8,
  147639. };
  147640. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147641. _vq_quantthresh__44u2__p7_0,
  147642. _vq_quantmap__44u2__p7_0,
  147643. 9,
  147644. 9
  147645. };
  147646. static static_codebook _44u2__p7_0 = {
  147647. 2, 81,
  147648. _vq_lengthlist__44u2__p7_0,
  147649. 1, -516612096, 1626677248, 4, 0,
  147650. _vq_quantlist__44u2__p7_0,
  147651. NULL,
  147652. &_vq_auxt__44u2__p7_0,
  147653. NULL,
  147654. 0
  147655. };
  147656. static long _vq_quantlist__44u2__p7_1[] = {
  147657. 6,
  147658. 5,
  147659. 7,
  147660. 4,
  147661. 8,
  147662. 3,
  147663. 9,
  147664. 2,
  147665. 10,
  147666. 1,
  147667. 11,
  147668. 0,
  147669. 12,
  147670. };
  147671. static long _vq_lengthlist__44u2__p7_1[] = {
  147672. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147673. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147674. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147675. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147676. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147677. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147678. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147679. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147680. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147681. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147682. 14,14,14,17,15,17,17,17,17,
  147683. };
  147684. static float _vq_quantthresh__44u2__p7_1[] = {
  147685. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147686. 32.5, 45.5, 58.5, 71.5,
  147687. };
  147688. static long _vq_quantmap__44u2__p7_1[] = {
  147689. 11, 9, 7, 5, 3, 1, 0, 2,
  147690. 4, 6, 8, 10, 12,
  147691. };
  147692. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147693. _vq_quantthresh__44u2__p7_1,
  147694. _vq_quantmap__44u2__p7_1,
  147695. 13,
  147696. 13
  147697. };
  147698. static static_codebook _44u2__p7_1 = {
  147699. 2, 169,
  147700. _vq_lengthlist__44u2__p7_1,
  147701. 1, -523010048, 1618608128, 4, 0,
  147702. _vq_quantlist__44u2__p7_1,
  147703. NULL,
  147704. &_vq_auxt__44u2__p7_1,
  147705. NULL,
  147706. 0
  147707. };
  147708. static long _vq_quantlist__44u2__p7_2[] = {
  147709. 6,
  147710. 5,
  147711. 7,
  147712. 4,
  147713. 8,
  147714. 3,
  147715. 9,
  147716. 2,
  147717. 10,
  147718. 1,
  147719. 11,
  147720. 0,
  147721. 12,
  147722. };
  147723. static long _vq_lengthlist__44u2__p7_2[] = {
  147724. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147725. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147726. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147727. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147728. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147729. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147730. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147731. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147732. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147733. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147734. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147735. };
  147736. static float _vq_quantthresh__44u2__p7_2[] = {
  147737. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147738. 2.5, 3.5, 4.5, 5.5,
  147739. };
  147740. static long _vq_quantmap__44u2__p7_2[] = {
  147741. 11, 9, 7, 5, 3, 1, 0, 2,
  147742. 4, 6, 8, 10, 12,
  147743. };
  147744. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147745. _vq_quantthresh__44u2__p7_2,
  147746. _vq_quantmap__44u2__p7_2,
  147747. 13,
  147748. 13
  147749. };
  147750. static static_codebook _44u2__p7_2 = {
  147751. 2, 169,
  147752. _vq_lengthlist__44u2__p7_2,
  147753. 1, -531103744, 1611661312, 4, 0,
  147754. _vq_quantlist__44u2__p7_2,
  147755. NULL,
  147756. &_vq_auxt__44u2__p7_2,
  147757. NULL,
  147758. 0
  147759. };
  147760. static long _huff_lengthlist__44u2__short[] = {
  147761. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147762. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147763. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147764. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147765. };
  147766. static static_codebook _huff_book__44u2__short = {
  147767. 2, 64,
  147768. _huff_lengthlist__44u2__short,
  147769. 0, 0, 0, 0, 0,
  147770. NULL,
  147771. NULL,
  147772. NULL,
  147773. NULL,
  147774. 0
  147775. };
  147776. static long _huff_lengthlist__44u3__long[] = {
  147777. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147778. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147779. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147780. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147781. };
  147782. static static_codebook _huff_book__44u3__long = {
  147783. 2, 64,
  147784. _huff_lengthlist__44u3__long,
  147785. 0, 0, 0, 0, 0,
  147786. NULL,
  147787. NULL,
  147788. NULL,
  147789. NULL,
  147790. 0
  147791. };
  147792. static long _vq_quantlist__44u3__p1_0[] = {
  147793. 1,
  147794. 0,
  147795. 2,
  147796. };
  147797. static long _vq_lengthlist__44u3__p1_0[] = {
  147798. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147799. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147800. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147801. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147802. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147803. 13,
  147804. };
  147805. static float _vq_quantthresh__44u3__p1_0[] = {
  147806. -0.5, 0.5,
  147807. };
  147808. static long _vq_quantmap__44u3__p1_0[] = {
  147809. 1, 0, 2,
  147810. };
  147811. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147812. _vq_quantthresh__44u3__p1_0,
  147813. _vq_quantmap__44u3__p1_0,
  147814. 3,
  147815. 3
  147816. };
  147817. static static_codebook _44u3__p1_0 = {
  147818. 4, 81,
  147819. _vq_lengthlist__44u3__p1_0,
  147820. 1, -535822336, 1611661312, 2, 0,
  147821. _vq_quantlist__44u3__p1_0,
  147822. NULL,
  147823. &_vq_auxt__44u3__p1_0,
  147824. NULL,
  147825. 0
  147826. };
  147827. static long _vq_quantlist__44u3__p2_0[] = {
  147828. 1,
  147829. 0,
  147830. 2,
  147831. };
  147832. static long _vq_lengthlist__44u3__p2_0[] = {
  147833. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147834. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147835. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147836. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147837. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147838. 9,
  147839. };
  147840. static float _vq_quantthresh__44u3__p2_0[] = {
  147841. -0.5, 0.5,
  147842. };
  147843. static long _vq_quantmap__44u3__p2_0[] = {
  147844. 1, 0, 2,
  147845. };
  147846. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147847. _vq_quantthresh__44u3__p2_0,
  147848. _vq_quantmap__44u3__p2_0,
  147849. 3,
  147850. 3
  147851. };
  147852. static static_codebook _44u3__p2_0 = {
  147853. 4, 81,
  147854. _vq_lengthlist__44u3__p2_0,
  147855. 1, -535822336, 1611661312, 2, 0,
  147856. _vq_quantlist__44u3__p2_0,
  147857. NULL,
  147858. &_vq_auxt__44u3__p2_0,
  147859. NULL,
  147860. 0
  147861. };
  147862. static long _vq_quantlist__44u3__p3_0[] = {
  147863. 2,
  147864. 1,
  147865. 3,
  147866. 0,
  147867. 4,
  147868. };
  147869. static long _vq_lengthlist__44u3__p3_0[] = {
  147870. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147871. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147872. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147873. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147874. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147875. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147876. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147877. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147878. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147879. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147880. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147881. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147882. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147883. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147884. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147885. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147886. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147887. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147888. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147889. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147890. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147891. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147892. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147893. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147894. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147895. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147896. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147897. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147898. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147899. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147900. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147901. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147902. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147903. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147904. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147905. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147906. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147907. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147908. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147909. 0,
  147910. };
  147911. static float _vq_quantthresh__44u3__p3_0[] = {
  147912. -1.5, -0.5, 0.5, 1.5,
  147913. };
  147914. static long _vq_quantmap__44u3__p3_0[] = {
  147915. 3, 1, 0, 2, 4,
  147916. };
  147917. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147918. _vq_quantthresh__44u3__p3_0,
  147919. _vq_quantmap__44u3__p3_0,
  147920. 5,
  147921. 5
  147922. };
  147923. static static_codebook _44u3__p3_0 = {
  147924. 4, 625,
  147925. _vq_lengthlist__44u3__p3_0,
  147926. 1, -533725184, 1611661312, 3, 0,
  147927. _vq_quantlist__44u3__p3_0,
  147928. NULL,
  147929. &_vq_auxt__44u3__p3_0,
  147930. NULL,
  147931. 0
  147932. };
  147933. static long _vq_quantlist__44u3__p4_0[] = {
  147934. 2,
  147935. 1,
  147936. 3,
  147937. 0,
  147938. 4,
  147939. };
  147940. static long _vq_lengthlist__44u3__p4_0[] = {
  147941. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147942. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147943. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147944. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147945. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147946. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147947. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147948. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147949. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147950. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147951. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147952. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147953. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147954. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147955. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147956. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147957. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147958. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147959. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147960. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147961. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147962. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147963. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147964. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147965. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147966. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147967. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147968. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147969. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147970. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147971. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147972. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147973. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147974. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147975. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147976. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147977. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147978. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147979. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147980. 13,
  147981. };
  147982. static float _vq_quantthresh__44u3__p4_0[] = {
  147983. -1.5, -0.5, 0.5, 1.5,
  147984. };
  147985. static long _vq_quantmap__44u3__p4_0[] = {
  147986. 3, 1, 0, 2, 4,
  147987. };
  147988. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147989. _vq_quantthresh__44u3__p4_0,
  147990. _vq_quantmap__44u3__p4_0,
  147991. 5,
  147992. 5
  147993. };
  147994. static static_codebook _44u3__p4_0 = {
  147995. 4, 625,
  147996. _vq_lengthlist__44u3__p4_0,
  147997. 1, -533725184, 1611661312, 3, 0,
  147998. _vq_quantlist__44u3__p4_0,
  147999. NULL,
  148000. &_vq_auxt__44u3__p4_0,
  148001. NULL,
  148002. 0
  148003. };
  148004. static long _vq_quantlist__44u3__p5_0[] = {
  148005. 4,
  148006. 3,
  148007. 5,
  148008. 2,
  148009. 6,
  148010. 1,
  148011. 7,
  148012. 0,
  148013. 8,
  148014. };
  148015. static long _vq_lengthlist__44u3__p5_0[] = {
  148016. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148017. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148018. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148019. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148020. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148021. 12,
  148022. };
  148023. static float _vq_quantthresh__44u3__p5_0[] = {
  148024. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148025. };
  148026. static long _vq_quantmap__44u3__p5_0[] = {
  148027. 7, 5, 3, 1, 0, 2, 4, 6,
  148028. 8,
  148029. };
  148030. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148031. _vq_quantthresh__44u3__p5_0,
  148032. _vq_quantmap__44u3__p5_0,
  148033. 9,
  148034. 9
  148035. };
  148036. static static_codebook _44u3__p5_0 = {
  148037. 2, 81,
  148038. _vq_lengthlist__44u3__p5_0,
  148039. 1, -531628032, 1611661312, 4, 0,
  148040. _vq_quantlist__44u3__p5_0,
  148041. NULL,
  148042. &_vq_auxt__44u3__p5_0,
  148043. NULL,
  148044. 0
  148045. };
  148046. static long _vq_quantlist__44u3__p6_0[] = {
  148047. 6,
  148048. 5,
  148049. 7,
  148050. 4,
  148051. 8,
  148052. 3,
  148053. 9,
  148054. 2,
  148055. 10,
  148056. 1,
  148057. 11,
  148058. 0,
  148059. 12,
  148060. };
  148061. static long _vq_lengthlist__44u3__p6_0[] = {
  148062. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148063. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148064. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148065. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148066. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148067. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148068. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148069. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148070. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148071. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148072. 15,16,16,16,17,18,16,20,18,
  148073. };
  148074. static float _vq_quantthresh__44u3__p6_0[] = {
  148075. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148076. 12.5, 17.5, 22.5, 27.5,
  148077. };
  148078. static long _vq_quantmap__44u3__p6_0[] = {
  148079. 11, 9, 7, 5, 3, 1, 0, 2,
  148080. 4, 6, 8, 10, 12,
  148081. };
  148082. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148083. _vq_quantthresh__44u3__p6_0,
  148084. _vq_quantmap__44u3__p6_0,
  148085. 13,
  148086. 13
  148087. };
  148088. static static_codebook _44u3__p6_0 = {
  148089. 2, 169,
  148090. _vq_lengthlist__44u3__p6_0,
  148091. 1, -526516224, 1616117760, 4, 0,
  148092. _vq_quantlist__44u3__p6_0,
  148093. NULL,
  148094. &_vq_auxt__44u3__p6_0,
  148095. NULL,
  148096. 0
  148097. };
  148098. static long _vq_quantlist__44u3__p6_1[] = {
  148099. 2,
  148100. 1,
  148101. 3,
  148102. 0,
  148103. 4,
  148104. };
  148105. static long _vq_lengthlist__44u3__p6_1[] = {
  148106. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148107. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148108. };
  148109. static float _vq_quantthresh__44u3__p6_1[] = {
  148110. -1.5, -0.5, 0.5, 1.5,
  148111. };
  148112. static long _vq_quantmap__44u3__p6_1[] = {
  148113. 3, 1, 0, 2, 4,
  148114. };
  148115. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148116. _vq_quantthresh__44u3__p6_1,
  148117. _vq_quantmap__44u3__p6_1,
  148118. 5,
  148119. 5
  148120. };
  148121. static static_codebook _44u3__p6_1 = {
  148122. 2, 25,
  148123. _vq_lengthlist__44u3__p6_1,
  148124. 1, -533725184, 1611661312, 3, 0,
  148125. _vq_quantlist__44u3__p6_1,
  148126. NULL,
  148127. &_vq_auxt__44u3__p6_1,
  148128. NULL,
  148129. 0
  148130. };
  148131. static long _vq_quantlist__44u3__p7_0[] = {
  148132. 4,
  148133. 3,
  148134. 5,
  148135. 2,
  148136. 6,
  148137. 1,
  148138. 7,
  148139. 0,
  148140. 8,
  148141. };
  148142. static long _vq_lengthlist__44u3__p7_0[] = {
  148143. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148144. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148145. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148146. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148147. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148148. 9,
  148149. };
  148150. static float _vq_quantthresh__44u3__p7_0[] = {
  148151. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148152. };
  148153. static long _vq_quantmap__44u3__p7_0[] = {
  148154. 7, 5, 3, 1, 0, 2, 4, 6,
  148155. 8,
  148156. };
  148157. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148158. _vq_quantthresh__44u3__p7_0,
  148159. _vq_quantmap__44u3__p7_0,
  148160. 9,
  148161. 9
  148162. };
  148163. static static_codebook _44u3__p7_0 = {
  148164. 2, 81,
  148165. _vq_lengthlist__44u3__p7_0,
  148166. 1, -515907584, 1627381760, 4, 0,
  148167. _vq_quantlist__44u3__p7_0,
  148168. NULL,
  148169. &_vq_auxt__44u3__p7_0,
  148170. NULL,
  148171. 0
  148172. };
  148173. static long _vq_quantlist__44u3__p7_1[] = {
  148174. 7,
  148175. 6,
  148176. 8,
  148177. 5,
  148178. 9,
  148179. 4,
  148180. 10,
  148181. 3,
  148182. 11,
  148183. 2,
  148184. 12,
  148185. 1,
  148186. 13,
  148187. 0,
  148188. 14,
  148189. };
  148190. static long _vq_lengthlist__44u3__p7_1[] = {
  148191. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148192. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148193. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148194. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148195. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148196. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148197. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148198. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148199. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148200. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148201. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148202. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148203. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148204. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148205. 17,
  148206. };
  148207. static float _vq_quantthresh__44u3__p7_1[] = {
  148208. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148209. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148210. };
  148211. static long _vq_quantmap__44u3__p7_1[] = {
  148212. 13, 11, 9, 7, 5, 3, 1, 0,
  148213. 2, 4, 6, 8, 10, 12, 14,
  148214. };
  148215. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148216. _vq_quantthresh__44u3__p7_1,
  148217. _vq_quantmap__44u3__p7_1,
  148218. 15,
  148219. 15
  148220. };
  148221. static static_codebook _44u3__p7_1 = {
  148222. 2, 225,
  148223. _vq_lengthlist__44u3__p7_1,
  148224. 1, -522338304, 1620115456, 4, 0,
  148225. _vq_quantlist__44u3__p7_1,
  148226. NULL,
  148227. &_vq_auxt__44u3__p7_1,
  148228. NULL,
  148229. 0
  148230. };
  148231. static long _vq_quantlist__44u3__p7_2[] = {
  148232. 8,
  148233. 7,
  148234. 9,
  148235. 6,
  148236. 10,
  148237. 5,
  148238. 11,
  148239. 4,
  148240. 12,
  148241. 3,
  148242. 13,
  148243. 2,
  148244. 14,
  148245. 1,
  148246. 15,
  148247. 0,
  148248. 16,
  148249. };
  148250. static long _vq_lengthlist__44u3__p7_2[] = {
  148251. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148252. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148253. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148254. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148255. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148256. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148257. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148258. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148259. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148260. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148261. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148262. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148263. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148264. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148265. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148266. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148268. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148269. 11,
  148270. };
  148271. static float _vq_quantthresh__44u3__p7_2[] = {
  148272. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148273. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148274. };
  148275. static long _vq_quantmap__44u3__p7_2[] = {
  148276. 15, 13, 11, 9, 7, 5, 3, 1,
  148277. 0, 2, 4, 6, 8, 10, 12, 14,
  148278. 16,
  148279. };
  148280. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148281. _vq_quantthresh__44u3__p7_2,
  148282. _vq_quantmap__44u3__p7_2,
  148283. 17,
  148284. 17
  148285. };
  148286. static static_codebook _44u3__p7_2 = {
  148287. 2, 289,
  148288. _vq_lengthlist__44u3__p7_2,
  148289. 1, -529530880, 1611661312, 5, 0,
  148290. _vq_quantlist__44u3__p7_2,
  148291. NULL,
  148292. &_vq_auxt__44u3__p7_2,
  148293. NULL,
  148294. 0
  148295. };
  148296. static long _huff_lengthlist__44u3__short[] = {
  148297. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148298. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148299. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148300. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148301. };
  148302. static static_codebook _huff_book__44u3__short = {
  148303. 2, 64,
  148304. _huff_lengthlist__44u3__short,
  148305. 0, 0, 0, 0, 0,
  148306. NULL,
  148307. NULL,
  148308. NULL,
  148309. NULL,
  148310. 0
  148311. };
  148312. static long _huff_lengthlist__44u4__long[] = {
  148313. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148314. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148315. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148316. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148317. };
  148318. static static_codebook _huff_book__44u4__long = {
  148319. 2, 64,
  148320. _huff_lengthlist__44u4__long,
  148321. 0, 0, 0, 0, 0,
  148322. NULL,
  148323. NULL,
  148324. NULL,
  148325. NULL,
  148326. 0
  148327. };
  148328. static long _vq_quantlist__44u4__p1_0[] = {
  148329. 1,
  148330. 0,
  148331. 2,
  148332. };
  148333. static long _vq_lengthlist__44u4__p1_0[] = {
  148334. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148335. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148336. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148337. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148338. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148339. 13,
  148340. };
  148341. static float _vq_quantthresh__44u4__p1_0[] = {
  148342. -0.5, 0.5,
  148343. };
  148344. static long _vq_quantmap__44u4__p1_0[] = {
  148345. 1, 0, 2,
  148346. };
  148347. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148348. _vq_quantthresh__44u4__p1_0,
  148349. _vq_quantmap__44u4__p1_0,
  148350. 3,
  148351. 3
  148352. };
  148353. static static_codebook _44u4__p1_0 = {
  148354. 4, 81,
  148355. _vq_lengthlist__44u4__p1_0,
  148356. 1, -535822336, 1611661312, 2, 0,
  148357. _vq_quantlist__44u4__p1_0,
  148358. NULL,
  148359. &_vq_auxt__44u4__p1_0,
  148360. NULL,
  148361. 0
  148362. };
  148363. static long _vq_quantlist__44u4__p2_0[] = {
  148364. 1,
  148365. 0,
  148366. 2,
  148367. };
  148368. static long _vq_lengthlist__44u4__p2_0[] = {
  148369. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148370. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148371. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148372. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148373. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148374. 9,
  148375. };
  148376. static float _vq_quantthresh__44u4__p2_0[] = {
  148377. -0.5, 0.5,
  148378. };
  148379. static long _vq_quantmap__44u4__p2_0[] = {
  148380. 1, 0, 2,
  148381. };
  148382. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148383. _vq_quantthresh__44u4__p2_0,
  148384. _vq_quantmap__44u4__p2_0,
  148385. 3,
  148386. 3
  148387. };
  148388. static static_codebook _44u4__p2_0 = {
  148389. 4, 81,
  148390. _vq_lengthlist__44u4__p2_0,
  148391. 1, -535822336, 1611661312, 2, 0,
  148392. _vq_quantlist__44u4__p2_0,
  148393. NULL,
  148394. &_vq_auxt__44u4__p2_0,
  148395. NULL,
  148396. 0
  148397. };
  148398. static long _vq_quantlist__44u4__p3_0[] = {
  148399. 2,
  148400. 1,
  148401. 3,
  148402. 0,
  148403. 4,
  148404. };
  148405. static long _vq_lengthlist__44u4__p3_0[] = {
  148406. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148407. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148408. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148409. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148410. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148411. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148412. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148413. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148414. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148415. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148416. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148417. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148418. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148419. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148420. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148421. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148422. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148423. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148424. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148425. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148426. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148427. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148428. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148429. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148430. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148431. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148432. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148433. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148434. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148435. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148436. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148437. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148438. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148439. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148440. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148441. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148442. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148443. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148444. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148445. 0,
  148446. };
  148447. static float _vq_quantthresh__44u4__p3_0[] = {
  148448. -1.5, -0.5, 0.5, 1.5,
  148449. };
  148450. static long _vq_quantmap__44u4__p3_0[] = {
  148451. 3, 1, 0, 2, 4,
  148452. };
  148453. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148454. _vq_quantthresh__44u4__p3_0,
  148455. _vq_quantmap__44u4__p3_0,
  148456. 5,
  148457. 5
  148458. };
  148459. static static_codebook _44u4__p3_0 = {
  148460. 4, 625,
  148461. _vq_lengthlist__44u4__p3_0,
  148462. 1, -533725184, 1611661312, 3, 0,
  148463. _vq_quantlist__44u4__p3_0,
  148464. NULL,
  148465. &_vq_auxt__44u4__p3_0,
  148466. NULL,
  148467. 0
  148468. };
  148469. static long _vq_quantlist__44u4__p4_0[] = {
  148470. 2,
  148471. 1,
  148472. 3,
  148473. 0,
  148474. 4,
  148475. };
  148476. static long _vq_lengthlist__44u4__p4_0[] = {
  148477. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148478. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148479. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148480. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148481. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148482. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148483. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148484. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148485. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148486. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148487. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148488. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148489. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148490. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148491. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148492. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148493. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148494. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148495. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148496. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148497. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148498. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148499. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148500. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148501. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148502. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148503. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148504. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148505. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148506. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148507. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148508. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148509. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148510. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148511. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148512. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148513. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148514. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148515. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148516. 13,
  148517. };
  148518. static float _vq_quantthresh__44u4__p4_0[] = {
  148519. -1.5, -0.5, 0.5, 1.5,
  148520. };
  148521. static long _vq_quantmap__44u4__p4_0[] = {
  148522. 3, 1, 0, 2, 4,
  148523. };
  148524. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148525. _vq_quantthresh__44u4__p4_0,
  148526. _vq_quantmap__44u4__p4_0,
  148527. 5,
  148528. 5
  148529. };
  148530. static static_codebook _44u4__p4_0 = {
  148531. 4, 625,
  148532. _vq_lengthlist__44u4__p4_0,
  148533. 1, -533725184, 1611661312, 3, 0,
  148534. _vq_quantlist__44u4__p4_0,
  148535. NULL,
  148536. &_vq_auxt__44u4__p4_0,
  148537. NULL,
  148538. 0
  148539. };
  148540. static long _vq_quantlist__44u4__p5_0[] = {
  148541. 4,
  148542. 3,
  148543. 5,
  148544. 2,
  148545. 6,
  148546. 1,
  148547. 7,
  148548. 0,
  148549. 8,
  148550. };
  148551. static long _vq_lengthlist__44u4__p5_0[] = {
  148552. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148553. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148554. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148555. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148556. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148557. 12,
  148558. };
  148559. static float _vq_quantthresh__44u4__p5_0[] = {
  148560. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148561. };
  148562. static long _vq_quantmap__44u4__p5_0[] = {
  148563. 7, 5, 3, 1, 0, 2, 4, 6,
  148564. 8,
  148565. };
  148566. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148567. _vq_quantthresh__44u4__p5_0,
  148568. _vq_quantmap__44u4__p5_0,
  148569. 9,
  148570. 9
  148571. };
  148572. static static_codebook _44u4__p5_0 = {
  148573. 2, 81,
  148574. _vq_lengthlist__44u4__p5_0,
  148575. 1, -531628032, 1611661312, 4, 0,
  148576. _vq_quantlist__44u4__p5_0,
  148577. NULL,
  148578. &_vq_auxt__44u4__p5_0,
  148579. NULL,
  148580. 0
  148581. };
  148582. static long _vq_quantlist__44u4__p6_0[] = {
  148583. 6,
  148584. 5,
  148585. 7,
  148586. 4,
  148587. 8,
  148588. 3,
  148589. 9,
  148590. 2,
  148591. 10,
  148592. 1,
  148593. 11,
  148594. 0,
  148595. 12,
  148596. };
  148597. static long _vq_lengthlist__44u4__p6_0[] = {
  148598. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148599. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148600. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148601. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148602. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148603. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148604. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148605. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148606. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148607. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148608. 16,16,16,17,17,18,17,20,21,
  148609. };
  148610. static float _vq_quantthresh__44u4__p6_0[] = {
  148611. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148612. 12.5, 17.5, 22.5, 27.5,
  148613. };
  148614. static long _vq_quantmap__44u4__p6_0[] = {
  148615. 11, 9, 7, 5, 3, 1, 0, 2,
  148616. 4, 6, 8, 10, 12,
  148617. };
  148618. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148619. _vq_quantthresh__44u4__p6_0,
  148620. _vq_quantmap__44u4__p6_0,
  148621. 13,
  148622. 13
  148623. };
  148624. static static_codebook _44u4__p6_0 = {
  148625. 2, 169,
  148626. _vq_lengthlist__44u4__p6_0,
  148627. 1, -526516224, 1616117760, 4, 0,
  148628. _vq_quantlist__44u4__p6_0,
  148629. NULL,
  148630. &_vq_auxt__44u4__p6_0,
  148631. NULL,
  148632. 0
  148633. };
  148634. static long _vq_quantlist__44u4__p6_1[] = {
  148635. 2,
  148636. 1,
  148637. 3,
  148638. 0,
  148639. 4,
  148640. };
  148641. static long _vq_lengthlist__44u4__p6_1[] = {
  148642. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148643. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148644. };
  148645. static float _vq_quantthresh__44u4__p6_1[] = {
  148646. -1.5, -0.5, 0.5, 1.5,
  148647. };
  148648. static long _vq_quantmap__44u4__p6_1[] = {
  148649. 3, 1, 0, 2, 4,
  148650. };
  148651. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148652. _vq_quantthresh__44u4__p6_1,
  148653. _vq_quantmap__44u4__p6_1,
  148654. 5,
  148655. 5
  148656. };
  148657. static static_codebook _44u4__p6_1 = {
  148658. 2, 25,
  148659. _vq_lengthlist__44u4__p6_1,
  148660. 1, -533725184, 1611661312, 3, 0,
  148661. _vq_quantlist__44u4__p6_1,
  148662. NULL,
  148663. &_vq_auxt__44u4__p6_1,
  148664. NULL,
  148665. 0
  148666. };
  148667. static long _vq_quantlist__44u4__p7_0[] = {
  148668. 6,
  148669. 5,
  148670. 7,
  148671. 4,
  148672. 8,
  148673. 3,
  148674. 9,
  148675. 2,
  148676. 10,
  148677. 1,
  148678. 11,
  148679. 0,
  148680. 12,
  148681. };
  148682. static long _vq_lengthlist__44u4__p7_0[] = {
  148683. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148684. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148685. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148686. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148687. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148688. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148693. 11,11,11,11,11,11,11,11,11,
  148694. };
  148695. static float _vq_quantthresh__44u4__p7_0[] = {
  148696. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148697. 637.5, 892.5, 1147.5, 1402.5,
  148698. };
  148699. static long _vq_quantmap__44u4__p7_0[] = {
  148700. 11, 9, 7, 5, 3, 1, 0, 2,
  148701. 4, 6, 8, 10, 12,
  148702. };
  148703. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148704. _vq_quantthresh__44u4__p7_0,
  148705. _vq_quantmap__44u4__p7_0,
  148706. 13,
  148707. 13
  148708. };
  148709. static static_codebook _44u4__p7_0 = {
  148710. 2, 169,
  148711. _vq_lengthlist__44u4__p7_0,
  148712. 1, -514332672, 1627381760, 4, 0,
  148713. _vq_quantlist__44u4__p7_0,
  148714. NULL,
  148715. &_vq_auxt__44u4__p7_0,
  148716. NULL,
  148717. 0
  148718. };
  148719. static long _vq_quantlist__44u4__p7_1[] = {
  148720. 7,
  148721. 6,
  148722. 8,
  148723. 5,
  148724. 9,
  148725. 4,
  148726. 10,
  148727. 3,
  148728. 11,
  148729. 2,
  148730. 12,
  148731. 1,
  148732. 13,
  148733. 0,
  148734. 14,
  148735. };
  148736. static long _vq_lengthlist__44u4__p7_1[] = {
  148737. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148738. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148739. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148740. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148741. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148742. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148743. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148744. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148745. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148746. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148747. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148748. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148749. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148750. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148751. 16,
  148752. };
  148753. static float _vq_quantthresh__44u4__p7_1[] = {
  148754. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148755. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148756. };
  148757. static long _vq_quantmap__44u4__p7_1[] = {
  148758. 13, 11, 9, 7, 5, 3, 1, 0,
  148759. 2, 4, 6, 8, 10, 12, 14,
  148760. };
  148761. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148762. _vq_quantthresh__44u4__p7_1,
  148763. _vq_quantmap__44u4__p7_1,
  148764. 15,
  148765. 15
  148766. };
  148767. static static_codebook _44u4__p7_1 = {
  148768. 2, 225,
  148769. _vq_lengthlist__44u4__p7_1,
  148770. 1, -522338304, 1620115456, 4, 0,
  148771. _vq_quantlist__44u4__p7_1,
  148772. NULL,
  148773. &_vq_auxt__44u4__p7_1,
  148774. NULL,
  148775. 0
  148776. };
  148777. static long _vq_quantlist__44u4__p7_2[] = {
  148778. 8,
  148779. 7,
  148780. 9,
  148781. 6,
  148782. 10,
  148783. 5,
  148784. 11,
  148785. 4,
  148786. 12,
  148787. 3,
  148788. 13,
  148789. 2,
  148790. 14,
  148791. 1,
  148792. 15,
  148793. 0,
  148794. 16,
  148795. };
  148796. static long _vq_lengthlist__44u4__p7_2[] = {
  148797. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148798. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148799. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148800. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148801. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148802. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148803. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148804. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148805. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148806. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148807. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148808. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148809. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148810. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148812. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148813. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148814. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148815. 10,
  148816. };
  148817. static float _vq_quantthresh__44u4__p7_2[] = {
  148818. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148819. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148820. };
  148821. static long _vq_quantmap__44u4__p7_2[] = {
  148822. 15, 13, 11, 9, 7, 5, 3, 1,
  148823. 0, 2, 4, 6, 8, 10, 12, 14,
  148824. 16,
  148825. };
  148826. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148827. _vq_quantthresh__44u4__p7_2,
  148828. _vq_quantmap__44u4__p7_2,
  148829. 17,
  148830. 17
  148831. };
  148832. static static_codebook _44u4__p7_2 = {
  148833. 2, 289,
  148834. _vq_lengthlist__44u4__p7_2,
  148835. 1, -529530880, 1611661312, 5, 0,
  148836. _vq_quantlist__44u4__p7_2,
  148837. NULL,
  148838. &_vq_auxt__44u4__p7_2,
  148839. NULL,
  148840. 0
  148841. };
  148842. static long _huff_lengthlist__44u4__short[] = {
  148843. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148844. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148845. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148846. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148847. };
  148848. static static_codebook _huff_book__44u4__short = {
  148849. 2, 64,
  148850. _huff_lengthlist__44u4__short,
  148851. 0, 0, 0, 0, 0,
  148852. NULL,
  148853. NULL,
  148854. NULL,
  148855. NULL,
  148856. 0
  148857. };
  148858. static long _huff_lengthlist__44u5__long[] = {
  148859. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148860. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148861. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148862. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148863. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148864. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148865. 14, 8, 7, 8,
  148866. };
  148867. static static_codebook _huff_book__44u5__long = {
  148868. 2, 100,
  148869. _huff_lengthlist__44u5__long,
  148870. 0, 0, 0, 0, 0,
  148871. NULL,
  148872. NULL,
  148873. NULL,
  148874. NULL,
  148875. 0
  148876. };
  148877. static long _vq_quantlist__44u5__p1_0[] = {
  148878. 1,
  148879. 0,
  148880. 2,
  148881. };
  148882. static long _vq_lengthlist__44u5__p1_0[] = {
  148883. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148884. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148885. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148886. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148887. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148888. 12,
  148889. };
  148890. static float _vq_quantthresh__44u5__p1_0[] = {
  148891. -0.5, 0.5,
  148892. };
  148893. static long _vq_quantmap__44u5__p1_0[] = {
  148894. 1, 0, 2,
  148895. };
  148896. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148897. _vq_quantthresh__44u5__p1_0,
  148898. _vq_quantmap__44u5__p1_0,
  148899. 3,
  148900. 3
  148901. };
  148902. static static_codebook _44u5__p1_0 = {
  148903. 4, 81,
  148904. _vq_lengthlist__44u5__p1_0,
  148905. 1, -535822336, 1611661312, 2, 0,
  148906. _vq_quantlist__44u5__p1_0,
  148907. NULL,
  148908. &_vq_auxt__44u5__p1_0,
  148909. NULL,
  148910. 0
  148911. };
  148912. static long _vq_quantlist__44u5__p2_0[] = {
  148913. 1,
  148914. 0,
  148915. 2,
  148916. };
  148917. static long _vq_lengthlist__44u5__p2_0[] = {
  148918. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148919. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148920. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148921. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148922. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148923. 9,
  148924. };
  148925. static float _vq_quantthresh__44u5__p2_0[] = {
  148926. -0.5, 0.5,
  148927. };
  148928. static long _vq_quantmap__44u5__p2_0[] = {
  148929. 1, 0, 2,
  148930. };
  148931. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148932. _vq_quantthresh__44u5__p2_0,
  148933. _vq_quantmap__44u5__p2_0,
  148934. 3,
  148935. 3
  148936. };
  148937. static static_codebook _44u5__p2_0 = {
  148938. 4, 81,
  148939. _vq_lengthlist__44u5__p2_0,
  148940. 1, -535822336, 1611661312, 2, 0,
  148941. _vq_quantlist__44u5__p2_0,
  148942. NULL,
  148943. &_vq_auxt__44u5__p2_0,
  148944. NULL,
  148945. 0
  148946. };
  148947. static long _vq_quantlist__44u5__p3_0[] = {
  148948. 2,
  148949. 1,
  148950. 3,
  148951. 0,
  148952. 4,
  148953. };
  148954. static long _vq_lengthlist__44u5__p3_0[] = {
  148955. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148956. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148957. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148958. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148959. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148960. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148961. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148962. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148963. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148964. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148965. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148966. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148967. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148968. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148969. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148970. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148971. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148972. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148973. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148974. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148975. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148976. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148977. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148978. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148979. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148980. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148981. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148982. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148983. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148984. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148985. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148986. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148987. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148988. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148989. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148990. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148991. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148992. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148993. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148994. 0,
  148995. };
  148996. static float _vq_quantthresh__44u5__p3_0[] = {
  148997. -1.5, -0.5, 0.5, 1.5,
  148998. };
  148999. static long _vq_quantmap__44u5__p3_0[] = {
  149000. 3, 1, 0, 2, 4,
  149001. };
  149002. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149003. _vq_quantthresh__44u5__p3_0,
  149004. _vq_quantmap__44u5__p3_0,
  149005. 5,
  149006. 5
  149007. };
  149008. static static_codebook _44u5__p3_0 = {
  149009. 4, 625,
  149010. _vq_lengthlist__44u5__p3_0,
  149011. 1, -533725184, 1611661312, 3, 0,
  149012. _vq_quantlist__44u5__p3_0,
  149013. NULL,
  149014. &_vq_auxt__44u5__p3_0,
  149015. NULL,
  149016. 0
  149017. };
  149018. static long _vq_quantlist__44u5__p4_0[] = {
  149019. 2,
  149020. 1,
  149021. 3,
  149022. 0,
  149023. 4,
  149024. };
  149025. static long _vq_lengthlist__44u5__p4_0[] = {
  149026. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149027. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149028. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149029. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149030. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149031. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149032. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149033. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149034. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149035. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149036. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149037. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149038. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149039. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149040. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149041. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149042. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149043. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149044. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149045. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149046. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149047. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149048. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149049. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149050. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149051. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149052. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149053. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149054. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149055. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149056. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149057. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149058. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149059. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149060. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149061. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149062. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149063. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149064. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149065. 12,
  149066. };
  149067. static float _vq_quantthresh__44u5__p4_0[] = {
  149068. -1.5, -0.5, 0.5, 1.5,
  149069. };
  149070. static long _vq_quantmap__44u5__p4_0[] = {
  149071. 3, 1, 0, 2, 4,
  149072. };
  149073. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149074. _vq_quantthresh__44u5__p4_0,
  149075. _vq_quantmap__44u5__p4_0,
  149076. 5,
  149077. 5
  149078. };
  149079. static static_codebook _44u5__p4_0 = {
  149080. 4, 625,
  149081. _vq_lengthlist__44u5__p4_0,
  149082. 1, -533725184, 1611661312, 3, 0,
  149083. _vq_quantlist__44u5__p4_0,
  149084. NULL,
  149085. &_vq_auxt__44u5__p4_0,
  149086. NULL,
  149087. 0
  149088. };
  149089. static long _vq_quantlist__44u5__p5_0[] = {
  149090. 4,
  149091. 3,
  149092. 5,
  149093. 2,
  149094. 6,
  149095. 1,
  149096. 7,
  149097. 0,
  149098. 8,
  149099. };
  149100. static long _vq_lengthlist__44u5__p5_0[] = {
  149101. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149102. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149103. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149104. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149105. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149106. 14,
  149107. };
  149108. static float _vq_quantthresh__44u5__p5_0[] = {
  149109. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149110. };
  149111. static long _vq_quantmap__44u5__p5_0[] = {
  149112. 7, 5, 3, 1, 0, 2, 4, 6,
  149113. 8,
  149114. };
  149115. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149116. _vq_quantthresh__44u5__p5_0,
  149117. _vq_quantmap__44u5__p5_0,
  149118. 9,
  149119. 9
  149120. };
  149121. static static_codebook _44u5__p5_0 = {
  149122. 2, 81,
  149123. _vq_lengthlist__44u5__p5_0,
  149124. 1, -531628032, 1611661312, 4, 0,
  149125. _vq_quantlist__44u5__p5_0,
  149126. NULL,
  149127. &_vq_auxt__44u5__p5_0,
  149128. NULL,
  149129. 0
  149130. };
  149131. static long _vq_quantlist__44u5__p6_0[] = {
  149132. 4,
  149133. 3,
  149134. 5,
  149135. 2,
  149136. 6,
  149137. 1,
  149138. 7,
  149139. 0,
  149140. 8,
  149141. };
  149142. static long _vq_lengthlist__44u5__p6_0[] = {
  149143. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149144. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149145. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149146. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149147. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149148. 11,
  149149. };
  149150. static float _vq_quantthresh__44u5__p6_0[] = {
  149151. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149152. };
  149153. static long _vq_quantmap__44u5__p6_0[] = {
  149154. 7, 5, 3, 1, 0, 2, 4, 6,
  149155. 8,
  149156. };
  149157. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149158. _vq_quantthresh__44u5__p6_0,
  149159. _vq_quantmap__44u5__p6_0,
  149160. 9,
  149161. 9
  149162. };
  149163. static static_codebook _44u5__p6_0 = {
  149164. 2, 81,
  149165. _vq_lengthlist__44u5__p6_0,
  149166. 1, -531628032, 1611661312, 4, 0,
  149167. _vq_quantlist__44u5__p6_0,
  149168. NULL,
  149169. &_vq_auxt__44u5__p6_0,
  149170. NULL,
  149171. 0
  149172. };
  149173. static long _vq_quantlist__44u5__p7_0[] = {
  149174. 1,
  149175. 0,
  149176. 2,
  149177. };
  149178. static long _vq_lengthlist__44u5__p7_0[] = {
  149179. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149180. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149181. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149182. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149183. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149184. 12,
  149185. };
  149186. static float _vq_quantthresh__44u5__p7_0[] = {
  149187. -5.5, 5.5,
  149188. };
  149189. static long _vq_quantmap__44u5__p7_0[] = {
  149190. 1, 0, 2,
  149191. };
  149192. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149193. _vq_quantthresh__44u5__p7_0,
  149194. _vq_quantmap__44u5__p7_0,
  149195. 3,
  149196. 3
  149197. };
  149198. static static_codebook _44u5__p7_0 = {
  149199. 4, 81,
  149200. _vq_lengthlist__44u5__p7_0,
  149201. 1, -529137664, 1618345984, 2, 0,
  149202. _vq_quantlist__44u5__p7_0,
  149203. NULL,
  149204. &_vq_auxt__44u5__p7_0,
  149205. NULL,
  149206. 0
  149207. };
  149208. static long _vq_quantlist__44u5__p7_1[] = {
  149209. 5,
  149210. 4,
  149211. 6,
  149212. 3,
  149213. 7,
  149214. 2,
  149215. 8,
  149216. 1,
  149217. 9,
  149218. 0,
  149219. 10,
  149220. };
  149221. static long _vq_lengthlist__44u5__p7_1[] = {
  149222. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149223. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149224. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149225. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149226. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149227. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149228. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149229. 9, 9, 9, 9, 9,10,10,10,10,
  149230. };
  149231. static float _vq_quantthresh__44u5__p7_1[] = {
  149232. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149233. 3.5, 4.5,
  149234. };
  149235. static long _vq_quantmap__44u5__p7_1[] = {
  149236. 9, 7, 5, 3, 1, 0, 2, 4,
  149237. 6, 8, 10,
  149238. };
  149239. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149240. _vq_quantthresh__44u5__p7_1,
  149241. _vq_quantmap__44u5__p7_1,
  149242. 11,
  149243. 11
  149244. };
  149245. static static_codebook _44u5__p7_1 = {
  149246. 2, 121,
  149247. _vq_lengthlist__44u5__p7_1,
  149248. 1, -531365888, 1611661312, 4, 0,
  149249. _vq_quantlist__44u5__p7_1,
  149250. NULL,
  149251. &_vq_auxt__44u5__p7_1,
  149252. NULL,
  149253. 0
  149254. };
  149255. static long _vq_quantlist__44u5__p8_0[] = {
  149256. 5,
  149257. 4,
  149258. 6,
  149259. 3,
  149260. 7,
  149261. 2,
  149262. 8,
  149263. 1,
  149264. 9,
  149265. 0,
  149266. 10,
  149267. };
  149268. static long _vq_lengthlist__44u5__p8_0[] = {
  149269. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149270. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149271. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149272. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149273. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149274. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149275. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149276. 12,13,13,14,14,14,14,15,15,
  149277. };
  149278. static float _vq_quantthresh__44u5__p8_0[] = {
  149279. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149280. 38.5, 49.5,
  149281. };
  149282. static long _vq_quantmap__44u5__p8_0[] = {
  149283. 9, 7, 5, 3, 1, 0, 2, 4,
  149284. 6, 8, 10,
  149285. };
  149286. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149287. _vq_quantthresh__44u5__p8_0,
  149288. _vq_quantmap__44u5__p8_0,
  149289. 11,
  149290. 11
  149291. };
  149292. static static_codebook _44u5__p8_0 = {
  149293. 2, 121,
  149294. _vq_lengthlist__44u5__p8_0,
  149295. 1, -524582912, 1618345984, 4, 0,
  149296. _vq_quantlist__44u5__p8_0,
  149297. NULL,
  149298. &_vq_auxt__44u5__p8_0,
  149299. NULL,
  149300. 0
  149301. };
  149302. static long _vq_quantlist__44u5__p8_1[] = {
  149303. 5,
  149304. 4,
  149305. 6,
  149306. 3,
  149307. 7,
  149308. 2,
  149309. 8,
  149310. 1,
  149311. 9,
  149312. 0,
  149313. 10,
  149314. };
  149315. static long _vq_lengthlist__44u5__p8_1[] = {
  149316. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149317. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149318. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149319. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149320. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149321. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149322. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149323. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149324. };
  149325. static float _vq_quantthresh__44u5__p8_1[] = {
  149326. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149327. 3.5, 4.5,
  149328. };
  149329. static long _vq_quantmap__44u5__p8_1[] = {
  149330. 9, 7, 5, 3, 1, 0, 2, 4,
  149331. 6, 8, 10,
  149332. };
  149333. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149334. _vq_quantthresh__44u5__p8_1,
  149335. _vq_quantmap__44u5__p8_1,
  149336. 11,
  149337. 11
  149338. };
  149339. static static_codebook _44u5__p8_1 = {
  149340. 2, 121,
  149341. _vq_lengthlist__44u5__p8_1,
  149342. 1, -531365888, 1611661312, 4, 0,
  149343. _vq_quantlist__44u5__p8_1,
  149344. NULL,
  149345. &_vq_auxt__44u5__p8_1,
  149346. NULL,
  149347. 0
  149348. };
  149349. static long _vq_quantlist__44u5__p9_0[] = {
  149350. 6,
  149351. 5,
  149352. 7,
  149353. 4,
  149354. 8,
  149355. 3,
  149356. 9,
  149357. 2,
  149358. 10,
  149359. 1,
  149360. 11,
  149361. 0,
  149362. 12,
  149363. };
  149364. static long _vq_lengthlist__44u5__p9_0[] = {
  149365. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149366. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149367. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149368. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149369. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149370. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149371. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149372. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149373. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149374. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149375. 12,12,12,12,12,12,12,12,12,
  149376. };
  149377. static float _vq_quantthresh__44u5__p9_0[] = {
  149378. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149379. 637.5, 892.5, 1147.5, 1402.5,
  149380. };
  149381. static long _vq_quantmap__44u5__p9_0[] = {
  149382. 11, 9, 7, 5, 3, 1, 0, 2,
  149383. 4, 6, 8, 10, 12,
  149384. };
  149385. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149386. _vq_quantthresh__44u5__p9_0,
  149387. _vq_quantmap__44u5__p9_0,
  149388. 13,
  149389. 13
  149390. };
  149391. static static_codebook _44u5__p9_0 = {
  149392. 2, 169,
  149393. _vq_lengthlist__44u5__p9_0,
  149394. 1, -514332672, 1627381760, 4, 0,
  149395. _vq_quantlist__44u5__p9_0,
  149396. NULL,
  149397. &_vq_auxt__44u5__p9_0,
  149398. NULL,
  149399. 0
  149400. };
  149401. static long _vq_quantlist__44u5__p9_1[] = {
  149402. 7,
  149403. 6,
  149404. 8,
  149405. 5,
  149406. 9,
  149407. 4,
  149408. 10,
  149409. 3,
  149410. 11,
  149411. 2,
  149412. 12,
  149413. 1,
  149414. 13,
  149415. 0,
  149416. 14,
  149417. };
  149418. static long _vq_lengthlist__44u5__p9_1[] = {
  149419. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149420. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149421. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149422. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149423. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149424. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149425. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149426. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149427. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149428. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149429. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149430. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149431. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149432. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149433. 14,
  149434. };
  149435. static float _vq_quantthresh__44u5__p9_1[] = {
  149436. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149437. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149438. };
  149439. static long _vq_quantmap__44u5__p9_1[] = {
  149440. 13, 11, 9, 7, 5, 3, 1, 0,
  149441. 2, 4, 6, 8, 10, 12, 14,
  149442. };
  149443. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149444. _vq_quantthresh__44u5__p9_1,
  149445. _vq_quantmap__44u5__p9_1,
  149446. 15,
  149447. 15
  149448. };
  149449. static static_codebook _44u5__p9_1 = {
  149450. 2, 225,
  149451. _vq_lengthlist__44u5__p9_1,
  149452. 1, -522338304, 1620115456, 4, 0,
  149453. _vq_quantlist__44u5__p9_1,
  149454. NULL,
  149455. &_vq_auxt__44u5__p9_1,
  149456. NULL,
  149457. 0
  149458. };
  149459. static long _vq_quantlist__44u5__p9_2[] = {
  149460. 8,
  149461. 7,
  149462. 9,
  149463. 6,
  149464. 10,
  149465. 5,
  149466. 11,
  149467. 4,
  149468. 12,
  149469. 3,
  149470. 13,
  149471. 2,
  149472. 14,
  149473. 1,
  149474. 15,
  149475. 0,
  149476. 16,
  149477. };
  149478. static long _vq_lengthlist__44u5__p9_2[] = {
  149479. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149480. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149481. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149482. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149483. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149484. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149485. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149486. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149487. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149488. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149489. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149490. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149491. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149492. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149493. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149494. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149495. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149496. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149497. 10,
  149498. };
  149499. static float _vq_quantthresh__44u5__p9_2[] = {
  149500. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149501. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149502. };
  149503. static long _vq_quantmap__44u5__p9_2[] = {
  149504. 15, 13, 11, 9, 7, 5, 3, 1,
  149505. 0, 2, 4, 6, 8, 10, 12, 14,
  149506. 16,
  149507. };
  149508. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149509. _vq_quantthresh__44u5__p9_2,
  149510. _vq_quantmap__44u5__p9_2,
  149511. 17,
  149512. 17
  149513. };
  149514. static static_codebook _44u5__p9_2 = {
  149515. 2, 289,
  149516. _vq_lengthlist__44u5__p9_2,
  149517. 1, -529530880, 1611661312, 5, 0,
  149518. _vq_quantlist__44u5__p9_2,
  149519. NULL,
  149520. &_vq_auxt__44u5__p9_2,
  149521. NULL,
  149522. 0
  149523. };
  149524. static long _huff_lengthlist__44u5__short[] = {
  149525. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149526. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149527. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149528. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149529. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149530. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149531. 6, 8,15,17,
  149532. };
  149533. static static_codebook _huff_book__44u5__short = {
  149534. 2, 100,
  149535. _huff_lengthlist__44u5__short,
  149536. 0, 0, 0, 0, 0,
  149537. NULL,
  149538. NULL,
  149539. NULL,
  149540. NULL,
  149541. 0
  149542. };
  149543. static long _huff_lengthlist__44u6__long[] = {
  149544. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149545. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149546. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149547. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149548. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149549. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149550. 13, 8, 7, 7,
  149551. };
  149552. static static_codebook _huff_book__44u6__long = {
  149553. 2, 100,
  149554. _huff_lengthlist__44u6__long,
  149555. 0, 0, 0, 0, 0,
  149556. NULL,
  149557. NULL,
  149558. NULL,
  149559. NULL,
  149560. 0
  149561. };
  149562. static long _vq_quantlist__44u6__p1_0[] = {
  149563. 1,
  149564. 0,
  149565. 2,
  149566. };
  149567. static long _vq_lengthlist__44u6__p1_0[] = {
  149568. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149569. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149570. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149571. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149572. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149573. 12,
  149574. };
  149575. static float _vq_quantthresh__44u6__p1_0[] = {
  149576. -0.5, 0.5,
  149577. };
  149578. static long _vq_quantmap__44u6__p1_0[] = {
  149579. 1, 0, 2,
  149580. };
  149581. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149582. _vq_quantthresh__44u6__p1_0,
  149583. _vq_quantmap__44u6__p1_0,
  149584. 3,
  149585. 3
  149586. };
  149587. static static_codebook _44u6__p1_0 = {
  149588. 4, 81,
  149589. _vq_lengthlist__44u6__p1_0,
  149590. 1, -535822336, 1611661312, 2, 0,
  149591. _vq_quantlist__44u6__p1_0,
  149592. NULL,
  149593. &_vq_auxt__44u6__p1_0,
  149594. NULL,
  149595. 0
  149596. };
  149597. static long _vq_quantlist__44u6__p2_0[] = {
  149598. 1,
  149599. 0,
  149600. 2,
  149601. };
  149602. static long _vq_lengthlist__44u6__p2_0[] = {
  149603. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149604. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149605. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149606. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149607. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149608. 9,
  149609. };
  149610. static float _vq_quantthresh__44u6__p2_0[] = {
  149611. -0.5, 0.5,
  149612. };
  149613. static long _vq_quantmap__44u6__p2_0[] = {
  149614. 1, 0, 2,
  149615. };
  149616. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149617. _vq_quantthresh__44u6__p2_0,
  149618. _vq_quantmap__44u6__p2_0,
  149619. 3,
  149620. 3
  149621. };
  149622. static static_codebook _44u6__p2_0 = {
  149623. 4, 81,
  149624. _vq_lengthlist__44u6__p2_0,
  149625. 1, -535822336, 1611661312, 2, 0,
  149626. _vq_quantlist__44u6__p2_0,
  149627. NULL,
  149628. &_vq_auxt__44u6__p2_0,
  149629. NULL,
  149630. 0
  149631. };
  149632. static long _vq_quantlist__44u6__p3_0[] = {
  149633. 2,
  149634. 1,
  149635. 3,
  149636. 0,
  149637. 4,
  149638. };
  149639. static long _vq_lengthlist__44u6__p3_0[] = {
  149640. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149641. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149642. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149643. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149644. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149645. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149646. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149647. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149648. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149649. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149650. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149651. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149652. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149653. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149654. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149655. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149656. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149657. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149658. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149659. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149660. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149661. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149662. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149663. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149664. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149665. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149666. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149667. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149668. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149669. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149670. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149671. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149672. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149673. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149674. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149675. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149676. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149677. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149678. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149679. 19,
  149680. };
  149681. static float _vq_quantthresh__44u6__p3_0[] = {
  149682. -1.5, -0.5, 0.5, 1.5,
  149683. };
  149684. static long _vq_quantmap__44u6__p3_0[] = {
  149685. 3, 1, 0, 2, 4,
  149686. };
  149687. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149688. _vq_quantthresh__44u6__p3_0,
  149689. _vq_quantmap__44u6__p3_0,
  149690. 5,
  149691. 5
  149692. };
  149693. static static_codebook _44u6__p3_0 = {
  149694. 4, 625,
  149695. _vq_lengthlist__44u6__p3_0,
  149696. 1, -533725184, 1611661312, 3, 0,
  149697. _vq_quantlist__44u6__p3_0,
  149698. NULL,
  149699. &_vq_auxt__44u6__p3_0,
  149700. NULL,
  149701. 0
  149702. };
  149703. static long _vq_quantlist__44u6__p4_0[] = {
  149704. 2,
  149705. 1,
  149706. 3,
  149707. 0,
  149708. 4,
  149709. };
  149710. static long _vq_lengthlist__44u6__p4_0[] = {
  149711. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149712. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149713. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149714. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149715. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149716. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149717. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149718. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149719. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149720. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149721. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149722. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149723. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149724. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149725. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149726. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149727. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149728. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149729. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149730. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149731. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149732. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149733. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149734. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149735. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149736. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149737. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149738. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149739. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149740. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149741. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149742. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149743. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149744. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149745. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149746. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149747. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149748. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149749. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149750. 13,
  149751. };
  149752. static float _vq_quantthresh__44u6__p4_0[] = {
  149753. -1.5, -0.5, 0.5, 1.5,
  149754. };
  149755. static long _vq_quantmap__44u6__p4_0[] = {
  149756. 3, 1, 0, 2, 4,
  149757. };
  149758. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149759. _vq_quantthresh__44u6__p4_0,
  149760. _vq_quantmap__44u6__p4_0,
  149761. 5,
  149762. 5
  149763. };
  149764. static static_codebook _44u6__p4_0 = {
  149765. 4, 625,
  149766. _vq_lengthlist__44u6__p4_0,
  149767. 1, -533725184, 1611661312, 3, 0,
  149768. _vq_quantlist__44u6__p4_0,
  149769. NULL,
  149770. &_vq_auxt__44u6__p4_0,
  149771. NULL,
  149772. 0
  149773. };
  149774. static long _vq_quantlist__44u6__p5_0[] = {
  149775. 4,
  149776. 3,
  149777. 5,
  149778. 2,
  149779. 6,
  149780. 1,
  149781. 7,
  149782. 0,
  149783. 8,
  149784. };
  149785. static long _vq_lengthlist__44u6__p5_0[] = {
  149786. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149787. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149788. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149789. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149790. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149791. 14,
  149792. };
  149793. static float _vq_quantthresh__44u6__p5_0[] = {
  149794. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149795. };
  149796. static long _vq_quantmap__44u6__p5_0[] = {
  149797. 7, 5, 3, 1, 0, 2, 4, 6,
  149798. 8,
  149799. };
  149800. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149801. _vq_quantthresh__44u6__p5_0,
  149802. _vq_quantmap__44u6__p5_0,
  149803. 9,
  149804. 9
  149805. };
  149806. static static_codebook _44u6__p5_0 = {
  149807. 2, 81,
  149808. _vq_lengthlist__44u6__p5_0,
  149809. 1, -531628032, 1611661312, 4, 0,
  149810. _vq_quantlist__44u6__p5_0,
  149811. NULL,
  149812. &_vq_auxt__44u6__p5_0,
  149813. NULL,
  149814. 0
  149815. };
  149816. static long _vq_quantlist__44u6__p6_0[] = {
  149817. 4,
  149818. 3,
  149819. 5,
  149820. 2,
  149821. 6,
  149822. 1,
  149823. 7,
  149824. 0,
  149825. 8,
  149826. };
  149827. static long _vq_lengthlist__44u6__p6_0[] = {
  149828. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149829. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149830. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149831. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149832. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149833. 12,
  149834. };
  149835. static float _vq_quantthresh__44u6__p6_0[] = {
  149836. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149837. };
  149838. static long _vq_quantmap__44u6__p6_0[] = {
  149839. 7, 5, 3, 1, 0, 2, 4, 6,
  149840. 8,
  149841. };
  149842. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149843. _vq_quantthresh__44u6__p6_0,
  149844. _vq_quantmap__44u6__p6_0,
  149845. 9,
  149846. 9
  149847. };
  149848. static static_codebook _44u6__p6_0 = {
  149849. 2, 81,
  149850. _vq_lengthlist__44u6__p6_0,
  149851. 1, -531628032, 1611661312, 4, 0,
  149852. _vq_quantlist__44u6__p6_0,
  149853. NULL,
  149854. &_vq_auxt__44u6__p6_0,
  149855. NULL,
  149856. 0
  149857. };
  149858. static long _vq_quantlist__44u6__p7_0[] = {
  149859. 1,
  149860. 0,
  149861. 2,
  149862. };
  149863. static long _vq_lengthlist__44u6__p7_0[] = {
  149864. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149865. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149866. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149867. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149868. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149869. 10,
  149870. };
  149871. static float _vq_quantthresh__44u6__p7_0[] = {
  149872. -5.5, 5.5,
  149873. };
  149874. static long _vq_quantmap__44u6__p7_0[] = {
  149875. 1, 0, 2,
  149876. };
  149877. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149878. _vq_quantthresh__44u6__p7_0,
  149879. _vq_quantmap__44u6__p7_0,
  149880. 3,
  149881. 3
  149882. };
  149883. static static_codebook _44u6__p7_0 = {
  149884. 4, 81,
  149885. _vq_lengthlist__44u6__p7_0,
  149886. 1, -529137664, 1618345984, 2, 0,
  149887. _vq_quantlist__44u6__p7_0,
  149888. NULL,
  149889. &_vq_auxt__44u6__p7_0,
  149890. NULL,
  149891. 0
  149892. };
  149893. static long _vq_quantlist__44u6__p7_1[] = {
  149894. 5,
  149895. 4,
  149896. 6,
  149897. 3,
  149898. 7,
  149899. 2,
  149900. 8,
  149901. 1,
  149902. 9,
  149903. 0,
  149904. 10,
  149905. };
  149906. static long _vq_lengthlist__44u6__p7_1[] = {
  149907. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149908. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149909. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149910. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149911. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149912. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149913. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149914. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149915. };
  149916. static float _vq_quantthresh__44u6__p7_1[] = {
  149917. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149918. 3.5, 4.5,
  149919. };
  149920. static long _vq_quantmap__44u6__p7_1[] = {
  149921. 9, 7, 5, 3, 1, 0, 2, 4,
  149922. 6, 8, 10,
  149923. };
  149924. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149925. _vq_quantthresh__44u6__p7_1,
  149926. _vq_quantmap__44u6__p7_1,
  149927. 11,
  149928. 11
  149929. };
  149930. static static_codebook _44u6__p7_1 = {
  149931. 2, 121,
  149932. _vq_lengthlist__44u6__p7_1,
  149933. 1, -531365888, 1611661312, 4, 0,
  149934. _vq_quantlist__44u6__p7_1,
  149935. NULL,
  149936. &_vq_auxt__44u6__p7_1,
  149937. NULL,
  149938. 0
  149939. };
  149940. static long _vq_quantlist__44u6__p8_0[] = {
  149941. 5,
  149942. 4,
  149943. 6,
  149944. 3,
  149945. 7,
  149946. 2,
  149947. 8,
  149948. 1,
  149949. 9,
  149950. 0,
  149951. 10,
  149952. };
  149953. static long _vq_lengthlist__44u6__p8_0[] = {
  149954. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149955. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149956. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149957. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149958. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149959. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149960. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149961. 12,13,13,14,14,14,15,15,15,
  149962. };
  149963. static float _vq_quantthresh__44u6__p8_0[] = {
  149964. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149965. 38.5, 49.5,
  149966. };
  149967. static long _vq_quantmap__44u6__p8_0[] = {
  149968. 9, 7, 5, 3, 1, 0, 2, 4,
  149969. 6, 8, 10,
  149970. };
  149971. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149972. _vq_quantthresh__44u6__p8_0,
  149973. _vq_quantmap__44u6__p8_0,
  149974. 11,
  149975. 11
  149976. };
  149977. static static_codebook _44u6__p8_0 = {
  149978. 2, 121,
  149979. _vq_lengthlist__44u6__p8_0,
  149980. 1, -524582912, 1618345984, 4, 0,
  149981. _vq_quantlist__44u6__p8_0,
  149982. NULL,
  149983. &_vq_auxt__44u6__p8_0,
  149984. NULL,
  149985. 0
  149986. };
  149987. static long _vq_quantlist__44u6__p8_1[] = {
  149988. 5,
  149989. 4,
  149990. 6,
  149991. 3,
  149992. 7,
  149993. 2,
  149994. 8,
  149995. 1,
  149996. 9,
  149997. 0,
  149998. 10,
  149999. };
  150000. static long _vq_lengthlist__44u6__p8_1[] = {
  150001. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150002. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150003. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150004. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150005. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150006. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150007. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150008. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150009. };
  150010. static float _vq_quantthresh__44u6__p8_1[] = {
  150011. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150012. 3.5, 4.5,
  150013. };
  150014. static long _vq_quantmap__44u6__p8_1[] = {
  150015. 9, 7, 5, 3, 1, 0, 2, 4,
  150016. 6, 8, 10,
  150017. };
  150018. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150019. _vq_quantthresh__44u6__p8_1,
  150020. _vq_quantmap__44u6__p8_1,
  150021. 11,
  150022. 11
  150023. };
  150024. static static_codebook _44u6__p8_1 = {
  150025. 2, 121,
  150026. _vq_lengthlist__44u6__p8_1,
  150027. 1, -531365888, 1611661312, 4, 0,
  150028. _vq_quantlist__44u6__p8_1,
  150029. NULL,
  150030. &_vq_auxt__44u6__p8_1,
  150031. NULL,
  150032. 0
  150033. };
  150034. static long _vq_quantlist__44u6__p9_0[] = {
  150035. 7,
  150036. 6,
  150037. 8,
  150038. 5,
  150039. 9,
  150040. 4,
  150041. 10,
  150042. 3,
  150043. 11,
  150044. 2,
  150045. 12,
  150046. 1,
  150047. 13,
  150048. 0,
  150049. 14,
  150050. };
  150051. static long _vq_lengthlist__44u6__p9_0[] = {
  150052. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150053. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150054. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150055. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150056. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150057. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150058. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150059. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150060. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150061. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150062. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150063. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150064. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150065. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150066. 14,
  150067. };
  150068. static float _vq_quantthresh__44u6__p9_0[] = {
  150069. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150070. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150071. };
  150072. static long _vq_quantmap__44u6__p9_0[] = {
  150073. 13, 11, 9, 7, 5, 3, 1, 0,
  150074. 2, 4, 6, 8, 10, 12, 14,
  150075. };
  150076. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150077. _vq_quantthresh__44u6__p9_0,
  150078. _vq_quantmap__44u6__p9_0,
  150079. 15,
  150080. 15
  150081. };
  150082. static static_codebook _44u6__p9_0 = {
  150083. 2, 225,
  150084. _vq_lengthlist__44u6__p9_0,
  150085. 1, -514071552, 1627381760, 4, 0,
  150086. _vq_quantlist__44u6__p9_0,
  150087. NULL,
  150088. &_vq_auxt__44u6__p9_0,
  150089. NULL,
  150090. 0
  150091. };
  150092. static long _vq_quantlist__44u6__p9_1[] = {
  150093. 7,
  150094. 6,
  150095. 8,
  150096. 5,
  150097. 9,
  150098. 4,
  150099. 10,
  150100. 3,
  150101. 11,
  150102. 2,
  150103. 12,
  150104. 1,
  150105. 13,
  150106. 0,
  150107. 14,
  150108. };
  150109. static long _vq_lengthlist__44u6__p9_1[] = {
  150110. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150111. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150112. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150113. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150114. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150115. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150116. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150117. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150118. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150119. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150120. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150121. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150122. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150123. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150124. 13,
  150125. };
  150126. static float _vq_quantthresh__44u6__p9_1[] = {
  150127. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150128. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150129. };
  150130. static long _vq_quantmap__44u6__p9_1[] = {
  150131. 13, 11, 9, 7, 5, 3, 1, 0,
  150132. 2, 4, 6, 8, 10, 12, 14,
  150133. };
  150134. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150135. _vq_quantthresh__44u6__p9_1,
  150136. _vq_quantmap__44u6__p9_1,
  150137. 15,
  150138. 15
  150139. };
  150140. static static_codebook _44u6__p9_1 = {
  150141. 2, 225,
  150142. _vq_lengthlist__44u6__p9_1,
  150143. 1, -522338304, 1620115456, 4, 0,
  150144. _vq_quantlist__44u6__p9_1,
  150145. NULL,
  150146. &_vq_auxt__44u6__p9_1,
  150147. NULL,
  150148. 0
  150149. };
  150150. static long _vq_quantlist__44u6__p9_2[] = {
  150151. 8,
  150152. 7,
  150153. 9,
  150154. 6,
  150155. 10,
  150156. 5,
  150157. 11,
  150158. 4,
  150159. 12,
  150160. 3,
  150161. 13,
  150162. 2,
  150163. 14,
  150164. 1,
  150165. 15,
  150166. 0,
  150167. 16,
  150168. };
  150169. static long _vq_lengthlist__44u6__p9_2[] = {
  150170. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150171. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150172. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150173. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150174. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150175. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150176. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150177. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150178. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150179. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150180. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150181. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150182. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150183. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150184. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150185. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150186. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150187. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150188. 10,
  150189. };
  150190. static float _vq_quantthresh__44u6__p9_2[] = {
  150191. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150192. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150193. };
  150194. static long _vq_quantmap__44u6__p9_2[] = {
  150195. 15, 13, 11, 9, 7, 5, 3, 1,
  150196. 0, 2, 4, 6, 8, 10, 12, 14,
  150197. 16,
  150198. };
  150199. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150200. _vq_quantthresh__44u6__p9_2,
  150201. _vq_quantmap__44u6__p9_2,
  150202. 17,
  150203. 17
  150204. };
  150205. static static_codebook _44u6__p9_2 = {
  150206. 2, 289,
  150207. _vq_lengthlist__44u6__p9_2,
  150208. 1, -529530880, 1611661312, 5, 0,
  150209. _vq_quantlist__44u6__p9_2,
  150210. NULL,
  150211. &_vq_auxt__44u6__p9_2,
  150212. NULL,
  150213. 0
  150214. };
  150215. static long _huff_lengthlist__44u6__short[] = {
  150216. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150217. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150218. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150219. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150220. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150221. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150222. 7, 6, 9,16,
  150223. };
  150224. static static_codebook _huff_book__44u6__short = {
  150225. 2, 100,
  150226. _huff_lengthlist__44u6__short,
  150227. 0, 0, 0, 0, 0,
  150228. NULL,
  150229. NULL,
  150230. NULL,
  150231. NULL,
  150232. 0
  150233. };
  150234. static long _huff_lengthlist__44u7__long[] = {
  150235. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150236. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150237. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150238. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150239. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150240. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150241. 12, 8, 6, 7,
  150242. };
  150243. static static_codebook _huff_book__44u7__long = {
  150244. 2, 100,
  150245. _huff_lengthlist__44u7__long,
  150246. 0, 0, 0, 0, 0,
  150247. NULL,
  150248. NULL,
  150249. NULL,
  150250. NULL,
  150251. 0
  150252. };
  150253. static long _vq_quantlist__44u7__p1_0[] = {
  150254. 1,
  150255. 0,
  150256. 2,
  150257. };
  150258. static long _vq_lengthlist__44u7__p1_0[] = {
  150259. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150260. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150261. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150262. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150263. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150264. 12,
  150265. };
  150266. static float _vq_quantthresh__44u7__p1_0[] = {
  150267. -0.5, 0.5,
  150268. };
  150269. static long _vq_quantmap__44u7__p1_0[] = {
  150270. 1, 0, 2,
  150271. };
  150272. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150273. _vq_quantthresh__44u7__p1_0,
  150274. _vq_quantmap__44u7__p1_0,
  150275. 3,
  150276. 3
  150277. };
  150278. static static_codebook _44u7__p1_0 = {
  150279. 4, 81,
  150280. _vq_lengthlist__44u7__p1_0,
  150281. 1, -535822336, 1611661312, 2, 0,
  150282. _vq_quantlist__44u7__p1_0,
  150283. NULL,
  150284. &_vq_auxt__44u7__p1_0,
  150285. NULL,
  150286. 0
  150287. };
  150288. static long _vq_quantlist__44u7__p2_0[] = {
  150289. 1,
  150290. 0,
  150291. 2,
  150292. };
  150293. static long _vq_lengthlist__44u7__p2_0[] = {
  150294. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150295. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150296. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150297. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150298. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150299. 9,
  150300. };
  150301. static float _vq_quantthresh__44u7__p2_0[] = {
  150302. -0.5, 0.5,
  150303. };
  150304. static long _vq_quantmap__44u7__p2_0[] = {
  150305. 1, 0, 2,
  150306. };
  150307. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150308. _vq_quantthresh__44u7__p2_0,
  150309. _vq_quantmap__44u7__p2_0,
  150310. 3,
  150311. 3
  150312. };
  150313. static static_codebook _44u7__p2_0 = {
  150314. 4, 81,
  150315. _vq_lengthlist__44u7__p2_0,
  150316. 1, -535822336, 1611661312, 2, 0,
  150317. _vq_quantlist__44u7__p2_0,
  150318. NULL,
  150319. &_vq_auxt__44u7__p2_0,
  150320. NULL,
  150321. 0
  150322. };
  150323. static long _vq_quantlist__44u7__p3_0[] = {
  150324. 2,
  150325. 1,
  150326. 3,
  150327. 0,
  150328. 4,
  150329. };
  150330. static long _vq_lengthlist__44u7__p3_0[] = {
  150331. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150332. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150333. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150334. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150335. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150336. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150337. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150338. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150339. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150340. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150341. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150342. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150343. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150344. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150345. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150346. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150347. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150348. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150349. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150350. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150351. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150352. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150353. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150354. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150355. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150356. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150357. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150358. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150359. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150360. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150361. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150362. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150363. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150364. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150365. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150366. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150367. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150368. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150369. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150370. 0,
  150371. };
  150372. static float _vq_quantthresh__44u7__p3_0[] = {
  150373. -1.5, -0.5, 0.5, 1.5,
  150374. };
  150375. static long _vq_quantmap__44u7__p3_0[] = {
  150376. 3, 1, 0, 2, 4,
  150377. };
  150378. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150379. _vq_quantthresh__44u7__p3_0,
  150380. _vq_quantmap__44u7__p3_0,
  150381. 5,
  150382. 5
  150383. };
  150384. static static_codebook _44u7__p3_0 = {
  150385. 4, 625,
  150386. _vq_lengthlist__44u7__p3_0,
  150387. 1, -533725184, 1611661312, 3, 0,
  150388. _vq_quantlist__44u7__p3_0,
  150389. NULL,
  150390. &_vq_auxt__44u7__p3_0,
  150391. NULL,
  150392. 0
  150393. };
  150394. static long _vq_quantlist__44u7__p4_0[] = {
  150395. 2,
  150396. 1,
  150397. 3,
  150398. 0,
  150399. 4,
  150400. };
  150401. static long _vq_lengthlist__44u7__p4_0[] = {
  150402. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150403. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150404. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150405. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150406. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150407. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150408. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150409. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150410. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150411. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150412. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150413. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150414. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150415. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150416. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150417. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150418. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150419. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150420. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150421. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150422. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150423. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150424. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150425. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150426. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150427. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150428. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150429. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150430. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150431. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150432. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150433. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150434. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150435. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150436. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150437. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150438. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150439. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150440. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150441. 14,
  150442. };
  150443. static float _vq_quantthresh__44u7__p4_0[] = {
  150444. -1.5, -0.5, 0.5, 1.5,
  150445. };
  150446. static long _vq_quantmap__44u7__p4_0[] = {
  150447. 3, 1, 0, 2, 4,
  150448. };
  150449. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150450. _vq_quantthresh__44u7__p4_0,
  150451. _vq_quantmap__44u7__p4_0,
  150452. 5,
  150453. 5
  150454. };
  150455. static static_codebook _44u7__p4_0 = {
  150456. 4, 625,
  150457. _vq_lengthlist__44u7__p4_0,
  150458. 1, -533725184, 1611661312, 3, 0,
  150459. _vq_quantlist__44u7__p4_0,
  150460. NULL,
  150461. &_vq_auxt__44u7__p4_0,
  150462. NULL,
  150463. 0
  150464. };
  150465. static long _vq_quantlist__44u7__p5_0[] = {
  150466. 4,
  150467. 3,
  150468. 5,
  150469. 2,
  150470. 6,
  150471. 1,
  150472. 7,
  150473. 0,
  150474. 8,
  150475. };
  150476. static long _vq_lengthlist__44u7__p5_0[] = {
  150477. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150478. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150479. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150480. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150481. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150482. 14,
  150483. };
  150484. static float _vq_quantthresh__44u7__p5_0[] = {
  150485. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150486. };
  150487. static long _vq_quantmap__44u7__p5_0[] = {
  150488. 7, 5, 3, 1, 0, 2, 4, 6,
  150489. 8,
  150490. };
  150491. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150492. _vq_quantthresh__44u7__p5_0,
  150493. _vq_quantmap__44u7__p5_0,
  150494. 9,
  150495. 9
  150496. };
  150497. static static_codebook _44u7__p5_0 = {
  150498. 2, 81,
  150499. _vq_lengthlist__44u7__p5_0,
  150500. 1, -531628032, 1611661312, 4, 0,
  150501. _vq_quantlist__44u7__p5_0,
  150502. NULL,
  150503. &_vq_auxt__44u7__p5_0,
  150504. NULL,
  150505. 0
  150506. };
  150507. static long _vq_quantlist__44u7__p6_0[] = {
  150508. 4,
  150509. 3,
  150510. 5,
  150511. 2,
  150512. 6,
  150513. 1,
  150514. 7,
  150515. 0,
  150516. 8,
  150517. };
  150518. static long _vq_lengthlist__44u7__p6_0[] = {
  150519. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150520. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150521. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150522. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150523. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150524. 12,
  150525. };
  150526. static float _vq_quantthresh__44u7__p6_0[] = {
  150527. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150528. };
  150529. static long _vq_quantmap__44u7__p6_0[] = {
  150530. 7, 5, 3, 1, 0, 2, 4, 6,
  150531. 8,
  150532. };
  150533. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150534. _vq_quantthresh__44u7__p6_0,
  150535. _vq_quantmap__44u7__p6_0,
  150536. 9,
  150537. 9
  150538. };
  150539. static static_codebook _44u7__p6_0 = {
  150540. 2, 81,
  150541. _vq_lengthlist__44u7__p6_0,
  150542. 1, -531628032, 1611661312, 4, 0,
  150543. _vq_quantlist__44u7__p6_0,
  150544. NULL,
  150545. &_vq_auxt__44u7__p6_0,
  150546. NULL,
  150547. 0
  150548. };
  150549. static long _vq_quantlist__44u7__p7_0[] = {
  150550. 1,
  150551. 0,
  150552. 2,
  150553. };
  150554. static long _vq_lengthlist__44u7__p7_0[] = {
  150555. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150556. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150557. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150558. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150559. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150560. 10,
  150561. };
  150562. static float _vq_quantthresh__44u7__p7_0[] = {
  150563. -5.5, 5.5,
  150564. };
  150565. static long _vq_quantmap__44u7__p7_0[] = {
  150566. 1, 0, 2,
  150567. };
  150568. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150569. _vq_quantthresh__44u7__p7_0,
  150570. _vq_quantmap__44u7__p7_0,
  150571. 3,
  150572. 3
  150573. };
  150574. static static_codebook _44u7__p7_0 = {
  150575. 4, 81,
  150576. _vq_lengthlist__44u7__p7_0,
  150577. 1, -529137664, 1618345984, 2, 0,
  150578. _vq_quantlist__44u7__p7_0,
  150579. NULL,
  150580. &_vq_auxt__44u7__p7_0,
  150581. NULL,
  150582. 0
  150583. };
  150584. static long _vq_quantlist__44u7__p7_1[] = {
  150585. 5,
  150586. 4,
  150587. 6,
  150588. 3,
  150589. 7,
  150590. 2,
  150591. 8,
  150592. 1,
  150593. 9,
  150594. 0,
  150595. 10,
  150596. };
  150597. static long _vq_lengthlist__44u7__p7_1[] = {
  150598. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150599. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150600. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150601. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150602. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150603. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150604. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150605. 8, 9, 9, 9, 9, 9,10,10,10,
  150606. };
  150607. static float _vq_quantthresh__44u7__p7_1[] = {
  150608. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150609. 3.5, 4.5,
  150610. };
  150611. static long _vq_quantmap__44u7__p7_1[] = {
  150612. 9, 7, 5, 3, 1, 0, 2, 4,
  150613. 6, 8, 10,
  150614. };
  150615. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150616. _vq_quantthresh__44u7__p7_1,
  150617. _vq_quantmap__44u7__p7_1,
  150618. 11,
  150619. 11
  150620. };
  150621. static static_codebook _44u7__p7_1 = {
  150622. 2, 121,
  150623. _vq_lengthlist__44u7__p7_1,
  150624. 1, -531365888, 1611661312, 4, 0,
  150625. _vq_quantlist__44u7__p7_1,
  150626. NULL,
  150627. &_vq_auxt__44u7__p7_1,
  150628. NULL,
  150629. 0
  150630. };
  150631. static long _vq_quantlist__44u7__p8_0[] = {
  150632. 5,
  150633. 4,
  150634. 6,
  150635. 3,
  150636. 7,
  150637. 2,
  150638. 8,
  150639. 1,
  150640. 9,
  150641. 0,
  150642. 10,
  150643. };
  150644. static long _vq_lengthlist__44u7__p8_0[] = {
  150645. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150646. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150647. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150648. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150649. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150650. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150651. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150652. 12,13,13,14,14,15,15,15,16,
  150653. };
  150654. static float _vq_quantthresh__44u7__p8_0[] = {
  150655. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150656. 38.5, 49.5,
  150657. };
  150658. static long _vq_quantmap__44u7__p8_0[] = {
  150659. 9, 7, 5, 3, 1, 0, 2, 4,
  150660. 6, 8, 10,
  150661. };
  150662. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150663. _vq_quantthresh__44u7__p8_0,
  150664. _vq_quantmap__44u7__p8_0,
  150665. 11,
  150666. 11
  150667. };
  150668. static static_codebook _44u7__p8_0 = {
  150669. 2, 121,
  150670. _vq_lengthlist__44u7__p8_0,
  150671. 1, -524582912, 1618345984, 4, 0,
  150672. _vq_quantlist__44u7__p8_0,
  150673. NULL,
  150674. &_vq_auxt__44u7__p8_0,
  150675. NULL,
  150676. 0
  150677. };
  150678. static long _vq_quantlist__44u7__p8_1[] = {
  150679. 5,
  150680. 4,
  150681. 6,
  150682. 3,
  150683. 7,
  150684. 2,
  150685. 8,
  150686. 1,
  150687. 9,
  150688. 0,
  150689. 10,
  150690. };
  150691. static long _vq_lengthlist__44u7__p8_1[] = {
  150692. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150693. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150694. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150695. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150696. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150697. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150698. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150699. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150700. };
  150701. static float _vq_quantthresh__44u7__p8_1[] = {
  150702. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150703. 3.5, 4.5,
  150704. };
  150705. static long _vq_quantmap__44u7__p8_1[] = {
  150706. 9, 7, 5, 3, 1, 0, 2, 4,
  150707. 6, 8, 10,
  150708. };
  150709. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150710. _vq_quantthresh__44u7__p8_1,
  150711. _vq_quantmap__44u7__p8_1,
  150712. 11,
  150713. 11
  150714. };
  150715. static static_codebook _44u7__p8_1 = {
  150716. 2, 121,
  150717. _vq_lengthlist__44u7__p8_1,
  150718. 1, -531365888, 1611661312, 4, 0,
  150719. _vq_quantlist__44u7__p8_1,
  150720. NULL,
  150721. &_vq_auxt__44u7__p8_1,
  150722. NULL,
  150723. 0
  150724. };
  150725. static long _vq_quantlist__44u7__p9_0[] = {
  150726. 5,
  150727. 4,
  150728. 6,
  150729. 3,
  150730. 7,
  150731. 2,
  150732. 8,
  150733. 1,
  150734. 9,
  150735. 0,
  150736. 10,
  150737. };
  150738. static long _vq_lengthlist__44u7__p9_0[] = {
  150739. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150740. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150741. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150742. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150743. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150744. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150745. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150746. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150747. };
  150748. static float _vq_quantthresh__44u7__p9_0[] = {
  150749. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150750. 2229.5, 2866.5,
  150751. };
  150752. static long _vq_quantmap__44u7__p9_0[] = {
  150753. 9, 7, 5, 3, 1, 0, 2, 4,
  150754. 6, 8, 10,
  150755. };
  150756. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150757. _vq_quantthresh__44u7__p9_0,
  150758. _vq_quantmap__44u7__p9_0,
  150759. 11,
  150760. 11
  150761. };
  150762. static static_codebook _44u7__p9_0 = {
  150763. 2, 121,
  150764. _vq_lengthlist__44u7__p9_0,
  150765. 1, -512171520, 1630791680, 4, 0,
  150766. _vq_quantlist__44u7__p9_0,
  150767. NULL,
  150768. &_vq_auxt__44u7__p9_0,
  150769. NULL,
  150770. 0
  150771. };
  150772. static long _vq_quantlist__44u7__p9_1[] = {
  150773. 6,
  150774. 5,
  150775. 7,
  150776. 4,
  150777. 8,
  150778. 3,
  150779. 9,
  150780. 2,
  150781. 10,
  150782. 1,
  150783. 11,
  150784. 0,
  150785. 12,
  150786. };
  150787. static long _vq_lengthlist__44u7__p9_1[] = {
  150788. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150789. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150790. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150791. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150792. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150793. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150794. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150795. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150796. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150797. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150798. 15,15,15,15,17,17,16,17,16,
  150799. };
  150800. static float _vq_quantthresh__44u7__p9_1[] = {
  150801. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150802. 122.5, 171.5, 220.5, 269.5,
  150803. };
  150804. static long _vq_quantmap__44u7__p9_1[] = {
  150805. 11, 9, 7, 5, 3, 1, 0, 2,
  150806. 4, 6, 8, 10, 12,
  150807. };
  150808. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150809. _vq_quantthresh__44u7__p9_1,
  150810. _vq_quantmap__44u7__p9_1,
  150811. 13,
  150812. 13
  150813. };
  150814. static static_codebook _44u7__p9_1 = {
  150815. 2, 169,
  150816. _vq_lengthlist__44u7__p9_1,
  150817. 1, -518889472, 1622704128, 4, 0,
  150818. _vq_quantlist__44u7__p9_1,
  150819. NULL,
  150820. &_vq_auxt__44u7__p9_1,
  150821. NULL,
  150822. 0
  150823. };
  150824. static long _vq_quantlist__44u7__p9_2[] = {
  150825. 24,
  150826. 23,
  150827. 25,
  150828. 22,
  150829. 26,
  150830. 21,
  150831. 27,
  150832. 20,
  150833. 28,
  150834. 19,
  150835. 29,
  150836. 18,
  150837. 30,
  150838. 17,
  150839. 31,
  150840. 16,
  150841. 32,
  150842. 15,
  150843. 33,
  150844. 14,
  150845. 34,
  150846. 13,
  150847. 35,
  150848. 12,
  150849. 36,
  150850. 11,
  150851. 37,
  150852. 10,
  150853. 38,
  150854. 9,
  150855. 39,
  150856. 8,
  150857. 40,
  150858. 7,
  150859. 41,
  150860. 6,
  150861. 42,
  150862. 5,
  150863. 43,
  150864. 4,
  150865. 44,
  150866. 3,
  150867. 45,
  150868. 2,
  150869. 46,
  150870. 1,
  150871. 47,
  150872. 0,
  150873. 48,
  150874. };
  150875. static long _vq_lengthlist__44u7__p9_2[] = {
  150876. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150877. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150878. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150879. 8,
  150880. };
  150881. static float _vq_quantthresh__44u7__p9_2[] = {
  150882. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150883. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150884. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150885. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150886. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150887. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150888. };
  150889. static long _vq_quantmap__44u7__p9_2[] = {
  150890. 47, 45, 43, 41, 39, 37, 35, 33,
  150891. 31, 29, 27, 25, 23, 21, 19, 17,
  150892. 15, 13, 11, 9, 7, 5, 3, 1,
  150893. 0, 2, 4, 6, 8, 10, 12, 14,
  150894. 16, 18, 20, 22, 24, 26, 28, 30,
  150895. 32, 34, 36, 38, 40, 42, 44, 46,
  150896. 48,
  150897. };
  150898. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150899. _vq_quantthresh__44u7__p9_2,
  150900. _vq_quantmap__44u7__p9_2,
  150901. 49,
  150902. 49
  150903. };
  150904. static static_codebook _44u7__p9_2 = {
  150905. 1, 49,
  150906. _vq_lengthlist__44u7__p9_2,
  150907. 1, -526909440, 1611661312, 6, 0,
  150908. _vq_quantlist__44u7__p9_2,
  150909. NULL,
  150910. &_vq_auxt__44u7__p9_2,
  150911. NULL,
  150912. 0
  150913. };
  150914. static long _huff_lengthlist__44u7__short[] = {
  150915. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150916. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150917. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150918. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150919. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150920. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150921. 6, 8, 5, 9,
  150922. };
  150923. static static_codebook _huff_book__44u7__short = {
  150924. 2, 100,
  150925. _huff_lengthlist__44u7__short,
  150926. 0, 0, 0, 0, 0,
  150927. NULL,
  150928. NULL,
  150929. NULL,
  150930. NULL,
  150931. 0
  150932. };
  150933. static long _huff_lengthlist__44u8__long[] = {
  150934. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150935. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150936. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150937. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150938. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150939. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150940. 10, 8, 8, 9,
  150941. };
  150942. static static_codebook _huff_book__44u8__long = {
  150943. 2, 100,
  150944. _huff_lengthlist__44u8__long,
  150945. 0, 0, 0, 0, 0,
  150946. NULL,
  150947. NULL,
  150948. NULL,
  150949. NULL,
  150950. 0
  150951. };
  150952. static long _huff_lengthlist__44u8__short[] = {
  150953. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150954. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150955. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150956. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150957. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150958. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150959. 10,10,15,17,
  150960. };
  150961. static static_codebook _huff_book__44u8__short = {
  150962. 2, 100,
  150963. _huff_lengthlist__44u8__short,
  150964. 0, 0, 0, 0, 0,
  150965. NULL,
  150966. NULL,
  150967. NULL,
  150968. NULL,
  150969. 0
  150970. };
  150971. static long _vq_quantlist__44u8_p1_0[] = {
  150972. 1,
  150973. 0,
  150974. 2,
  150975. };
  150976. static long _vq_lengthlist__44u8_p1_0[] = {
  150977. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150978. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150979. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150980. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150981. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150982. 10,
  150983. };
  150984. static float _vq_quantthresh__44u8_p1_0[] = {
  150985. -0.5, 0.5,
  150986. };
  150987. static long _vq_quantmap__44u8_p1_0[] = {
  150988. 1, 0, 2,
  150989. };
  150990. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150991. _vq_quantthresh__44u8_p1_0,
  150992. _vq_quantmap__44u8_p1_0,
  150993. 3,
  150994. 3
  150995. };
  150996. static static_codebook _44u8_p1_0 = {
  150997. 4, 81,
  150998. _vq_lengthlist__44u8_p1_0,
  150999. 1, -535822336, 1611661312, 2, 0,
  151000. _vq_quantlist__44u8_p1_0,
  151001. NULL,
  151002. &_vq_auxt__44u8_p1_0,
  151003. NULL,
  151004. 0
  151005. };
  151006. static long _vq_quantlist__44u8_p2_0[] = {
  151007. 2,
  151008. 1,
  151009. 3,
  151010. 0,
  151011. 4,
  151012. };
  151013. static long _vq_lengthlist__44u8_p2_0[] = {
  151014. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151015. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151016. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151017. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151018. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151019. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151020. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151021. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151022. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151023. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151024. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151025. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151026. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151027. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151028. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151029. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151030. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151031. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151032. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151033. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151034. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151035. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151036. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151037. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151038. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151039. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151040. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151041. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151042. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151043. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151044. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151045. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151046. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151047. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151048. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151049. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151050. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151051. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151052. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151053. 14,
  151054. };
  151055. static float _vq_quantthresh__44u8_p2_0[] = {
  151056. -1.5, -0.5, 0.5, 1.5,
  151057. };
  151058. static long _vq_quantmap__44u8_p2_0[] = {
  151059. 3, 1, 0, 2, 4,
  151060. };
  151061. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151062. _vq_quantthresh__44u8_p2_0,
  151063. _vq_quantmap__44u8_p2_0,
  151064. 5,
  151065. 5
  151066. };
  151067. static static_codebook _44u8_p2_0 = {
  151068. 4, 625,
  151069. _vq_lengthlist__44u8_p2_0,
  151070. 1, -533725184, 1611661312, 3, 0,
  151071. _vq_quantlist__44u8_p2_0,
  151072. NULL,
  151073. &_vq_auxt__44u8_p2_0,
  151074. NULL,
  151075. 0
  151076. };
  151077. static long _vq_quantlist__44u8_p3_0[] = {
  151078. 4,
  151079. 3,
  151080. 5,
  151081. 2,
  151082. 6,
  151083. 1,
  151084. 7,
  151085. 0,
  151086. 8,
  151087. };
  151088. static long _vq_lengthlist__44u8_p3_0[] = {
  151089. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151090. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151091. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151092. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151093. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151094. 12,
  151095. };
  151096. static float _vq_quantthresh__44u8_p3_0[] = {
  151097. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151098. };
  151099. static long _vq_quantmap__44u8_p3_0[] = {
  151100. 7, 5, 3, 1, 0, 2, 4, 6,
  151101. 8,
  151102. };
  151103. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151104. _vq_quantthresh__44u8_p3_0,
  151105. _vq_quantmap__44u8_p3_0,
  151106. 9,
  151107. 9
  151108. };
  151109. static static_codebook _44u8_p3_0 = {
  151110. 2, 81,
  151111. _vq_lengthlist__44u8_p3_0,
  151112. 1, -531628032, 1611661312, 4, 0,
  151113. _vq_quantlist__44u8_p3_0,
  151114. NULL,
  151115. &_vq_auxt__44u8_p3_0,
  151116. NULL,
  151117. 0
  151118. };
  151119. static long _vq_quantlist__44u8_p4_0[] = {
  151120. 8,
  151121. 7,
  151122. 9,
  151123. 6,
  151124. 10,
  151125. 5,
  151126. 11,
  151127. 4,
  151128. 12,
  151129. 3,
  151130. 13,
  151131. 2,
  151132. 14,
  151133. 1,
  151134. 15,
  151135. 0,
  151136. 16,
  151137. };
  151138. static long _vq_lengthlist__44u8_p4_0[] = {
  151139. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151140. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151141. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151142. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151143. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151144. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151145. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151146. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151147. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151148. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151149. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151150. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151151. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151152. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151153. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151154. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151155. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151156. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151157. 14,
  151158. };
  151159. static float _vq_quantthresh__44u8_p4_0[] = {
  151160. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151161. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151162. };
  151163. static long _vq_quantmap__44u8_p4_0[] = {
  151164. 15, 13, 11, 9, 7, 5, 3, 1,
  151165. 0, 2, 4, 6, 8, 10, 12, 14,
  151166. 16,
  151167. };
  151168. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151169. _vq_quantthresh__44u8_p4_0,
  151170. _vq_quantmap__44u8_p4_0,
  151171. 17,
  151172. 17
  151173. };
  151174. static static_codebook _44u8_p4_0 = {
  151175. 2, 289,
  151176. _vq_lengthlist__44u8_p4_0,
  151177. 1, -529530880, 1611661312, 5, 0,
  151178. _vq_quantlist__44u8_p4_0,
  151179. NULL,
  151180. &_vq_auxt__44u8_p4_0,
  151181. NULL,
  151182. 0
  151183. };
  151184. static long _vq_quantlist__44u8_p5_0[] = {
  151185. 1,
  151186. 0,
  151187. 2,
  151188. };
  151189. static long _vq_lengthlist__44u8_p5_0[] = {
  151190. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151191. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151192. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151193. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151194. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151195. 10,
  151196. };
  151197. static float _vq_quantthresh__44u8_p5_0[] = {
  151198. -5.5, 5.5,
  151199. };
  151200. static long _vq_quantmap__44u8_p5_0[] = {
  151201. 1, 0, 2,
  151202. };
  151203. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151204. _vq_quantthresh__44u8_p5_0,
  151205. _vq_quantmap__44u8_p5_0,
  151206. 3,
  151207. 3
  151208. };
  151209. static static_codebook _44u8_p5_0 = {
  151210. 4, 81,
  151211. _vq_lengthlist__44u8_p5_0,
  151212. 1, -529137664, 1618345984, 2, 0,
  151213. _vq_quantlist__44u8_p5_0,
  151214. NULL,
  151215. &_vq_auxt__44u8_p5_0,
  151216. NULL,
  151217. 0
  151218. };
  151219. static long _vq_quantlist__44u8_p5_1[] = {
  151220. 5,
  151221. 4,
  151222. 6,
  151223. 3,
  151224. 7,
  151225. 2,
  151226. 8,
  151227. 1,
  151228. 9,
  151229. 0,
  151230. 10,
  151231. };
  151232. static long _vq_lengthlist__44u8_p5_1[] = {
  151233. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151234. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151235. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151236. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151237. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151238. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151239. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151240. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151241. };
  151242. static float _vq_quantthresh__44u8_p5_1[] = {
  151243. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151244. 3.5, 4.5,
  151245. };
  151246. static long _vq_quantmap__44u8_p5_1[] = {
  151247. 9, 7, 5, 3, 1, 0, 2, 4,
  151248. 6, 8, 10,
  151249. };
  151250. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151251. _vq_quantthresh__44u8_p5_1,
  151252. _vq_quantmap__44u8_p5_1,
  151253. 11,
  151254. 11
  151255. };
  151256. static static_codebook _44u8_p5_1 = {
  151257. 2, 121,
  151258. _vq_lengthlist__44u8_p5_1,
  151259. 1, -531365888, 1611661312, 4, 0,
  151260. _vq_quantlist__44u8_p5_1,
  151261. NULL,
  151262. &_vq_auxt__44u8_p5_1,
  151263. NULL,
  151264. 0
  151265. };
  151266. static long _vq_quantlist__44u8_p6_0[] = {
  151267. 6,
  151268. 5,
  151269. 7,
  151270. 4,
  151271. 8,
  151272. 3,
  151273. 9,
  151274. 2,
  151275. 10,
  151276. 1,
  151277. 11,
  151278. 0,
  151279. 12,
  151280. };
  151281. static long _vq_lengthlist__44u8_p6_0[] = {
  151282. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151283. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151284. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151285. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151286. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151287. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151288. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151289. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151290. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151291. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151292. 11,11,11,11,11,12,11,12,12,
  151293. };
  151294. static float _vq_quantthresh__44u8_p6_0[] = {
  151295. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151296. 12.5, 17.5, 22.5, 27.5,
  151297. };
  151298. static long _vq_quantmap__44u8_p6_0[] = {
  151299. 11, 9, 7, 5, 3, 1, 0, 2,
  151300. 4, 6, 8, 10, 12,
  151301. };
  151302. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151303. _vq_quantthresh__44u8_p6_0,
  151304. _vq_quantmap__44u8_p6_0,
  151305. 13,
  151306. 13
  151307. };
  151308. static static_codebook _44u8_p6_0 = {
  151309. 2, 169,
  151310. _vq_lengthlist__44u8_p6_0,
  151311. 1, -526516224, 1616117760, 4, 0,
  151312. _vq_quantlist__44u8_p6_0,
  151313. NULL,
  151314. &_vq_auxt__44u8_p6_0,
  151315. NULL,
  151316. 0
  151317. };
  151318. static long _vq_quantlist__44u8_p6_1[] = {
  151319. 2,
  151320. 1,
  151321. 3,
  151322. 0,
  151323. 4,
  151324. };
  151325. static long _vq_lengthlist__44u8_p6_1[] = {
  151326. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151327. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151328. };
  151329. static float _vq_quantthresh__44u8_p6_1[] = {
  151330. -1.5, -0.5, 0.5, 1.5,
  151331. };
  151332. static long _vq_quantmap__44u8_p6_1[] = {
  151333. 3, 1, 0, 2, 4,
  151334. };
  151335. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151336. _vq_quantthresh__44u8_p6_1,
  151337. _vq_quantmap__44u8_p6_1,
  151338. 5,
  151339. 5
  151340. };
  151341. static static_codebook _44u8_p6_1 = {
  151342. 2, 25,
  151343. _vq_lengthlist__44u8_p6_1,
  151344. 1, -533725184, 1611661312, 3, 0,
  151345. _vq_quantlist__44u8_p6_1,
  151346. NULL,
  151347. &_vq_auxt__44u8_p6_1,
  151348. NULL,
  151349. 0
  151350. };
  151351. static long _vq_quantlist__44u8_p7_0[] = {
  151352. 6,
  151353. 5,
  151354. 7,
  151355. 4,
  151356. 8,
  151357. 3,
  151358. 9,
  151359. 2,
  151360. 10,
  151361. 1,
  151362. 11,
  151363. 0,
  151364. 12,
  151365. };
  151366. static long _vq_lengthlist__44u8_p7_0[] = {
  151367. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151368. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151369. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151370. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151371. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151372. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151373. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151374. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151375. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151376. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151377. 13,13,14,14,14,15,15,15,16,
  151378. };
  151379. static float _vq_quantthresh__44u8_p7_0[] = {
  151380. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151381. 27.5, 38.5, 49.5, 60.5,
  151382. };
  151383. static long _vq_quantmap__44u8_p7_0[] = {
  151384. 11, 9, 7, 5, 3, 1, 0, 2,
  151385. 4, 6, 8, 10, 12,
  151386. };
  151387. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151388. _vq_quantthresh__44u8_p7_0,
  151389. _vq_quantmap__44u8_p7_0,
  151390. 13,
  151391. 13
  151392. };
  151393. static static_codebook _44u8_p7_0 = {
  151394. 2, 169,
  151395. _vq_lengthlist__44u8_p7_0,
  151396. 1, -523206656, 1618345984, 4, 0,
  151397. _vq_quantlist__44u8_p7_0,
  151398. NULL,
  151399. &_vq_auxt__44u8_p7_0,
  151400. NULL,
  151401. 0
  151402. };
  151403. static long _vq_quantlist__44u8_p7_1[] = {
  151404. 5,
  151405. 4,
  151406. 6,
  151407. 3,
  151408. 7,
  151409. 2,
  151410. 8,
  151411. 1,
  151412. 9,
  151413. 0,
  151414. 10,
  151415. };
  151416. static long _vq_lengthlist__44u8_p7_1[] = {
  151417. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151418. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151419. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151420. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151421. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151422. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151423. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151424. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151425. };
  151426. static float _vq_quantthresh__44u8_p7_1[] = {
  151427. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151428. 3.5, 4.5,
  151429. };
  151430. static long _vq_quantmap__44u8_p7_1[] = {
  151431. 9, 7, 5, 3, 1, 0, 2, 4,
  151432. 6, 8, 10,
  151433. };
  151434. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151435. _vq_quantthresh__44u8_p7_1,
  151436. _vq_quantmap__44u8_p7_1,
  151437. 11,
  151438. 11
  151439. };
  151440. static static_codebook _44u8_p7_1 = {
  151441. 2, 121,
  151442. _vq_lengthlist__44u8_p7_1,
  151443. 1, -531365888, 1611661312, 4, 0,
  151444. _vq_quantlist__44u8_p7_1,
  151445. NULL,
  151446. &_vq_auxt__44u8_p7_1,
  151447. NULL,
  151448. 0
  151449. };
  151450. static long _vq_quantlist__44u8_p8_0[] = {
  151451. 7,
  151452. 6,
  151453. 8,
  151454. 5,
  151455. 9,
  151456. 4,
  151457. 10,
  151458. 3,
  151459. 11,
  151460. 2,
  151461. 12,
  151462. 1,
  151463. 13,
  151464. 0,
  151465. 14,
  151466. };
  151467. static long _vq_lengthlist__44u8_p8_0[] = {
  151468. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151469. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151470. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151471. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151472. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151473. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151474. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151475. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151476. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151477. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151478. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151479. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151480. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151481. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151482. 17,
  151483. };
  151484. static float _vq_quantthresh__44u8_p8_0[] = {
  151485. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151486. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151487. };
  151488. static long _vq_quantmap__44u8_p8_0[] = {
  151489. 13, 11, 9, 7, 5, 3, 1, 0,
  151490. 2, 4, 6, 8, 10, 12, 14,
  151491. };
  151492. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151493. _vq_quantthresh__44u8_p8_0,
  151494. _vq_quantmap__44u8_p8_0,
  151495. 15,
  151496. 15
  151497. };
  151498. static static_codebook _44u8_p8_0 = {
  151499. 2, 225,
  151500. _vq_lengthlist__44u8_p8_0,
  151501. 1, -520986624, 1620377600, 4, 0,
  151502. _vq_quantlist__44u8_p8_0,
  151503. NULL,
  151504. &_vq_auxt__44u8_p8_0,
  151505. NULL,
  151506. 0
  151507. };
  151508. static long _vq_quantlist__44u8_p8_1[] = {
  151509. 10,
  151510. 9,
  151511. 11,
  151512. 8,
  151513. 12,
  151514. 7,
  151515. 13,
  151516. 6,
  151517. 14,
  151518. 5,
  151519. 15,
  151520. 4,
  151521. 16,
  151522. 3,
  151523. 17,
  151524. 2,
  151525. 18,
  151526. 1,
  151527. 19,
  151528. 0,
  151529. 20,
  151530. };
  151531. static long _vq_lengthlist__44u8_p8_1[] = {
  151532. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151533. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151535. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151536. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151537. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151538. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151539. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151540. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151541. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151542. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151543. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151544. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151545. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151546. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151547. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151548. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151549. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151550. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151551. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151552. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151553. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151554. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151555. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151556. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151557. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151558. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151559. 10,10,10,10,10,10,10,10,10,
  151560. };
  151561. static float _vq_quantthresh__44u8_p8_1[] = {
  151562. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151563. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151564. 6.5, 7.5, 8.5, 9.5,
  151565. };
  151566. static long _vq_quantmap__44u8_p8_1[] = {
  151567. 19, 17, 15, 13, 11, 9, 7, 5,
  151568. 3, 1, 0, 2, 4, 6, 8, 10,
  151569. 12, 14, 16, 18, 20,
  151570. };
  151571. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151572. _vq_quantthresh__44u8_p8_1,
  151573. _vq_quantmap__44u8_p8_1,
  151574. 21,
  151575. 21
  151576. };
  151577. static static_codebook _44u8_p8_1 = {
  151578. 2, 441,
  151579. _vq_lengthlist__44u8_p8_1,
  151580. 1, -529268736, 1611661312, 5, 0,
  151581. _vq_quantlist__44u8_p8_1,
  151582. NULL,
  151583. &_vq_auxt__44u8_p8_1,
  151584. NULL,
  151585. 0
  151586. };
  151587. static long _vq_quantlist__44u8_p9_0[] = {
  151588. 4,
  151589. 3,
  151590. 5,
  151591. 2,
  151592. 6,
  151593. 1,
  151594. 7,
  151595. 0,
  151596. 8,
  151597. };
  151598. static long _vq_lengthlist__44u8_p9_0[] = {
  151599. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151600. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151602. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151603. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151604. 8,
  151605. };
  151606. static float _vq_quantthresh__44u8_p9_0[] = {
  151607. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151608. };
  151609. static long _vq_quantmap__44u8_p9_0[] = {
  151610. 7, 5, 3, 1, 0, 2, 4, 6,
  151611. 8,
  151612. };
  151613. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151614. _vq_quantthresh__44u8_p9_0,
  151615. _vq_quantmap__44u8_p9_0,
  151616. 9,
  151617. 9
  151618. };
  151619. static static_codebook _44u8_p9_0 = {
  151620. 2, 81,
  151621. _vq_lengthlist__44u8_p9_0,
  151622. 1, -511895552, 1631393792, 4, 0,
  151623. _vq_quantlist__44u8_p9_0,
  151624. NULL,
  151625. &_vq_auxt__44u8_p9_0,
  151626. NULL,
  151627. 0
  151628. };
  151629. static long _vq_quantlist__44u8_p9_1[] = {
  151630. 9,
  151631. 8,
  151632. 10,
  151633. 7,
  151634. 11,
  151635. 6,
  151636. 12,
  151637. 5,
  151638. 13,
  151639. 4,
  151640. 14,
  151641. 3,
  151642. 15,
  151643. 2,
  151644. 16,
  151645. 1,
  151646. 17,
  151647. 0,
  151648. 18,
  151649. };
  151650. static long _vq_lengthlist__44u8_p9_1[] = {
  151651. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151652. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151653. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151654. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151655. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151656. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151657. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151658. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151659. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151660. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151661. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151662. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151663. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151664. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151665. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151666. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151667. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151668. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151669. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151670. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151671. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151672. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151673. 16,15,16,16,16,16,16,16,16,
  151674. };
  151675. static float _vq_quantthresh__44u8_p9_1[] = {
  151676. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151677. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151678. 367.5, 416.5,
  151679. };
  151680. static long _vq_quantmap__44u8_p9_1[] = {
  151681. 17, 15, 13, 11, 9, 7, 5, 3,
  151682. 1, 0, 2, 4, 6, 8, 10, 12,
  151683. 14, 16, 18,
  151684. };
  151685. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151686. _vq_quantthresh__44u8_p9_1,
  151687. _vq_quantmap__44u8_p9_1,
  151688. 19,
  151689. 19
  151690. };
  151691. static static_codebook _44u8_p9_1 = {
  151692. 2, 361,
  151693. _vq_lengthlist__44u8_p9_1,
  151694. 1, -518287360, 1622704128, 5, 0,
  151695. _vq_quantlist__44u8_p9_1,
  151696. NULL,
  151697. &_vq_auxt__44u8_p9_1,
  151698. NULL,
  151699. 0
  151700. };
  151701. static long _vq_quantlist__44u8_p9_2[] = {
  151702. 24,
  151703. 23,
  151704. 25,
  151705. 22,
  151706. 26,
  151707. 21,
  151708. 27,
  151709. 20,
  151710. 28,
  151711. 19,
  151712. 29,
  151713. 18,
  151714. 30,
  151715. 17,
  151716. 31,
  151717. 16,
  151718. 32,
  151719. 15,
  151720. 33,
  151721. 14,
  151722. 34,
  151723. 13,
  151724. 35,
  151725. 12,
  151726. 36,
  151727. 11,
  151728. 37,
  151729. 10,
  151730. 38,
  151731. 9,
  151732. 39,
  151733. 8,
  151734. 40,
  151735. 7,
  151736. 41,
  151737. 6,
  151738. 42,
  151739. 5,
  151740. 43,
  151741. 4,
  151742. 44,
  151743. 3,
  151744. 45,
  151745. 2,
  151746. 46,
  151747. 1,
  151748. 47,
  151749. 0,
  151750. 48,
  151751. };
  151752. static long _vq_lengthlist__44u8_p9_2[] = {
  151753. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151754. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151755. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151756. 7,
  151757. };
  151758. static float _vq_quantthresh__44u8_p9_2[] = {
  151759. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151760. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151761. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151762. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151763. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151764. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151765. };
  151766. static long _vq_quantmap__44u8_p9_2[] = {
  151767. 47, 45, 43, 41, 39, 37, 35, 33,
  151768. 31, 29, 27, 25, 23, 21, 19, 17,
  151769. 15, 13, 11, 9, 7, 5, 3, 1,
  151770. 0, 2, 4, 6, 8, 10, 12, 14,
  151771. 16, 18, 20, 22, 24, 26, 28, 30,
  151772. 32, 34, 36, 38, 40, 42, 44, 46,
  151773. 48,
  151774. };
  151775. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151776. _vq_quantthresh__44u8_p9_2,
  151777. _vq_quantmap__44u8_p9_2,
  151778. 49,
  151779. 49
  151780. };
  151781. static static_codebook _44u8_p9_2 = {
  151782. 1, 49,
  151783. _vq_lengthlist__44u8_p9_2,
  151784. 1, -526909440, 1611661312, 6, 0,
  151785. _vq_quantlist__44u8_p9_2,
  151786. NULL,
  151787. &_vq_auxt__44u8_p9_2,
  151788. NULL,
  151789. 0
  151790. };
  151791. static long _huff_lengthlist__44u9__long[] = {
  151792. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151793. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151794. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151795. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151796. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151797. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151798. 10, 8, 8, 9,
  151799. };
  151800. static static_codebook _huff_book__44u9__long = {
  151801. 2, 100,
  151802. _huff_lengthlist__44u9__long,
  151803. 0, 0, 0, 0, 0,
  151804. NULL,
  151805. NULL,
  151806. NULL,
  151807. NULL,
  151808. 0
  151809. };
  151810. static long _huff_lengthlist__44u9__short[] = {
  151811. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151812. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151813. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151814. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151815. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151816. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151817. 9, 9,12,15,
  151818. };
  151819. static static_codebook _huff_book__44u9__short = {
  151820. 2, 100,
  151821. _huff_lengthlist__44u9__short,
  151822. 0, 0, 0, 0, 0,
  151823. NULL,
  151824. NULL,
  151825. NULL,
  151826. NULL,
  151827. 0
  151828. };
  151829. static long _vq_quantlist__44u9_p1_0[] = {
  151830. 1,
  151831. 0,
  151832. 2,
  151833. };
  151834. static long _vq_lengthlist__44u9_p1_0[] = {
  151835. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151836. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151837. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151838. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151839. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151840. 10,
  151841. };
  151842. static float _vq_quantthresh__44u9_p1_0[] = {
  151843. -0.5, 0.5,
  151844. };
  151845. static long _vq_quantmap__44u9_p1_0[] = {
  151846. 1, 0, 2,
  151847. };
  151848. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151849. _vq_quantthresh__44u9_p1_0,
  151850. _vq_quantmap__44u9_p1_0,
  151851. 3,
  151852. 3
  151853. };
  151854. static static_codebook _44u9_p1_0 = {
  151855. 4, 81,
  151856. _vq_lengthlist__44u9_p1_0,
  151857. 1, -535822336, 1611661312, 2, 0,
  151858. _vq_quantlist__44u9_p1_0,
  151859. NULL,
  151860. &_vq_auxt__44u9_p1_0,
  151861. NULL,
  151862. 0
  151863. };
  151864. static long _vq_quantlist__44u9_p2_0[] = {
  151865. 2,
  151866. 1,
  151867. 3,
  151868. 0,
  151869. 4,
  151870. };
  151871. static long _vq_lengthlist__44u9_p2_0[] = {
  151872. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151873. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151874. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151875. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151876. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151877. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151878. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151879. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151880. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151881. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151882. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151883. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151884. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151885. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151886. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151887. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151888. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151889. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151890. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151891. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151892. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151893. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151894. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151895. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151896. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151897. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151898. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151899. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151900. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151901. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151902. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151903. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151904. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151905. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151906. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151907. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151908. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151909. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151910. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151911. 14,
  151912. };
  151913. static float _vq_quantthresh__44u9_p2_0[] = {
  151914. -1.5, -0.5, 0.5, 1.5,
  151915. };
  151916. static long _vq_quantmap__44u9_p2_0[] = {
  151917. 3, 1, 0, 2, 4,
  151918. };
  151919. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151920. _vq_quantthresh__44u9_p2_0,
  151921. _vq_quantmap__44u9_p2_0,
  151922. 5,
  151923. 5
  151924. };
  151925. static static_codebook _44u9_p2_0 = {
  151926. 4, 625,
  151927. _vq_lengthlist__44u9_p2_0,
  151928. 1, -533725184, 1611661312, 3, 0,
  151929. _vq_quantlist__44u9_p2_0,
  151930. NULL,
  151931. &_vq_auxt__44u9_p2_0,
  151932. NULL,
  151933. 0
  151934. };
  151935. static long _vq_quantlist__44u9_p3_0[] = {
  151936. 4,
  151937. 3,
  151938. 5,
  151939. 2,
  151940. 6,
  151941. 1,
  151942. 7,
  151943. 0,
  151944. 8,
  151945. };
  151946. static long _vq_lengthlist__44u9_p3_0[] = {
  151947. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151948. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151949. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151950. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151951. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151952. 11,
  151953. };
  151954. static float _vq_quantthresh__44u9_p3_0[] = {
  151955. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151956. };
  151957. static long _vq_quantmap__44u9_p3_0[] = {
  151958. 7, 5, 3, 1, 0, 2, 4, 6,
  151959. 8,
  151960. };
  151961. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151962. _vq_quantthresh__44u9_p3_0,
  151963. _vq_quantmap__44u9_p3_0,
  151964. 9,
  151965. 9
  151966. };
  151967. static static_codebook _44u9_p3_0 = {
  151968. 2, 81,
  151969. _vq_lengthlist__44u9_p3_0,
  151970. 1, -531628032, 1611661312, 4, 0,
  151971. _vq_quantlist__44u9_p3_0,
  151972. NULL,
  151973. &_vq_auxt__44u9_p3_0,
  151974. NULL,
  151975. 0
  151976. };
  151977. static long _vq_quantlist__44u9_p4_0[] = {
  151978. 8,
  151979. 7,
  151980. 9,
  151981. 6,
  151982. 10,
  151983. 5,
  151984. 11,
  151985. 4,
  151986. 12,
  151987. 3,
  151988. 13,
  151989. 2,
  151990. 14,
  151991. 1,
  151992. 15,
  151993. 0,
  151994. 16,
  151995. };
  151996. static long _vq_lengthlist__44u9_p4_0[] = {
  151997. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151998. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151999. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152000. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152001. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152002. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152003. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152004. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152005. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152006. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152007. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152008. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152009. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152010. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152011. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152012. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152013. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152014. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152015. 14,
  152016. };
  152017. static float _vq_quantthresh__44u9_p4_0[] = {
  152018. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152019. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152020. };
  152021. static long _vq_quantmap__44u9_p4_0[] = {
  152022. 15, 13, 11, 9, 7, 5, 3, 1,
  152023. 0, 2, 4, 6, 8, 10, 12, 14,
  152024. 16,
  152025. };
  152026. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152027. _vq_quantthresh__44u9_p4_0,
  152028. _vq_quantmap__44u9_p4_0,
  152029. 17,
  152030. 17
  152031. };
  152032. static static_codebook _44u9_p4_0 = {
  152033. 2, 289,
  152034. _vq_lengthlist__44u9_p4_0,
  152035. 1, -529530880, 1611661312, 5, 0,
  152036. _vq_quantlist__44u9_p4_0,
  152037. NULL,
  152038. &_vq_auxt__44u9_p4_0,
  152039. NULL,
  152040. 0
  152041. };
  152042. static long _vq_quantlist__44u9_p5_0[] = {
  152043. 1,
  152044. 0,
  152045. 2,
  152046. };
  152047. static long _vq_lengthlist__44u9_p5_0[] = {
  152048. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152049. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152050. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152051. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152052. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152053. 10,
  152054. };
  152055. static float _vq_quantthresh__44u9_p5_0[] = {
  152056. -5.5, 5.5,
  152057. };
  152058. static long _vq_quantmap__44u9_p5_0[] = {
  152059. 1, 0, 2,
  152060. };
  152061. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152062. _vq_quantthresh__44u9_p5_0,
  152063. _vq_quantmap__44u9_p5_0,
  152064. 3,
  152065. 3
  152066. };
  152067. static static_codebook _44u9_p5_0 = {
  152068. 4, 81,
  152069. _vq_lengthlist__44u9_p5_0,
  152070. 1, -529137664, 1618345984, 2, 0,
  152071. _vq_quantlist__44u9_p5_0,
  152072. NULL,
  152073. &_vq_auxt__44u9_p5_0,
  152074. NULL,
  152075. 0
  152076. };
  152077. static long _vq_quantlist__44u9_p5_1[] = {
  152078. 5,
  152079. 4,
  152080. 6,
  152081. 3,
  152082. 7,
  152083. 2,
  152084. 8,
  152085. 1,
  152086. 9,
  152087. 0,
  152088. 10,
  152089. };
  152090. static long _vq_lengthlist__44u9_p5_1[] = {
  152091. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152092. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152093. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152094. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152095. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152096. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152097. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152098. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152099. };
  152100. static float _vq_quantthresh__44u9_p5_1[] = {
  152101. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152102. 3.5, 4.5,
  152103. };
  152104. static long _vq_quantmap__44u9_p5_1[] = {
  152105. 9, 7, 5, 3, 1, 0, 2, 4,
  152106. 6, 8, 10,
  152107. };
  152108. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152109. _vq_quantthresh__44u9_p5_1,
  152110. _vq_quantmap__44u9_p5_1,
  152111. 11,
  152112. 11
  152113. };
  152114. static static_codebook _44u9_p5_1 = {
  152115. 2, 121,
  152116. _vq_lengthlist__44u9_p5_1,
  152117. 1, -531365888, 1611661312, 4, 0,
  152118. _vq_quantlist__44u9_p5_1,
  152119. NULL,
  152120. &_vq_auxt__44u9_p5_1,
  152121. NULL,
  152122. 0
  152123. };
  152124. static long _vq_quantlist__44u9_p6_0[] = {
  152125. 6,
  152126. 5,
  152127. 7,
  152128. 4,
  152129. 8,
  152130. 3,
  152131. 9,
  152132. 2,
  152133. 10,
  152134. 1,
  152135. 11,
  152136. 0,
  152137. 12,
  152138. };
  152139. static long _vq_lengthlist__44u9_p6_0[] = {
  152140. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152141. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152142. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152143. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152144. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152145. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152146. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152147. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152148. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152149. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152150. 10,11,11,11,11,12,11,12,12,
  152151. };
  152152. static float _vq_quantthresh__44u9_p6_0[] = {
  152153. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152154. 12.5, 17.5, 22.5, 27.5,
  152155. };
  152156. static long _vq_quantmap__44u9_p6_0[] = {
  152157. 11, 9, 7, 5, 3, 1, 0, 2,
  152158. 4, 6, 8, 10, 12,
  152159. };
  152160. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152161. _vq_quantthresh__44u9_p6_0,
  152162. _vq_quantmap__44u9_p6_0,
  152163. 13,
  152164. 13
  152165. };
  152166. static static_codebook _44u9_p6_0 = {
  152167. 2, 169,
  152168. _vq_lengthlist__44u9_p6_0,
  152169. 1, -526516224, 1616117760, 4, 0,
  152170. _vq_quantlist__44u9_p6_0,
  152171. NULL,
  152172. &_vq_auxt__44u9_p6_0,
  152173. NULL,
  152174. 0
  152175. };
  152176. static long _vq_quantlist__44u9_p6_1[] = {
  152177. 2,
  152178. 1,
  152179. 3,
  152180. 0,
  152181. 4,
  152182. };
  152183. static long _vq_lengthlist__44u9_p6_1[] = {
  152184. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152185. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152186. };
  152187. static float _vq_quantthresh__44u9_p6_1[] = {
  152188. -1.5, -0.5, 0.5, 1.5,
  152189. };
  152190. static long _vq_quantmap__44u9_p6_1[] = {
  152191. 3, 1, 0, 2, 4,
  152192. };
  152193. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152194. _vq_quantthresh__44u9_p6_1,
  152195. _vq_quantmap__44u9_p6_1,
  152196. 5,
  152197. 5
  152198. };
  152199. static static_codebook _44u9_p6_1 = {
  152200. 2, 25,
  152201. _vq_lengthlist__44u9_p6_1,
  152202. 1, -533725184, 1611661312, 3, 0,
  152203. _vq_quantlist__44u9_p6_1,
  152204. NULL,
  152205. &_vq_auxt__44u9_p6_1,
  152206. NULL,
  152207. 0
  152208. };
  152209. static long _vq_quantlist__44u9_p7_0[] = {
  152210. 6,
  152211. 5,
  152212. 7,
  152213. 4,
  152214. 8,
  152215. 3,
  152216. 9,
  152217. 2,
  152218. 10,
  152219. 1,
  152220. 11,
  152221. 0,
  152222. 12,
  152223. };
  152224. static long _vq_lengthlist__44u9_p7_0[] = {
  152225. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152226. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152227. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152228. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152229. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152230. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152231. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152232. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152233. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152234. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152235. 12,13,13,14,14,14,15,15,15,
  152236. };
  152237. static float _vq_quantthresh__44u9_p7_0[] = {
  152238. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152239. 27.5, 38.5, 49.5, 60.5,
  152240. };
  152241. static long _vq_quantmap__44u9_p7_0[] = {
  152242. 11, 9, 7, 5, 3, 1, 0, 2,
  152243. 4, 6, 8, 10, 12,
  152244. };
  152245. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152246. _vq_quantthresh__44u9_p7_0,
  152247. _vq_quantmap__44u9_p7_0,
  152248. 13,
  152249. 13
  152250. };
  152251. static static_codebook _44u9_p7_0 = {
  152252. 2, 169,
  152253. _vq_lengthlist__44u9_p7_0,
  152254. 1, -523206656, 1618345984, 4, 0,
  152255. _vq_quantlist__44u9_p7_0,
  152256. NULL,
  152257. &_vq_auxt__44u9_p7_0,
  152258. NULL,
  152259. 0
  152260. };
  152261. static long _vq_quantlist__44u9_p7_1[] = {
  152262. 5,
  152263. 4,
  152264. 6,
  152265. 3,
  152266. 7,
  152267. 2,
  152268. 8,
  152269. 1,
  152270. 9,
  152271. 0,
  152272. 10,
  152273. };
  152274. static long _vq_lengthlist__44u9_p7_1[] = {
  152275. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152276. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152277. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152278. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152279. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152280. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152281. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152282. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152283. };
  152284. static float _vq_quantthresh__44u9_p7_1[] = {
  152285. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152286. 3.5, 4.5,
  152287. };
  152288. static long _vq_quantmap__44u9_p7_1[] = {
  152289. 9, 7, 5, 3, 1, 0, 2, 4,
  152290. 6, 8, 10,
  152291. };
  152292. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152293. _vq_quantthresh__44u9_p7_1,
  152294. _vq_quantmap__44u9_p7_1,
  152295. 11,
  152296. 11
  152297. };
  152298. static static_codebook _44u9_p7_1 = {
  152299. 2, 121,
  152300. _vq_lengthlist__44u9_p7_1,
  152301. 1, -531365888, 1611661312, 4, 0,
  152302. _vq_quantlist__44u9_p7_1,
  152303. NULL,
  152304. &_vq_auxt__44u9_p7_1,
  152305. NULL,
  152306. 0
  152307. };
  152308. static long _vq_quantlist__44u9_p8_0[] = {
  152309. 7,
  152310. 6,
  152311. 8,
  152312. 5,
  152313. 9,
  152314. 4,
  152315. 10,
  152316. 3,
  152317. 11,
  152318. 2,
  152319. 12,
  152320. 1,
  152321. 13,
  152322. 0,
  152323. 14,
  152324. };
  152325. static long _vq_lengthlist__44u9_p8_0[] = {
  152326. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152327. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152328. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152329. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152330. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152331. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152332. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152333. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152334. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152335. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152336. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152337. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152338. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152339. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152340. 15,
  152341. };
  152342. static float _vq_quantthresh__44u9_p8_0[] = {
  152343. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152344. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152345. };
  152346. static long _vq_quantmap__44u9_p8_0[] = {
  152347. 13, 11, 9, 7, 5, 3, 1, 0,
  152348. 2, 4, 6, 8, 10, 12, 14,
  152349. };
  152350. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152351. _vq_quantthresh__44u9_p8_0,
  152352. _vq_quantmap__44u9_p8_0,
  152353. 15,
  152354. 15
  152355. };
  152356. static static_codebook _44u9_p8_0 = {
  152357. 2, 225,
  152358. _vq_lengthlist__44u9_p8_0,
  152359. 1, -520986624, 1620377600, 4, 0,
  152360. _vq_quantlist__44u9_p8_0,
  152361. NULL,
  152362. &_vq_auxt__44u9_p8_0,
  152363. NULL,
  152364. 0
  152365. };
  152366. static long _vq_quantlist__44u9_p8_1[] = {
  152367. 10,
  152368. 9,
  152369. 11,
  152370. 8,
  152371. 12,
  152372. 7,
  152373. 13,
  152374. 6,
  152375. 14,
  152376. 5,
  152377. 15,
  152378. 4,
  152379. 16,
  152380. 3,
  152381. 17,
  152382. 2,
  152383. 18,
  152384. 1,
  152385. 19,
  152386. 0,
  152387. 20,
  152388. };
  152389. static long _vq_lengthlist__44u9_p8_1[] = {
  152390. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152391. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152393. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152394. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152395. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152396. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152397. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152398. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152399. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152400. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152401. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152402. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152403. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152404. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152405. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152406. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152407. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152408. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152409. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152410. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152411. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152412. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152413. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152415. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152416. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152417. 10,10,10,10,10,10,10,10,10,
  152418. };
  152419. static float _vq_quantthresh__44u9_p8_1[] = {
  152420. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152421. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152422. 6.5, 7.5, 8.5, 9.5,
  152423. };
  152424. static long _vq_quantmap__44u9_p8_1[] = {
  152425. 19, 17, 15, 13, 11, 9, 7, 5,
  152426. 3, 1, 0, 2, 4, 6, 8, 10,
  152427. 12, 14, 16, 18, 20,
  152428. };
  152429. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152430. _vq_quantthresh__44u9_p8_1,
  152431. _vq_quantmap__44u9_p8_1,
  152432. 21,
  152433. 21
  152434. };
  152435. static static_codebook _44u9_p8_1 = {
  152436. 2, 441,
  152437. _vq_lengthlist__44u9_p8_1,
  152438. 1, -529268736, 1611661312, 5, 0,
  152439. _vq_quantlist__44u9_p8_1,
  152440. NULL,
  152441. &_vq_auxt__44u9_p8_1,
  152442. NULL,
  152443. 0
  152444. };
  152445. static long _vq_quantlist__44u9_p9_0[] = {
  152446. 7,
  152447. 6,
  152448. 8,
  152449. 5,
  152450. 9,
  152451. 4,
  152452. 10,
  152453. 3,
  152454. 11,
  152455. 2,
  152456. 12,
  152457. 1,
  152458. 13,
  152459. 0,
  152460. 14,
  152461. };
  152462. static long _vq_lengthlist__44u9_p9_0[] = {
  152463. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152464. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152465. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152476. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152477. 10,
  152478. };
  152479. static float _vq_quantthresh__44u9_p9_0[] = {
  152480. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152481. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152482. };
  152483. static long _vq_quantmap__44u9_p9_0[] = {
  152484. 13, 11, 9, 7, 5, 3, 1, 0,
  152485. 2, 4, 6, 8, 10, 12, 14,
  152486. };
  152487. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152488. _vq_quantthresh__44u9_p9_0,
  152489. _vq_quantmap__44u9_p9_0,
  152490. 15,
  152491. 15
  152492. };
  152493. static static_codebook _44u9_p9_0 = {
  152494. 2, 225,
  152495. _vq_lengthlist__44u9_p9_0,
  152496. 1, -510036736, 1631393792, 4, 0,
  152497. _vq_quantlist__44u9_p9_0,
  152498. NULL,
  152499. &_vq_auxt__44u9_p9_0,
  152500. NULL,
  152501. 0
  152502. };
  152503. static long _vq_quantlist__44u9_p9_1[] = {
  152504. 9,
  152505. 8,
  152506. 10,
  152507. 7,
  152508. 11,
  152509. 6,
  152510. 12,
  152511. 5,
  152512. 13,
  152513. 4,
  152514. 14,
  152515. 3,
  152516. 15,
  152517. 2,
  152518. 16,
  152519. 1,
  152520. 17,
  152521. 0,
  152522. 18,
  152523. };
  152524. static long _vq_lengthlist__44u9_p9_1[] = {
  152525. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152526. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152527. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152528. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152529. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152530. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152531. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152532. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152533. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152534. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152535. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152536. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152537. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152538. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152539. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152540. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152541. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152542. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152543. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152544. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152545. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152546. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152547. 17,17,15,17,15,17,16,16,17,
  152548. };
  152549. static float _vq_quantthresh__44u9_p9_1[] = {
  152550. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152551. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152552. 367.5, 416.5,
  152553. };
  152554. static long _vq_quantmap__44u9_p9_1[] = {
  152555. 17, 15, 13, 11, 9, 7, 5, 3,
  152556. 1, 0, 2, 4, 6, 8, 10, 12,
  152557. 14, 16, 18,
  152558. };
  152559. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152560. _vq_quantthresh__44u9_p9_1,
  152561. _vq_quantmap__44u9_p9_1,
  152562. 19,
  152563. 19
  152564. };
  152565. static static_codebook _44u9_p9_1 = {
  152566. 2, 361,
  152567. _vq_lengthlist__44u9_p9_1,
  152568. 1, -518287360, 1622704128, 5, 0,
  152569. _vq_quantlist__44u9_p9_1,
  152570. NULL,
  152571. &_vq_auxt__44u9_p9_1,
  152572. NULL,
  152573. 0
  152574. };
  152575. static long _vq_quantlist__44u9_p9_2[] = {
  152576. 24,
  152577. 23,
  152578. 25,
  152579. 22,
  152580. 26,
  152581. 21,
  152582. 27,
  152583. 20,
  152584. 28,
  152585. 19,
  152586. 29,
  152587. 18,
  152588. 30,
  152589. 17,
  152590. 31,
  152591. 16,
  152592. 32,
  152593. 15,
  152594. 33,
  152595. 14,
  152596. 34,
  152597. 13,
  152598. 35,
  152599. 12,
  152600. 36,
  152601. 11,
  152602. 37,
  152603. 10,
  152604. 38,
  152605. 9,
  152606. 39,
  152607. 8,
  152608. 40,
  152609. 7,
  152610. 41,
  152611. 6,
  152612. 42,
  152613. 5,
  152614. 43,
  152615. 4,
  152616. 44,
  152617. 3,
  152618. 45,
  152619. 2,
  152620. 46,
  152621. 1,
  152622. 47,
  152623. 0,
  152624. 48,
  152625. };
  152626. static long _vq_lengthlist__44u9_p9_2[] = {
  152627. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152628. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152629. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152630. 7,
  152631. };
  152632. static float _vq_quantthresh__44u9_p9_2[] = {
  152633. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152634. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152635. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152636. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152637. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152638. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152639. };
  152640. static long _vq_quantmap__44u9_p9_2[] = {
  152641. 47, 45, 43, 41, 39, 37, 35, 33,
  152642. 31, 29, 27, 25, 23, 21, 19, 17,
  152643. 15, 13, 11, 9, 7, 5, 3, 1,
  152644. 0, 2, 4, 6, 8, 10, 12, 14,
  152645. 16, 18, 20, 22, 24, 26, 28, 30,
  152646. 32, 34, 36, 38, 40, 42, 44, 46,
  152647. 48,
  152648. };
  152649. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152650. _vq_quantthresh__44u9_p9_2,
  152651. _vq_quantmap__44u9_p9_2,
  152652. 49,
  152653. 49
  152654. };
  152655. static static_codebook _44u9_p9_2 = {
  152656. 1, 49,
  152657. _vq_lengthlist__44u9_p9_2,
  152658. 1, -526909440, 1611661312, 6, 0,
  152659. _vq_quantlist__44u9_p9_2,
  152660. NULL,
  152661. &_vq_auxt__44u9_p9_2,
  152662. NULL,
  152663. 0
  152664. };
  152665. static long _huff_lengthlist__44un1__long[] = {
  152666. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152667. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152668. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152669. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152670. };
  152671. static static_codebook _huff_book__44un1__long = {
  152672. 2, 64,
  152673. _huff_lengthlist__44un1__long,
  152674. 0, 0, 0, 0, 0,
  152675. NULL,
  152676. NULL,
  152677. NULL,
  152678. NULL,
  152679. 0
  152680. };
  152681. static long _vq_quantlist__44un1__p1_0[] = {
  152682. 1,
  152683. 0,
  152684. 2,
  152685. };
  152686. static long _vq_lengthlist__44un1__p1_0[] = {
  152687. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152688. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152689. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152690. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152691. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152692. 12,
  152693. };
  152694. static float _vq_quantthresh__44un1__p1_0[] = {
  152695. -0.5, 0.5,
  152696. };
  152697. static long _vq_quantmap__44un1__p1_0[] = {
  152698. 1, 0, 2,
  152699. };
  152700. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152701. _vq_quantthresh__44un1__p1_0,
  152702. _vq_quantmap__44un1__p1_0,
  152703. 3,
  152704. 3
  152705. };
  152706. static static_codebook _44un1__p1_0 = {
  152707. 4, 81,
  152708. _vq_lengthlist__44un1__p1_0,
  152709. 1, -535822336, 1611661312, 2, 0,
  152710. _vq_quantlist__44un1__p1_0,
  152711. NULL,
  152712. &_vq_auxt__44un1__p1_0,
  152713. NULL,
  152714. 0
  152715. };
  152716. static long _vq_quantlist__44un1__p2_0[] = {
  152717. 1,
  152718. 0,
  152719. 2,
  152720. };
  152721. static long _vq_lengthlist__44un1__p2_0[] = {
  152722. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152723. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152724. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152725. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152726. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152727. 8,
  152728. };
  152729. static float _vq_quantthresh__44un1__p2_0[] = {
  152730. -0.5, 0.5,
  152731. };
  152732. static long _vq_quantmap__44un1__p2_0[] = {
  152733. 1, 0, 2,
  152734. };
  152735. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152736. _vq_quantthresh__44un1__p2_0,
  152737. _vq_quantmap__44un1__p2_0,
  152738. 3,
  152739. 3
  152740. };
  152741. static static_codebook _44un1__p2_0 = {
  152742. 4, 81,
  152743. _vq_lengthlist__44un1__p2_0,
  152744. 1, -535822336, 1611661312, 2, 0,
  152745. _vq_quantlist__44un1__p2_0,
  152746. NULL,
  152747. &_vq_auxt__44un1__p2_0,
  152748. NULL,
  152749. 0
  152750. };
  152751. static long _vq_quantlist__44un1__p3_0[] = {
  152752. 2,
  152753. 1,
  152754. 3,
  152755. 0,
  152756. 4,
  152757. };
  152758. static long _vq_lengthlist__44un1__p3_0[] = {
  152759. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152760. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152761. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152762. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152763. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152764. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152765. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152766. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152767. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152768. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152769. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152770. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152771. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152772. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152773. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152774. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152775. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152776. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152777. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152778. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152779. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152780. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152781. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152782. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152783. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152784. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152785. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152786. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152787. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152788. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152789. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152790. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152791. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152792. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152793. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152794. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152795. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152796. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152797. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152798. 17,
  152799. };
  152800. static float _vq_quantthresh__44un1__p3_0[] = {
  152801. -1.5, -0.5, 0.5, 1.5,
  152802. };
  152803. static long _vq_quantmap__44un1__p3_0[] = {
  152804. 3, 1, 0, 2, 4,
  152805. };
  152806. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152807. _vq_quantthresh__44un1__p3_0,
  152808. _vq_quantmap__44un1__p3_0,
  152809. 5,
  152810. 5
  152811. };
  152812. static static_codebook _44un1__p3_0 = {
  152813. 4, 625,
  152814. _vq_lengthlist__44un1__p3_0,
  152815. 1, -533725184, 1611661312, 3, 0,
  152816. _vq_quantlist__44un1__p3_0,
  152817. NULL,
  152818. &_vq_auxt__44un1__p3_0,
  152819. NULL,
  152820. 0
  152821. };
  152822. static long _vq_quantlist__44un1__p4_0[] = {
  152823. 2,
  152824. 1,
  152825. 3,
  152826. 0,
  152827. 4,
  152828. };
  152829. static long _vq_lengthlist__44un1__p4_0[] = {
  152830. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152831. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152832. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152833. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152834. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152835. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152836. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152837. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152838. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152839. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152840. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152841. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152842. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152843. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152844. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152845. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152846. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152847. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152848. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152849. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152850. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152851. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152852. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152853. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152854. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152855. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152856. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152857. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152858. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152859. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152860. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152861. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152862. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152863. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152864. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152865. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152866. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152867. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152868. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152869. 12,
  152870. };
  152871. static float _vq_quantthresh__44un1__p4_0[] = {
  152872. -1.5, -0.5, 0.5, 1.5,
  152873. };
  152874. static long _vq_quantmap__44un1__p4_0[] = {
  152875. 3, 1, 0, 2, 4,
  152876. };
  152877. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152878. _vq_quantthresh__44un1__p4_0,
  152879. _vq_quantmap__44un1__p4_0,
  152880. 5,
  152881. 5
  152882. };
  152883. static static_codebook _44un1__p4_0 = {
  152884. 4, 625,
  152885. _vq_lengthlist__44un1__p4_0,
  152886. 1, -533725184, 1611661312, 3, 0,
  152887. _vq_quantlist__44un1__p4_0,
  152888. NULL,
  152889. &_vq_auxt__44un1__p4_0,
  152890. NULL,
  152891. 0
  152892. };
  152893. static long _vq_quantlist__44un1__p5_0[] = {
  152894. 4,
  152895. 3,
  152896. 5,
  152897. 2,
  152898. 6,
  152899. 1,
  152900. 7,
  152901. 0,
  152902. 8,
  152903. };
  152904. static long _vq_lengthlist__44un1__p5_0[] = {
  152905. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152906. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152907. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152908. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152909. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152910. 12,
  152911. };
  152912. static float _vq_quantthresh__44un1__p5_0[] = {
  152913. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152914. };
  152915. static long _vq_quantmap__44un1__p5_0[] = {
  152916. 7, 5, 3, 1, 0, 2, 4, 6,
  152917. 8,
  152918. };
  152919. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152920. _vq_quantthresh__44un1__p5_0,
  152921. _vq_quantmap__44un1__p5_0,
  152922. 9,
  152923. 9
  152924. };
  152925. static static_codebook _44un1__p5_0 = {
  152926. 2, 81,
  152927. _vq_lengthlist__44un1__p5_0,
  152928. 1, -531628032, 1611661312, 4, 0,
  152929. _vq_quantlist__44un1__p5_0,
  152930. NULL,
  152931. &_vq_auxt__44un1__p5_0,
  152932. NULL,
  152933. 0
  152934. };
  152935. static long _vq_quantlist__44un1__p6_0[] = {
  152936. 6,
  152937. 5,
  152938. 7,
  152939. 4,
  152940. 8,
  152941. 3,
  152942. 9,
  152943. 2,
  152944. 10,
  152945. 1,
  152946. 11,
  152947. 0,
  152948. 12,
  152949. };
  152950. static long _vq_lengthlist__44un1__p6_0[] = {
  152951. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152952. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152953. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152954. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152955. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152956. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152957. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152958. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152959. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152960. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152961. 16, 0,15,18,18, 0,16, 0, 0,
  152962. };
  152963. static float _vq_quantthresh__44un1__p6_0[] = {
  152964. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152965. 12.5, 17.5, 22.5, 27.5,
  152966. };
  152967. static long _vq_quantmap__44un1__p6_0[] = {
  152968. 11, 9, 7, 5, 3, 1, 0, 2,
  152969. 4, 6, 8, 10, 12,
  152970. };
  152971. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152972. _vq_quantthresh__44un1__p6_0,
  152973. _vq_quantmap__44un1__p6_0,
  152974. 13,
  152975. 13
  152976. };
  152977. static static_codebook _44un1__p6_0 = {
  152978. 2, 169,
  152979. _vq_lengthlist__44un1__p6_0,
  152980. 1, -526516224, 1616117760, 4, 0,
  152981. _vq_quantlist__44un1__p6_0,
  152982. NULL,
  152983. &_vq_auxt__44un1__p6_0,
  152984. NULL,
  152985. 0
  152986. };
  152987. static long _vq_quantlist__44un1__p6_1[] = {
  152988. 2,
  152989. 1,
  152990. 3,
  152991. 0,
  152992. 4,
  152993. };
  152994. static long _vq_lengthlist__44un1__p6_1[] = {
  152995. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152996. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152997. };
  152998. static float _vq_quantthresh__44un1__p6_1[] = {
  152999. -1.5, -0.5, 0.5, 1.5,
  153000. };
  153001. static long _vq_quantmap__44un1__p6_1[] = {
  153002. 3, 1, 0, 2, 4,
  153003. };
  153004. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153005. _vq_quantthresh__44un1__p6_1,
  153006. _vq_quantmap__44un1__p6_1,
  153007. 5,
  153008. 5
  153009. };
  153010. static static_codebook _44un1__p6_1 = {
  153011. 2, 25,
  153012. _vq_lengthlist__44un1__p6_1,
  153013. 1, -533725184, 1611661312, 3, 0,
  153014. _vq_quantlist__44un1__p6_1,
  153015. NULL,
  153016. &_vq_auxt__44un1__p6_1,
  153017. NULL,
  153018. 0
  153019. };
  153020. static long _vq_quantlist__44un1__p7_0[] = {
  153021. 2,
  153022. 1,
  153023. 3,
  153024. 0,
  153025. 4,
  153026. };
  153027. static long _vq_lengthlist__44un1__p7_0[] = {
  153028. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153029. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153031. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153035. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153043. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153045. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153046. 11,11,11,11,11,11,11,11,11,11,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,11,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,11,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,11,
  153056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153058. 11,11,11,11,11,11,11,11,11,11,11,11,11,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,11,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,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153064. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153065. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153067. 10,
  153068. };
  153069. static float _vq_quantthresh__44un1__p7_0[] = {
  153070. -253.5, -84.5, 84.5, 253.5,
  153071. };
  153072. static long _vq_quantmap__44un1__p7_0[] = {
  153073. 3, 1, 0, 2, 4,
  153074. };
  153075. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153076. _vq_quantthresh__44un1__p7_0,
  153077. _vq_quantmap__44un1__p7_0,
  153078. 5,
  153079. 5
  153080. };
  153081. static static_codebook _44un1__p7_0 = {
  153082. 4, 625,
  153083. _vq_lengthlist__44un1__p7_0,
  153084. 1, -518709248, 1626677248, 3, 0,
  153085. _vq_quantlist__44un1__p7_0,
  153086. NULL,
  153087. &_vq_auxt__44un1__p7_0,
  153088. NULL,
  153089. 0
  153090. };
  153091. static long _vq_quantlist__44un1__p7_1[] = {
  153092. 6,
  153093. 5,
  153094. 7,
  153095. 4,
  153096. 8,
  153097. 3,
  153098. 9,
  153099. 2,
  153100. 10,
  153101. 1,
  153102. 11,
  153103. 0,
  153104. 12,
  153105. };
  153106. static long _vq_lengthlist__44un1__p7_1[] = {
  153107. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153108. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153109. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153110. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153111. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153112. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153113. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153114. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153115. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153116. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153117. 12,13,13,12,13,13,14,14,14,
  153118. };
  153119. static float _vq_quantthresh__44un1__p7_1[] = {
  153120. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153121. 32.5, 45.5, 58.5, 71.5,
  153122. };
  153123. static long _vq_quantmap__44un1__p7_1[] = {
  153124. 11, 9, 7, 5, 3, 1, 0, 2,
  153125. 4, 6, 8, 10, 12,
  153126. };
  153127. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153128. _vq_quantthresh__44un1__p7_1,
  153129. _vq_quantmap__44un1__p7_1,
  153130. 13,
  153131. 13
  153132. };
  153133. static static_codebook _44un1__p7_1 = {
  153134. 2, 169,
  153135. _vq_lengthlist__44un1__p7_1,
  153136. 1, -523010048, 1618608128, 4, 0,
  153137. _vq_quantlist__44un1__p7_1,
  153138. NULL,
  153139. &_vq_auxt__44un1__p7_1,
  153140. NULL,
  153141. 0
  153142. };
  153143. static long _vq_quantlist__44un1__p7_2[] = {
  153144. 6,
  153145. 5,
  153146. 7,
  153147. 4,
  153148. 8,
  153149. 3,
  153150. 9,
  153151. 2,
  153152. 10,
  153153. 1,
  153154. 11,
  153155. 0,
  153156. 12,
  153157. };
  153158. static long _vq_lengthlist__44un1__p7_2[] = {
  153159. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153160. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153161. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153162. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153163. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153164. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153165. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153166. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153167. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153168. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153169. 9, 9, 9,10,10,10,10,10,10,
  153170. };
  153171. static float _vq_quantthresh__44un1__p7_2[] = {
  153172. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153173. 2.5, 3.5, 4.5, 5.5,
  153174. };
  153175. static long _vq_quantmap__44un1__p7_2[] = {
  153176. 11, 9, 7, 5, 3, 1, 0, 2,
  153177. 4, 6, 8, 10, 12,
  153178. };
  153179. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153180. _vq_quantthresh__44un1__p7_2,
  153181. _vq_quantmap__44un1__p7_2,
  153182. 13,
  153183. 13
  153184. };
  153185. static static_codebook _44un1__p7_2 = {
  153186. 2, 169,
  153187. _vq_lengthlist__44un1__p7_2,
  153188. 1, -531103744, 1611661312, 4, 0,
  153189. _vq_quantlist__44un1__p7_2,
  153190. NULL,
  153191. &_vq_auxt__44un1__p7_2,
  153192. NULL,
  153193. 0
  153194. };
  153195. static long _huff_lengthlist__44un1__short[] = {
  153196. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153197. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153198. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153199. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153200. };
  153201. static static_codebook _huff_book__44un1__short = {
  153202. 2, 64,
  153203. _huff_lengthlist__44un1__short,
  153204. 0, 0, 0, 0, 0,
  153205. NULL,
  153206. NULL,
  153207. NULL,
  153208. NULL,
  153209. 0
  153210. };
  153211. /*** End of inlined file: res_books_uncoupled.h ***/
  153212. /***** residue backends *********************************************/
  153213. static vorbis_info_residue0 _residue_44_low_un={
  153214. 0,-1, -1, 8,-1,
  153215. {0},
  153216. {-1},
  153217. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153218. { -1, 25, -1, 45, -1, -1, -1}
  153219. };
  153220. static vorbis_info_residue0 _residue_44_mid_un={
  153221. 0,-1, -1, 10,-1,
  153222. /* 0 1 2 3 4 5 6 7 8 9 */
  153223. {0},
  153224. {-1},
  153225. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153226. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153227. };
  153228. static vorbis_info_residue0 _residue_44_hi_un={
  153229. 0,-1, -1, 10,-1,
  153230. /* 0 1 2 3 4 5 6 7 8 9 */
  153231. {0},
  153232. {-1},
  153233. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153234. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153235. };
  153236. /* mapping conventions:
  153237. only one submap (this would change for efficient 5.1 support for example)*/
  153238. /* Four psychoacoustic profiles are used, one for each blocktype */
  153239. static vorbis_info_mapping0 _map_nominal_u[2]={
  153240. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153241. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153242. };
  153243. static static_bookblock _resbook_44u_n1={
  153244. {
  153245. {0},
  153246. {0,0,&_44un1__p1_0},
  153247. {0,0,&_44un1__p2_0},
  153248. {0,0,&_44un1__p3_0},
  153249. {0,0,&_44un1__p4_0},
  153250. {0,0,&_44un1__p5_0},
  153251. {&_44un1__p6_0,&_44un1__p6_1},
  153252. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153253. }
  153254. };
  153255. static static_bookblock _resbook_44u_0={
  153256. {
  153257. {0},
  153258. {0,0,&_44u0__p1_0},
  153259. {0,0,&_44u0__p2_0},
  153260. {0,0,&_44u0__p3_0},
  153261. {0,0,&_44u0__p4_0},
  153262. {0,0,&_44u0__p5_0},
  153263. {&_44u0__p6_0,&_44u0__p6_1},
  153264. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153265. }
  153266. };
  153267. static static_bookblock _resbook_44u_1={
  153268. {
  153269. {0},
  153270. {0,0,&_44u1__p1_0},
  153271. {0,0,&_44u1__p2_0},
  153272. {0,0,&_44u1__p3_0},
  153273. {0,0,&_44u1__p4_0},
  153274. {0,0,&_44u1__p5_0},
  153275. {&_44u1__p6_0,&_44u1__p6_1},
  153276. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153277. }
  153278. };
  153279. static static_bookblock _resbook_44u_2={
  153280. {
  153281. {0},
  153282. {0,0,&_44u2__p1_0},
  153283. {0,0,&_44u2__p2_0},
  153284. {0,0,&_44u2__p3_0},
  153285. {0,0,&_44u2__p4_0},
  153286. {0,0,&_44u2__p5_0},
  153287. {&_44u2__p6_0,&_44u2__p6_1},
  153288. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153289. }
  153290. };
  153291. static static_bookblock _resbook_44u_3={
  153292. {
  153293. {0},
  153294. {0,0,&_44u3__p1_0},
  153295. {0,0,&_44u3__p2_0},
  153296. {0,0,&_44u3__p3_0},
  153297. {0,0,&_44u3__p4_0},
  153298. {0,0,&_44u3__p5_0},
  153299. {&_44u3__p6_0,&_44u3__p6_1},
  153300. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153301. }
  153302. };
  153303. static static_bookblock _resbook_44u_4={
  153304. {
  153305. {0},
  153306. {0,0,&_44u4__p1_0},
  153307. {0,0,&_44u4__p2_0},
  153308. {0,0,&_44u4__p3_0},
  153309. {0,0,&_44u4__p4_0},
  153310. {0,0,&_44u4__p5_0},
  153311. {&_44u4__p6_0,&_44u4__p6_1},
  153312. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153313. }
  153314. };
  153315. static static_bookblock _resbook_44u_5={
  153316. {
  153317. {0},
  153318. {0,0,&_44u5__p1_0},
  153319. {0,0,&_44u5__p2_0},
  153320. {0,0,&_44u5__p3_0},
  153321. {0,0,&_44u5__p4_0},
  153322. {0,0,&_44u5__p5_0},
  153323. {0,0,&_44u5__p6_0},
  153324. {&_44u5__p7_0,&_44u5__p7_1},
  153325. {&_44u5__p8_0,&_44u5__p8_1},
  153326. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153327. }
  153328. };
  153329. static static_bookblock _resbook_44u_6={
  153330. {
  153331. {0},
  153332. {0,0,&_44u6__p1_0},
  153333. {0,0,&_44u6__p2_0},
  153334. {0,0,&_44u6__p3_0},
  153335. {0,0,&_44u6__p4_0},
  153336. {0,0,&_44u6__p5_0},
  153337. {0,0,&_44u6__p6_0},
  153338. {&_44u6__p7_0,&_44u6__p7_1},
  153339. {&_44u6__p8_0,&_44u6__p8_1},
  153340. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153341. }
  153342. };
  153343. static static_bookblock _resbook_44u_7={
  153344. {
  153345. {0},
  153346. {0,0,&_44u7__p1_0},
  153347. {0,0,&_44u7__p2_0},
  153348. {0,0,&_44u7__p3_0},
  153349. {0,0,&_44u7__p4_0},
  153350. {0,0,&_44u7__p5_0},
  153351. {0,0,&_44u7__p6_0},
  153352. {&_44u7__p7_0,&_44u7__p7_1},
  153353. {&_44u7__p8_0,&_44u7__p8_1},
  153354. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153355. }
  153356. };
  153357. static static_bookblock _resbook_44u_8={
  153358. {
  153359. {0},
  153360. {0,0,&_44u8_p1_0},
  153361. {0,0,&_44u8_p2_0},
  153362. {0,0,&_44u8_p3_0},
  153363. {0,0,&_44u8_p4_0},
  153364. {&_44u8_p5_0,&_44u8_p5_1},
  153365. {&_44u8_p6_0,&_44u8_p6_1},
  153366. {&_44u8_p7_0,&_44u8_p7_1},
  153367. {&_44u8_p8_0,&_44u8_p8_1},
  153368. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153369. }
  153370. };
  153371. static static_bookblock _resbook_44u_9={
  153372. {
  153373. {0},
  153374. {0,0,&_44u9_p1_0},
  153375. {0,0,&_44u9_p2_0},
  153376. {0,0,&_44u9_p3_0},
  153377. {0,0,&_44u9_p4_0},
  153378. {&_44u9_p5_0,&_44u9_p5_1},
  153379. {&_44u9_p6_0,&_44u9_p6_1},
  153380. {&_44u9_p7_0,&_44u9_p7_1},
  153381. {&_44u9_p8_0,&_44u9_p8_1},
  153382. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153383. }
  153384. };
  153385. static vorbis_residue_template _res_44u_n1[]={
  153386. {1,0, &_residue_44_low_un,
  153387. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153388. &_resbook_44u_n1,&_resbook_44u_n1},
  153389. {1,0, &_residue_44_low_un,
  153390. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153391. &_resbook_44u_n1,&_resbook_44u_n1}
  153392. };
  153393. static vorbis_residue_template _res_44u_0[]={
  153394. {1,0, &_residue_44_low_un,
  153395. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153396. &_resbook_44u_0,&_resbook_44u_0},
  153397. {1,0, &_residue_44_low_un,
  153398. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153399. &_resbook_44u_0,&_resbook_44u_0}
  153400. };
  153401. static vorbis_residue_template _res_44u_1[]={
  153402. {1,0, &_residue_44_low_un,
  153403. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153404. &_resbook_44u_1,&_resbook_44u_1},
  153405. {1,0, &_residue_44_low_un,
  153406. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153407. &_resbook_44u_1,&_resbook_44u_1}
  153408. };
  153409. static vorbis_residue_template _res_44u_2[]={
  153410. {1,0, &_residue_44_low_un,
  153411. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153412. &_resbook_44u_2,&_resbook_44u_2},
  153413. {1,0, &_residue_44_low_un,
  153414. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153415. &_resbook_44u_2,&_resbook_44u_2}
  153416. };
  153417. static vorbis_residue_template _res_44u_3[]={
  153418. {1,0, &_residue_44_low_un,
  153419. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153420. &_resbook_44u_3,&_resbook_44u_3},
  153421. {1,0, &_residue_44_low_un,
  153422. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153423. &_resbook_44u_3,&_resbook_44u_3}
  153424. };
  153425. static vorbis_residue_template _res_44u_4[]={
  153426. {1,0, &_residue_44_low_un,
  153427. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153428. &_resbook_44u_4,&_resbook_44u_4},
  153429. {1,0, &_residue_44_low_un,
  153430. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153431. &_resbook_44u_4,&_resbook_44u_4}
  153432. };
  153433. static vorbis_residue_template _res_44u_5[]={
  153434. {1,0, &_residue_44_mid_un,
  153435. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153436. &_resbook_44u_5,&_resbook_44u_5},
  153437. {1,0, &_residue_44_mid_un,
  153438. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153439. &_resbook_44u_5,&_resbook_44u_5}
  153440. };
  153441. static vorbis_residue_template _res_44u_6[]={
  153442. {1,0, &_residue_44_mid_un,
  153443. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153444. &_resbook_44u_6,&_resbook_44u_6},
  153445. {1,0, &_residue_44_mid_un,
  153446. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153447. &_resbook_44u_6,&_resbook_44u_6}
  153448. };
  153449. static vorbis_residue_template _res_44u_7[]={
  153450. {1,0, &_residue_44_mid_un,
  153451. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153452. &_resbook_44u_7,&_resbook_44u_7},
  153453. {1,0, &_residue_44_mid_un,
  153454. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153455. &_resbook_44u_7,&_resbook_44u_7}
  153456. };
  153457. static vorbis_residue_template _res_44u_8[]={
  153458. {1,0, &_residue_44_hi_un,
  153459. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153460. &_resbook_44u_8,&_resbook_44u_8},
  153461. {1,0, &_residue_44_hi_un,
  153462. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153463. &_resbook_44u_8,&_resbook_44u_8}
  153464. };
  153465. static vorbis_residue_template _res_44u_9[]={
  153466. {1,0, &_residue_44_hi_un,
  153467. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153468. &_resbook_44u_9,&_resbook_44u_9},
  153469. {1,0, &_residue_44_hi_un,
  153470. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153471. &_resbook_44u_9,&_resbook_44u_9}
  153472. };
  153473. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153474. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153475. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153476. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153477. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153478. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153479. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153480. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153481. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153482. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153483. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153484. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153485. };
  153486. /*** End of inlined file: residue_44u.h ***/
  153487. static double rate_mapping_44_un[12]={
  153488. 32000.,48000.,60000.,70000.,80000.,86000.,
  153489. 96000.,110000.,120000.,140000.,160000.,240001.
  153490. };
  153491. ve_setup_data_template ve_setup_44_uncoupled={
  153492. 11,
  153493. rate_mapping_44_un,
  153494. quality_mapping_44,
  153495. -1,
  153496. 40000,
  153497. 50000,
  153498. blocksize_short_44,
  153499. blocksize_long_44,
  153500. _psy_tone_masteratt_44,
  153501. _psy_tone_0dB,
  153502. _psy_tone_suppress,
  153503. _vp_tonemask_adj_otherblock,
  153504. _vp_tonemask_adj_longblock,
  153505. _vp_tonemask_adj_otherblock,
  153506. _psy_noiseguards_44,
  153507. _psy_noisebias_impulse,
  153508. _psy_noisebias_padding,
  153509. _psy_noisebias_trans,
  153510. _psy_noisebias_long,
  153511. _psy_noise_suppress,
  153512. _psy_compand_44,
  153513. _psy_compand_short_mapping,
  153514. _psy_compand_long_mapping,
  153515. {_noise_start_short_44,_noise_start_long_44},
  153516. {_noise_part_short_44,_noise_part_long_44},
  153517. _noise_thresh_44,
  153518. _psy_ath_floater,
  153519. _psy_ath_abs,
  153520. _psy_lowpass_44,
  153521. _psy_global_44,
  153522. _global_mapping_44,
  153523. NULL,
  153524. _floor_books,
  153525. _floor,
  153526. _floor_short_mapping_44,
  153527. _floor_long_mapping_44,
  153528. _mapres_template_44_uncoupled
  153529. };
  153530. /*** End of inlined file: setup_44u.h ***/
  153531. /*** Start of inlined file: setup_32.h ***/
  153532. static double rate_mapping_32[12]={
  153533. 18000.,28000.,35000.,45000.,56000.,60000.,
  153534. 75000.,90000.,100000.,115000.,150000.,190000.,
  153535. };
  153536. static double rate_mapping_32_un[12]={
  153537. 30000.,42000.,52000.,64000.,72000.,78000.,
  153538. 86000.,92000.,110000.,120000.,140000.,190000.,
  153539. };
  153540. static double _psy_lowpass_32[12]={
  153541. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153542. };
  153543. ve_setup_data_template ve_setup_32_stereo={
  153544. 11,
  153545. rate_mapping_32,
  153546. quality_mapping_44,
  153547. 2,
  153548. 26000,
  153549. 40000,
  153550. blocksize_short_44,
  153551. blocksize_long_44,
  153552. _psy_tone_masteratt_44,
  153553. _psy_tone_0dB,
  153554. _psy_tone_suppress,
  153555. _vp_tonemask_adj_otherblock,
  153556. _vp_tonemask_adj_longblock,
  153557. _vp_tonemask_adj_otherblock,
  153558. _psy_noiseguards_44,
  153559. _psy_noisebias_impulse,
  153560. _psy_noisebias_padding,
  153561. _psy_noisebias_trans,
  153562. _psy_noisebias_long,
  153563. _psy_noise_suppress,
  153564. _psy_compand_44,
  153565. _psy_compand_short_mapping,
  153566. _psy_compand_long_mapping,
  153567. {_noise_start_short_44,_noise_start_long_44},
  153568. {_noise_part_short_44,_noise_part_long_44},
  153569. _noise_thresh_44,
  153570. _psy_ath_floater,
  153571. _psy_ath_abs,
  153572. _psy_lowpass_32,
  153573. _psy_global_44,
  153574. _global_mapping_44,
  153575. _psy_stereo_modes_44,
  153576. _floor_books,
  153577. _floor,
  153578. _floor_short_mapping_44,
  153579. _floor_long_mapping_44,
  153580. _mapres_template_44_stereo
  153581. };
  153582. ve_setup_data_template ve_setup_32_uncoupled={
  153583. 11,
  153584. rate_mapping_32_un,
  153585. quality_mapping_44,
  153586. -1,
  153587. 26000,
  153588. 40000,
  153589. blocksize_short_44,
  153590. blocksize_long_44,
  153591. _psy_tone_masteratt_44,
  153592. _psy_tone_0dB,
  153593. _psy_tone_suppress,
  153594. _vp_tonemask_adj_otherblock,
  153595. _vp_tonemask_adj_longblock,
  153596. _vp_tonemask_adj_otherblock,
  153597. _psy_noiseguards_44,
  153598. _psy_noisebias_impulse,
  153599. _psy_noisebias_padding,
  153600. _psy_noisebias_trans,
  153601. _psy_noisebias_long,
  153602. _psy_noise_suppress,
  153603. _psy_compand_44,
  153604. _psy_compand_short_mapping,
  153605. _psy_compand_long_mapping,
  153606. {_noise_start_short_44,_noise_start_long_44},
  153607. {_noise_part_short_44,_noise_part_long_44},
  153608. _noise_thresh_44,
  153609. _psy_ath_floater,
  153610. _psy_ath_abs,
  153611. _psy_lowpass_32,
  153612. _psy_global_44,
  153613. _global_mapping_44,
  153614. NULL,
  153615. _floor_books,
  153616. _floor,
  153617. _floor_short_mapping_44,
  153618. _floor_long_mapping_44,
  153619. _mapres_template_44_uncoupled
  153620. };
  153621. /*** End of inlined file: setup_32.h ***/
  153622. /*** Start of inlined file: setup_8.h ***/
  153623. /*** Start of inlined file: psych_8.h ***/
  153624. static att3 _psy_tone_masteratt_8[3]={
  153625. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153626. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153627. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153628. };
  153629. static vp_adjblock _vp_tonemask_adj_8[3]={
  153630. /* adjust for mode zero */
  153631. /* 63 125 250 500 1 2 4 8 16 */
  153632. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153633. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153634. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153635. };
  153636. static noise3 _psy_noisebias_8[3]={
  153637. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153638. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153639. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153640. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153641. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153642. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153643. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153644. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153645. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153646. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153647. };
  153648. /* stereo mode by base quality level */
  153649. static adj_stereo _psy_stereo_modes_8[3]={
  153650. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153651. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153652. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153653. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153654. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153655. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153656. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153657. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153658. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153659. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153660. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153661. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153662. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153663. };
  153664. static noiseguard _psy_noiseguards_8[2]={
  153665. {10,10,-1},
  153666. {10,10,-1},
  153667. };
  153668. static compandblock _psy_compand_8[2]={
  153669. {{
  153670. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153671. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153672. 12,12,13,13,14,14,15, 15, /* 23dB */
  153673. 16,16,17,17,17,18,18, 19, /* 31dB */
  153674. 19,19,20,21,22,23,24, 25, /* 39dB */
  153675. }},
  153676. {{
  153677. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153678. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153679. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153680. 9,10,11,12,13,14,15, 16, /* 31dB */
  153681. 17,18,19,20,21,22,23, 24, /* 39dB */
  153682. }},
  153683. };
  153684. static double _psy_lowpass_8[3]={3.,4.,4.};
  153685. static int _noise_start_8[2]={
  153686. 64,64,
  153687. };
  153688. static int _noise_part_8[2]={
  153689. 8,8,
  153690. };
  153691. static int _psy_ath_floater_8[3]={
  153692. -100,-100,-105,
  153693. };
  153694. static int _psy_ath_abs_8[3]={
  153695. -130,-130,-140,
  153696. };
  153697. /*** End of inlined file: psych_8.h ***/
  153698. /*** Start of inlined file: residue_8.h ***/
  153699. /***** residue backends *********************************************/
  153700. static static_bookblock _resbook_8s_0={
  153701. {
  153702. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153703. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153704. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153705. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153706. }
  153707. };
  153708. static static_bookblock _resbook_8s_1={
  153709. {
  153710. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153711. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153712. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153713. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153714. }
  153715. };
  153716. static vorbis_residue_template _res_8s_0[]={
  153717. {2,0, &_residue_44_mid,
  153718. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153719. &_resbook_8s_0,&_resbook_8s_0},
  153720. };
  153721. static vorbis_residue_template _res_8s_1[]={
  153722. {2,0, &_residue_44_mid,
  153723. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153724. &_resbook_8s_1,&_resbook_8s_1},
  153725. };
  153726. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153727. { _map_nominal, _res_8s_0 }, /* 0 */
  153728. { _map_nominal, _res_8s_1 }, /* 1 */
  153729. };
  153730. static static_bookblock _resbook_8u_0={
  153731. {
  153732. {0},
  153733. {0,0,&_8u0__p1_0},
  153734. {0,0,&_8u0__p2_0},
  153735. {0,0,&_8u0__p3_0},
  153736. {0,0,&_8u0__p4_0},
  153737. {0,0,&_8u0__p5_0},
  153738. {&_8u0__p6_0,&_8u0__p6_1},
  153739. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153740. }
  153741. };
  153742. static static_bookblock _resbook_8u_1={
  153743. {
  153744. {0},
  153745. {0,0,&_8u1__p1_0},
  153746. {0,0,&_8u1__p2_0},
  153747. {0,0,&_8u1__p3_0},
  153748. {0,0,&_8u1__p4_0},
  153749. {0,0,&_8u1__p5_0},
  153750. {0,0,&_8u1__p6_0},
  153751. {&_8u1__p7_0,&_8u1__p7_1},
  153752. {&_8u1__p8_0,&_8u1__p8_1},
  153753. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153754. }
  153755. };
  153756. static vorbis_residue_template _res_8u_0[]={
  153757. {1,0, &_residue_44_low_un,
  153758. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153759. &_resbook_8u_0,&_resbook_8u_0},
  153760. };
  153761. static vorbis_residue_template _res_8u_1[]={
  153762. {1,0, &_residue_44_mid_un,
  153763. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153764. &_resbook_8u_1,&_resbook_8u_1},
  153765. };
  153766. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153767. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153768. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153769. };
  153770. /*** End of inlined file: residue_8.h ***/
  153771. static int blocksize_8[2]={
  153772. 512,512
  153773. };
  153774. static int _floor_mapping_8[2]={
  153775. 6,6,
  153776. };
  153777. static double rate_mapping_8[3]={
  153778. 6000.,9000.,32000.,
  153779. };
  153780. static double rate_mapping_8_uncoupled[3]={
  153781. 8000.,14000.,42000.,
  153782. };
  153783. static double quality_mapping_8[3]={
  153784. -.1,.0,1.
  153785. };
  153786. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153787. static double _global_mapping_8[3]={ 1., 2., 3. };
  153788. ve_setup_data_template ve_setup_8_stereo={
  153789. 2,
  153790. rate_mapping_8,
  153791. quality_mapping_8,
  153792. 2,
  153793. 8000,
  153794. 9000,
  153795. blocksize_8,
  153796. blocksize_8,
  153797. _psy_tone_masteratt_8,
  153798. _psy_tone_0dB,
  153799. _psy_tone_suppress,
  153800. _vp_tonemask_adj_8,
  153801. NULL,
  153802. _vp_tonemask_adj_8,
  153803. _psy_noiseguards_8,
  153804. _psy_noisebias_8,
  153805. _psy_noisebias_8,
  153806. NULL,
  153807. NULL,
  153808. _psy_noise_suppress,
  153809. _psy_compand_8,
  153810. _psy_compand_8_mapping,
  153811. NULL,
  153812. {_noise_start_8,_noise_start_8},
  153813. {_noise_part_8,_noise_part_8},
  153814. _noise_thresh_5only,
  153815. _psy_ath_floater_8,
  153816. _psy_ath_abs_8,
  153817. _psy_lowpass_8,
  153818. _psy_global_44,
  153819. _global_mapping_8,
  153820. _psy_stereo_modes_8,
  153821. _floor_books,
  153822. _floor,
  153823. _floor_mapping_8,
  153824. NULL,
  153825. _mapres_template_8_stereo
  153826. };
  153827. ve_setup_data_template ve_setup_8_uncoupled={
  153828. 2,
  153829. rate_mapping_8_uncoupled,
  153830. quality_mapping_8,
  153831. -1,
  153832. 8000,
  153833. 9000,
  153834. blocksize_8,
  153835. blocksize_8,
  153836. _psy_tone_masteratt_8,
  153837. _psy_tone_0dB,
  153838. _psy_tone_suppress,
  153839. _vp_tonemask_adj_8,
  153840. NULL,
  153841. _vp_tonemask_adj_8,
  153842. _psy_noiseguards_8,
  153843. _psy_noisebias_8,
  153844. _psy_noisebias_8,
  153845. NULL,
  153846. NULL,
  153847. _psy_noise_suppress,
  153848. _psy_compand_8,
  153849. _psy_compand_8_mapping,
  153850. NULL,
  153851. {_noise_start_8,_noise_start_8},
  153852. {_noise_part_8,_noise_part_8},
  153853. _noise_thresh_5only,
  153854. _psy_ath_floater_8,
  153855. _psy_ath_abs_8,
  153856. _psy_lowpass_8,
  153857. _psy_global_44,
  153858. _global_mapping_8,
  153859. _psy_stereo_modes_8,
  153860. _floor_books,
  153861. _floor,
  153862. _floor_mapping_8,
  153863. NULL,
  153864. _mapres_template_8_uncoupled
  153865. };
  153866. /*** End of inlined file: setup_8.h ***/
  153867. /*** Start of inlined file: setup_11.h ***/
  153868. /*** Start of inlined file: psych_11.h ***/
  153869. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153870. static att3 _psy_tone_masteratt_11[3]={
  153871. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153872. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153873. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153874. };
  153875. static vp_adjblock _vp_tonemask_adj_11[3]={
  153876. /* adjust for mode zero */
  153877. /* 63 125 250 500 1 2 4 8 16 */
  153878. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153879. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153880. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153881. };
  153882. static noise3 _psy_noisebias_11[3]={
  153883. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153884. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153885. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153886. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153887. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153888. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153889. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153890. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153891. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153892. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153893. };
  153894. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153895. /*** End of inlined file: psych_11.h ***/
  153896. static int blocksize_11[2]={
  153897. 512,512
  153898. };
  153899. static int _floor_mapping_11[2]={
  153900. 6,6,
  153901. };
  153902. static double rate_mapping_11[3]={
  153903. 8000.,13000.,44000.,
  153904. };
  153905. static double rate_mapping_11_uncoupled[3]={
  153906. 12000.,20000.,50000.,
  153907. };
  153908. static double quality_mapping_11[3]={
  153909. -.1,.0,1.
  153910. };
  153911. ve_setup_data_template ve_setup_11_stereo={
  153912. 2,
  153913. rate_mapping_11,
  153914. quality_mapping_11,
  153915. 2,
  153916. 9000,
  153917. 15000,
  153918. blocksize_11,
  153919. blocksize_11,
  153920. _psy_tone_masteratt_11,
  153921. _psy_tone_0dB,
  153922. _psy_tone_suppress,
  153923. _vp_tonemask_adj_11,
  153924. NULL,
  153925. _vp_tonemask_adj_11,
  153926. _psy_noiseguards_8,
  153927. _psy_noisebias_11,
  153928. _psy_noisebias_11,
  153929. NULL,
  153930. NULL,
  153931. _psy_noise_suppress,
  153932. _psy_compand_8,
  153933. _psy_compand_8_mapping,
  153934. NULL,
  153935. {_noise_start_8,_noise_start_8},
  153936. {_noise_part_8,_noise_part_8},
  153937. _noise_thresh_11,
  153938. _psy_ath_floater_8,
  153939. _psy_ath_abs_8,
  153940. _psy_lowpass_11,
  153941. _psy_global_44,
  153942. _global_mapping_8,
  153943. _psy_stereo_modes_8,
  153944. _floor_books,
  153945. _floor,
  153946. _floor_mapping_11,
  153947. NULL,
  153948. _mapres_template_8_stereo
  153949. };
  153950. ve_setup_data_template ve_setup_11_uncoupled={
  153951. 2,
  153952. rate_mapping_11_uncoupled,
  153953. quality_mapping_11,
  153954. -1,
  153955. 9000,
  153956. 15000,
  153957. blocksize_11,
  153958. blocksize_11,
  153959. _psy_tone_masteratt_11,
  153960. _psy_tone_0dB,
  153961. _psy_tone_suppress,
  153962. _vp_tonemask_adj_11,
  153963. NULL,
  153964. _vp_tonemask_adj_11,
  153965. _psy_noiseguards_8,
  153966. _psy_noisebias_11,
  153967. _psy_noisebias_11,
  153968. NULL,
  153969. NULL,
  153970. _psy_noise_suppress,
  153971. _psy_compand_8,
  153972. _psy_compand_8_mapping,
  153973. NULL,
  153974. {_noise_start_8,_noise_start_8},
  153975. {_noise_part_8,_noise_part_8},
  153976. _noise_thresh_11,
  153977. _psy_ath_floater_8,
  153978. _psy_ath_abs_8,
  153979. _psy_lowpass_11,
  153980. _psy_global_44,
  153981. _global_mapping_8,
  153982. _psy_stereo_modes_8,
  153983. _floor_books,
  153984. _floor,
  153985. _floor_mapping_11,
  153986. NULL,
  153987. _mapres_template_8_uncoupled
  153988. };
  153989. /*** End of inlined file: setup_11.h ***/
  153990. /*** Start of inlined file: setup_16.h ***/
  153991. /*** Start of inlined file: psych_16.h ***/
  153992. /* stereo mode by base quality level */
  153993. static adj_stereo _psy_stereo_modes_16[4]={
  153994. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153995. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153996. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153997. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153998. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153999. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154000. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154001. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154002. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154003. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154004. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154005. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154006. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154007. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154008. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154009. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154010. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154011. };
  154012. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154013. static att3 _psy_tone_masteratt_16[4]={
  154014. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154015. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154016. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154017. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154018. };
  154019. static vp_adjblock _vp_tonemask_adj_16[4]={
  154020. /* adjust for mode zero */
  154021. /* 63 125 250 500 1 2 4 8 16 */
  154022. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154023. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154024. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154025. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154026. };
  154027. static noise3 _psy_noisebias_16_short[4]={
  154028. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154029. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154030. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154031. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154032. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154033. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154034. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154035. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154036. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154037. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154038. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154039. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154040. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154041. };
  154042. static noise3 _psy_noisebias_16_impulse[4]={
  154043. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154044. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154045. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154046. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154047. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154048. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154049. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154050. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154051. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154052. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154053. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154054. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154055. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154056. };
  154057. static noise3 _psy_noisebias_16[4]={
  154058. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154059. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154060. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154061. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154062. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154063. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154064. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154065. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154066. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154067. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154068. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154069. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154070. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154071. };
  154072. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154073. static int _noise_start_16[3]={ 256,256,9999 };
  154074. static int _noise_part_16[4]={ 8,8,8,8 };
  154075. static int _psy_ath_floater_16[4]={
  154076. -100,-100,-100,-105,
  154077. };
  154078. static int _psy_ath_abs_16[4]={
  154079. -130,-130,-130,-140,
  154080. };
  154081. /*** End of inlined file: psych_16.h ***/
  154082. /*** Start of inlined file: residue_16.h ***/
  154083. /***** residue backends *********************************************/
  154084. static static_bookblock _resbook_16s_0={
  154085. {
  154086. {0},
  154087. {0,0,&_16c0_s_p1_0},
  154088. {0,0,&_16c0_s_p2_0},
  154089. {0,0,&_16c0_s_p3_0},
  154090. {0,0,&_16c0_s_p4_0},
  154091. {0,0,&_16c0_s_p5_0},
  154092. {0,0,&_16c0_s_p6_0},
  154093. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154094. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154095. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154096. }
  154097. };
  154098. static static_bookblock _resbook_16s_1={
  154099. {
  154100. {0},
  154101. {0,0,&_16c1_s_p1_0},
  154102. {0,0,&_16c1_s_p2_0},
  154103. {0,0,&_16c1_s_p3_0},
  154104. {0,0,&_16c1_s_p4_0},
  154105. {0,0,&_16c1_s_p5_0},
  154106. {0,0,&_16c1_s_p6_0},
  154107. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154108. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154109. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154110. }
  154111. };
  154112. static static_bookblock _resbook_16s_2={
  154113. {
  154114. {0},
  154115. {0,0,&_16c2_s_p1_0},
  154116. {0,0,&_16c2_s_p2_0},
  154117. {0,0,&_16c2_s_p3_0},
  154118. {0,0,&_16c2_s_p4_0},
  154119. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154120. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154121. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154122. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154123. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154124. }
  154125. };
  154126. static vorbis_residue_template _res_16s_0[]={
  154127. {2,0, &_residue_44_mid,
  154128. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154129. &_resbook_16s_0,&_resbook_16s_0},
  154130. };
  154131. static vorbis_residue_template _res_16s_1[]={
  154132. {2,0, &_residue_44_mid,
  154133. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154134. &_resbook_16s_1,&_resbook_16s_1},
  154135. {2,0, &_residue_44_mid,
  154136. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154137. &_resbook_16s_1,&_resbook_16s_1}
  154138. };
  154139. static vorbis_residue_template _res_16s_2[]={
  154140. {2,0, &_residue_44_high,
  154141. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154142. &_resbook_16s_2,&_resbook_16s_2},
  154143. {2,0, &_residue_44_high,
  154144. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154145. &_resbook_16s_2,&_resbook_16s_2}
  154146. };
  154147. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154148. { _map_nominal, _res_16s_0 }, /* 0 */
  154149. { _map_nominal, _res_16s_1 }, /* 1 */
  154150. { _map_nominal, _res_16s_2 }, /* 2 */
  154151. };
  154152. static static_bookblock _resbook_16u_0={
  154153. {
  154154. {0},
  154155. {0,0,&_16u0__p1_0},
  154156. {0,0,&_16u0__p2_0},
  154157. {0,0,&_16u0__p3_0},
  154158. {0,0,&_16u0__p4_0},
  154159. {0,0,&_16u0__p5_0},
  154160. {&_16u0__p6_0,&_16u0__p6_1},
  154161. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154162. }
  154163. };
  154164. static static_bookblock _resbook_16u_1={
  154165. {
  154166. {0},
  154167. {0,0,&_16u1__p1_0},
  154168. {0,0,&_16u1__p2_0},
  154169. {0,0,&_16u1__p3_0},
  154170. {0,0,&_16u1__p4_0},
  154171. {0,0,&_16u1__p5_0},
  154172. {0,0,&_16u1__p6_0},
  154173. {&_16u1__p7_0,&_16u1__p7_1},
  154174. {&_16u1__p8_0,&_16u1__p8_1},
  154175. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154176. }
  154177. };
  154178. static static_bookblock _resbook_16u_2={
  154179. {
  154180. {0},
  154181. {0,0,&_16u2_p1_0},
  154182. {0,0,&_16u2_p2_0},
  154183. {0,0,&_16u2_p3_0},
  154184. {0,0,&_16u2_p4_0},
  154185. {&_16u2_p5_0,&_16u2_p5_1},
  154186. {&_16u2_p6_0,&_16u2_p6_1},
  154187. {&_16u2_p7_0,&_16u2_p7_1},
  154188. {&_16u2_p8_0,&_16u2_p8_1},
  154189. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154190. }
  154191. };
  154192. static vorbis_residue_template _res_16u_0[]={
  154193. {1,0, &_residue_44_low_un,
  154194. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154195. &_resbook_16u_0,&_resbook_16u_0},
  154196. };
  154197. static vorbis_residue_template _res_16u_1[]={
  154198. {1,0, &_residue_44_mid_un,
  154199. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154200. &_resbook_16u_1,&_resbook_16u_1},
  154201. {1,0, &_residue_44_mid_un,
  154202. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154203. &_resbook_16u_1,&_resbook_16u_1}
  154204. };
  154205. static vorbis_residue_template _res_16u_2[]={
  154206. {1,0, &_residue_44_hi_un,
  154207. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154208. &_resbook_16u_2,&_resbook_16u_2},
  154209. {1,0, &_residue_44_hi_un,
  154210. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154211. &_resbook_16u_2,&_resbook_16u_2}
  154212. };
  154213. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154214. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154215. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154216. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154217. };
  154218. /*** End of inlined file: residue_16.h ***/
  154219. static int blocksize_16_short[3]={
  154220. 1024,512,512
  154221. };
  154222. static int blocksize_16_long[3]={
  154223. 1024,1024,1024
  154224. };
  154225. static int _floor_mapping_16_short[3]={
  154226. 9,3,3
  154227. };
  154228. static int _floor_mapping_16[3]={
  154229. 9,9,9
  154230. };
  154231. static double rate_mapping_16[4]={
  154232. 12000.,20000.,44000.,86000.
  154233. };
  154234. static double rate_mapping_16_uncoupled[4]={
  154235. 16000.,28000.,64000.,100000.
  154236. };
  154237. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154238. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154239. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154240. ve_setup_data_template ve_setup_16_stereo={
  154241. 3,
  154242. rate_mapping_16,
  154243. quality_mapping_16,
  154244. 2,
  154245. 15000,
  154246. 19000,
  154247. blocksize_16_short,
  154248. blocksize_16_long,
  154249. _psy_tone_masteratt_16,
  154250. _psy_tone_0dB,
  154251. _psy_tone_suppress,
  154252. _vp_tonemask_adj_16,
  154253. _vp_tonemask_adj_16,
  154254. _vp_tonemask_adj_16,
  154255. _psy_noiseguards_8,
  154256. _psy_noisebias_16_impulse,
  154257. _psy_noisebias_16_short,
  154258. _psy_noisebias_16_short,
  154259. _psy_noisebias_16,
  154260. _psy_noise_suppress,
  154261. _psy_compand_8,
  154262. _psy_compand_16_mapping,
  154263. _psy_compand_16_mapping,
  154264. {_noise_start_16,_noise_start_16},
  154265. { _noise_part_16, _noise_part_16},
  154266. _noise_thresh_16,
  154267. _psy_ath_floater_16,
  154268. _psy_ath_abs_16,
  154269. _psy_lowpass_16,
  154270. _psy_global_44,
  154271. _global_mapping_16,
  154272. _psy_stereo_modes_16,
  154273. _floor_books,
  154274. _floor,
  154275. _floor_mapping_16_short,
  154276. _floor_mapping_16,
  154277. _mapres_template_16_stereo
  154278. };
  154279. ve_setup_data_template ve_setup_16_uncoupled={
  154280. 3,
  154281. rate_mapping_16_uncoupled,
  154282. quality_mapping_16,
  154283. -1,
  154284. 15000,
  154285. 19000,
  154286. blocksize_16_short,
  154287. blocksize_16_long,
  154288. _psy_tone_masteratt_16,
  154289. _psy_tone_0dB,
  154290. _psy_tone_suppress,
  154291. _vp_tonemask_adj_16,
  154292. _vp_tonemask_adj_16,
  154293. _vp_tonemask_adj_16,
  154294. _psy_noiseguards_8,
  154295. _psy_noisebias_16_impulse,
  154296. _psy_noisebias_16_short,
  154297. _psy_noisebias_16_short,
  154298. _psy_noisebias_16,
  154299. _psy_noise_suppress,
  154300. _psy_compand_8,
  154301. _psy_compand_16_mapping,
  154302. _psy_compand_16_mapping,
  154303. {_noise_start_16,_noise_start_16},
  154304. { _noise_part_16, _noise_part_16},
  154305. _noise_thresh_16,
  154306. _psy_ath_floater_16,
  154307. _psy_ath_abs_16,
  154308. _psy_lowpass_16,
  154309. _psy_global_44,
  154310. _global_mapping_16,
  154311. _psy_stereo_modes_16,
  154312. _floor_books,
  154313. _floor,
  154314. _floor_mapping_16_short,
  154315. _floor_mapping_16,
  154316. _mapres_template_16_uncoupled
  154317. };
  154318. /*** End of inlined file: setup_16.h ***/
  154319. /*** Start of inlined file: setup_22.h ***/
  154320. static double rate_mapping_22[4]={
  154321. 15000.,20000.,44000.,86000.
  154322. };
  154323. static double rate_mapping_22_uncoupled[4]={
  154324. 16000.,28000.,50000.,90000.
  154325. };
  154326. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154327. ve_setup_data_template ve_setup_22_stereo={
  154328. 3,
  154329. rate_mapping_22,
  154330. quality_mapping_16,
  154331. 2,
  154332. 19000,
  154333. 26000,
  154334. blocksize_16_short,
  154335. blocksize_16_long,
  154336. _psy_tone_masteratt_16,
  154337. _psy_tone_0dB,
  154338. _psy_tone_suppress,
  154339. _vp_tonemask_adj_16,
  154340. _vp_tonemask_adj_16,
  154341. _vp_tonemask_adj_16,
  154342. _psy_noiseguards_8,
  154343. _psy_noisebias_16_impulse,
  154344. _psy_noisebias_16_short,
  154345. _psy_noisebias_16_short,
  154346. _psy_noisebias_16,
  154347. _psy_noise_suppress,
  154348. _psy_compand_8,
  154349. _psy_compand_8_mapping,
  154350. _psy_compand_8_mapping,
  154351. {_noise_start_16,_noise_start_16},
  154352. { _noise_part_16, _noise_part_16},
  154353. _noise_thresh_16,
  154354. _psy_ath_floater_16,
  154355. _psy_ath_abs_16,
  154356. _psy_lowpass_22,
  154357. _psy_global_44,
  154358. _global_mapping_16,
  154359. _psy_stereo_modes_16,
  154360. _floor_books,
  154361. _floor,
  154362. _floor_mapping_16_short,
  154363. _floor_mapping_16,
  154364. _mapres_template_16_stereo
  154365. };
  154366. ve_setup_data_template ve_setup_22_uncoupled={
  154367. 3,
  154368. rate_mapping_22_uncoupled,
  154369. quality_mapping_16,
  154370. -1,
  154371. 19000,
  154372. 26000,
  154373. blocksize_16_short,
  154374. blocksize_16_long,
  154375. _psy_tone_masteratt_16,
  154376. _psy_tone_0dB,
  154377. _psy_tone_suppress,
  154378. _vp_tonemask_adj_16,
  154379. _vp_tonemask_adj_16,
  154380. _vp_tonemask_adj_16,
  154381. _psy_noiseguards_8,
  154382. _psy_noisebias_16_impulse,
  154383. _psy_noisebias_16_short,
  154384. _psy_noisebias_16_short,
  154385. _psy_noisebias_16,
  154386. _psy_noise_suppress,
  154387. _psy_compand_8,
  154388. _psy_compand_8_mapping,
  154389. _psy_compand_8_mapping,
  154390. {_noise_start_16,_noise_start_16},
  154391. { _noise_part_16, _noise_part_16},
  154392. _noise_thresh_16,
  154393. _psy_ath_floater_16,
  154394. _psy_ath_abs_16,
  154395. _psy_lowpass_22,
  154396. _psy_global_44,
  154397. _global_mapping_16,
  154398. _psy_stereo_modes_16,
  154399. _floor_books,
  154400. _floor,
  154401. _floor_mapping_16_short,
  154402. _floor_mapping_16,
  154403. _mapres_template_16_uncoupled
  154404. };
  154405. /*** End of inlined file: setup_22.h ***/
  154406. /*** Start of inlined file: setup_X.h ***/
  154407. static double rate_mapping_X[12]={
  154408. -1.,-1.,-1.,-1.,-1.,-1.,
  154409. -1.,-1.,-1.,-1.,-1.,-1.
  154410. };
  154411. ve_setup_data_template ve_setup_X_stereo={
  154412. 11,
  154413. rate_mapping_X,
  154414. quality_mapping_44,
  154415. 2,
  154416. 50000,
  154417. 200000,
  154418. blocksize_short_44,
  154419. blocksize_long_44,
  154420. _psy_tone_masteratt_44,
  154421. _psy_tone_0dB,
  154422. _psy_tone_suppress,
  154423. _vp_tonemask_adj_otherblock,
  154424. _vp_tonemask_adj_longblock,
  154425. _vp_tonemask_adj_otherblock,
  154426. _psy_noiseguards_44,
  154427. _psy_noisebias_impulse,
  154428. _psy_noisebias_padding,
  154429. _psy_noisebias_trans,
  154430. _psy_noisebias_long,
  154431. _psy_noise_suppress,
  154432. _psy_compand_44,
  154433. _psy_compand_short_mapping,
  154434. _psy_compand_long_mapping,
  154435. {_noise_start_short_44,_noise_start_long_44},
  154436. {_noise_part_short_44,_noise_part_long_44},
  154437. _noise_thresh_44,
  154438. _psy_ath_floater,
  154439. _psy_ath_abs,
  154440. _psy_lowpass_44,
  154441. _psy_global_44,
  154442. _global_mapping_44,
  154443. _psy_stereo_modes_44,
  154444. _floor_books,
  154445. _floor,
  154446. _floor_short_mapping_44,
  154447. _floor_long_mapping_44,
  154448. _mapres_template_44_stereo
  154449. };
  154450. ve_setup_data_template ve_setup_X_uncoupled={
  154451. 11,
  154452. rate_mapping_X,
  154453. quality_mapping_44,
  154454. -1,
  154455. 50000,
  154456. 200000,
  154457. blocksize_short_44,
  154458. blocksize_long_44,
  154459. _psy_tone_masteratt_44,
  154460. _psy_tone_0dB,
  154461. _psy_tone_suppress,
  154462. _vp_tonemask_adj_otherblock,
  154463. _vp_tonemask_adj_longblock,
  154464. _vp_tonemask_adj_otherblock,
  154465. _psy_noiseguards_44,
  154466. _psy_noisebias_impulse,
  154467. _psy_noisebias_padding,
  154468. _psy_noisebias_trans,
  154469. _psy_noisebias_long,
  154470. _psy_noise_suppress,
  154471. _psy_compand_44,
  154472. _psy_compand_short_mapping,
  154473. _psy_compand_long_mapping,
  154474. {_noise_start_short_44,_noise_start_long_44},
  154475. {_noise_part_short_44,_noise_part_long_44},
  154476. _noise_thresh_44,
  154477. _psy_ath_floater,
  154478. _psy_ath_abs,
  154479. _psy_lowpass_44,
  154480. _psy_global_44,
  154481. _global_mapping_44,
  154482. NULL,
  154483. _floor_books,
  154484. _floor,
  154485. _floor_short_mapping_44,
  154486. _floor_long_mapping_44,
  154487. _mapres_template_44_uncoupled
  154488. };
  154489. ve_setup_data_template ve_setup_XX_stereo={
  154490. 2,
  154491. rate_mapping_X,
  154492. quality_mapping_8,
  154493. 2,
  154494. 0,
  154495. 8000,
  154496. blocksize_8,
  154497. blocksize_8,
  154498. _psy_tone_masteratt_8,
  154499. _psy_tone_0dB,
  154500. _psy_tone_suppress,
  154501. _vp_tonemask_adj_8,
  154502. NULL,
  154503. _vp_tonemask_adj_8,
  154504. _psy_noiseguards_8,
  154505. _psy_noisebias_8,
  154506. _psy_noisebias_8,
  154507. NULL,
  154508. NULL,
  154509. _psy_noise_suppress,
  154510. _psy_compand_8,
  154511. _psy_compand_8_mapping,
  154512. NULL,
  154513. {_noise_start_8,_noise_start_8},
  154514. {_noise_part_8,_noise_part_8},
  154515. _noise_thresh_5only,
  154516. _psy_ath_floater_8,
  154517. _psy_ath_abs_8,
  154518. _psy_lowpass_8,
  154519. _psy_global_44,
  154520. _global_mapping_8,
  154521. _psy_stereo_modes_8,
  154522. _floor_books,
  154523. _floor,
  154524. _floor_mapping_8,
  154525. NULL,
  154526. _mapres_template_8_stereo
  154527. };
  154528. ve_setup_data_template ve_setup_XX_uncoupled={
  154529. 2,
  154530. rate_mapping_X,
  154531. quality_mapping_8,
  154532. -1,
  154533. 0,
  154534. 8000,
  154535. blocksize_8,
  154536. blocksize_8,
  154537. _psy_tone_masteratt_8,
  154538. _psy_tone_0dB,
  154539. _psy_tone_suppress,
  154540. _vp_tonemask_adj_8,
  154541. NULL,
  154542. _vp_tonemask_adj_8,
  154543. _psy_noiseguards_8,
  154544. _psy_noisebias_8,
  154545. _psy_noisebias_8,
  154546. NULL,
  154547. NULL,
  154548. _psy_noise_suppress,
  154549. _psy_compand_8,
  154550. _psy_compand_8_mapping,
  154551. NULL,
  154552. {_noise_start_8,_noise_start_8},
  154553. {_noise_part_8,_noise_part_8},
  154554. _noise_thresh_5only,
  154555. _psy_ath_floater_8,
  154556. _psy_ath_abs_8,
  154557. _psy_lowpass_8,
  154558. _psy_global_44,
  154559. _global_mapping_8,
  154560. _psy_stereo_modes_8,
  154561. _floor_books,
  154562. _floor,
  154563. _floor_mapping_8,
  154564. NULL,
  154565. _mapres_template_8_uncoupled
  154566. };
  154567. /*** End of inlined file: setup_X.h ***/
  154568. static ve_setup_data_template *setup_list[]={
  154569. &ve_setup_44_stereo,
  154570. &ve_setup_44_uncoupled,
  154571. &ve_setup_32_stereo,
  154572. &ve_setup_32_uncoupled,
  154573. &ve_setup_22_stereo,
  154574. &ve_setup_22_uncoupled,
  154575. &ve_setup_16_stereo,
  154576. &ve_setup_16_uncoupled,
  154577. &ve_setup_11_stereo,
  154578. &ve_setup_11_uncoupled,
  154579. &ve_setup_8_stereo,
  154580. &ve_setup_8_uncoupled,
  154581. &ve_setup_X_stereo,
  154582. &ve_setup_X_uncoupled,
  154583. &ve_setup_XX_stereo,
  154584. &ve_setup_XX_uncoupled,
  154585. 0
  154586. };
  154587. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154588. if(vi && vi->codec_setup){
  154589. vi->version=0;
  154590. vi->channels=ch;
  154591. vi->rate=rate;
  154592. return(0);
  154593. }
  154594. return(OV_EINVAL);
  154595. }
  154596. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154597. static_codebook ***books,
  154598. vorbis_info_floor1 *in,
  154599. int *x){
  154600. int i,k,is=s;
  154601. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154602. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154603. memcpy(f,in+x[is],sizeof(*f));
  154604. /* fill in the lowpass field, even if it's temporary */
  154605. f->n=ci->blocksizes[block]>>1;
  154606. /* books */
  154607. {
  154608. int partitions=f->partitions;
  154609. int maxclass=-1;
  154610. int maxbook=-1;
  154611. for(i=0;i<partitions;i++)
  154612. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154613. for(i=0;i<=maxclass;i++){
  154614. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154615. f->class_book[i]+=ci->books;
  154616. for(k=0;k<(1<<f->class_subs[i]);k++){
  154617. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154618. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154619. }
  154620. }
  154621. for(i=0;i<=maxbook;i++)
  154622. ci->book_param[ci->books++]=books[x[is]][i];
  154623. }
  154624. /* for now, we're only using floor 1 */
  154625. ci->floor_type[ci->floors]=1;
  154626. ci->floor_param[ci->floors]=f;
  154627. ci->floors++;
  154628. return;
  154629. }
  154630. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154631. vorbis_info_psy_global *in,
  154632. double *x){
  154633. int i,is=s;
  154634. double ds=s-is;
  154635. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154636. vorbis_info_psy_global *g=&ci->psy_g_param;
  154637. memcpy(g,in+(int)x[is],sizeof(*g));
  154638. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154639. is=(int)ds;
  154640. ds-=is;
  154641. if(ds==0 && is>0){
  154642. is--;
  154643. ds=1.;
  154644. }
  154645. /* interpolate the trigger threshholds */
  154646. for(i=0;i<4;i++){
  154647. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154648. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154649. }
  154650. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154651. return;
  154652. }
  154653. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154654. highlevel_encode_setup *hi,
  154655. adj_stereo *p){
  154656. float s=hi->stereo_point_setting;
  154657. int i,is=s;
  154658. double ds=s-is;
  154659. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154660. vorbis_info_psy_global *g=&ci->psy_g_param;
  154661. if(p){
  154662. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154663. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154664. if(hi->managed){
  154665. /* interpolate the kHz threshholds */
  154666. for(i=0;i<PACKETBLOBS;i++){
  154667. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154668. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154669. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154670. g->coupling_pkHz[i]=kHz;
  154671. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154672. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154673. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154674. }
  154675. }else{
  154676. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154677. for(i=0;i<PACKETBLOBS;i++){
  154678. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154679. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154680. g->coupling_pkHz[i]=kHz;
  154681. }
  154682. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154683. for(i=0;i<PACKETBLOBS;i++){
  154684. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154685. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154686. }
  154687. }
  154688. }else{
  154689. for(i=0;i<PACKETBLOBS;i++){
  154690. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154691. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154692. }
  154693. }
  154694. return;
  154695. }
  154696. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154697. int *nn_start,
  154698. int *nn_partition,
  154699. double *nn_thresh,
  154700. int block){
  154701. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154702. vorbis_info_psy *p=ci->psy_param[block];
  154703. highlevel_encode_setup *hi=&ci->hi;
  154704. int is=s;
  154705. if(block>=ci->psys)
  154706. ci->psys=block+1;
  154707. if(!p){
  154708. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154709. ci->psy_param[block]=p;
  154710. }
  154711. memcpy(p,&_psy_info_template,sizeof(*p));
  154712. p->blockflag=block>>1;
  154713. if(hi->noise_normalize_p){
  154714. p->normal_channel_p=1;
  154715. p->normal_point_p=1;
  154716. p->normal_start=nn_start[is];
  154717. p->normal_partition=nn_partition[is];
  154718. p->normal_thresh=nn_thresh[is];
  154719. }
  154720. return;
  154721. }
  154722. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154723. att3 *att,
  154724. int *max,
  154725. vp_adjblock *in){
  154726. int i,is=s;
  154727. double ds=s-is;
  154728. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154729. vorbis_info_psy *p=ci->psy_param[block];
  154730. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154731. filling the values in here */
  154732. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154733. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154734. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154735. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154736. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154737. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154738. for(i=0;i<P_BANDS;i++)
  154739. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154740. return;
  154741. }
  154742. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154743. compandblock *in, double *x){
  154744. int i,is=s;
  154745. double ds=s-is;
  154746. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154747. vorbis_info_psy *p=ci->psy_param[block];
  154748. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154749. is=(int)ds;
  154750. ds-=is;
  154751. if(ds==0 && is>0){
  154752. is--;
  154753. ds=1.;
  154754. }
  154755. /* interpolate the compander settings */
  154756. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154757. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154758. return;
  154759. }
  154760. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154761. int *suppress){
  154762. int is=s;
  154763. double ds=s-is;
  154764. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154765. vorbis_info_psy *p=ci->psy_param[block];
  154766. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154767. return;
  154768. }
  154769. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154770. int *suppress,
  154771. noise3 *in,
  154772. noiseguard *guard,
  154773. double userbias){
  154774. int i,is=s,j;
  154775. double ds=s-is;
  154776. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154777. vorbis_info_psy *p=ci->psy_param[block];
  154778. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154779. p->noisewindowlomin=guard[block].lo;
  154780. p->noisewindowhimin=guard[block].hi;
  154781. p->noisewindowfixed=guard[block].fixed;
  154782. for(j=0;j<P_NOISECURVES;j++)
  154783. for(i=0;i<P_BANDS;i++)
  154784. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154785. /* impulse blocks may take a user specified bias to boost the
  154786. nominal/high noise encoding depth */
  154787. for(j=0;j<P_NOISECURVES;j++){
  154788. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154789. for(i=0;i<P_BANDS;i++){
  154790. p->noiseoff[j][i]+=userbias;
  154791. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154792. }
  154793. }
  154794. return;
  154795. }
  154796. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154797. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154798. vorbis_info_psy *p=ci->psy_param[block];
  154799. p->ath_adjatt=ci->hi.ath_floating_dB;
  154800. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154801. return;
  154802. }
  154803. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154804. int i;
  154805. for(i=0;i<ci->books;i++)
  154806. if(ci->book_param[i]==book)return(i);
  154807. return(ci->books++);
  154808. }
  154809. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154810. int *shortb,int *longb){
  154811. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154812. int is=s;
  154813. int blockshort=shortb[is];
  154814. int blocklong=longb[is];
  154815. ci->blocksizes[0]=blockshort;
  154816. ci->blocksizes[1]=blocklong;
  154817. }
  154818. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154819. int number, int block,
  154820. vorbis_residue_template *res){
  154821. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154822. int i,n;
  154823. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154824. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154825. memcpy(r,res->res,sizeof(*r));
  154826. if(ci->residues<=number)ci->residues=number+1;
  154827. switch(ci->blocksizes[block]){
  154828. case 64:case 128:case 256:
  154829. r->grouping=16;
  154830. break;
  154831. default:
  154832. r->grouping=32;
  154833. break;
  154834. }
  154835. ci->residue_type[number]=res->res_type;
  154836. /* to be adjusted by lowpass/pointlimit later */
  154837. n=r->end=ci->blocksizes[block]>>1;
  154838. if(res->res_type==2)
  154839. n=r->end*=vi->channels;
  154840. /* fill in all the books */
  154841. {
  154842. int booklist=0,k;
  154843. if(ci->hi.managed){
  154844. for(i=0;i<r->partitions;i++)
  154845. for(k=0;k<3;k++)
  154846. if(res->books_base_managed->books[i][k])
  154847. r->secondstages[i]|=(1<<k);
  154848. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154849. ci->book_param[r->groupbook]=res->book_aux_managed;
  154850. for(i=0;i<r->partitions;i++){
  154851. for(k=0;k<3;k++){
  154852. if(res->books_base_managed->books[i][k]){
  154853. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154854. r->booklist[booklist++]=bookid;
  154855. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154856. }
  154857. }
  154858. }
  154859. }else{
  154860. for(i=0;i<r->partitions;i++)
  154861. for(k=0;k<3;k++)
  154862. if(res->books_base->books[i][k])
  154863. r->secondstages[i]|=(1<<k);
  154864. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154865. ci->book_param[r->groupbook]=res->book_aux;
  154866. for(i=0;i<r->partitions;i++){
  154867. for(k=0;k<3;k++){
  154868. if(res->books_base->books[i][k]){
  154869. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154870. r->booklist[booklist++]=bookid;
  154871. ci->book_param[bookid]=res->books_base->books[i][k];
  154872. }
  154873. }
  154874. }
  154875. }
  154876. }
  154877. /* lowpass setup/pointlimit */
  154878. {
  154879. double freq=ci->hi.lowpass_kHz*1000.;
  154880. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154881. double nyq=vi->rate/2.;
  154882. long blocksize=ci->blocksizes[block]>>1;
  154883. /* lowpass needs to be set in the floor and the residue. */
  154884. if(freq>nyq)freq=nyq;
  154885. /* in the floor, the granularity can be very fine; it doesn't alter
  154886. the encoding structure, only the samples used to fit the floor
  154887. approximation */
  154888. f->n=freq/nyq*blocksize;
  154889. /* this res may by limited by the maximum pointlimit of the mode,
  154890. not the lowpass. the floor is always lowpass limited. */
  154891. if(res->limit_type){
  154892. if(ci->hi.managed)
  154893. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154894. else
  154895. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154896. if(freq>nyq)freq=nyq;
  154897. }
  154898. /* in the residue, we're constrained, physically, by partition
  154899. boundaries. We still lowpass 'wherever', but we have to round up
  154900. here to next boundary, or the vorbis spec will round it *down* to
  154901. previous boundary in encode/decode */
  154902. if(ci->residue_type[block]==2)
  154903. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154904. r->grouping;
  154905. else
  154906. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154907. r->grouping;
  154908. }
  154909. }
  154910. /* we assume two maps in this encoder */
  154911. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154912. vorbis_mapping_template *maps){
  154913. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154914. int i,j,is=s,modes=2;
  154915. vorbis_info_mapping0 *map=maps[is].map;
  154916. vorbis_info_mode *mode=_mode_template;
  154917. vorbis_residue_template *res=maps[is].res;
  154918. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154919. for(i=0;i<modes;i++){
  154920. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154921. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154922. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154923. if(i>=ci->modes)ci->modes=i+1;
  154924. ci->map_type[i]=0;
  154925. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154926. if(i>=ci->maps)ci->maps=i+1;
  154927. for(j=0;j<map[i].submaps;j++)
  154928. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154929. ,res+map[i].residuesubmap[j]);
  154930. }
  154931. }
  154932. static double setting_to_approx_bitrate(vorbis_info *vi){
  154933. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154934. highlevel_encode_setup *hi=&ci->hi;
  154935. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154936. int is=hi->base_setting;
  154937. double ds=hi->base_setting-is;
  154938. int ch=vi->channels;
  154939. double *r=setup->rate_mapping;
  154940. if(r==NULL)
  154941. return(-1);
  154942. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154943. }
  154944. static void get_setup_template(vorbis_info *vi,
  154945. long ch,long srate,
  154946. double req,int q_or_bitrate){
  154947. int i=0,j;
  154948. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154949. highlevel_encode_setup *hi=&ci->hi;
  154950. if(q_or_bitrate)req/=ch;
  154951. while(setup_list[i]){
  154952. if(setup_list[i]->coupling_restriction==-1 ||
  154953. setup_list[i]->coupling_restriction==ch){
  154954. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154955. srate<=setup_list[i]->samplerate_max_restriction){
  154956. int mappings=setup_list[i]->mappings;
  154957. double *map=(q_or_bitrate?
  154958. setup_list[i]->rate_mapping:
  154959. setup_list[i]->quality_mapping);
  154960. /* the template matches. Does the requested quality mode
  154961. fall within this template's modes? */
  154962. if(req<map[0]){++i;continue;}
  154963. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154964. for(j=0;j<mappings;j++)
  154965. if(req>=map[j] && req<map[j+1])break;
  154966. /* an all-points match */
  154967. hi->setup=setup_list[i];
  154968. if(j==mappings)
  154969. hi->base_setting=j-.001;
  154970. else{
  154971. float low=map[j];
  154972. float high=map[j+1];
  154973. float del=(req-low)/(high-low);
  154974. hi->base_setting=j+del;
  154975. }
  154976. return;
  154977. }
  154978. }
  154979. i++;
  154980. }
  154981. hi->setup=NULL;
  154982. }
  154983. /* encoders will need to use vorbis_info_init beforehand and call
  154984. vorbis_info clear when all done */
  154985. /* two interfaces; this, more detailed one, and later a convenience
  154986. layer on top */
  154987. /* the final setup call */
  154988. int vorbis_encode_setup_init(vorbis_info *vi){
  154989. int i0=0,singleblock=0;
  154990. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154991. ve_setup_data_template *setup=NULL;
  154992. highlevel_encode_setup *hi=&ci->hi;
  154993. if(ci==NULL)return(OV_EINVAL);
  154994. if(!hi->impulse_block_p)i0=1;
  154995. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154996. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154997. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154998. /* again, bound this to avoid the app shooting itself int he foot
  154999. too badly */
  155000. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155001. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155002. /* get the appropriate setup template; matches the fetch in previous
  155003. stages */
  155004. setup=(ve_setup_data_template *)hi->setup;
  155005. if(setup==NULL)return(OV_EINVAL);
  155006. hi->set_in_stone=1;
  155007. /* choose block sizes from configured sizes as well as paying
  155008. attention to long_block_p and short_block_p. If the configured
  155009. short and long blocks are the same length, we set long_block_p
  155010. and unset short_block_p */
  155011. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155012. setup->blocksize_short,
  155013. setup->blocksize_long);
  155014. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155015. /* floor setup; choose proper floor params. Allocated on the floor
  155016. stack in order; if we alloc only long floor, it's 0 */
  155017. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155018. setup->floor_books,
  155019. setup->floor_params,
  155020. setup->floor_short_mapping);
  155021. if(!singleblock)
  155022. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155023. setup->floor_books,
  155024. setup->floor_params,
  155025. setup->floor_long_mapping);
  155026. /* setup of [mostly] short block detection and stereo*/
  155027. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155028. setup->global_params,
  155029. setup->global_mapping);
  155030. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155031. /* basic psych setup and noise normalization */
  155032. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155033. setup->psy_noise_normal_start[0],
  155034. setup->psy_noise_normal_partition[0],
  155035. setup->psy_noise_normal_thresh,
  155036. 0);
  155037. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155038. setup->psy_noise_normal_start[0],
  155039. setup->psy_noise_normal_partition[0],
  155040. setup->psy_noise_normal_thresh,
  155041. 1);
  155042. if(!singleblock){
  155043. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155044. setup->psy_noise_normal_start[1],
  155045. setup->psy_noise_normal_partition[1],
  155046. setup->psy_noise_normal_thresh,
  155047. 2);
  155048. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155049. setup->psy_noise_normal_start[1],
  155050. setup->psy_noise_normal_partition[1],
  155051. setup->psy_noise_normal_thresh,
  155052. 3);
  155053. }
  155054. /* tone masking setup */
  155055. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155056. setup->psy_tone_masteratt,
  155057. setup->psy_tone_0dB,
  155058. setup->psy_tone_adj_impulse);
  155059. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155060. setup->psy_tone_masteratt,
  155061. setup->psy_tone_0dB,
  155062. setup->psy_tone_adj_other);
  155063. if(!singleblock){
  155064. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155065. setup->psy_tone_masteratt,
  155066. setup->psy_tone_0dB,
  155067. setup->psy_tone_adj_other);
  155068. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155069. setup->psy_tone_masteratt,
  155070. setup->psy_tone_0dB,
  155071. setup->psy_tone_adj_long);
  155072. }
  155073. /* noise companding setup */
  155074. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155075. setup->psy_noise_compand,
  155076. setup->psy_noise_compand_short_mapping);
  155077. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155078. setup->psy_noise_compand,
  155079. setup->psy_noise_compand_short_mapping);
  155080. if(!singleblock){
  155081. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155082. setup->psy_noise_compand,
  155083. setup->psy_noise_compand_long_mapping);
  155084. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155085. setup->psy_noise_compand,
  155086. setup->psy_noise_compand_long_mapping);
  155087. }
  155088. /* peak guarding setup */
  155089. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155090. setup->psy_tone_dBsuppress);
  155091. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155092. setup->psy_tone_dBsuppress);
  155093. if(!singleblock){
  155094. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155095. setup->psy_tone_dBsuppress);
  155096. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155097. setup->psy_tone_dBsuppress);
  155098. }
  155099. /* noise bias setup */
  155100. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155101. setup->psy_noise_dBsuppress,
  155102. setup->psy_noise_bias_impulse,
  155103. setup->psy_noiseguards,
  155104. (i0==0?hi->impulse_noisetune:0.));
  155105. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155106. setup->psy_noise_dBsuppress,
  155107. setup->psy_noise_bias_padding,
  155108. setup->psy_noiseguards,0.);
  155109. if(!singleblock){
  155110. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155111. setup->psy_noise_dBsuppress,
  155112. setup->psy_noise_bias_trans,
  155113. setup->psy_noiseguards,0.);
  155114. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155115. setup->psy_noise_dBsuppress,
  155116. setup->psy_noise_bias_long,
  155117. setup->psy_noiseguards,0.);
  155118. }
  155119. vorbis_encode_ath_setup(vi,0);
  155120. vorbis_encode_ath_setup(vi,1);
  155121. if(!singleblock){
  155122. vorbis_encode_ath_setup(vi,2);
  155123. vorbis_encode_ath_setup(vi,3);
  155124. }
  155125. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155126. /* set bitrate readonlies and management */
  155127. if(hi->bitrate_av>0)
  155128. vi->bitrate_nominal=hi->bitrate_av;
  155129. else{
  155130. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155131. }
  155132. vi->bitrate_lower=hi->bitrate_min;
  155133. vi->bitrate_upper=hi->bitrate_max;
  155134. if(hi->bitrate_av)
  155135. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155136. else
  155137. vi->bitrate_window=0.;
  155138. if(hi->managed){
  155139. ci->bi.avg_rate=hi->bitrate_av;
  155140. ci->bi.min_rate=hi->bitrate_min;
  155141. ci->bi.max_rate=hi->bitrate_max;
  155142. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155143. ci->bi.reservoir_bias=
  155144. hi->bitrate_reservoir_bias;
  155145. ci->bi.slew_damp=hi->bitrate_av_damp;
  155146. }
  155147. return(0);
  155148. }
  155149. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155150. long channels,
  155151. long rate){
  155152. int ret=0,i,is;
  155153. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155154. highlevel_encode_setup *hi=&ci->hi;
  155155. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155156. double ds;
  155157. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155158. if(ret)return(ret);
  155159. is=hi->base_setting;
  155160. ds=hi->base_setting-is;
  155161. hi->short_setting=hi->base_setting;
  155162. hi->long_setting=hi->base_setting;
  155163. hi->managed=0;
  155164. hi->impulse_block_p=1;
  155165. hi->noise_normalize_p=1;
  155166. hi->stereo_point_setting=hi->base_setting;
  155167. hi->lowpass_kHz=
  155168. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155169. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155170. setup->psy_ath_float[is+1]*ds;
  155171. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155172. setup->psy_ath_abs[is+1]*ds;
  155173. hi->amplitude_track_dBpersec=-6.;
  155174. hi->trigger_setting=hi->base_setting;
  155175. for(i=0;i<4;i++){
  155176. hi->block[i].tone_mask_setting=hi->base_setting;
  155177. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155178. hi->block[i].noise_bias_setting=hi->base_setting;
  155179. hi->block[i].noise_compand_setting=hi->base_setting;
  155180. }
  155181. return(ret);
  155182. }
  155183. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155184. long channels,
  155185. long rate,
  155186. float quality){
  155187. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155188. highlevel_encode_setup *hi=&ci->hi;
  155189. quality+=.0000001;
  155190. if(quality>=1.)quality=.9999;
  155191. get_setup_template(vi,channels,rate,quality,0);
  155192. if(!hi->setup)return OV_EIMPL;
  155193. return vorbis_encode_setup_setting(vi,channels,rate);
  155194. }
  155195. int vorbis_encode_init_vbr(vorbis_info *vi,
  155196. long channels,
  155197. long rate,
  155198. float base_quality /* 0. to 1. */
  155199. ){
  155200. int ret=0;
  155201. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155202. if(ret){
  155203. vorbis_info_clear(vi);
  155204. return ret;
  155205. }
  155206. ret=vorbis_encode_setup_init(vi);
  155207. if(ret)
  155208. vorbis_info_clear(vi);
  155209. return(ret);
  155210. }
  155211. int vorbis_encode_setup_managed(vorbis_info *vi,
  155212. long channels,
  155213. long rate,
  155214. long max_bitrate,
  155215. long nominal_bitrate,
  155216. long min_bitrate){
  155217. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155218. highlevel_encode_setup *hi=&ci->hi;
  155219. double tnominal=nominal_bitrate;
  155220. int ret=0;
  155221. if(nominal_bitrate<=0.){
  155222. if(max_bitrate>0.){
  155223. if(min_bitrate>0.)
  155224. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155225. else
  155226. nominal_bitrate=max_bitrate*.875;
  155227. }else{
  155228. if(min_bitrate>0.){
  155229. nominal_bitrate=min_bitrate;
  155230. }else{
  155231. return(OV_EINVAL);
  155232. }
  155233. }
  155234. }
  155235. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155236. if(!hi->setup)return OV_EIMPL;
  155237. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155238. if(ret){
  155239. vorbis_info_clear(vi);
  155240. return ret;
  155241. }
  155242. /* initialize management with sane defaults */
  155243. hi->managed=1;
  155244. hi->bitrate_min=min_bitrate;
  155245. hi->bitrate_max=max_bitrate;
  155246. hi->bitrate_av=tnominal;
  155247. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155248. hi->bitrate_reservoir=nominal_bitrate*2;
  155249. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155250. return(ret);
  155251. }
  155252. int vorbis_encode_init(vorbis_info *vi,
  155253. long channels,
  155254. long rate,
  155255. long max_bitrate,
  155256. long nominal_bitrate,
  155257. long min_bitrate){
  155258. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155259. max_bitrate,
  155260. nominal_bitrate,
  155261. min_bitrate);
  155262. if(ret){
  155263. vorbis_info_clear(vi);
  155264. return(ret);
  155265. }
  155266. ret=vorbis_encode_setup_init(vi);
  155267. if(ret)
  155268. vorbis_info_clear(vi);
  155269. return(ret);
  155270. }
  155271. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155272. if(vi){
  155273. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155274. highlevel_encode_setup *hi=&ci->hi;
  155275. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155276. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155277. switch(number){
  155278. /* now deprecated *****************/
  155279. case OV_ECTL_RATEMANAGE_GET:
  155280. {
  155281. struct ovectl_ratemanage_arg *ai=
  155282. (struct ovectl_ratemanage_arg *)arg;
  155283. ai->management_active=hi->managed;
  155284. ai->bitrate_hard_window=ai->bitrate_av_window=
  155285. (double)hi->bitrate_reservoir/vi->rate;
  155286. ai->bitrate_av_window_center=1.;
  155287. ai->bitrate_hard_min=hi->bitrate_min;
  155288. ai->bitrate_hard_max=hi->bitrate_max;
  155289. ai->bitrate_av_lo=hi->bitrate_av;
  155290. ai->bitrate_av_hi=hi->bitrate_av;
  155291. }
  155292. return(0);
  155293. /* now deprecated *****************/
  155294. case OV_ECTL_RATEMANAGE_SET:
  155295. {
  155296. struct ovectl_ratemanage_arg *ai=
  155297. (struct ovectl_ratemanage_arg *)arg;
  155298. if(ai==NULL){
  155299. hi->managed=0;
  155300. }else{
  155301. hi->managed=ai->management_active;
  155302. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155303. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155304. }
  155305. }
  155306. return 0;
  155307. /* now deprecated *****************/
  155308. case OV_ECTL_RATEMANAGE_AVG:
  155309. {
  155310. struct ovectl_ratemanage_arg *ai=
  155311. (struct ovectl_ratemanage_arg *)arg;
  155312. if(ai==NULL){
  155313. hi->bitrate_av=0;
  155314. }else{
  155315. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155316. }
  155317. }
  155318. return(0);
  155319. /* now deprecated *****************/
  155320. case OV_ECTL_RATEMANAGE_HARD:
  155321. {
  155322. struct ovectl_ratemanage_arg *ai=
  155323. (struct ovectl_ratemanage_arg *)arg;
  155324. if(ai==NULL){
  155325. hi->bitrate_min=0;
  155326. hi->bitrate_max=0;
  155327. }else{
  155328. hi->bitrate_min=ai->bitrate_hard_min;
  155329. hi->bitrate_max=ai->bitrate_hard_max;
  155330. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155331. (hi->bitrate_max+hi->bitrate_min)*.5;
  155332. }
  155333. if(hi->bitrate_reservoir<128.)
  155334. hi->bitrate_reservoir=128.;
  155335. }
  155336. return(0);
  155337. /* replacement ratemanage interface */
  155338. case OV_ECTL_RATEMANAGE2_GET:
  155339. {
  155340. struct ovectl_ratemanage2_arg *ai=
  155341. (struct ovectl_ratemanage2_arg *)arg;
  155342. if(ai==NULL)return OV_EINVAL;
  155343. ai->management_active=hi->managed;
  155344. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155345. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155346. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155347. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155348. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155349. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155350. }
  155351. return (0);
  155352. case OV_ECTL_RATEMANAGE2_SET:
  155353. {
  155354. struct ovectl_ratemanage2_arg *ai=
  155355. (struct ovectl_ratemanage2_arg *)arg;
  155356. if(ai==NULL){
  155357. hi->managed=0;
  155358. }else{
  155359. /* sanity check; only catch invariant violations */
  155360. if(ai->bitrate_limit_min_kbps>0 &&
  155361. ai->bitrate_average_kbps>0 &&
  155362. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155363. return OV_EINVAL;
  155364. if(ai->bitrate_limit_max_kbps>0 &&
  155365. ai->bitrate_average_kbps>0 &&
  155366. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155367. return OV_EINVAL;
  155368. if(ai->bitrate_limit_min_kbps>0 &&
  155369. ai->bitrate_limit_max_kbps>0 &&
  155370. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155371. return OV_EINVAL;
  155372. if(ai->bitrate_average_damping <= 0.)
  155373. return OV_EINVAL;
  155374. if(ai->bitrate_limit_reservoir_bits < 0)
  155375. return OV_EINVAL;
  155376. if(ai->bitrate_limit_reservoir_bias < 0.)
  155377. return OV_EINVAL;
  155378. if(ai->bitrate_limit_reservoir_bias > 1.)
  155379. return OV_EINVAL;
  155380. hi->managed=ai->management_active;
  155381. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155382. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155383. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155384. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155385. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155386. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155387. }
  155388. }
  155389. return 0;
  155390. case OV_ECTL_LOWPASS_GET:
  155391. {
  155392. double *farg=(double *)arg;
  155393. *farg=hi->lowpass_kHz;
  155394. }
  155395. return(0);
  155396. case OV_ECTL_LOWPASS_SET:
  155397. {
  155398. double *farg=(double *)arg;
  155399. hi->lowpass_kHz=*farg;
  155400. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155401. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155402. }
  155403. return(0);
  155404. case OV_ECTL_IBLOCK_GET:
  155405. {
  155406. double *farg=(double *)arg;
  155407. *farg=hi->impulse_noisetune;
  155408. }
  155409. return(0);
  155410. case OV_ECTL_IBLOCK_SET:
  155411. {
  155412. double *farg=(double *)arg;
  155413. hi->impulse_noisetune=*farg;
  155414. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155415. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155416. }
  155417. return(0);
  155418. }
  155419. return(OV_EIMPL);
  155420. }
  155421. return(OV_EINVAL);
  155422. }
  155423. #endif
  155424. /*** End of inlined file: vorbisenc.c ***/
  155425. /*** Start of inlined file: vorbisfile.c ***/
  155426. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155427. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155428. // tasks..
  155429. #if JUCE_MSVC
  155430. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155431. #endif
  155432. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155433. #if JUCE_USE_OGGVORBIS
  155434. #include <stdlib.h>
  155435. #include <stdio.h>
  155436. #include <errno.h>
  155437. #include <string.h>
  155438. #include <math.h>
  155439. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155440. one logical bitstream arranged end to end (the only form of Ogg
  155441. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155442. multiplexing] is not allowed in Vorbis) */
  155443. /* A Vorbis file can be played beginning to end (streamed) without
  155444. worrying ahead of time about chaining (see decoder_example.c). If
  155445. we have the whole file, however, and want random access
  155446. (seeking/scrubbing) or desire to know the total length/time of a
  155447. file, we need to account for the possibility of chaining. */
  155448. /* We can handle things a number of ways; we can determine the entire
  155449. bitstream structure right off the bat, or find pieces on demand.
  155450. This example determines and caches structure for the entire
  155451. bitstream, but builds a virtual decoder on the fly when moving
  155452. between links in the chain. */
  155453. /* There are also different ways to implement seeking. Enough
  155454. information exists in an Ogg bitstream to seek to
  155455. sample-granularity positions in the output. Or, one can seek by
  155456. picking some portion of the stream roughly in the desired area if
  155457. we only want coarse navigation through the stream. */
  155458. /*************************************************************************
  155459. * Many, many internal helpers. The intention is not to be confusing;
  155460. * rampant duplication and monolithic function implementation would be
  155461. * harder to understand anyway. The high level functions are last. Begin
  155462. * grokking near the end of the file */
  155463. /* read a little more data from the file/pipe into the ogg_sync framer
  155464. */
  155465. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155466. over 8k gets what they deserve */
  155467. static long _get_data(OggVorbis_File *vf){
  155468. errno=0;
  155469. if(vf->datasource){
  155470. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155471. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155472. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155473. if(bytes==0 && errno)return(-1);
  155474. return(bytes);
  155475. }else
  155476. return(0);
  155477. }
  155478. /* save a tiny smidge of verbosity to make the code more readable */
  155479. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155480. if(vf->datasource){
  155481. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155482. vf->offset=offset;
  155483. ogg_sync_reset(&vf->oy);
  155484. }else{
  155485. /* shouldn't happen unless someone writes a broken callback */
  155486. return;
  155487. }
  155488. }
  155489. /* The read/seek functions track absolute position within the stream */
  155490. /* from the head of the stream, get the next page. boundary specifies
  155491. if the function is allowed to fetch more data from the stream (and
  155492. how much) or only use internally buffered data.
  155493. boundary: -1) unbounded search
  155494. 0) read no additional data; use cached only
  155495. n) search for a new page beginning for n bytes
  155496. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155497. n) found a page at absolute offset n */
  155498. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155499. ogg_int64_t boundary){
  155500. if(boundary>0)boundary+=vf->offset;
  155501. while(1){
  155502. long more;
  155503. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155504. more=ogg_sync_pageseek(&vf->oy,og);
  155505. if(more<0){
  155506. /* skipped n bytes */
  155507. vf->offset-=more;
  155508. }else{
  155509. if(more==0){
  155510. /* send more paramedics */
  155511. if(!boundary)return(OV_FALSE);
  155512. {
  155513. long ret=_get_data(vf);
  155514. if(ret==0)return(OV_EOF);
  155515. if(ret<0)return(OV_EREAD);
  155516. }
  155517. }else{
  155518. /* got a page. Return the offset at the page beginning,
  155519. advance the internal offset past the page end */
  155520. ogg_int64_t ret=vf->offset;
  155521. vf->offset+=more;
  155522. return(ret);
  155523. }
  155524. }
  155525. }
  155526. }
  155527. /* find the latest page beginning before the current stream cursor
  155528. position. Much dirtier than the above as Ogg doesn't have any
  155529. backward search linkage. no 'readp' as it will certainly have to
  155530. read. */
  155531. /* returns offset or OV_EREAD, OV_FAULT */
  155532. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155533. ogg_int64_t begin=vf->offset;
  155534. ogg_int64_t end=begin;
  155535. ogg_int64_t ret;
  155536. ogg_int64_t offset=-1;
  155537. while(offset==-1){
  155538. begin-=CHUNKSIZE;
  155539. if(begin<0)
  155540. begin=0;
  155541. _seek_helper(vf,begin);
  155542. while(vf->offset<end){
  155543. ret=_get_next_page(vf,og,end-vf->offset);
  155544. if(ret==OV_EREAD)return(OV_EREAD);
  155545. if(ret<0){
  155546. break;
  155547. }else{
  155548. offset=ret;
  155549. }
  155550. }
  155551. }
  155552. /* we have the offset. Actually snork and hold the page now */
  155553. _seek_helper(vf,offset);
  155554. ret=_get_next_page(vf,og,CHUNKSIZE);
  155555. if(ret<0)
  155556. /* this shouldn't be possible */
  155557. return(OV_EFAULT);
  155558. return(offset);
  155559. }
  155560. /* finds each bitstream link one at a time using a bisection search
  155561. (has to begin by knowing the offset of the lb's initial page).
  155562. Recurses for each link so it can alloc the link storage after
  155563. finding them all, then unroll and fill the cache at the same time */
  155564. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155565. ogg_int64_t begin,
  155566. ogg_int64_t searched,
  155567. ogg_int64_t end,
  155568. long currentno,
  155569. long m){
  155570. ogg_int64_t endsearched=end;
  155571. ogg_int64_t next=end;
  155572. ogg_page og;
  155573. ogg_int64_t ret;
  155574. /* the below guards against garbage seperating the last and
  155575. first pages of two links. */
  155576. while(searched<endsearched){
  155577. ogg_int64_t bisect;
  155578. if(endsearched-searched<CHUNKSIZE){
  155579. bisect=searched;
  155580. }else{
  155581. bisect=(searched+endsearched)/2;
  155582. }
  155583. _seek_helper(vf,bisect);
  155584. ret=_get_next_page(vf,&og,-1);
  155585. if(ret==OV_EREAD)return(OV_EREAD);
  155586. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155587. endsearched=bisect;
  155588. if(ret>=0)next=ret;
  155589. }else{
  155590. searched=ret+og.header_len+og.body_len;
  155591. }
  155592. }
  155593. _seek_helper(vf,next);
  155594. ret=_get_next_page(vf,&og,-1);
  155595. if(ret==OV_EREAD)return(OV_EREAD);
  155596. if(searched>=end || ret<0){
  155597. vf->links=m+1;
  155598. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155599. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155600. vf->offsets[m+1]=searched;
  155601. }else{
  155602. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155603. end,ogg_page_serialno(&og),m+1);
  155604. if(ret==OV_EREAD)return(OV_EREAD);
  155605. }
  155606. vf->offsets[m]=begin;
  155607. vf->serialnos[m]=currentno;
  155608. return(0);
  155609. }
  155610. /* uses the local ogg_stream storage in vf; this is important for
  155611. non-streaming input sources */
  155612. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155613. long *serialno,ogg_page *og_ptr){
  155614. ogg_page og;
  155615. ogg_packet op;
  155616. int i,ret;
  155617. if(!og_ptr){
  155618. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155619. if(llret==OV_EREAD)return(OV_EREAD);
  155620. if(llret<0)return OV_ENOTVORBIS;
  155621. og_ptr=&og;
  155622. }
  155623. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155624. if(serialno)*serialno=vf->os.serialno;
  155625. vf->ready_state=STREAMSET;
  155626. /* extract the initial header from the first page and verify that the
  155627. Ogg bitstream is in fact Vorbis data */
  155628. vorbis_info_init(vi);
  155629. vorbis_comment_init(vc);
  155630. i=0;
  155631. while(i<3){
  155632. ogg_stream_pagein(&vf->os,og_ptr);
  155633. while(i<3){
  155634. int result=ogg_stream_packetout(&vf->os,&op);
  155635. if(result==0)break;
  155636. if(result==-1){
  155637. ret=OV_EBADHEADER;
  155638. goto bail_header;
  155639. }
  155640. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155641. goto bail_header;
  155642. }
  155643. i++;
  155644. }
  155645. if(i<3)
  155646. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155647. ret=OV_EBADHEADER;
  155648. goto bail_header;
  155649. }
  155650. }
  155651. return 0;
  155652. bail_header:
  155653. vorbis_info_clear(vi);
  155654. vorbis_comment_clear(vc);
  155655. vf->ready_state=OPENED;
  155656. return ret;
  155657. }
  155658. /* last step of the OggVorbis_File initialization; get all the
  155659. vorbis_info structs and PCM positions. Only called by the seekable
  155660. initialization (local stream storage is hacked slightly; pay
  155661. attention to how that's done) */
  155662. /* this is void and does not propogate errors up because we want to be
  155663. able to open and use damaged bitstreams as well as we can. Just
  155664. watch out for missing information for links in the OggVorbis_File
  155665. struct */
  155666. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155667. ogg_page og;
  155668. int i;
  155669. ogg_int64_t ret;
  155670. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155671. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155672. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155673. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155674. for(i=0;i<vf->links;i++){
  155675. if(i==0){
  155676. /* we already grabbed the initial header earlier. Just set the offset */
  155677. vf->dataoffsets[i]=dataoffset;
  155678. _seek_helper(vf,dataoffset);
  155679. }else{
  155680. /* seek to the location of the initial header */
  155681. _seek_helper(vf,vf->offsets[i]);
  155682. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155683. vf->dataoffsets[i]=-1;
  155684. }else{
  155685. vf->dataoffsets[i]=vf->offset;
  155686. }
  155687. }
  155688. /* fetch beginning PCM offset */
  155689. if(vf->dataoffsets[i]!=-1){
  155690. ogg_int64_t accumulated=0;
  155691. long lastblock=-1;
  155692. int result;
  155693. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155694. while(1){
  155695. ogg_packet op;
  155696. ret=_get_next_page(vf,&og,-1);
  155697. if(ret<0)
  155698. /* this should not be possible unless the file is
  155699. truncated/mangled */
  155700. break;
  155701. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155702. break;
  155703. /* count blocksizes of all frames in the page */
  155704. ogg_stream_pagein(&vf->os,&og);
  155705. while((result=ogg_stream_packetout(&vf->os,&op))){
  155706. if(result>0){ /* ignore holes */
  155707. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155708. if(lastblock!=-1)
  155709. accumulated+=(lastblock+thisblock)>>2;
  155710. lastblock=thisblock;
  155711. }
  155712. }
  155713. if(ogg_page_granulepos(&og)!=-1){
  155714. /* pcm offset of last packet on the first audio page */
  155715. accumulated= ogg_page_granulepos(&og)-accumulated;
  155716. break;
  155717. }
  155718. }
  155719. /* less than zero? This is a stream with samples trimmed off
  155720. the beginning, a normal occurrence; set the offset to zero */
  155721. if(accumulated<0)accumulated=0;
  155722. vf->pcmlengths[i*2]=accumulated;
  155723. }
  155724. /* get the PCM length of this link. To do this,
  155725. get the last page of the stream */
  155726. {
  155727. ogg_int64_t end=vf->offsets[i+1];
  155728. _seek_helper(vf,end);
  155729. while(1){
  155730. ret=_get_prev_page(vf,&og);
  155731. if(ret<0){
  155732. /* this should not be possible */
  155733. vorbis_info_clear(vf->vi+i);
  155734. vorbis_comment_clear(vf->vc+i);
  155735. break;
  155736. }
  155737. if(ogg_page_granulepos(&og)!=-1){
  155738. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155739. break;
  155740. }
  155741. vf->offset=ret;
  155742. }
  155743. }
  155744. }
  155745. }
  155746. static int _make_decode_ready(OggVorbis_File *vf){
  155747. if(vf->ready_state>STREAMSET)return 0;
  155748. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155749. if(vf->seekable){
  155750. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155751. return OV_EBADLINK;
  155752. }else{
  155753. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155754. return OV_EBADLINK;
  155755. }
  155756. vorbis_block_init(&vf->vd,&vf->vb);
  155757. vf->ready_state=INITSET;
  155758. vf->bittrack=0.f;
  155759. vf->samptrack=0.f;
  155760. return 0;
  155761. }
  155762. static int _open_seekable2(OggVorbis_File *vf){
  155763. long serialno=vf->current_serialno;
  155764. ogg_int64_t dataoffset=vf->offset, end;
  155765. ogg_page og;
  155766. /* we're partially open and have a first link header state in
  155767. storage in vf */
  155768. /* we can seek, so set out learning all about this file */
  155769. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155770. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155771. /* We get the offset for the last page of the physical bitstream.
  155772. Most OggVorbis files will contain a single logical bitstream */
  155773. end=_get_prev_page(vf,&og);
  155774. if(end<0)return(end);
  155775. /* more than one logical bitstream? */
  155776. if(ogg_page_serialno(&og)!=serialno){
  155777. /* Chained bitstream. Bisect-search each logical bitstream
  155778. section. Do so based on serial number only */
  155779. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155780. }else{
  155781. /* Only one logical bitstream */
  155782. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155783. }
  155784. /* the initial header memory is referenced by vf after; don't free it */
  155785. _prefetch_all_headers(vf,dataoffset);
  155786. return(ov_raw_seek(vf,0));
  155787. }
  155788. /* clear out the current logical bitstream decoder */
  155789. static void _decode_clear(OggVorbis_File *vf){
  155790. vorbis_dsp_clear(&vf->vd);
  155791. vorbis_block_clear(&vf->vb);
  155792. vf->ready_state=OPENED;
  155793. }
  155794. /* fetch and process a packet. Handles the case where we're at a
  155795. bitstream boundary and dumps the decoding machine. If the decoding
  155796. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155797. date (seek and read both use this. seek uses a special hack with
  155798. readp).
  155799. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155800. 0) need more data (only if readp==0)
  155801. 1) got a packet
  155802. */
  155803. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155804. ogg_packet *op_in,
  155805. int readp,
  155806. int spanp){
  155807. ogg_page og;
  155808. /* handle one packet. Try to fetch it from current stream state */
  155809. /* extract packets from page */
  155810. while(1){
  155811. /* process a packet if we can. If the machine isn't loaded,
  155812. neither is a page */
  155813. if(vf->ready_state==INITSET){
  155814. while(1) {
  155815. ogg_packet op;
  155816. ogg_packet *op_ptr=(op_in?op_in:&op);
  155817. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155818. ogg_int64_t granulepos;
  155819. op_in=NULL;
  155820. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155821. if(result>0){
  155822. /* got a packet. process it */
  155823. granulepos=op_ptr->granulepos;
  155824. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155825. header handling. The
  155826. header packets aren't
  155827. audio, so if/when we
  155828. submit them,
  155829. vorbis_synthesis will
  155830. reject them */
  155831. /* suck in the synthesis data and track bitrate */
  155832. {
  155833. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155834. /* for proper use of libvorbis within libvorbisfile,
  155835. oldsamples will always be zero. */
  155836. if(oldsamples)return(OV_EFAULT);
  155837. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155838. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155839. vf->bittrack+=op_ptr->bytes*8;
  155840. }
  155841. /* update the pcm offset. */
  155842. if(granulepos!=-1 && !op_ptr->e_o_s){
  155843. int link=(vf->seekable?vf->current_link:0);
  155844. int i,samples;
  155845. /* this packet has a pcm_offset on it (the last packet
  155846. completed on a page carries the offset) After processing
  155847. (above), we know the pcm position of the *last* sample
  155848. ready to be returned. Find the offset of the *first*
  155849. As an aside, this trick is inaccurate if we begin
  155850. reading anew right at the last page; the end-of-stream
  155851. granulepos declares the last frame in the stream, and the
  155852. last packet of the last page may be a partial frame.
  155853. So, we need a previous granulepos from an in-sequence page
  155854. to have a reference point. Thus the !op_ptr->e_o_s clause
  155855. above */
  155856. if(vf->seekable && link>0)
  155857. granulepos-=vf->pcmlengths[link*2];
  155858. if(granulepos<0)granulepos=0; /* actually, this
  155859. shouldn't be possible
  155860. here unless the stream
  155861. is very broken */
  155862. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155863. granulepos-=samples;
  155864. for(i=0;i<link;i++)
  155865. granulepos+=vf->pcmlengths[i*2+1];
  155866. vf->pcm_offset=granulepos;
  155867. }
  155868. return(1);
  155869. }
  155870. }
  155871. else
  155872. break;
  155873. }
  155874. }
  155875. if(vf->ready_state>=OPENED){
  155876. ogg_int64_t ret;
  155877. if(!readp)return(0);
  155878. if((ret=_get_next_page(vf,&og,-1))<0){
  155879. return(OV_EOF); /* eof.
  155880. leave unitialized */
  155881. }
  155882. /* bitrate tracking; add the header's bytes here, the body bytes
  155883. are done by packet above */
  155884. vf->bittrack+=og.header_len*8;
  155885. /* has our decoding just traversed a bitstream boundary? */
  155886. if(vf->ready_state==INITSET){
  155887. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155888. if(!spanp)
  155889. return(OV_EOF);
  155890. _decode_clear(vf);
  155891. if(!vf->seekable){
  155892. vorbis_info_clear(vf->vi);
  155893. vorbis_comment_clear(vf->vc);
  155894. }
  155895. }
  155896. }
  155897. }
  155898. /* Do we need to load a new machine before submitting the page? */
  155899. /* This is different in the seekable and non-seekable cases.
  155900. In the seekable case, we already have all the header
  155901. information loaded and cached; we just initialize the machine
  155902. with it and continue on our merry way.
  155903. In the non-seekable (streaming) case, we'll only be at a
  155904. boundary if we just left the previous logical bitstream and
  155905. we're now nominally at the header of the next bitstream
  155906. */
  155907. if(vf->ready_state!=INITSET){
  155908. int link;
  155909. if(vf->ready_state<STREAMSET){
  155910. if(vf->seekable){
  155911. vf->current_serialno=ogg_page_serialno(&og);
  155912. /* match the serialno to bitstream section. We use this rather than
  155913. offset positions to avoid problems near logical bitstream
  155914. boundaries */
  155915. for(link=0;link<vf->links;link++)
  155916. if(vf->serialnos[link]==vf->current_serialno)break;
  155917. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155918. stream. error out,
  155919. leave machine
  155920. uninitialized */
  155921. vf->current_link=link;
  155922. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155923. vf->ready_state=STREAMSET;
  155924. }else{
  155925. /* we're streaming */
  155926. /* fetch the three header packets, build the info struct */
  155927. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155928. if(ret)return(ret);
  155929. vf->current_link++;
  155930. link=0;
  155931. }
  155932. }
  155933. {
  155934. int ret=_make_decode_ready(vf);
  155935. if(ret<0)return ret;
  155936. }
  155937. }
  155938. ogg_stream_pagein(&vf->os,&og);
  155939. }
  155940. }
  155941. /* if, eg, 64 bit stdio is configured by default, this will build with
  155942. fseek64 */
  155943. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155944. if(f==NULL)return(-1);
  155945. return fseek(f,off,whence);
  155946. }
  155947. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155948. long ibytes, ov_callbacks callbacks){
  155949. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155950. int ret;
  155951. memset(vf,0,sizeof(*vf));
  155952. vf->datasource=f;
  155953. vf->callbacks = callbacks;
  155954. /* init the framing state */
  155955. ogg_sync_init(&vf->oy);
  155956. /* perhaps some data was previously read into a buffer for testing
  155957. against other stream types. Allow initialization from this
  155958. previously read data (as we may be reading from a non-seekable
  155959. stream) */
  155960. if(initial){
  155961. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155962. memcpy(buffer,initial,ibytes);
  155963. ogg_sync_wrote(&vf->oy,ibytes);
  155964. }
  155965. /* can we seek? Stevens suggests the seek test was portable */
  155966. if(offsettest!=-1)vf->seekable=1;
  155967. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155968. entry for partial open */
  155969. vf->links=1;
  155970. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155971. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155972. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155973. /* Try to fetch the headers, maintaining all the storage */
  155974. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155975. vf->datasource=NULL;
  155976. ov_clear(vf);
  155977. }else
  155978. vf->ready_state=PARTOPEN;
  155979. return(ret);
  155980. }
  155981. static int _ov_open2(OggVorbis_File *vf){
  155982. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155983. vf->ready_state=OPENED;
  155984. if(vf->seekable){
  155985. int ret=_open_seekable2(vf);
  155986. if(ret){
  155987. vf->datasource=NULL;
  155988. ov_clear(vf);
  155989. }
  155990. return(ret);
  155991. }else
  155992. vf->ready_state=STREAMSET;
  155993. return 0;
  155994. }
  155995. /* clear out the OggVorbis_File struct */
  155996. int ov_clear(OggVorbis_File *vf){
  155997. if(vf){
  155998. vorbis_block_clear(&vf->vb);
  155999. vorbis_dsp_clear(&vf->vd);
  156000. ogg_stream_clear(&vf->os);
  156001. if(vf->vi && vf->links){
  156002. int i;
  156003. for(i=0;i<vf->links;i++){
  156004. vorbis_info_clear(vf->vi+i);
  156005. vorbis_comment_clear(vf->vc+i);
  156006. }
  156007. _ogg_free(vf->vi);
  156008. _ogg_free(vf->vc);
  156009. }
  156010. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156011. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156012. if(vf->serialnos)_ogg_free(vf->serialnos);
  156013. if(vf->offsets)_ogg_free(vf->offsets);
  156014. ogg_sync_clear(&vf->oy);
  156015. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156016. memset(vf,0,sizeof(*vf));
  156017. }
  156018. #ifdef DEBUG_LEAKS
  156019. _VDBG_dump();
  156020. #endif
  156021. return(0);
  156022. }
  156023. /* inspects the OggVorbis file and finds/documents all the logical
  156024. bitstreams contained in it. Tries to be tolerant of logical
  156025. bitstream sections that are truncated/woogie.
  156026. return: -1) error
  156027. 0) OK
  156028. */
  156029. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156030. ov_callbacks callbacks){
  156031. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156032. if(ret)return ret;
  156033. return _ov_open2(vf);
  156034. }
  156035. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156036. ov_callbacks callbacks = {
  156037. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156038. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156039. (int (*)(void *)) fclose,
  156040. (long (*)(void *)) ftell
  156041. };
  156042. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156043. }
  156044. /* cheap hack for game usage where downsampling is desirable; there's
  156045. no need for SRC as we can just do it cheaply in libvorbis. */
  156046. int ov_halfrate(OggVorbis_File *vf,int flag){
  156047. int i;
  156048. if(vf->vi==NULL)return OV_EINVAL;
  156049. if(!vf->seekable)return OV_EINVAL;
  156050. if(vf->ready_state>=STREAMSET)
  156051. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156052. will be able to swap this on the fly, but
  156053. for now dumping the decode machine is needed
  156054. to reinit the MDCT lookups. 1.1 libvorbis
  156055. is planned to be able to switch on the fly */
  156056. for(i=0;i<vf->links;i++){
  156057. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156058. ov_halfrate(vf,0);
  156059. return OV_EINVAL;
  156060. }
  156061. }
  156062. return 0;
  156063. }
  156064. int ov_halfrate_p(OggVorbis_File *vf){
  156065. if(vf->vi==NULL)return OV_EINVAL;
  156066. return vorbis_synthesis_halfrate_p(vf->vi);
  156067. }
  156068. /* Only partially open the vorbis file; test for Vorbisness, and load
  156069. the headers for the first chain. Do not seek (although test for
  156070. seekability). Use ov_test_open to finish opening the file, else
  156071. ov_clear to close/free it. Same return codes as open. */
  156072. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156073. ov_callbacks callbacks)
  156074. {
  156075. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156076. }
  156077. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156078. ov_callbacks callbacks = {
  156079. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156080. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156081. (int (*)(void *)) fclose,
  156082. (long (*)(void *)) ftell
  156083. };
  156084. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156085. }
  156086. int ov_test_open(OggVorbis_File *vf){
  156087. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156088. return _ov_open2(vf);
  156089. }
  156090. /* How many logical bitstreams in this physical bitstream? */
  156091. long ov_streams(OggVorbis_File *vf){
  156092. return vf->links;
  156093. }
  156094. /* Is the FILE * associated with vf seekable? */
  156095. long ov_seekable(OggVorbis_File *vf){
  156096. return vf->seekable;
  156097. }
  156098. /* returns the bitrate for a given logical bitstream or the entire
  156099. physical bitstream. If the file is open for random access, it will
  156100. find the *actual* average bitrate. If the file is streaming, it
  156101. returns the nominal bitrate (if set) else the average of the
  156102. upper/lower bounds (if set) else -1 (unset).
  156103. If you want the actual bitrate field settings, get them from the
  156104. vorbis_info structs */
  156105. long ov_bitrate(OggVorbis_File *vf,int i){
  156106. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156107. if(i>=vf->links)return(OV_EINVAL);
  156108. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156109. if(i<0){
  156110. ogg_int64_t bits=0;
  156111. int i;
  156112. float br;
  156113. for(i=0;i<vf->links;i++)
  156114. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156115. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156116. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156117. * so this is slightly transformed to make it work.
  156118. */
  156119. br = bits/ov_time_total(vf,-1);
  156120. return(rint(br));
  156121. }else{
  156122. if(vf->seekable){
  156123. /* return the actual bitrate */
  156124. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156125. }else{
  156126. /* return nominal if set */
  156127. if(vf->vi[i].bitrate_nominal>0){
  156128. return vf->vi[i].bitrate_nominal;
  156129. }else{
  156130. if(vf->vi[i].bitrate_upper>0){
  156131. if(vf->vi[i].bitrate_lower>0){
  156132. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156133. }else{
  156134. return vf->vi[i].bitrate_upper;
  156135. }
  156136. }
  156137. return(OV_FALSE);
  156138. }
  156139. }
  156140. }
  156141. }
  156142. /* returns the actual bitrate since last call. returns -1 if no
  156143. additional data to offer since last call (or at beginning of stream),
  156144. EINVAL if stream is only partially open
  156145. */
  156146. long ov_bitrate_instant(OggVorbis_File *vf){
  156147. int link=(vf->seekable?vf->current_link:0);
  156148. long ret;
  156149. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156150. if(vf->samptrack==0)return(OV_FALSE);
  156151. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156152. vf->bittrack=0.f;
  156153. vf->samptrack=0.f;
  156154. return(ret);
  156155. }
  156156. /* Guess */
  156157. long ov_serialnumber(OggVorbis_File *vf,int i){
  156158. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156159. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156160. if(i<0){
  156161. return(vf->current_serialno);
  156162. }else{
  156163. return(vf->serialnos[i]);
  156164. }
  156165. }
  156166. /* returns: total raw (compressed) length of content if i==-1
  156167. raw (compressed) length of that logical bitstream for i==0 to n
  156168. OV_EINVAL if the stream is not seekable (we can't know the length)
  156169. or if stream is only partially open
  156170. */
  156171. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156172. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156173. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156174. if(i<0){
  156175. ogg_int64_t acc=0;
  156176. int i;
  156177. for(i=0;i<vf->links;i++)
  156178. acc+=ov_raw_total(vf,i);
  156179. return(acc);
  156180. }else{
  156181. return(vf->offsets[i+1]-vf->offsets[i]);
  156182. }
  156183. }
  156184. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156185. (samples) of that logical bitstream for i==0 to n
  156186. OV_EINVAL if the stream is not seekable (we can't know the
  156187. length) or only partially open
  156188. */
  156189. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156190. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156191. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156192. if(i<0){
  156193. ogg_int64_t acc=0;
  156194. int i;
  156195. for(i=0;i<vf->links;i++)
  156196. acc+=ov_pcm_total(vf,i);
  156197. return(acc);
  156198. }else{
  156199. return(vf->pcmlengths[i*2+1]);
  156200. }
  156201. }
  156202. /* returns: total seconds of content if i==-1
  156203. seconds in that logical bitstream for i==0 to n
  156204. OV_EINVAL if the stream is not seekable (we can't know the
  156205. length) or only partially open
  156206. */
  156207. double ov_time_total(OggVorbis_File *vf,int i){
  156208. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156209. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156210. if(i<0){
  156211. double acc=0;
  156212. int i;
  156213. for(i=0;i<vf->links;i++)
  156214. acc+=ov_time_total(vf,i);
  156215. return(acc);
  156216. }else{
  156217. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156218. }
  156219. }
  156220. /* seek to an offset relative to the *compressed* data. This also
  156221. scans packets to update the PCM cursor. It will cross a logical
  156222. bitstream boundary, but only if it can't get any packets out of the
  156223. tail of the bitstream we seek to (so no surprises).
  156224. returns zero on success, nonzero on failure */
  156225. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156226. ogg_stream_state work_os;
  156227. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156228. if(!vf->seekable)
  156229. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156230. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156231. /* don't yet clear out decoding machine (if it's initialized), in
  156232. the case we're in the same link. Restart the decode lapping, and
  156233. let _fetch_and_process_packet deal with a potential bitstream
  156234. boundary */
  156235. vf->pcm_offset=-1;
  156236. ogg_stream_reset_serialno(&vf->os,
  156237. vf->current_serialno); /* must set serialno */
  156238. vorbis_synthesis_restart(&vf->vd);
  156239. _seek_helper(vf,pos);
  156240. /* we need to make sure the pcm_offset is set, but we don't want to
  156241. advance the raw cursor past good packets just to get to the first
  156242. with a granulepos. That's not equivalent behavior to beginning
  156243. decoding as immediately after the seek position as possible.
  156244. So, a hack. We use two stream states; a local scratch state and
  156245. the shared vf->os stream state. We use the local state to
  156246. scan, and the shared state as a buffer for later decode.
  156247. Unfortuantely, on the last page we still advance to last packet
  156248. because the granulepos on the last page is not necessarily on a
  156249. packet boundary, and we need to make sure the granpos is
  156250. correct.
  156251. */
  156252. {
  156253. ogg_page og;
  156254. ogg_packet op;
  156255. int lastblock=0;
  156256. int accblock=0;
  156257. int thisblock;
  156258. int eosflag;
  156259. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156260. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156261. return from not necessarily
  156262. starting from the beginning */
  156263. while(1){
  156264. if(vf->ready_state>=STREAMSET){
  156265. /* snarf/scan a packet if we can */
  156266. int result=ogg_stream_packetout(&work_os,&op);
  156267. if(result>0){
  156268. if(vf->vi[vf->current_link].codec_setup){
  156269. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156270. if(thisblock<0){
  156271. ogg_stream_packetout(&vf->os,NULL);
  156272. thisblock=0;
  156273. }else{
  156274. if(eosflag)
  156275. ogg_stream_packetout(&vf->os,NULL);
  156276. else
  156277. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156278. }
  156279. if(op.granulepos!=-1){
  156280. int i,link=vf->current_link;
  156281. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156282. if(granulepos<0)granulepos=0;
  156283. for(i=0;i<link;i++)
  156284. granulepos+=vf->pcmlengths[i*2+1];
  156285. vf->pcm_offset=granulepos-accblock;
  156286. break;
  156287. }
  156288. lastblock=thisblock;
  156289. continue;
  156290. }else
  156291. ogg_stream_packetout(&vf->os,NULL);
  156292. }
  156293. }
  156294. if(!lastblock){
  156295. if(_get_next_page(vf,&og,-1)<0){
  156296. vf->pcm_offset=ov_pcm_total(vf,-1);
  156297. break;
  156298. }
  156299. }else{
  156300. /* huh? Bogus stream with packets but no granulepos */
  156301. vf->pcm_offset=-1;
  156302. break;
  156303. }
  156304. /* has our decoding just traversed a bitstream boundary? */
  156305. if(vf->ready_state>=STREAMSET)
  156306. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156307. _decode_clear(vf); /* clear out stream state */
  156308. ogg_stream_clear(&work_os);
  156309. }
  156310. if(vf->ready_state<STREAMSET){
  156311. int link;
  156312. vf->current_serialno=ogg_page_serialno(&og);
  156313. for(link=0;link<vf->links;link++)
  156314. if(vf->serialnos[link]==vf->current_serialno)break;
  156315. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156316. error out, leave
  156317. machine uninitialized */
  156318. vf->current_link=link;
  156319. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156320. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156321. vf->ready_state=STREAMSET;
  156322. }
  156323. ogg_stream_pagein(&vf->os,&og);
  156324. ogg_stream_pagein(&work_os,&og);
  156325. eosflag=ogg_page_eos(&og);
  156326. }
  156327. }
  156328. ogg_stream_clear(&work_os);
  156329. vf->bittrack=0.f;
  156330. vf->samptrack=0.f;
  156331. return(0);
  156332. seek_error:
  156333. /* dump the machine so we're in a known state */
  156334. vf->pcm_offset=-1;
  156335. ogg_stream_clear(&work_os);
  156336. _decode_clear(vf);
  156337. return OV_EBADLINK;
  156338. }
  156339. /* Page granularity seek (faster than sample granularity because we
  156340. don't do the last bit of decode to find a specific sample).
  156341. Seek to the last [granule marked] page preceeding the specified pos
  156342. location, such that decoding past the returned point will quickly
  156343. arrive at the requested position. */
  156344. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156345. int link=-1;
  156346. ogg_int64_t result=0;
  156347. ogg_int64_t total=ov_pcm_total(vf,-1);
  156348. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156349. if(!vf->seekable)return(OV_ENOSEEK);
  156350. if(pos<0 || pos>total)return(OV_EINVAL);
  156351. /* which bitstream section does this pcm offset occur in? */
  156352. for(link=vf->links-1;link>=0;link--){
  156353. total-=vf->pcmlengths[link*2+1];
  156354. if(pos>=total)break;
  156355. }
  156356. /* search within the logical bitstream for the page with the highest
  156357. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156358. missing pages or incorrect frame number information in the
  156359. bitstream could make our task impossible. Account for that (it
  156360. would be an error condition) */
  156361. /* new search algorithm by HB (Nicholas Vinen) */
  156362. {
  156363. ogg_int64_t end=vf->offsets[link+1];
  156364. ogg_int64_t begin=vf->offsets[link];
  156365. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156366. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156367. ogg_int64_t target=pos-total+begintime;
  156368. ogg_int64_t best=begin;
  156369. ogg_page og;
  156370. while(begin<end){
  156371. ogg_int64_t bisect;
  156372. if(end-begin<CHUNKSIZE){
  156373. bisect=begin;
  156374. }else{
  156375. /* take a (pretty decent) guess. */
  156376. bisect=begin +
  156377. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156378. if(bisect<=begin)
  156379. bisect=begin+1;
  156380. }
  156381. _seek_helper(vf,bisect);
  156382. while(begin<end){
  156383. result=_get_next_page(vf,&og,end-vf->offset);
  156384. if(result==OV_EREAD) goto seek_error;
  156385. if(result<0){
  156386. if(bisect<=begin+1)
  156387. end=begin; /* found it */
  156388. else{
  156389. if(bisect==0) goto seek_error;
  156390. bisect-=CHUNKSIZE;
  156391. if(bisect<=begin)bisect=begin+1;
  156392. _seek_helper(vf,bisect);
  156393. }
  156394. }else{
  156395. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156396. if(granulepos==-1)continue;
  156397. if(granulepos<target){
  156398. best=result; /* raw offset of packet with granulepos */
  156399. begin=vf->offset; /* raw offset of next page */
  156400. begintime=granulepos;
  156401. if(target-begintime>44100)break;
  156402. bisect=begin; /* *not* begin + 1 */
  156403. }else{
  156404. if(bisect<=begin+1)
  156405. end=begin; /* found it */
  156406. else{
  156407. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156408. end=result;
  156409. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156410. if(bisect<=begin)bisect=begin+1;
  156411. _seek_helper(vf,bisect);
  156412. }else{
  156413. end=result;
  156414. endtime=granulepos;
  156415. break;
  156416. }
  156417. }
  156418. }
  156419. }
  156420. }
  156421. }
  156422. /* found our page. seek to it, update pcm offset. Easier case than
  156423. raw_seek, don't keep packets preceeding granulepos. */
  156424. {
  156425. ogg_page og;
  156426. ogg_packet op;
  156427. /* seek */
  156428. _seek_helper(vf,best);
  156429. vf->pcm_offset=-1;
  156430. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156431. if(link!=vf->current_link){
  156432. /* Different link; dump entire decode machine */
  156433. _decode_clear(vf);
  156434. vf->current_link=link;
  156435. vf->current_serialno=ogg_page_serialno(&og);
  156436. vf->ready_state=STREAMSET;
  156437. }else{
  156438. vorbis_synthesis_restart(&vf->vd);
  156439. }
  156440. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156441. ogg_stream_pagein(&vf->os,&og);
  156442. /* pull out all but last packet; the one with granulepos */
  156443. while(1){
  156444. result=ogg_stream_packetpeek(&vf->os,&op);
  156445. if(result==0){
  156446. /* !!! the packet finishing this page originated on a
  156447. preceeding page. Keep fetching previous pages until we
  156448. get one with a granulepos or without the 'continued' flag
  156449. set. Then just use raw_seek for simplicity. */
  156450. _seek_helper(vf,best);
  156451. while(1){
  156452. result=_get_prev_page(vf,&og);
  156453. if(result<0) goto seek_error;
  156454. if(ogg_page_granulepos(&og)>-1 ||
  156455. !ogg_page_continued(&og)){
  156456. return ov_raw_seek(vf,result);
  156457. }
  156458. vf->offset=result;
  156459. }
  156460. }
  156461. if(result<0){
  156462. result = OV_EBADPACKET;
  156463. goto seek_error;
  156464. }
  156465. if(op.granulepos!=-1){
  156466. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156467. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156468. vf->pcm_offset+=total;
  156469. break;
  156470. }else
  156471. result=ogg_stream_packetout(&vf->os,NULL);
  156472. }
  156473. }
  156474. }
  156475. /* verify result */
  156476. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156477. result=OV_EFAULT;
  156478. goto seek_error;
  156479. }
  156480. vf->bittrack=0.f;
  156481. vf->samptrack=0.f;
  156482. return(0);
  156483. seek_error:
  156484. /* dump machine so we're in a known state */
  156485. vf->pcm_offset=-1;
  156486. _decode_clear(vf);
  156487. return (int)result;
  156488. }
  156489. /* seek to a sample offset relative to the decompressed pcm stream
  156490. returns zero on success, nonzero on failure */
  156491. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156492. int thisblock,lastblock=0;
  156493. int ret=ov_pcm_seek_page(vf,pos);
  156494. if(ret<0)return(ret);
  156495. if((ret=_make_decode_ready(vf)))return ret;
  156496. /* discard leading packets we don't need for the lapping of the
  156497. position we want; don't decode them */
  156498. while(1){
  156499. ogg_packet op;
  156500. ogg_page og;
  156501. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156502. if(ret>0){
  156503. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156504. if(thisblock<0){
  156505. ogg_stream_packetout(&vf->os,NULL);
  156506. continue; /* non audio packet */
  156507. }
  156508. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156509. if(vf->pcm_offset+((thisblock+
  156510. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156511. /* remove the packet from packet queue and track its granulepos */
  156512. ogg_stream_packetout(&vf->os,NULL);
  156513. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156514. only tracking, no
  156515. pcm_decode */
  156516. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156517. /* end of logical stream case is hard, especially with exact
  156518. length positioning. */
  156519. if(op.granulepos>-1){
  156520. int i;
  156521. /* always believe the stream markers */
  156522. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156523. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156524. for(i=0;i<vf->current_link;i++)
  156525. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156526. }
  156527. lastblock=thisblock;
  156528. }else{
  156529. if(ret<0 && ret!=OV_HOLE)break;
  156530. /* suck in a new page */
  156531. if(_get_next_page(vf,&og,-1)<0)break;
  156532. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156533. if(vf->ready_state<STREAMSET){
  156534. int link;
  156535. vf->current_serialno=ogg_page_serialno(&og);
  156536. for(link=0;link<vf->links;link++)
  156537. if(vf->serialnos[link]==vf->current_serialno)break;
  156538. if(link==vf->links)return(OV_EBADLINK);
  156539. vf->current_link=link;
  156540. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156541. vf->ready_state=STREAMSET;
  156542. ret=_make_decode_ready(vf);
  156543. if(ret)return ret;
  156544. lastblock=0;
  156545. }
  156546. ogg_stream_pagein(&vf->os,&og);
  156547. }
  156548. }
  156549. vf->bittrack=0.f;
  156550. vf->samptrack=0.f;
  156551. /* discard samples until we reach the desired position. Crossing a
  156552. logical bitstream boundary with abandon is OK. */
  156553. while(vf->pcm_offset<pos){
  156554. ogg_int64_t target=pos-vf->pcm_offset;
  156555. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156556. if(samples>target)samples=target;
  156557. vorbis_synthesis_read(&vf->vd,samples);
  156558. vf->pcm_offset+=samples;
  156559. if(samples<target)
  156560. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156561. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156562. }
  156563. return 0;
  156564. }
  156565. /* seek to a playback time relative to the decompressed pcm stream
  156566. returns zero on success, nonzero on failure */
  156567. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156568. /* translate time to PCM position and call ov_pcm_seek */
  156569. int link=-1;
  156570. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156571. double time_total=ov_time_total(vf,-1);
  156572. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156573. if(!vf->seekable)return(OV_ENOSEEK);
  156574. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156575. /* which bitstream section does this time offset occur in? */
  156576. for(link=vf->links-1;link>=0;link--){
  156577. pcm_total-=vf->pcmlengths[link*2+1];
  156578. time_total-=ov_time_total(vf,link);
  156579. if(seconds>=time_total)break;
  156580. }
  156581. /* enough information to convert time offset to pcm offset */
  156582. {
  156583. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156584. return(ov_pcm_seek(vf,target));
  156585. }
  156586. }
  156587. /* page-granularity version of ov_time_seek
  156588. returns zero on success, nonzero on failure */
  156589. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156590. /* translate time to PCM position and call ov_pcm_seek */
  156591. int link=-1;
  156592. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156593. double time_total=ov_time_total(vf,-1);
  156594. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156595. if(!vf->seekable)return(OV_ENOSEEK);
  156596. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156597. /* which bitstream section does this time offset occur in? */
  156598. for(link=vf->links-1;link>=0;link--){
  156599. pcm_total-=vf->pcmlengths[link*2+1];
  156600. time_total-=ov_time_total(vf,link);
  156601. if(seconds>=time_total)break;
  156602. }
  156603. /* enough information to convert time offset to pcm offset */
  156604. {
  156605. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156606. return(ov_pcm_seek_page(vf,target));
  156607. }
  156608. }
  156609. /* tell the current stream offset cursor. Note that seek followed by
  156610. tell will likely not give the set offset due to caching */
  156611. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156612. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156613. return(vf->offset);
  156614. }
  156615. /* return PCM offset (sample) of next PCM sample to be read */
  156616. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156617. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156618. return(vf->pcm_offset);
  156619. }
  156620. /* return time offset (seconds) of next PCM sample to be read */
  156621. double ov_time_tell(OggVorbis_File *vf){
  156622. int link=0;
  156623. ogg_int64_t pcm_total=0;
  156624. double time_total=0.f;
  156625. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156626. if(vf->seekable){
  156627. pcm_total=ov_pcm_total(vf,-1);
  156628. time_total=ov_time_total(vf,-1);
  156629. /* which bitstream section does this time offset occur in? */
  156630. for(link=vf->links-1;link>=0;link--){
  156631. pcm_total-=vf->pcmlengths[link*2+1];
  156632. time_total-=ov_time_total(vf,link);
  156633. if(vf->pcm_offset>=pcm_total)break;
  156634. }
  156635. }
  156636. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156637. }
  156638. /* link: -1) return the vorbis_info struct for the bitstream section
  156639. currently being decoded
  156640. 0-n) to request information for a specific bitstream section
  156641. In the case of a non-seekable bitstream, any call returns the
  156642. current bitstream. NULL in the case that the machine is not
  156643. initialized */
  156644. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156645. if(vf->seekable){
  156646. if(link<0)
  156647. if(vf->ready_state>=STREAMSET)
  156648. return vf->vi+vf->current_link;
  156649. else
  156650. return vf->vi;
  156651. else
  156652. if(link>=vf->links)
  156653. return NULL;
  156654. else
  156655. return vf->vi+link;
  156656. }else{
  156657. return vf->vi;
  156658. }
  156659. }
  156660. /* grr, strong typing, grr, no templates/inheritence, grr */
  156661. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156662. if(vf->seekable){
  156663. if(link<0)
  156664. if(vf->ready_state>=STREAMSET)
  156665. return vf->vc+vf->current_link;
  156666. else
  156667. return vf->vc;
  156668. else
  156669. if(link>=vf->links)
  156670. return NULL;
  156671. else
  156672. return vf->vc+link;
  156673. }else{
  156674. return vf->vc;
  156675. }
  156676. }
  156677. static int host_is_big_endian() {
  156678. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156679. unsigned char *bytewise = (unsigned char *)&pattern;
  156680. if (bytewise[0] == 0xfe) return 1;
  156681. return 0;
  156682. }
  156683. /* up to this point, everything could more or less hide the multiple
  156684. logical bitstream nature of chaining from the toplevel application
  156685. if the toplevel application didn't particularly care. However, at
  156686. the point that we actually read audio back, the multiple-section
  156687. nature must surface: Multiple bitstream sections do not necessarily
  156688. have to have the same number of channels or sampling rate.
  156689. ov_read returns the sequential logical bitstream number currently
  156690. being decoded along with the PCM data in order that the toplevel
  156691. application can take action on channel/sample rate changes. This
  156692. number will be incremented even for streamed (non-seekable) streams
  156693. (for seekable streams, it represents the actual logical bitstream
  156694. index within the physical bitstream. Note that the accessor
  156695. functions above are aware of this dichotomy).
  156696. input values: buffer) a buffer to hold packed PCM data for return
  156697. length) the byte length requested to be placed into buffer
  156698. bigendianp) should the data be packed LSB first (0) or
  156699. MSB first (1)
  156700. word) word size for output. currently 1 (byte) or
  156701. 2 (16 bit short)
  156702. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156703. 0) EOF
  156704. n) number of bytes of PCM actually returned. The
  156705. below works on a packet-by-packet basis, so the
  156706. return length is not related to the 'length' passed
  156707. in, just guaranteed to fit.
  156708. *section) set to the logical bitstream number */
  156709. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156710. int bigendianp,int word,int sgned,int *bitstream){
  156711. int i,j;
  156712. int host_endian = host_is_big_endian();
  156713. float **pcm;
  156714. long samples;
  156715. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156716. while(1){
  156717. if(vf->ready_state==INITSET){
  156718. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156719. if(samples)break;
  156720. }
  156721. /* suck in another packet */
  156722. {
  156723. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156724. if(ret==OV_EOF)
  156725. return(0);
  156726. if(ret<=0)
  156727. return(ret);
  156728. }
  156729. }
  156730. if(samples>0){
  156731. /* yay! proceed to pack data into the byte buffer */
  156732. long channels=ov_info(vf,-1)->channels;
  156733. long bytespersample=word * channels;
  156734. vorbis_fpu_control fpu;
  156735. (void) fpu; // (to avoid a warning about it being unused)
  156736. if(samples>length/bytespersample)samples=length/bytespersample;
  156737. if(samples <= 0)
  156738. return OV_EINVAL;
  156739. /* a tight loop to pack each size */
  156740. {
  156741. int val;
  156742. if(word==1){
  156743. int off=(sgned?0:128);
  156744. vorbis_fpu_setround(&fpu);
  156745. for(j=0;j<samples;j++)
  156746. for(i=0;i<channels;i++){
  156747. val=vorbis_ftoi(pcm[i][j]*128.f);
  156748. if(val>127)val=127;
  156749. else if(val<-128)val=-128;
  156750. *buffer++=val+off;
  156751. }
  156752. vorbis_fpu_restore(fpu);
  156753. }else{
  156754. int off=(sgned?0:32768);
  156755. if(host_endian==bigendianp){
  156756. if(sgned){
  156757. vorbis_fpu_setround(&fpu);
  156758. for(i=0;i<channels;i++) { /* It's faster in this order */
  156759. float *src=pcm[i];
  156760. short *dest=((short *)buffer)+i;
  156761. for(j=0;j<samples;j++) {
  156762. val=vorbis_ftoi(src[j]*32768.f);
  156763. if(val>32767)val=32767;
  156764. else if(val<-32768)val=-32768;
  156765. *dest=val;
  156766. dest+=channels;
  156767. }
  156768. }
  156769. vorbis_fpu_restore(fpu);
  156770. }else{
  156771. vorbis_fpu_setround(&fpu);
  156772. for(i=0;i<channels;i++) {
  156773. float *src=pcm[i];
  156774. short *dest=((short *)buffer)+i;
  156775. for(j=0;j<samples;j++) {
  156776. val=vorbis_ftoi(src[j]*32768.f);
  156777. if(val>32767)val=32767;
  156778. else if(val<-32768)val=-32768;
  156779. *dest=val+off;
  156780. dest+=channels;
  156781. }
  156782. }
  156783. vorbis_fpu_restore(fpu);
  156784. }
  156785. }else if(bigendianp){
  156786. vorbis_fpu_setround(&fpu);
  156787. for(j=0;j<samples;j++)
  156788. for(i=0;i<channels;i++){
  156789. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156790. if(val>32767)val=32767;
  156791. else if(val<-32768)val=-32768;
  156792. val+=off;
  156793. *buffer++=(val>>8);
  156794. *buffer++=(val&0xff);
  156795. }
  156796. vorbis_fpu_restore(fpu);
  156797. }else{
  156798. int val;
  156799. vorbis_fpu_setround(&fpu);
  156800. for(j=0;j<samples;j++)
  156801. for(i=0;i<channels;i++){
  156802. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156803. if(val>32767)val=32767;
  156804. else if(val<-32768)val=-32768;
  156805. val+=off;
  156806. *buffer++=(val&0xff);
  156807. *buffer++=(val>>8);
  156808. }
  156809. vorbis_fpu_restore(fpu);
  156810. }
  156811. }
  156812. }
  156813. vorbis_synthesis_read(&vf->vd,samples);
  156814. vf->pcm_offset+=samples;
  156815. if(bitstream)*bitstream=vf->current_link;
  156816. return(samples*bytespersample);
  156817. }else{
  156818. return(samples);
  156819. }
  156820. }
  156821. /* input values: pcm_channels) a float vector per channel of output
  156822. length) the sample length being read by the app
  156823. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156824. 0) EOF
  156825. n) number of samples of PCM actually returned. The
  156826. below works on a packet-by-packet basis, so the
  156827. return length is not related to the 'length' passed
  156828. in, just guaranteed to fit.
  156829. *section) set to the logical bitstream number */
  156830. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156831. int *bitstream){
  156832. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156833. while(1){
  156834. if(vf->ready_state==INITSET){
  156835. float **pcm;
  156836. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156837. if(samples){
  156838. if(pcm_channels)*pcm_channels=pcm;
  156839. if(samples>length)samples=length;
  156840. vorbis_synthesis_read(&vf->vd,samples);
  156841. vf->pcm_offset+=samples;
  156842. if(bitstream)*bitstream=vf->current_link;
  156843. return samples;
  156844. }
  156845. }
  156846. /* suck in another packet */
  156847. {
  156848. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156849. if(ret==OV_EOF)return(0);
  156850. if(ret<=0)return(ret);
  156851. }
  156852. }
  156853. }
  156854. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156855. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156856. ogg_int64_t off);
  156857. static void _ov_splice(float **pcm,float **lappcm,
  156858. int n1, int n2,
  156859. int ch1, int ch2,
  156860. float *w1, float *w2){
  156861. int i,j;
  156862. float *w=w1;
  156863. int n=n1;
  156864. if(n1>n2){
  156865. n=n2;
  156866. w=w2;
  156867. }
  156868. /* splice */
  156869. for(j=0;j<ch1 && j<ch2;j++){
  156870. float *s=lappcm[j];
  156871. float *d=pcm[j];
  156872. for(i=0;i<n;i++){
  156873. float wd=w[i]*w[i];
  156874. float ws=1.-wd;
  156875. d[i]=d[i]*wd + s[i]*ws;
  156876. }
  156877. }
  156878. /* window from zero */
  156879. for(;j<ch2;j++){
  156880. float *d=pcm[j];
  156881. for(i=0;i<n;i++){
  156882. float wd=w[i]*w[i];
  156883. d[i]=d[i]*wd;
  156884. }
  156885. }
  156886. }
  156887. /* make sure vf is INITSET */
  156888. static int _ov_initset(OggVorbis_File *vf){
  156889. while(1){
  156890. if(vf->ready_state==INITSET)break;
  156891. /* suck in another packet */
  156892. {
  156893. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156894. if(ret<0 && ret!=OV_HOLE)return(ret);
  156895. }
  156896. }
  156897. return 0;
  156898. }
  156899. /* make sure vf is INITSET and that we have a primed buffer; if
  156900. we're crosslapping at a stream section boundary, this also makes
  156901. sure we're sanity checking against the right stream information */
  156902. static int _ov_initprime(OggVorbis_File *vf){
  156903. vorbis_dsp_state *vd=&vf->vd;
  156904. while(1){
  156905. if(vf->ready_state==INITSET)
  156906. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156907. /* suck in another packet */
  156908. {
  156909. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156910. if(ret<0 && ret!=OV_HOLE)return(ret);
  156911. }
  156912. }
  156913. return 0;
  156914. }
  156915. /* grab enough data for lapping from vf; this may be in the form of
  156916. unreturned, already-decoded pcm, remaining PCM we will need to
  156917. decode, or synthetic postextrapolation from last packets. */
  156918. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156919. float **lappcm,int lapsize){
  156920. int lapcount=0,i;
  156921. float **pcm;
  156922. /* try first to decode the lapping data */
  156923. while(lapcount<lapsize){
  156924. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156925. if(samples){
  156926. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156927. for(i=0;i<vi->channels;i++)
  156928. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156929. lapcount+=samples;
  156930. vorbis_synthesis_read(vd,samples);
  156931. }else{
  156932. /* suck in another packet */
  156933. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156934. if(ret==OV_EOF)break;
  156935. }
  156936. }
  156937. if(lapcount<lapsize){
  156938. /* failed to get lapping data from normal decode; pry it from the
  156939. postextrapolation buffering, or the second half of the MDCT
  156940. from the last packet */
  156941. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156942. if(samples==0){
  156943. for(i=0;i<vi->channels;i++)
  156944. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156945. lapcount=lapsize;
  156946. }else{
  156947. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156948. for(i=0;i<vi->channels;i++)
  156949. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156950. lapcount+=samples;
  156951. }
  156952. }
  156953. }
  156954. /* this sets up crosslapping of a sample by using trailing data from
  156955. sample 1 and lapping it into the windowing buffer of sample 2 */
  156956. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156957. vorbis_info *vi1,*vi2;
  156958. float **lappcm;
  156959. float **pcm;
  156960. float *w1,*w2;
  156961. int n1,n2,i,ret,hs1,hs2;
  156962. if(vf1==vf2)return(0); /* degenerate case */
  156963. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156964. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156965. /* the relevant overlap buffers must be pre-checked and pre-primed
  156966. before looking at settings in the event that priming would cross
  156967. a bitstream boundary. So, do it now */
  156968. ret=_ov_initset(vf1);
  156969. if(ret)return(ret);
  156970. ret=_ov_initprime(vf2);
  156971. if(ret)return(ret);
  156972. vi1=ov_info(vf1,-1);
  156973. vi2=ov_info(vf2,-1);
  156974. hs1=ov_halfrate_p(vf1);
  156975. hs2=ov_halfrate_p(vf2);
  156976. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156977. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156978. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156979. w1=vorbis_window(&vf1->vd,0);
  156980. w2=vorbis_window(&vf2->vd,0);
  156981. for(i=0;i<vi1->channels;i++)
  156982. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156983. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156984. /* have a lapping buffer from vf1; now to splice it into the lapping
  156985. buffer of vf2 */
  156986. /* consolidate and expose the buffer. */
  156987. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156988. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156989. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156990. /* splice */
  156991. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156992. /* done */
  156993. return(0);
  156994. }
  156995. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156996. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156997. vorbis_info *vi;
  156998. float **lappcm;
  156999. float **pcm;
  157000. float *w1,*w2;
  157001. int n1,n2,ch1,ch2,hs;
  157002. int i,ret;
  157003. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157004. ret=_ov_initset(vf);
  157005. if(ret)return(ret);
  157006. vi=ov_info(vf,-1);
  157007. hs=ov_halfrate_p(vf);
  157008. ch1=vi->channels;
  157009. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157010. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157011. persistent; even if the decode state
  157012. from this link gets dumped, this
  157013. window array continues to exist */
  157014. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157015. for(i=0;i<ch1;i++)
  157016. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157017. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157018. /* have lapping data; seek and prime the buffer */
  157019. ret=localseek(vf,pos);
  157020. if(ret)return ret;
  157021. ret=_ov_initprime(vf);
  157022. if(ret)return(ret);
  157023. /* Guard against cross-link changes; they're perfectly legal */
  157024. vi=ov_info(vf,-1);
  157025. ch2=vi->channels;
  157026. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157027. w2=vorbis_window(&vf->vd,0);
  157028. /* consolidate and expose the buffer. */
  157029. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157030. /* splice */
  157031. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157032. /* done */
  157033. return(0);
  157034. }
  157035. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157036. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157037. }
  157038. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157039. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157040. }
  157041. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157042. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157043. }
  157044. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157045. int (*localseek)(OggVorbis_File *,double)){
  157046. vorbis_info *vi;
  157047. float **lappcm;
  157048. float **pcm;
  157049. float *w1,*w2;
  157050. int n1,n2,ch1,ch2,hs;
  157051. int i,ret;
  157052. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157053. ret=_ov_initset(vf);
  157054. if(ret)return(ret);
  157055. vi=ov_info(vf,-1);
  157056. hs=ov_halfrate_p(vf);
  157057. ch1=vi->channels;
  157058. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157059. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157060. persistent; even if the decode state
  157061. from this link gets dumped, this
  157062. window array continues to exist */
  157063. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157064. for(i=0;i<ch1;i++)
  157065. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157066. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157067. /* have lapping data; seek and prime the buffer */
  157068. ret=localseek(vf,pos);
  157069. if(ret)return ret;
  157070. ret=_ov_initprime(vf);
  157071. if(ret)return(ret);
  157072. /* Guard against cross-link changes; they're perfectly legal */
  157073. vi=ov_info(vf,-1);
  157074. ch2=vi->channels;
  157075. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157076. w2=vorbis_window(&vf->vd,0);
  157077. /* consolidate and expose the buffer. */
  157078. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157079. /* splice */
  157080. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157081. /* done */
  157082. return(0);
  157083. }
  157084. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157085. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157086. }
  157087. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157088. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157089. }
  157090. #endif
  157091. /*** End of inlined file: vorbisfile.c ***/
  157092. /*** Start of inlined file: window.c ***/
  157093. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157094. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157095. // tasks..
  157096. #if JUCE_MSVC
  157097. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157098. #endif
  157099. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157100. #if JUCE_USE_OGGVORBIS
  157101. #include <stdlib.h>
  157102. #include <math.h>
  157103. static float vwin64[32] = {
  157104. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157105. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157106. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157107. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157108. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157109. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157110. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157111. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157112. };
  157113. static float vwin128[64] = {
  157114. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157115. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157116. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157117. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157118. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157119. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157120. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157121. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157122. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157123. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157124. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157125. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157126. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157127. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157128. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157129. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157130. };
  157131. static float vwin256[128] = {
  157132. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157133. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157134. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157135. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157136. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157137. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157138. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157139. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157140. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157141. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157142. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157143. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157144. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157145. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157146. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157147. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157148. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157149. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157150. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157151. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157152. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157153. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157154. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157155. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157156. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157157. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157158. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157159. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157160. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157161. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157162. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157163. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157164. };
  157165. static float vwin512[256] = {
  157166. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157167. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157168. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157169. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157170. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157171. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157172. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157173. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157174. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157175. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157176. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157177. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157178. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157179. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157180. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157181. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157182. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157183. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157184. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157185. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157186. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157187. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157188. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157189. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157190. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157191. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157192. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157193. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157194. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157195. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157196. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157197. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157198. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157199. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157200. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157201. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157202. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157203. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157204. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157205. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157206. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157207. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157208. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157209. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157210. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157211. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157212. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157213. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157214. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157215. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157216. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157217. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157218. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157219. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157220. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157221. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157222. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157223. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157224. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157225. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157226. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157227. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157228. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157229. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157230. };
  157231. static float vwin1024[512] = {
  157232. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157233. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157234. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157235. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157236. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157237. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157238. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157239. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157240. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157241. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157242. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157243. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157244. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157245. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157246. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157247. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157248. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157249. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157250. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157251. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157252. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157253. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157254. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157255. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157256. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157257. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157258. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157259. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157260. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157261. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157262. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157263. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157264. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157265. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157266. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157267. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157268. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157269. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157270. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157271. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157272. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157273. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157274. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157275. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157276. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157277. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157278. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157279. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157280. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157281. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157282. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157283. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157284. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157285. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157286. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157287. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157288. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157289. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157290. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157291. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157292. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157293. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157294. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157295. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157296. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157297. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157298. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157299. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157300. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157301. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157302. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157303. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157304. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157305. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157306. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157307. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157308. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157309. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157310. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157311. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157312. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157313. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157314. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157315. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157316. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157317. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157318. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157319. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157320. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157321. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157322. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157323. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157324. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157325. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157326. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157327. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157328. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157329. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157330. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157331. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157332. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157333. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157334. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157335. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157336. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157337. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157338. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157339. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157340. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157341. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157342. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157343. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157344. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157345. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157346. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157347. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157348. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157349. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157350. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157351. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157352. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157353. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157354. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157355. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157356. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157357. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157358. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157359. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157360. };
  157361. static float vwin2048[1024] = {
  157362. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157363. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157364. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157365. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157366. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157367. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157368. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157369. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157370. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157371. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157372. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157373. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157374. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157375. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157376. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157377. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157378. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157379. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157380. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157381. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157382. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157383. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157384. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157385. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157386. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157387. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157388. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157389. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157390. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157391. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157392. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157393. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157394. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157395. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157396. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157397. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157398. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157399. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157400. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157401. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157402. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157403. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157404. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157405. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157406. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157407. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157408. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157409. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157410. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157411. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157412. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157413. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157414. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157415. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157416. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157417. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157418. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157419. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157420. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157421. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157422. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157423. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157424. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157425. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157426. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157427. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157428. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157429. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157430. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157431. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157432. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157433. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157434. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157435. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157436. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157437. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157438. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157439. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157440. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157441. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157442. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157443. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157444. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157445. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157446. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157447. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157448. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157449. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157450. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157451. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157452. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157453. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157454. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157455. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157456. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157457. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157458. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157459. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157460. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157461. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157462. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157463. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157464. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157465. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157466. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157467. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157468. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157469. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157470. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157471. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157472. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157473. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157474. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157475. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157476. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157477. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157478. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157479. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157480. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157481. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157482. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157483. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157484. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157485. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157486. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157487. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157488. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157489. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157490. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157491. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157492. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157493. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157494. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157495. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157496. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157497. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157498. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157499. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157500. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157501. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157502. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157503. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157504. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157505. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157506. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157507. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157508. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157509. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157510. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157511. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157512. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157513. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157514. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157515. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157516. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157517. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157518. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157519. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157520. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157521. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157522. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157523. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157524. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157525. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157526. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157527. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157528. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157529. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157530. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157531. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157532. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157533. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157534. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157535. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157536. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157537. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157538. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157539. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157540. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157541. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157542. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157543. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157544. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157545. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157546. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157547. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157548. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157549. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157550. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157551. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157552. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157553. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157554. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157555. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157556. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157557. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157558. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157559. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157560. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157561. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157562. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157563. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157564. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157565. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157566. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157567. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157568. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157569. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157570. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157571. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157572. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157573. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157574. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157575. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157576. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157577. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157578. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157579. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157580. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157581. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157582. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157583. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157584. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157585. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157586. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157587. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157588. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157589. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157590. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157591. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157592. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157593. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157594. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157595. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157596. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157597. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157598. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157599. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157600. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157601. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157602. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157603. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157604. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157605. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157606. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157607. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157608. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157609. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157610. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157611. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157612. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157613. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157614. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157615. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157616. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157617. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157618. };
  157619. static float vwin4096[2048] = {
  157620. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157621. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157622. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157623. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157624. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157625. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157626. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157627. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157628. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157629. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157630. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157631. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157632. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157633. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157634. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157635. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157636. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157637. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157638. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157639. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157640. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157641. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157642. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157643. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157644. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157645. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157646. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157647. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157648. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157649. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157650. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157651. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157652. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157653. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157654. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157655. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157656. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157657. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157658. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157659. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157660. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157661. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157662. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157663. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157664. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157665. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157666. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157667. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157668. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157669. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157670. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157671. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157672. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157673. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157674. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157675. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157676. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157677. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157678. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157679. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157680. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157681. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157682. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157683. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157684. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157685. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157686. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157687. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157688. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157689. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157690. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157691. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157692. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157693. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157694. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157695. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157696. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157697. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157698. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157699. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157700. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157701. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157702. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157703. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157704. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157705. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157706. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157707. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157708. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157709. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157710. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157711. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157712. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157713. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157714. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157715. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157716. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157717. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157718. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157719. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157720. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157721. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157722. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157723. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157724. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157725. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157726. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157727. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157728. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157729. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157730. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157731. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157732. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157733. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157734. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157735. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157736. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157737. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157738. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157739. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157740. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157741. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157742. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157743. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157744. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157745. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157746. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157747. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157748. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157749. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157750. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157751. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157752. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157753. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157754. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157755. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157756. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157757. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157758. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157759. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157760. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157761. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157762. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157763. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157764. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157765. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157766. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157767. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157768. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157769. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157770. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157771. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157772. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157773. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157774. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157775. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157776. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157777. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157778. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157779. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157780. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157781. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157782. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157783. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157784. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157785. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157786. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157787. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157788. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157789. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157790. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157791. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157792. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157793. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157794. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157795. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157796. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157797. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157798. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157799. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157800. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157801. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157802. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157803. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157804. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157805. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157806. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157807. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157808. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157809. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157810. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157811. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157812. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157813. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157814. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157815. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157816. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157817. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157818. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157819. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157820. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157821. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157822. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157823. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157824. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157825. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157826. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157827. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157828. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157829. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157830. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157831. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157832. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157833. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157834. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157835. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157836. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157837. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157838. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157839. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157840. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157841. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157842. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157843. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157844. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157845. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157846. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157847. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157848. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157849. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157850. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157851. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157852. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157853. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157854. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157855. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157856. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157857. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157858. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157859. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157860. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157861. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157862. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157863. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157864. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157865. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157866. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157867. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157868. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157869. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157870. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157871. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157872. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157873. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157874. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157875. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157876. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157877. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157878. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157879. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157880. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157881. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157882. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157883. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157884. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157885. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157886. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157887. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157888. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157889. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157890. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157891. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157892. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157893. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157894. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157895. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157896. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157897. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157898. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157899. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157900. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157901. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157902. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157903. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157904. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157905. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157906. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157907. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157908. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157909. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157910. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157911. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157912. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157913. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157914. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157915. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157916. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157917. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157918. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157919. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157920. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157921. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157922. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157923. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157924. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157925. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157926. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157927. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157928. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157929. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157930. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157931. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157932. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157933. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157934. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157935. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157936. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157937. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157938. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157939. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157940. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157941. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157942. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157943. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157944. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157945. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157946. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157947. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157948. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157949. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157950. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157951. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157952. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157953. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157954. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157955. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157956. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157957. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157958. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157959. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157960. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157961. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157962. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157963. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157964. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157965. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157966. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157967. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157968. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157969. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157970. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157971. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157972. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157973. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157974. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157975. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157976. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157977. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157978. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157979. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157980. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157981. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157982. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157983. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157984. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157985. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157986. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157987. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157988. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157989. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157990. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157991. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157992. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157993. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157994. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157995. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157996. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157997. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157998. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157999. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158000. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158001. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158002. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158003. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158004. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158005. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158006. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158007. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158008. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158009. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158010. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158011. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158012. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158013. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158014. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158015. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158016. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158017. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158018. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158019. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158020. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158021. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158022. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158023. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158024. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158025. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158026. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158027. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158028. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158029. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158030. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158031. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158032. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158033. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158034. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158035. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158036. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158037. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158038. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158039. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158040. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158041. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158042. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158043. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158044. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158045. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158046. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158047. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158048. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158049. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158050. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158051. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158052. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158053. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158054. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158055. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158056. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158057. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158058. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158059. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158060. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158061. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158062. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158063. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158064. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158065. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158066. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158067. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158068. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158069. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158070. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158071. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158072. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158073. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158074. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158075. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158076. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158077. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158078. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158079. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158080. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158081. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158082. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158083. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158084. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158085. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158086. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158087. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158088. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158089. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158090. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158091. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158092. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158093. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158094. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158095. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158096. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158097. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158098. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158099. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158100. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158101. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158102. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158103. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158104. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158105. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158106. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158107. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158108. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158109. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158110. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158111. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158112. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158113. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158114. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158115. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158116. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158117. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158118. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158119. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158120. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158121. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158122. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158123. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158124. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158125. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158126. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158127. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158128. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158129. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158130. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158131. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158132. };
  158133. static float vwin8192[4096] = {
  158134. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158135. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158136. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158137. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158138. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158139. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158140. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158141. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158142. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158143. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158144. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158145. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158146. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158147. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158148. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158149. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158150. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158151. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158152. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158153. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158154. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158155. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158156. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158157. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158158. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158159. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158160. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158161. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158162. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158163. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158164. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158165. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158166. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158167. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158168. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158169. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158170. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158171. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158172. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158173. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158174. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158175. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158176. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158177. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158178. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158179. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158180. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158181. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158182. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158183. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158184. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158185. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158186. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158187. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158188. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158189. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158190. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158191. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158192. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158193. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158194. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158195. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158196. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158197. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158198. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158199. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158200. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158201. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158202. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158203. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158204. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158205. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158206. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158207. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158208. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158209. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158210. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158211. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158212. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158213. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158214. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158215. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158216. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158217. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158218. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158219. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158220. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158221. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158222. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158223. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158224. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158225. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158226. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158227. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158228. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158229. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158230. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158231. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158232. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158233. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158234. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158235. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158236. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158237. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158238. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158239. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158240. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158241. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158242. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158243. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158244. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158245. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158246. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158247. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158248. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158249. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158250. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158251. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158252. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158253. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158254. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158255. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158256. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158257. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158258. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158259. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158260. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158261. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158262. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158263. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158264. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158265. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158266. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158267. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158268. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158269. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158270. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158271. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158272. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158273. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158274. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158275. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158276. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158277. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158278. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158279. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158280. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158281. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158282. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158283. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158284. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158285. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158286. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158287. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158288. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158289. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158290. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158291. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158292. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158293. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158294. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158295. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158296. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158297. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158298. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158299. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158300. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158301. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158302. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158303. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158304. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158305. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158306. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158307. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158308. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158309. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158310. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158311. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158312. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158313. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158314. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158315. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158316. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158317. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158318. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158319. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158320. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158321. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158322. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158323. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158324. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158325. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158326. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158327. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158328. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158329. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158330. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158331. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158332. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158333. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158334. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158335. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158336. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158337. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158338. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158339. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158340. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158341. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158342. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158343. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158344. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158345. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158346. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158347. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158348. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158349. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158350. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158351. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158352. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158353. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158354. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158355. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158356. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158357. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158358. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158359. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158360. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158361. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158362. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158363. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158364. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158365. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158366. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158367. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158368. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158369. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158370. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158371. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158372. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158373. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158374. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158375. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158376. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158377. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158378. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158379. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158380. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158381. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158382. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158383. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158384. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158385. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158386. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158387. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158388. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158389. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158390. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158391. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158392. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158393. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158394. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158395. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158396. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158397. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158398. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158399. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158400. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158401. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158402. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158403. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158404. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158405. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158406. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158407. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158408. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158409. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158410. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158411. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158412. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158413. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158414. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158415. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158416. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158417. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158418. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158419. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158420. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158421. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158422. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158423. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158424. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158425. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158426. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158427. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158428. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158429. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158430. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158431. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158432. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158433. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158434. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158435. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158436. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158437. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158438. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158439. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158440. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158441. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158442. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158443. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158444. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158445. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158446. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158447. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158448. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158449. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158450. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158451. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158452. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158453. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158454. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158455. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158456. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158457. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158458. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158459. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158460. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158461. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158462. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158463. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158464. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158465. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158466. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158467. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158468. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158469. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158470. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158471. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158472. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158473. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158474. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158475. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158476. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158477. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158478. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158479. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158480. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158481. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158482. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158483. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158484. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158485. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158486. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158487. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158488. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158489. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158490. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158491. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158492. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158493. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158494. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158495. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158496. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158497. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158498. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158499. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158500. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158501. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158502. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158503. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158504. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158505. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158506. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158507. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158508. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158509. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158510. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158511. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158512. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158513. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158514. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158515. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158516. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158517. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158518. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158519. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158520. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158521. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158522. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158523. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158524. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158525. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158526. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158527. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158528. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158529. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158530. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158531. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158532. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158533. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158534. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158535. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158536. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158537. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158538. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158539. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158540. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158541. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158542. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158543. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158544. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158545. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158546. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158547. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158548. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158549. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158550. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158551. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158552. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158553. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158554. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158555. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158556. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158557. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158558. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158559. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158560. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158561. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158562. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158563. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158564. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158565. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158566. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158567. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158568. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158569. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158570. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158571. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158572. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158573. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158574. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158575. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158576. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158577. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158578. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158579. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158580. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158581. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158582. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158583. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158584. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158585. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158586. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158587. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158588. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158589. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158590. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158591. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158592. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158593. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158594. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158595. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158596. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158597. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158598. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158599. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158600. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158601. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158602. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158603. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158604. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158605. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158606. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158607. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158608. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158609. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158610. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158611. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158612. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158613. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158614. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158615. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158616. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158617. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158618. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158619. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158620. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158621. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158622. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158623. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158624. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158625. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158626. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158627. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158628. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158629. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158630. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158631. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158632. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158633. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158634. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158635. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158636. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158637. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158638. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158639. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158640. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158641. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158642. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158643. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158644. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158645. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158646. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158647. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158648. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158649. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158650. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158651. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158652. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158653. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158654. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158655. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158656. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158657. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158658. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158659. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158660. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158661. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158662. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158663. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158664. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158665. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158666. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158667. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158668. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158669. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158670. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158671. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158672. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158673. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158674. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158675. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158676. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158677. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158678. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158679. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158680. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158681. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158682. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158683. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158684. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158685. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158686. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158687. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158688. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158689. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158690. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158691. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158692. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158693. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158694. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158695. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158696. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158697. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158698. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158699. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158700. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158701. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158702. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158703. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158704. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158705. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158706. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158707. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158708. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158709. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158710. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158711. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158712. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158713. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158714. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158715. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158716. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158717. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158718. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158719. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158720. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158721. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158722. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158723. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158724. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158725. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158726. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158727. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158728. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158729. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158730. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158731. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158732. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158733. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158734. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158735. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158736. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158737. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158738. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158739. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158740. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158741. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158742. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158743. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158744. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158745. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158746. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158747. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158748. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158749. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158750. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158751. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158752. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158753. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158754. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158755. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158756. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158757. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158758. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158759. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158760. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158761. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158762. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158763. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158764. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158765. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158766. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158767. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158768. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158769. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158770. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158771. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158772. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158773. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158774. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158775. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158776. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158777. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158778. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158779. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158780. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158781. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158782. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158783. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158784. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158785. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158786. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158787. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158788. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158789. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158790. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158791. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158792. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158793. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158794. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158795. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158796. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158797. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158798. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158799. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158800. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158801. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158802. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158803. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158804. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158805. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158806. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158807. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158808. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158809. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158810. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158811. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158812. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158813. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158814. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158815. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158816. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158817. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158818. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158819. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158820. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158821. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158822. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158823. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158824. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158825. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158826. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158827. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158828. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158829. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158830. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158831. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158832. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158833. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158834. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158835. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158836. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158837. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158838. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158839. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158840. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158841. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158842. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158843. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158844. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158845. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158846. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158847. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158848. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158849. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158850. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158851. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158852. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158853. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158854. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158855. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158856. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158857. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158858. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158859. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158860. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158861. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158862. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158863. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158864. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158865. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158866. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158867. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158868. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158869. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158870. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158871. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158872. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158873. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158874. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158875. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158876. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158877. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158878. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158879. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158880. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158881. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158882. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158883. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158884. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158885. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158886. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158887. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158888. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158889. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158890. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158891. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158892. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158893. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158894. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158895. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158896. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158897. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158898. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158899. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158900. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158901. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158902. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158903. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158904. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158905. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158906. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158907. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158908. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158909. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158910. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158911. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158912. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158913. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158914. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158915. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158916. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158917. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158918. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158919. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158920. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158921. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158922. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158923. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158924. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158925. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158926. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158927. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158928. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158929. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158930. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158931. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158932. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158933. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158934. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158935. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158936. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158937. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158938. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158939. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158940. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158941. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158942. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158943. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158944. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158945. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158946. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158947. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158948. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158949. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158950. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158951. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158952. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158953. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158954. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158955. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158956. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158957. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158958. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158959. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158960. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158961. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158962. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158963. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158964. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158965. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158966. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158967. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158968. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158969. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158970. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158971. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158972. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158973. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158974. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158975. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158976. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158977. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158978. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158979. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158980. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158981. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158982. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158983. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158984. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158985. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158986. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158987. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158988. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158989. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158990. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158991. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158992. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158993. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158994. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158995. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158996. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158997. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158998. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158999. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159000. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159001. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159002. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159003. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159004. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159005. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159006. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159007. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159008. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159009. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159010. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159011. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159012. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159013. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159014. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159015. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159016. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159017. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159018. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159019. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159020. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159021. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159022. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159023. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159024. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159025. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159026. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159027. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159028. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159029. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159030. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159031. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159032. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159033. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159034. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159035. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159036. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159037. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159038. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159039. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159040. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159041. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159042. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159043. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159044. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159045. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159046. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159047. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159048. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159049. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159050. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159051. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159052. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159053. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159054. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159055. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159056. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159057. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159058. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159059. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159060. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159061. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159062. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159063. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159064. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159065. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159066. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159067. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159068. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159069. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159070. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159071. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159072. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159073. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159074. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159075. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159076. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159077. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159078. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159079. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159080. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159081. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159082. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159083. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159084. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159085. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159086. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159087. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159088. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159089. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159090. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159091. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159092. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159093. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159094. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159095. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159096. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159097. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159098. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159099. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159100. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159101. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159102. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159103. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159104. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159105. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159106. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159107. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159108. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159109. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159110. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159111. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159112. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159113. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159114. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159115. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159116. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159117. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159118. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159119. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159120. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159121. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159122. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159123. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159124. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159125. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159126. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159127. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159128. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159129. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159130. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159131. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159132. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159133. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159134. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159135. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159136. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159137. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159138. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159139. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159140. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159141. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159142. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159143. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159144. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159145. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159146. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159147. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159148. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159149. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159150. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159151. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159152. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159153. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159154. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159155. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159156. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159157. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159158. };
  159159. static float *vwin[8] = {
  159160. vwin64,
  159161. vwin128,
  159162. vwin256,
  159163. vwin512,
  159164. vwin1024,
  159165. vwin2048,
  159166. vwin4096,
  159167. vwin8192,
  159168. };
  159169. float *_vorbis_window_get(int n){
  159170. return vwin[n];
  159171. }
  159172. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159173. int lW,int W,int nW){
  159174. lW=(W?lW:0);
  159175. nW=(W?nW:0);
  159176. {
  159177. float *windowLW=vwin[winno[lW]];
  159178. float *windowNW=vwin[winno[nW]];
  159179. long n=blocksizes[W];
  159180. long ln=blocksizes[lW];
  159181. long rn=blocksizes[nW];
  159182. long leftbegin=n/4-ln/4;
  159183. long leftend=leftbegin+ln/2;
  159184. long rightbegin=n/2+n/4-rn/4;
  159185. long rightend=rightbegin+rn/2;
  159186. int i,p;
  159187. for(i=0;i<leftbegin;i++)
  159188. d[i]=0.f;
  159189. for(p=0;i<leftend;i++,p++)
  159190. d[i]*=windowLW[p];
  159191. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159192. d[i]*=windowNW[p];
  159193. for(;i<n;i++)
  159194. d[i]=0.f;
  159195. }
  159196. }
  159197. #endif
  159198. /*** End of inlined file: window.c ***/
  159199. #else
  159200. #include <vorbis/vorbisenc.h>
  159201. #include <vorbis/codec.h>
  159202. #include <vorbis/vorbisfile.h>
  159203. #endif
  159204. }
  159205. #undef max
  159206. #undef min
  159207. BEGIN_JUCE_NAMESPACE
  159208. static const char* const oggFormatName = "Ogg-Vorbis file";
  159209. static const char* const oggExtensions[] = { ".ogg", 0 };
  159210. class OggReader : public AudioFormatReader
  159211. {
  159212. OggVorbisNamespace::OggVorbis_File ovFile;
  159213. OggVorbisNamespace::ov_callbacks callbacks;
  159214. AudioSampleBuffer reservoir;
  159215. int reservoirStart, samplesInReservoir;
  159216. public:
  159217. OggReader (InputStream* const inp)
  159218. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159219. reservoir (2, 4096),
  159220. reservoirStart (0),
  159221. samplesInReservoir (0)
  159222. {
  159223. using namespace OggVorbisNamespace;
  159224. sampleRate = 0;
  159225. usesFloatingPointData = true;
  159226. callbacks.read_func = &oggReadCallback;
  159227. callbacks.seek_func = &oggSeekCallback;
  159228. callbacks.close_func = &oggCloseCallback;
  159229. callbacks.tell_func = &oggTellCallback;
  159230. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159231. if (err == 0)
  159232. {
  159233. vorbis_info* info = ov_info (&ovFile, -1);
  159234. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159235. numChannels = info->channels;
  159236. bitsPerSample = 16;
  159237. sampleRate = info->rate;
  159238. reservoir.setSize (numChannels,
  159239. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159240. }
  159241. }
  159242. ~OggReader()
  159243. {
  159244. OggVorbisNamespace::ov_clear (&ovFile);
  159245. }
  159246. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159247. int64 startSampleInFile, int numSamples)
  159248. {
  159249. while (numSamples > 0)
  159250. {
  159251. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159252. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159253. {
  159254. // got a few samples overlapping, so use them before seeking..
  159255. const int numToUse = jmin (numSamples, numAvailable);
  159256. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159257. if (destSamples[i] != 0)
  159258. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159259. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159260. sizeof (float) * numToUse);
  159261. startSampleInFile += numToUse;
  159262. numSamples -= numToUse;
  159263. startOffsetInDestBuffer += numToUse;
  159264. if (numSamples == 0)
  159265. break;
  159266. }
  159267. if (startSampleInFile < reservoirStart
  159268. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159269. {
  159270. // buffer miss, so refill the reservoir
  159271. int bitStream = 0;
  159272. reservoirStart = jmax (0, (int) startSampleInFile);
  159273. samplesInReservoir = reservoir.getNumSamples();
  159274. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159275. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159276. int offset = 0;
  159277. int numToRead = samplesInReservoir;
  159278. while (numToRead > 0)
  159279. {
  159280. float** dataIn = 0;
  159281. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159282. if (samps <= 0)
  159283. break;
  159284. jassert (samps <= numToRead);
  159285. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159286. {
  159287. memcpy (reservoir.getSampleData (i, offset),
  159288. dataIn[i],
  159289. sizeof (float) * samps);
  159290. }
  159291. numToRead -= samps;
  159292. offset += samps;
  159293. }
  159294. if (numToRead > 0)
  159295. reservoir.clear (offset, numToRead);
  159296. }
  159297. }
  159298. if (numSamples > 0)
  159299. {
  159300. for (int i = numDestChannels; --i >= 0;)
  159301. if (destSamples[i] != 0)
  159302. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159303. sizeof (int) * numSamples);
  159304. }
  159305. return true;
  159306. }
  159307. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159308. {
  159309. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159310. }
  159311. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159312. {
  159313. InputStream* const in = static_cast <InputStream*> (datasource);
  159314. if (whence == SEEK_CUR)
  159315. offset += in->getPosition();
  159316. else if (whence == SEEK_END)
  159317. offset += in->getTotalLength();
  159318. in->setPosition (offset);
  159319. return 0;
  159320. }
  159321. static int oggCloseCallback (void*)
  159322. {
  159323. return 0;
  159324. }
  159325. static long oggTellCallback (void* datasource)
  159326. {
  159327. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159328. }
  159329. juce_UseDebuggingNewOperator
  159330. };
  159331. class OggWriter : public AudioFormatWriter
  159332. {
  159333. OggVorbisNamespace::ogg_stream_state os;
  159334. OggVorbisNamespace::ogg_page og;
  159335. OggVorbisNamespace::ogg_packet op;
  159336. OggVorbisNamespace::vorbis_info vi;
  159337. OggVorbisNamespace::vorbis_comment vc;
  159338. OggVorbisNamespace::vorbis_dsp_state vd;
  159339. OggVorbisNamespace::vorbis_block vb;
  159340. public:
  159341. bool ok;
  159342. OggWriter (OutputStream* const out,
  159343. const double sampleRate,
  159344. const int numChannels,
  159345. const int bitsPerSample,
  159346. const int qualityIndex)
  159347. : AudioFormatWriter (out, TRANS (oggFormatName),
  159348. sampleRate,
  159349. numChannels,
  159350. bitsPerSample)
  159351. {
  159352. using namespace OggVorbisNamespace;
  159353. ok = false;
  159354. vorbis_info_init (&vi);
  159355. if (vorbis_encode_init_vbr (&vi,
  159356. numChannels,
  159357. (int) sampleRate,
  159358. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159359. {
  159360. vorbis_comment_init (&vc);
  159361. if (JUCEApplication::getInstance() != 0)
  159362. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159363. vorbis_analysis_init (&vd, &vi);
  159364. vorbis_block_init (&vd, &vb);
  159365. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159366. ogg_packet header;
  159367. ogg_packet header_comm;
  159368. ogg_packet header_code;
  159369. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159370. ogg_stream_packetin (&os, &header);
  159371. ogg_stream_packetin (&os, &header_comm);
  159372. ogg_stream_packetin (&os, &header_code);
  159373. for (;;)
  159374. {
  159375. if (ogg_stream_flush (&os, &og) == 0)
  159376. break;
  159377. output->write (og.header, og.header_len);
  159378. output->write (og.body, og.body_len);
  159379. }
  159380. ok = true;
  159381. }
  159382. }
  159383. ~OggWriter()
  159384. {
  159385. using namespace OggVorbisNamespace;
  159386. if (ok)
  159387. {
  159388. // write a zero-length packet to show ogg that we're finished..
  159389. write (0, 0);
  159390. ogg_stream_clear (&os);
  159391. vorbis_block_clear (&vb);
  159392. vorbis_dsp_clear (&vd);
  159393. vorbis_comment_clear (&vc);
  159394. vorbis_info_clear (&vi);
  159395. output->flush();
  159396. }
  159397. else
  159398. {
  159399. vorbis_info_clear (&vi);
  159400. output = 0; // to stop the base class deleting this, as it needs to be returned
  159401. // to the caller of createWriter()
  159402. }
  159403. }
  159404. bool write (const int** samplesToWrite, int numSamples)
  159405. {
  159406. using namespace OggVorbisNamespace;
  159407. if (! ok)
  159408. return false;
  159409. if (numSamples > 0)
  159410. {
  159411. const double gain = 1.0 / 0x80000000u;
  159412. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159413. for (int i = numChannels; --i >= 0;)
  159414. {
  159415. float* const dst = vorbisBuffer[i];
  159416. const int* const src = samplesToWrite [i];
  159417. if (src != 0 && dst != 0)
  159418. {
  159419. for (int j = 0; j < numSamples; ++j)
  159420. dst[j] = (float) (src[j] * gain);
  159421. }
  159422. }
  159423. }
  159424. vorbis_analysis_wrote (&vd, numSamples);
  159425. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159426. {
  159427. vorbis_analysis (&vb, 0);
  159428. vorbis_bitrate_addblock (&vb);
  159429. while (vorbis_bitrate_flushpacket (&vd, &op))
  159430. {
  159431. ogg_stream_packetin (&os, &op);
  159432. for (;;)
  159433. {
  159434. if (ogg_stream_pageout (&os, &og) == 0)
  159435. break;
  159436. output->write (og.header, og.header_len);
  159437. output->write (og.body, og.body_len);
  159438. if (ogg_page_eos (&og))
  159439. break;
  159440. }
  159441. }
  159442. }
  159443. return true;
  159444. }
  159445. juce_UseDebuggingNewOperator
  159446. };
  159447. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159448. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159449. {
  159450. }
  159451. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159452. {
  159453. }
  159454. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159455. {
  159456. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159457. return Array <int> (rates);
  159458. }
  159459. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159460. {
  159461. const int depths[] = { 32, 0 };
  159462. return Array <int> (depths);
  159463. }
  159464. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159465. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159466. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159467. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159468. const bool deleteStreamIfOpeningFails)
  159469. {
  159470. ScopedPointer <OggReader> r (new OggReader (in));
  159471. if (r->sampleRate != 0)
  159472. return r.release();
  159473. if (! deleteStreamIfOpeningFails)
  159474. r->input = 0;
  159475. return 0;
  159476. }
  159477. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159478. double sampleRate,
  159479. unsigned int numChannels,
  159480. int bitsPerSample,
  159481. const StringPairArray& /*metadataValues*/,
  159482. int qualityOptionIndex)
  159483. {
  159484. ScopedPointer <OggWriter> w (new OggWriter (out,
  159485. sampleRate,
  159486. numChannels,
  159487. bitsPerSample,
  159488. qualityOptionIndex));
  159489. return w->ok ? w.release() : 0;
  159490. }
  159491. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159492. {
  159493. StringArray s;
  159494. s.add ("Low Quality");
  159495. s.add ("Medium Quality");
  159496. s.add ("High Quality");
  159497. return s;
  159498. }
  159499. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159500. {
  159501. FileInputStream* const in = source.createInputStream();
  159502. if (in != 0)
  159503. {
  159504. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159505. if (r != 0)
  159506. {
  159507. const int64 numSamps = r->lengthInSamples;
  159508. r = 0;
  159509. const int64 fileNumSamps = source.getSize() / 4;
  159510. const double ratio = numSamps / (double) fileNumSamps;
  159511. if (ratio > 12.0)
  159512. return 0;
  159513. else if (ratio > 6.0)
  159514. return 1;
  159515. else
  159516. return 2;
  159517. }
  159518. }
  159519. return 1;
  159520. }
  159521. END_JUCE_NAMESPACE
  159522. #endif
  159523. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159524. #endif
  159525. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159526. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159527. #if JUCE_MSVC
  159528. #pragma warning (push)
  159529. #endif
  159530. namespace jpeglibNamespace
  159531. {
  159532. #if JUCE_INCLUDE_JPEGLIB_CODE
  159533. #if JUCE_MINGW
  159534. typedef unsigned char boolean;
  159535. #endif
  159536. #define JPEG_INTERNALS
  159537. #undef FAR
  159538. /*** Start of inlined file: jpeglib.h ***/
  159539. #ifndef JPEGLIB_H
  159540. #define JPEGLIB_H
  159541. /*
  159542. * First we include the configuration files that record how this
  159543. * installation of the JPEG library is set up. jconfig.h can be
  159544. * generated automatically for many systems. jmorecfg.h contains
  159545. * manual configuration options that most people need not worry about.
  159546. */
  159547. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159548. /*** Start of inlined file: jconfig.h ***/
  159549. /* see jconfig.doc for explanations */
  159550. // disable all the warnings under MSVC
  159551. #ifdef _MSC_VER
  159552. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159553. #endif
  159554. #ifdef __BORLANDC__
  159555. #pragma warn -8057
  159556. #pragma warn -8019
  159557. #pragma warn -8004
  159558. #pragma warn -8008
  159559. #endif
  159560. #define HAVE_PROTOTYPES
  159561. #define HAVE_UNSIGNED_CHAR
  159562. #define HAVE_UNSIGNED_SHORT
  159563. /* #define void char */
  159564. /* #define const */
  159565. #undef CHAR_IS_UNSIGNED
  159566. #define HAVE_STDDEF_H
  159567. #define HAVE_STDLIB_H
  159568. #undef NEED_BSD_STRINGS
  159569. #undef NEED_SYS_TYPES_H
  159570. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159571. #undef NEED_SHORT_EXTERNAL_NAMES
  159572. #undef INCOMPLETE_TYPES_BROKEN
  159573. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159574. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159575. typedef unsigned char boolean;
  159576. #endif
  159577. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159578. #ifdef JPEG_INTERNALS
  159579. #undef RIGHT_SHIFT_IS_UNSIGNED
  159580. #endif /* JPEG_INTERNALS */
  159581. #ifdef JPEG_CJPEG_DJPEG
  159582. #define BMP_SUPPORTED /* BMP image file format */
  159583. #define GIF_SUPPORTED /* GIF image file format */
  159584. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159585. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159586. #define TARGA_SUPPORTED /* Targa image file format */
  159587. #define TWO_FILE_COMMANDLINE /* optional */
  159588. #define USE_SETMODE /* Microsoft has setmode() */
  159589. #undef NEED_SIGNAL_CATCHER
  159590. #undef DONT_USE_B_MODE
  159591. #undef PROGRESS_REPORT /* optional */
  159592. #endif /* JPEG_CJPEG_DJPEG */
  159593. /*** End of inlined file: jconfig.h ***/
  159594. /* widely used configuration options */
  159595. #endif
  159596. /*** Start of inlined file: jmorecfg.h ***/
  159597. /*
  159598. * Define BITS_IN_JSAMPLE as either
  159599. * 8 for 8-bit sample values (the usual setting)
  159600. * 12 for 12-bit sample values
  159601. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159602. * JPEG standard, and the IJG code does not support anything else!
  159603. * We do not support run-time selection of data precision, sorry.
  159604. */
  159605. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159606. /*
  159607. * Maximum number of components (color channels) allowed in JPEG image.
  159608. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159609. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159610. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159611. * really short on memory. (Each allowed component costs a hundred or so
  159612. * bytes of storage, whether actually used in an image or not.)
  159613. */
  159614. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159615. /*
  159616. * Basic data types.
  159617. * You may need to change these if you have a machine with unusual data
  159618. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159619. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159620. * but it had better be at least 16.
  159621. */
  159622. /* Representation of a single sample (pixel element value).
  159623. * We frequently allocate large arrays of these, so it's important to keep
  159624. * them small. But if you have memory to burn and access to char or short
  159625. * arrays is very slow on your hardware, you might want to change these.
  159626. */
  159627. #if BITS_IN_JSAMPLE == 8
  159628. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159629. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159630. */
  159631. #ifdef HAVE_UNSIGNED_CHAR
  159632. typedef unsigned char JSAMPLE;
  159633. #define GETJSAMPLE(value) ((int) (value))
  159634. #else /* not HAVE_UNSIGNED_CHAR */
  159635. typedef char JSAMPLE;
  159636. #ifdef CHAR_IS_UNSIGNED
  159637. #define GETJSAMPLE(value) ((int) (value))
  159638. #else
  159639. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159640. #endif /* CHAR_IS_UNSIGNED */
  159641. #endif /* HAVE_UNSIGNED_CHAR */
  159642. #define MAXJSAMPLE 255
  159643. #define CENTERJSAMPLE 128
  159644. #endif /* BITS_IN_JSAMPLE == 8 */
  159645. #if BITS_IN_JSAMPLE == 12
  159646. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159647. * On nearly all machines "short" will do nicely.
  159648. */
  159649. typedef short JSAMPLE;
  159650. #define GETJSAMPLE(value) ((int) (value))
  159651. #define MAXJSAMPLE 4095
  159652. #define CENTERJSAMPLE 2048
  159653. #endif /* BITS_IN_JSAMPLE == 12 */
  159654. /* Representation of a DCT frequency coefficient.
  159655. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159656. * Again, we allocate large arrays of these, but you can change to int
  159657. * if you have memory to burn and "short" is really slow.
  159658. */
  159659. typedef short JCOEF;
  159660. /* Compressed datastreams are represented as arrays of JOCTET.
  159661. * These must be EXACTLY 8 bits wide, at least once they are written to
  159662. * external storage. Note that when using the stdio data source/destination
  159663. * managers, this is also the data type passed to fread/fwrite.
  159664. */
  159665. #ifdef HAVE_UNSIGNED_CHAR
  159666. typedef unsigned char JOCTET;
  159667. #define GETJOCTET(value) (value)
  159668. #else /* not HAVE_UNSIGNED_CHAR */
  159669. typedef char JOCTET;
  159670. #ifdef CHAR_IS_UNSIGNED
  159671. #define GETJOCTET(value) (value)
  159672. #else
  159673. #define GETJOCTET(value) ((value) & 0xFF)
  159674. #endif /* CHAR_IS_UNSIGNED */
  159675. #endif /* HAVE_UNSIGNED_CHAR */
  159676. /* These typedefs are used for various table entries and so forth.
  159677. * They must be at least as wide as specified; but making them too big
  159678. * won't cost a huge amount of memory, so we don't provide special
  159679. * extraction code like we did for JSAMPLE. (In other words, these
  159680. * typedefs live at a different point on the speed/space tradeoff curve.)
  159681. */
  159682. /* UINT8 must hold at least the values 0..255. */
  159683. #ifdef HAVE_UNSIGNED_CHAR
  159684. typedef unsigned char UINT8;
  159685. #else /* not HAVE_UNSIGNED_CHAR */
  159686. #ifdef CHAR_IS_UNSIGNED
  159687. typedef char UINT8;
  159688. #else /* not CHAR_IS_UNSIGNED */
  159689. typedef short UINT8;
  159690. #endif /* CHAR_IS_UNSIGNED */
  159691. #endif /* HAVE_UNSIGNED_CHAR */
  159692. /* UINT16 must hold at least the values 0..65535. */
  159693. #ifdef HAVE_UNSIGNED_SHORT
  159694. typedef unsigned short UINT16;
  159695. #else /* not HAVE_UNSIGNED_SHORT */
  159696. typedef unsigned int UINT16;
  159697. #endif /* HAVE_UNSIGNED_SHORT */
  159698. /* INT16 must hold at least the values -32768..32767. */
  159699. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159700. typedef short INT16;
  159701. #endif
  159702. /* INT32 must hold at least signed 32-bit values. */
  159703. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159704. typedef long INT32;
  159705. #endif
  159706. /* Datatype used for image dimensions. The JPEG standard only supports
  159707. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159708. * "unsigned int" is sufficient on all machines. However, if you need to
  159709. * handle larger images and you don't mind deviating from the spec, you
  159710. * can change this datatype.
  159711. */
  159712. typedef unsigned int JDIMENSION;
  159713. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159714. /* These macros are used in all function definitions and extern declarations.
  159715. * You could modify them if you need to change function linkage conventions;
  159716. * in particular, you'll need to do that to make the library a Windows DLL.
  159717. * Another application is to make all functions global for use with debuggers
  159718. * or code profilers that require it.
  159719. */
  159720. /* a function called through method pointers: */
  159721. #define METHODDEF(type) static type
  159722. /* a function used only in its module: */
  159723. #define LOCAL(type) static type
  159724. /* a function referenced thru EXTERNs: */
  159725. #define GLOBAL(type) type
  159726. /* a reference to a GLOBAL function: */
  159727. #define EXTERN(type) extern type
  159728. /* This macro is used to declare a "method", that is, a function pointer.
  159729. * We want to supply prototype parameters if the compiler can cope.
  159730. * Note that the arglist parameter must be parenthesized!
  159731. * Again, you can customize this if you need special linkage keywords.
  159732. */
  159733. #ifdef HAVE_PROTOTYPES
  159734. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159735. #else
  159736. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159737. #endif
  159738. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159739. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159740. * by just saying "FAR *" where such a pointer is needed. In a few places
  159741. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159742. */
  159743. #ifdef NEED_FAR_POINTERS
  159744. #define FAR far
  159745. #else
  159746. #define FAR
  159747. #endif
  159748. /*
  159749. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159750. * in standard header files. Or you may have conflicts with application-
  159751. * specific header files that you want to include together with these files.
  159752. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159753. */
  159754. #ifndef HAVE_BOOLEAN
  159755. typedef int boolean;
  159756. #endif
  159757. #ifndef FALSE /* in case these macros already exist */
  159758. #define FALSE 0 /* values of boolean */
  159759. #endif
  159760. #ifndef TRUE
  159761. #define TRUE 1
  159762. #endif
  159763. /*
  159764. * The remaining options affect code selection within the JPEG library,
  159765. * but they don't need to be visible to most applications using the library.
  159766. * To minimize application namespace pollution, the symbols won't be
  159767. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159768. */
  159769. #ifdef JPEG_INTERNALS
  159770. #define JPEG_INTERNAL_OPTIONS
  159771. #endif
  159772. #ifdef JPEG_INTERNAL_OPTIONS
  159773. /*
  159774. * These defines indicate whether to include various optional functions.
  159775. * Undefining some of these symbols will produce a smaller but less capable
  159776. * library. Note that you can leave certain source files out of the
  159777. * compilation/linking process if you've #undef'd the corresponding symbols.
  159778. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159779. */
  159780. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159781. /* Capability options common to encoder and decoder: */
  159782. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159783. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159784. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159785. /* Encoder capability options: */
  159786. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159787. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159788. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159789. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159790. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159791. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159792. * precision, so jchuff.c normally uses entropy optimization to compute
  159793. * usable tables for higher precision. If you don't want to do optimization,
  159794. * you'll have to supply different default Huffman tables.
  159795. * The exact same statements apply for progressive JPEG: the default tables
  159796. * don't work for progressive mode. (This may get fixed, however.)
  159797. */
  159798. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159799. /* Decoder capability options: */
  159800. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159801. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159802. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159803. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159804. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159805. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159806. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159807. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159808. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159809. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159810. /* more capability options later, no doubt */
  159811. /*
  159812. * Ordering of RGB data in scanlines passed to or from the application.
  159813. * If your application wants to deal with data in the order B,G,R, just
  159814. * change these macros. You can also deal with formats such as R,G,B,X
  159815. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159816. * the offsets will also change the order in which colormap data is organized.
  159817. * RESTRICTIONS:
  159818. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159819. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159820. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159821. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159822. * is not 3 (they don't understand about dummy color components!). So you
  159823. * can't use color quantization if you change that value.
  159824. */
  159825. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159826. #define RGB_GREEN 1 /* Offset of Green */
  159827. #define RGB_BLUE 2 /* Offset of Blue */
  159828. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159829. /* Definitions for speed-related optimizations. */
  159830. /* If your compiler supports inline functions, define INLINE
  159831. * as the inline keyword; otherwise define it as empty.
  159832. */
  159833. #ifndef INLINE
  159834. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159835. #define INLINE __inline__
  159836. #endif
  159837. #ifndef INLINE
  159838. #define INLINE /* default is to define it as empty */
  159839. #endif
  159840. #endif
  159841. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159842. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159843. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159844. */
  159845. #ifndef MULTIPLIER
  159846. #define MULTIPLIER int /* type for fastest integer multiply */
  159847. #endif
  159848. /* FAST_FLOAT should be either float or double, whichever is done faster
  159849. * by your compiler. (Note that this type is only used in the floating point
  159850. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159851. * Typically, float is faster in ANSI C compilers, while double is faster in
  159852. * pre-ANSI compilers (because they insist on converting to double anyway).
  159853. * The code below therefore chooses float if we have ANSI-style prototypes.
  159854. */
  159855. #ifndef FAST_FLOAT
  159856. #ifdef HAVE_PROTOTYPES
  159857. #define FAST_FLOAT float
  159858. #else
  159859. #define FAST_FLOAT double
  159860. #endif
  159861. #endif
  159862. #endif /* JPEG_INTERNAL_OPTIONS */
  159863. /*** End of inlined file: jmorecfg.h ***/
  159864. /* seldom changed options */
  159865. /* Version ID for the JPEG library.
  159866. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159867. */
  159868. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159869. /* Various constants determining the sizes of things.
  159870. * All of these are specified by the JPEG standard, so don't change them
  159871. * if you want to be compatible.
  159872. */
  159873. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159874. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159875. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159876. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159877. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159878. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159879. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159880. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159881. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159882. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159883. * to handle it. We even let you do this from the jconfig.h file. However,
  159884. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159885. * sometimes emits noncompliant files doesn't mean you should too.
  159886. */
  159887. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159888. #ifndef D_MAX_BLOCKS_IN_MCU
  159889. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159890. #endif
  159891. /* Data structures for images (arrays of samples and of DCT coefficients).
  159892. * On 80x86 machines, the image arrays are too big for near pointers,
  159893. * but the pointer arrays can fit in near memory.
  159894. */
  159895. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159896. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159897. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159898. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159899. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159900. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159901. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159902. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159903. /* Types for JPEG compression parameters and working tables. */
  159904. /* DCT coefficient quantization tables. */
  159905. typedef struct {
  159906. /* This array gives the coefficient quantizers in natural array order
  159907. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159908. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159909. */
  159910. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159911. /* This field is used only during compression. It's initialized FALSE when
  159912. * the table is created, and set TRUE when it's been output to the file.
  159913. * You could suppress output of a table by setting this to TRUE.
  159914. * (See jpeg_suppress_tables for an example.)
  159915. */
  159916. boolean sent_table; /* TRUE when table has been output */
  159917. } JQUANT_TBL;
  159918. /* Huffman coding tables. */
  159919. typedef struct {
  159920. /* These two fields directly represent the contents of a JPEG DHT marker */
  159921. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159922. /* length k bits; bits[0] is unused */
  159923. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159924. /* This field is used only during compression. It's initialized FALSE when
  159925. * the table is created, and set TRUE when it's been output to the file.
  159926. * You could suppress output of a table by setting this to TRUE.
  159927. * (See jpeg_suppress_tables for an example.)
  159928. */
  159929. boolean sent_table; /* TRUE when table has been output */
  159930. } JHUFF_TBL;
  159931. /* Basic info about one component (color channel). */
  159932. typedef struct {
  159933. /* These values are fixed over the whole image. */
  159934. /* For compression, they must be supplied by parameter setup; */
  159935. /* for decompression, they are read from the SOF marker. */
  159936. int component_id; /* identifier for this component (0..255) */
  159937. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159938. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159939. int v_samp_factor; /* vertical sampling factor (1..4) */
  159940. int quant_tbl_no; /* quantization table selector (0..3) */
  159941. /* These values may vary between scans. */
  159942. /* For compression, they must be supplied by parameter setup; */
  159943. /* for decompression, they are read from the SOS marker. */
  159944. /* The decompressor output side may not use these variables. */
  159945. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159946. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159947. /* Remaining fields should be treated as private by applications. */
  159948. /* These values are computed during compression or decompression startup: */
  159949. /* Component's size in DCT blocks.
  159950. * Any dummy blocks added to complete an MCU are not counted; therefore
  159951. * these values do not depend on whether a scan is interleaved or not.
  159952. */
  159953. JDIMENSION width_in_blocks;
  159954. JDIMENSION height_in_blocks;
  159955. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159956. * For decompression this is the size of the output from one DCT block,
  159957. * reflecting any scaling we choose to apply during the IDCT step.
  159958. * Values of 1,2,4,8 are likely to be supported. Note that different
  159959. * components may receive different IDCT scalings.
  159960. */
  159961. int DCT_scaled_size;
  159962. /* The downsampled dimensions are the component's actual, unpadded number
  159963. * of samples at the main buffer (preprocessing/compression interface), thus
  159964. * downsampled_width = ceil(image_width * Hi/Hmax)
  159965. * and similarly for height. For decompression, IDCT scaling is included, so
  159966. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159967. */
  159968. JDIMENSION downsampled_width; /* actual width in samples */
  159969. JDIMENSION downsampled_height; /* actual height in samples */
  159970. /* This flag is used only for decompression. In cases where some of the
  159971. * components will be ignored (eg grayscale output from YCbCr image),
  159972. * we can skip most computations for the unused components.
  159973. */
  159974. boolean component_needed; /* do we need the value of this component? */
  159975. /* These values are computed before starting a scan of the component. */
  159976. /* The decompressor output side may not use these variables. */
  159977. int MCU_width; /* number of blocks per MCU, horizontally */
  159978. int MCU_height; /* number of blocks per MCU, vertically */
  159979. int MCU_blocks; /* MCU_width * MCU_height */
  159980. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159981. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159982. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159983. /* Saved quantization table for component; NULL if none yet saved.
  159984. * See jdinput.c comments about the need for this information.
  159985. * This field is currently used only for decompression.
  159986. */
  159987. JQUANT_TBL * quant_table;
  159988. /* Private per-component storage for DCT or IDCT subsystem. */
  159989. void * dct_table;
  159990. } jpeg_component_info;
  159991. /* The script for encoding a multiple-scan file is an array of these: */
  159992. typedef struct {
  159993. int comps_in_scan; /* number of components encoded in this scan */
  159994. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159995. int Ss, Se; /* progressive JPEG spectral selection parms */
  159996. int Ah, Al; /* progressive JPEG successive approx. parms */
  159997. } jpeg_scan_info;
  159998. /* The decompressor can save APPn and COM markers in a list of these: */
  159999. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160000. struct jpeg_marker_struct {
  160001. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160002. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160003. unsigned int original_length; /* # bytes of data in the file */
  160004. unsigned int data_length; /* # bytes of data saved at data[] */
  160005. JOCTET FAR * data; /* the data contained in the marker */
  160006. /* the marker length word is not counted in data_length or original_length */
  160007. };
  160008. /* Known color spaces. */
  160009. typedef enum {
  160010. JCS_UNKNOWN, /* error/unspecified */
  160011. JCS_GRAYSCALE, /* monochrome */
  160012. JCS_RGB, /* red/green/blue */
  160013. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160014. JCS_CMYK, /* C/M/Y/K */
  160015. JCS_YCCK /* Y/Cb/Cr/K */
  160016. } J_COLOR_SPACE;
  160017. /* DCT/IDCT algorithm options. */
  160018. typedef enum {
  160019. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160020. JDCT_IFAST, /* faster, less accurate integer method */
  160021. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160022. } J_DCT_METHOD;
  160023. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160024. #define JDCT_DEFAULT JDCT_ISLOW
  160025. #endif
  160026. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160027. #define JDCT_FASTEST JDCT_IFAST
  160028. #endif
  160029. /* Dithering options for decompression. */
  160030. typedef enum {
  160031. JDITHER_NONE, /* no dithering */
  160032. JDITHER_ORDERED, /* simple ordered dither */
  160033. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160034. } J_DITHER_MODE;
  160035. /* Common fields between JPEG compression and decompression master structs. */
  160036. #define jpeg_common_fields \
  160037. struct jpeg_error_mgr * err; /* Error handler module */\
  160038. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160039. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160040. void * client_data; /* Available for use by application */\
  160041. boolean is_decompressor; /* So common code can tell which is which */\
  160042. int global_state /* For checking call sequence validity */
  160043. /* Routines that are to be used by both halves of the library are declared
  160044. * to receive a pointer to this structure. There are no actual instances of
  160045. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160046. */
  160047. struct jpeg_common_struct {
  160048. jpeg_common_fields; /* Fields common to both master struct types */
  160049. /* Additional fields follow in an actual jpeg_compress_struct or
  160050. * jpeg_decompress_struct. All three structs must agree on these
  160051. * initial fields! (This would be a lot cleaner in C++.)
  160052. */
  160053. };
  160054. typedef struct jpeg_common_struct * j_common_ptr;
  160055. typedef struct jpeg_compress_struct * j_compress_ptr;
  160056. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160057. /* Master record for a compression instance */
  160058. struct jpeg_compress_struct {
  160059. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160060. /* Destination for compressed data */
  160061. struct jpeg_destination_mgr * dest;
  160062. /* Description of source image --- these fields must be filled in by
  160063. * outer application before starting compression. in_color_space must
  160064. * be correct before you can even call jpeg_set_defaults().
  160065. */
  160066. JDIMENSION image_width; /* input image width */
  160067. JDIMENSION image_height; /* input image height */
  160068. int input_components; /* # of color components in input image */
  160069. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160070. double input_gamma; /* image gamma of input image */
  160071. /* Compression parameters --- these fields must be set before calling
  160072. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160073. * initialize everything to reasonable defaults, then changing anything
  160074. * the application specifically wants to change. That way you won't get
  160075. * burnt when new parameters are added. Also note that there are several
  160076. * helper routines to simplify changing parameters.
  160077. */
  160078. int data_precision; /* bits of precision in image data */
  160079. int num_components; /* # of color components in JPEG image */
  160080. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160081. jpeg_component_info * comp_info;
  160082. /* comp_info[i] describes component that appears i'th in SOF */
  160083. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160084. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160085. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160086. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160087. /* ptrs to Huffman coding tables, or NULL if not defined */
  160088. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160089. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160090. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160091. int num_scans; /* # of entries in scan_info array */
  160092. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160093. /* The default value of scan_info is NULL, which causes a single-scan
  160094. * sequential JPEG file to be emitted. To create a multi-scan file,
  160095. * set num_scans and scan_info to point to an array of scan definitions.
  160096. */
  160097. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160098. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160099. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160100. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160101. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160102. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160103. /* The restart interval can be specified in absolute MCUs by setting
  160104. * restart_interval, or in MCU rows by setting restart_in_rows
  160105. * (in which case the correct restart_interval will be figured
  160106. * for each scan).
  160107. */
  160108. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160109. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160110. /* Parameters controlling emission of special markers. */
  160111. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160112. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160113. UINT8 JFIF_minor_version;
  160114. /* These three values are not used by the JPEG code, merely copied */
  160115. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160116. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160117. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160118. UINT8 density_unit; /* JFIF code for pixel size units */
  160119. UINT16 X_density; /* Horizontal pixel density */
  160120. UINT16 Y_density; /* Vertical pixel density */
  160121. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160122. /* State variable: index of next scanline to be written to
  160123. * jpeg_write_scanlines(). Application may use this to control its
  160124. * processing loop, e.g., "while (next_scanline < image_height)".
  160125. */
  160126. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160127. /* Remaining fields are known throughout compressor, but generally
  160128. * should not be touched by a surrounding application.
  160129. */
  160130. /*
  160131. * These fields are computed during compression startup
  160132. */
  160133. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160134. int max_h_samp_factor; /* largest h_samp_factor */
  160135. int max_v_samp_factor; /* largest v_samp_factor */
  160136. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160137. /* The coefficient controller receives data in units of MCU rows as defined
  160138. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160139. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160140. * "iMCU" (interleaved MCU) row.
  160141. */
  160142. /*
  160143. * These fields are valid during any one scan.
  160144. * They describe the components and MCUs actually appearing in the scan.
  160145. */
  160146. int comps_in_scan; /* # of JPEG components in this scan */
  160147. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160148. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160149. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160150. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160151. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160152. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160153. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160154. /* i'th block in an MCU */
  160155. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160156. /*
  160157. * Links to compression subobjects (methods and private variables of modules)
  160158. */
  160159. struct jpeg_comp_master * master;
  160160. struct jpeg_c_main_controller * main;
  160161. struct jpeg_c_prep_controller * prep;
  160162. struct jpeg_c_coef_controller * coef;
  160163. struct jpeg_marker_writer * marker;
  160164. struct jpeg_color_converter * cconvert;
  160165. struct jpeg_downsampler * downsample;
  160166. struct jpeg_forward_dct * fdct;
  160167. struct jpeg_entropy_encoder * entropy;
  160168. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160169. int script_space_size;
  160170. };
  160171. /* Master record for a decompression instance */
  160172. struct jpeg_decompress_struct {
  160173. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160174. /* Source of compressed data */
  160175. struct jpeg_source_mgr * src;
  160176. /* Basic description of image --- filled in by jpeg_read_header(). */
  160177. /* Application may inspect these values to decide how to process image. */
  160178. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160179. JDIMENSION image_height; /* nominal image height */
  160180. int num_components; /* # of color components in JPEG image */
  160181. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160182. /* Decompression processing parameters --- these fields must be set before
  160183. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160184. * them to default values.
  160185. */
  160186. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160187. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160188. double output_gamma; /* image gamma wanted in output */
  160189. boolean buffered_image; /* TRUE=multiple output passes */
  160190. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160191. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160192. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160193. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160194. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160195. /* the following are ignored if not quantize_colors: */
  160196. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160197. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160198. int desired_number_of_colors; /* max # colors to use in created colormap */
  160199. /* these are significant only in buffered-image mode: */
  160200. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160201. boolean enable_external_quant;/* enable future use of external colormap */
  160202. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160203. /* Description of actual output image that will be returned to application.
  160204. * These fields are computed by jpeg_start_decompress().
  160205. * You can also use jpeg_calc_output_dimensions() to determine these values
  160206. * in advance of calling jpeg_start_decompress().
  160207. */
  160208. JDIMENSION output_width; /* scaled image width */
  160209. JDIMENSION output_height; /* scaled image height */
  160210. int out_color_components; /* # of color components in out_color_space */
  160211. int output_components; /* # of color components returned */
  160212. /* output_components is 1 (a colormap index) when quantizing colors;
  160213. * otherwise it equals out_color_components.
  160214. */
  160215. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160216. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160217. * high, space and time will be wasted due to unnecessary data copying.
  160218. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160219. */
  160220. /* When quantizing colors, the output colormap is described by these fields.
  160221. * The application can supply a colormap by setting colormap non-NULL before
  160222. * calling jpeg_start_decompress; otherwise a colormap is created during
  160223. * jpeg_start_decompress or jpeg_start_output.
  160224. * The map has out_color_components rows and actual_number_of_colors columns.
  160225. */
  160226. int actual_number_of_colors; /* number of entries in use */
  160227. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160228. /* State variables: these variables indicate the progress of decompression.
  160229. * The application may examine these but must not modify them.
  160230. */
  160231. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160232. * Application may use this to control its processing loop, e.g.,
  160233. * "while (output_scanline < output_height)".
  160234. */
  160235. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160236. /* Current input scan number and number of iMCU rows completed in scan.
  160237. * These indicate the progress of the decompressor input side.
  160238. */
  160239. int input_scan_number; /* Number of SOS markers seen so far */
  160240. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160241. /* The "output scan number" is the notional scan being displayed by the
  160242. * output side. The decompressor will not allow output scan/row number
  160243. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160244. */
  160245. int output_scan_number; /* Nominal scan number being displayed */
  160246. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160247. /* Current progression status. coef_bits[c][i] indicates the precision
  160248. * with which component c's DCT coefficient i (in zigzag order) is known.
  160249. * It is -1 when no data has yet been received, otherwise it is the point
  160250. * transform (shift) value for the most recent scan of the coefficient
  160251. * (thus, 0 at completion of the progression).
  160252. * This pointer is NULL when reading a non-progressive file.
  160253. */
  160254. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160255. /* Internal JPEG parameters --- the application usually need not look at
  160256. * these fields. Note that the decompressor output side may not use
  160257. * any parameters that can change between scans.
  160258. */
  160259. /* Quantization and Huffman tables are carried forward across input
  160260. * datastreams when processing abbreviated JPEG datastreams.
  160261. */
  160262. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160263. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160264. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160265. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160266. /* ptrs to Huffman coding tables, or NULL if not defined */
  160267. /* These parameters are never carried across datastreams, since they
  160268. * are given in SOF/SOS markers or defined to be reset by SOI.
  160269. */
  160270. int data_precision; /* bits of precision in image data */
  160271. jpeg_component_info * comp_info;
  160272. /* comp_info[i] describes component that appears i'th in SOF */
  160273. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160274. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160275. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160276. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160277. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160278. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160279. /* These fields record data obtained from optional markers recognized by
  160280. * the JPEG library.
  160281. */
  160282. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160283. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160284. UINT8 JFIF_major_version; /* JFIF version number */
  160285. UINT8 JFIF_minor_version;
  160286. UINT8 density_unit; /* JFIF code for pixel size units */
  160287. UINT16 X_density; /* Horizontal pixel density */
  160288. UINT16 Y_density; /* Vertical pixel density */
  160289. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160290. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160291. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160292. /* Aside from the specific data retained from APPn markers known to the
  160293. * library, the uninterpreted contents of any or all APPn and COM markers
  160294. * can be saved in a list for examination by the application.
  160295. */
  160296. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160297. /* Remaining fields are known throughout decompressor, but generally
  160298. * should not be touched by a surrounding application.
  160299. */
  160300. /*
  160301. * These fields are computed during decompression startup
  160302. */
  160303. int max_h_samp_factor; /* largest h_samp_factor */
  160304. int max_v_samp_factor; /* largest v_samp_factor */
  160305. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160306. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160307. /* The coefficient controller's input and output progress is measured in
  160308. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160309. * in fully interleaved JPEG scans, but are used whether the scan is
  160310. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160311. * rows of each component. Therefore, the IDCT output contains
  160312. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160313. */
  160314. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160315. /*
  160316. * These fields are valid during any one scan.
  160317. * They describe the components and MCUs actually appearing in the scan.
  160318. * Note that the decompressor output side must not use these fields.
  160319. */
  160320. int comps_in_scan; /* # of JPEG components in this scan */
  160321. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160322. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160323. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160324. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160325. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160326. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160327. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160328. /* i'th block in an MCU */
  160329. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160330. /* This field is shared between entropy decoder and marker parser.
  160331. * It is either zero or the code of a JPEG marker that has been
  160332. * read from the data source, but has not yet been processed.
  160333. */
  160334. int unread_marker;
  160335. /*
  160336. * Links to decompression subobjects (methods, private variables of modules)
  160337. */
  160338. struct jpeg_decomp_master * master;
  160339. struct jpeg_d_main_controller * main;
  160340. struct jpeg_d_coef_controller * coef;
  160341. struct jpeg_d_post_controller * post;
  160342. struct jpeg_input_controller * inputctl;
  160343. struct jpeg_marker_reader * marker;
  160344. struct jpeg_entropy_decoder * entropy;
  160345. struct jpeg_inverse_dct * idct;
  160346. struct jpeg_upsampler * upsample;
  160347. struct jpeg_color_deconverter * cconvert;
  160348. struct jpeg_color_quantizer * cquantize;
  160349. };
  160350. /* "Object" declarations for JPEG modules that may be supplied or called
  160351. * directly by the surrounding application.
  160352. * As with all objects in the JPEG library, these structs only define the
  160353. * publicly visible methods and state variables of a module. Additional
  160354. * private fields may exist after the public ones.
  160355. */
  160356. /* Error handler object */
  160357. struct jpeg_error_mgr {
  160358. /* Error exit handler: does not return to caller */
  160359. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160360. /* Conditionally emit a trace or warning message */
  160361. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160362. /* Routine that actually outputs a trace or error message */
  160363. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160364. /* Format a message string for the most recent JPEG error or message */
  160365. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160366. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160367. /* Reset error state variables at start of a new image */
  160368. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160369. /* The message ID code and any parameters are saved here.
  160370. * A message can have one string parameter or up to 8 int parameters.
  160371. */
  160372. int msg_code;
  160373. #define JMSG_STR_PARM_MAX 80
  160374. union {
  160375. int i[8];
  160376. char s[JMSG_STR_PARM_MAX];
  160377. } msg_parm;
  160378. /* Standard state variables for error facility */
  160379. int trace_level; /* max msg_level that will be displayed */
  160380. /* For recoverable corrupt-data errors, we emit a warning message,
  160381. * but keep going unless emit_message chooses to abort. emit_message
  160382. * should count warnings in num_warnings. The surrounding application
  160383. * can check for bad data by seeing if num_warnings is nonzero at the
  160384. * end of processing.
  160385. */
  160386. long num_warnings; /* number of corrupt-data warnings */
  160387. /* These fields point to the table(s) of error message strings.
  160388. * An application can change the table pointer to switch to a different
  160389. * message list (typically, to change the language in which errors are
  160390. * reported). Some applications may wish to add additional error codes
  160391. * that will be handled by the JPEG library error mechanism; the second
  160392. * table pointer is used for this purpose.
  160393. *
  160394. * First table includes all errors generated by JPEG library itself.
  160395. * Error code 0 is reserved for a "no such error string" message.
  160396. */
  160397. const char * const * jpeg_message_table; /* Library errors */
  160398. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160399. /* Second table can be added by application (see cjpeg/djpeg for example).
  160400. * It contains strings numbered first_addon_message..last_addon_message.
  160401. */
  160402. const char * const * addon_message_table; /* Non-library errors */
  160403. int first_addon_message; /* code for first string in addon table */
  160404. int last_addon_message; /* code for last string in addon table */
  160405. };
  160406. /* Progress monitor object */
  160407. struct jpeg_progress_mgr {
  160408. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160409. long pass_counter; /* work units completed in this pass */
  160410. long pass_limit; /* total number of work units in this pass */
  160411. int completed_passes; /* passes completed so far */
  160412. int total_passes; /* total number of passes expected */
  160413. };
  160414. /* Data destination object for compression */
  160415. struct jpeg_destination_mgr {
  160416. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160417. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160418. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160419. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160420. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160421. };
  160422. /* Data source object for decompression */
  160423. struct jpeg_source_mgr {
  160424. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160425. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160426. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160427. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160428. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160429. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160430. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160431. };
  160432. /* Memory manager object.
  160433. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160434. * and "really big" objects (virtual arrays with backing store if needed).
  160435. * The memory manager does not allow individual objects to be freed; rather,
  160436. * each created object is assigned to a pool, and whole pools can be freed
  160437. * at once. This is faster and more convenient than remembering exactly what
  160438. * to free, especially where malloc()/free() are not too speedy.
  160439. * NB: alloc routines never return NULL. They exit to error_exit if not
  160440. * successful.
  160441. */
  160442. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160443. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160444. #define JPOOL_NUMPOOLS 2
  160445. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160446. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160447. struct jpeg_memory_mgr {
  160448. /* Method pointers */
  160449. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160450. size_t sizeofobject));
  160451. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160452. size_t sizeofobject));
  160453. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160454. JDIMENSION samplesperrow,
  160455. JDIMENSION numrows));
  160456. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160457. JDIMENSION blocksperrow,
  160458. JDIMENSION numrows));
  160459. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160460. int pool_id,
  160461. boolean pre_zero,
  160462. JDIMENSION samplesperrow,
  160463. JDIMENSION numrows,
  160464. JDIMENSION maxaccess));
  160465. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160466. int pool_id,
  160467. boolean pre_zero,
  160468. JDIMENSION blocksperrow,
  160469. JDIMENSION numrows,
  160470. JDIMENSION maxaccess));
  160471. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160472. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160473. jvirt_sarray_ptr ptr,
  160474. JDIMENSION start_row,
  160475. JDIMENSION num_rows,
  160476. boolean writable));
  160477. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160478. jvirt_barray_ptr ptr,
  160479. JDIMENSION start_row,
  160480. JDIMENSION num_rows,
  160481. boolean writable));
  160482. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160483. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160484. /* Limit on memory allocation for this JPEG object. (Note that this is
  160485. * merely advisory, not a guaranteed maximum; it only affects the space
  160486. * used for virtual-array buffers.) May be changed by outer application
  160487. * after creating the JPEG object.
  160488. */
  160489. long max_memory_to_use;
  160490. /* Maximum allocation request accepted by alloc_large. */
  160491. long max_alloc_chunk;
  160492. };
  160493. /* Routine signature for application-supplied marker processing methods.
  160494. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160495. */
  160496. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160497. /* Declarations for routines called by application.
  160498. * The JPP macro hides prototype parameters from compilers that can't cope.
  160499. * Note JPP requires double parentheses.
  160500. */
  160501. #ifdef HAVE_PROTOTYPES
  160502. #define JPP(arglist) arglist
  160503. #else
  160504. #define JPP(arglist) ()
  160505. #endif
  160506. /* Short forms of external names for systems with brain-damaged linkers.
  160507. * We shorten external names to be unique in the first six letters, which
  160508. * is good enough for all known systems.
  160509. * (If your compiler itself needs names to be unique in less than 15
  160510. * characters, you are out of luck. Get a better compiler.)
  160511. */
  160512. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160513. #define jpeg_std_error jStdError
  160514. #define jpeg_CreateCompress jCreaCompress
  160515. #define jpeg_CreateDecompress jCreaDecompress
  160516. #define jpeg_destroy_compress jDestCompress
  160517. #define jpeg_destroy_decompress jDestDecompress
  160518. #define jpeg_stdio_dest jStdDest
  160519. #define jpeg_stdio_src jStdSrc
  160520. #define jpeg_set_defaults jSetDefaults
  160521. #define jpeg_set_colorspace jSetColorspace
  160522. #define jpeg_default_colorspace jDefColorspace
  160523. #define jpeg_set_quality jSetQuality
  160524. #define jpeg_set_linear_quality jSetLQuality
  160525. #define jpeg_add_quant_table jAddQuantTable
  160526. #define jpeg_quality_scaling jQualityScaling
  160527. #define jpeg_simple_progression jSimProgress
  160528. #define jpeg_suppress_tables jSuppressTables
  160529. #define jpeg_alloc_quant_table jAlcQTable
  160530. #define jpeg_alloc_huff_table jAlcHTable
  160531. #define jpeg_start_compress jStrtCompress
  160532. #define jpeg_write_scanlines jWrtScanlines
  160533. #define jpeg_finish_compress jFinCompress
  160534. #define jpeg_write_raw_data jWrtRawData
  160535. #define jpeg_write_marker jWrtMarker
  160536. #define jpeg_write_m_header jWrtMHeader
  160537. #define jpeg_write_m_byte jWrtMByte
  160538. #define jpeg_write_tables jWrtTables
  160539. #define jpeg_read_header jReadHeader
  160540. #define jpeg_start_decompress jStrtDecompress
  160541. #define jpeg_read_scanlines jReadScanlines
  160542. #define jpeg_finish_decompress jFinDecompress
  160543. #define jpeg_read_raw_data jReadRawData
  160544. #define jpeg_has_multiple_scans jHasMultScn
  160545. #define jpeg_start_output jStrtOutput
  160546. #define jpeg_finish_output jFinOutput
  160547. #define jpeg_input_complete jInComplete
  160548. #define jpeg_new_colormap jNewCMap
  160549. #define jpeg_consume_input jConsumeInput
  160550. #define jpeg_calc_output_dimensions jCalcDimensions
  160551. #define jpeg_save_markers jSaveMarkers
  160552. #define jpeg_set_marker_processor jSetMarker
  160553. #define jpeg_read_coefficients jReadCoefs
  160554. #define jpeg_write_coefficients jWrtCoefs
  160555. #define jpeg_copy_critical_parameters jCopyCrit
  160556. #define jpeg_abort_compress jAbrtCompress
  160557. #define jpeg_abort_decompress jAbrtDecompress
  160558. #define jpeg_abort jAbort
  160559. #define jpeg_destroy jDestroy
  160560. #define jpeg_resync_to_restart jResyncRestart
  160561. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160562. /* Default error-management setup */
  160563. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160564. JPP((struct jpeg_error_mgr * err));
  160565. /* Initialization of JPEG compression objects.
  160566. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160567. * names that applications should call. These expand to calls on
  160568. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160569. * passed for version mismatch checking.
  160570. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160571. */
  160572. #define jpeg_create_compress(cinfo) \
  160573. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160574. (size_t) sizeof(struct jpeg_compress_struct))
  160575. #define jpeg_create_decompress(cinfo) \
  160576. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160577. (size_t) sizeof(struct jpeg_decompress_struct))
  160578. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160579. int version, size_t structsize));
  160580. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160581. int version, size_t structsize));
  160582. /* Destruction of JPEG compression objects */
  160583. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160584. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160585. /* Standard data source and destination managers: stdio streams. */
  160586. /* Caller is responsible for opening the file before and closing after. */
  160587. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160588. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160589. /* Default parameter setup for compression */
  160590. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160591. /* Compression parameter setup aids */
  160592. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160593. J_COLOR_SPACE colorspace));
  160594. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160595. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160596. boolean force_baseline));
  160597. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160598. int scale_factor,
  160599. boolean force_baseline));
  160600. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160601. const unsigned int *basic_table,
  160602. int scale_factor,
  160603. boolean force_baseline));
  160604. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160605. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160606. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160607. boolean suppress));
  160608. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160609. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160610. /* Main entry points for compression */
  160611. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160612. boolean write_all_tables));
  160613. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160614. JSAMPARRAY scanlines,
  160615. JDIMENSION num_lines));
  160616. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160617. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160618. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160619. JSAMPIMAGE data,
  160620. JDIMENSION num_lines));
  160621. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160622. EXTERN(void) jpeg_write_marker
  160623. JPP((j_compress_ptr cinfo, int marker,
  160624. const JOCTET * dataptr, unsigned int datalen));
  160625. /* Same, but piecemeal. */
  160626. EXTERN(void) jpeg_write_m_header
  160627. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160628. EXTERN(void) jpeg_write_m_byte
  160629. JPP((j_compress_ptr cinfo, int val));
  160630. /* Alternate compression function: just write an abbreviated table file */
  160631. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160632. /* Decompression startup: read start of JPEG datastream to see what's there */
  160633. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160634. boolean require_image));
  160635. /* Return value is one of: */
  160636. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160637. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160638. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160639. /* If you pass require_image = TRUE (normal case), you need not check for
  160640. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160641. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160642. * give a suspension return (the stdio source module doesn't).
  160643. */
  160644. /* Main entry points for decompression */
  160645. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160646. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160647. JSAMPARRAY scanlines,
  160648. JDIMENSION max_lines));
  160649. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160650. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160651. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160652. JSAMPIMAGE data,
  160653. JDIMENSION max_lines));
  160654. /* Additional entry points for buffered-image mode. */
  160655. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160656. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160657. int scan_number));
  160658. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160659. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160660. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160661. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160662. /* Return value is one of: */
  160663. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160664. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160665. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160666. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160667. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160668. /* Precalculate output dimensions for current decompression parameters. */
  160669. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160670. /* Control saving of COM and APPn markers into marker_list. */
  160671. EXTERN(void) jpeg_save_markers
  160672. JPP((j_decompress_ptr cinfo, int marker_code,
  160673. unsigned int length_limit));
  160674. /* Install a special processing method for COM or APPn markers. */
  160675. EXTERN(void) jpeg_set_marker_processor
  160676. JPP((j_decompress_ptr cinfo, int marker_code,
  160677. jpeg_marker_parser_method routine));
  160678. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160679. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160680. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160681. jvirt_barray_ptr * coef_arrays));
  160682. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160683. j_compress_ptr dstinfo));
  160684. /* If you choose to abort compression or decompression before completing
  160685. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160686. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160687. * if you're done with the JPEG object, but if you want to clean it up and
  160688. * reuse it, call this:
  160689. */
  160690. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160691. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160692. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160693. * flavor of JPEG object. These may be more convenient in some places.
  160694. */
  160695. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160696. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160697. /* Default restart-marker-resync procedure for use by data source modules */
  160698. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160699. int desired));
  160700. /* These marker codes are exported since applications and data source modules
  160701. * are likely to want to use them.
  160702. */
  160703. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160704. #define JPEG_EOI 0xD9 /* EOI marker code */
  160705. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160706. #define JPEG_COM 0xFE /* COM marker code */
  160707. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160708. * for structure definitions that are never filled in, keep it quiet by
  160709. * supplying dummy definitions for the various substructures.
  160710. */
  160711. #ifdef INCOMPLETE_TYPES_BROKEN
  160712. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160713. struct jvirt_sarray_control { long dummy; };
  160714. struct jvirt_barray_control { long dummy; };
  160715. struct jpeg_comp_master { long dummy; };
  160716. struct jpeg_c_main_controller { long dummy; };
  160717. struct jpeg_c_prep_controller { long dummy; };
  160718. struct jpeg_c_coef_controller { long dummy; };
  160719. struct jpeg_marker_writer { long dummy; };
  160720. struct jpeg_color_converter { long dummy; };
  160721. struct jpeg_downsampler { long dummy; };
  160722. struct jpeg_forward_dct { long dummy; };
  160723. struct jpeg_entropy_encoder { long dummy; };
  160724. struct jpeg_decomp_master { long dummy; };
  160725. struct jpeg_d_main_controller { long dummy; };
  160726. struct jpeg_d_coef_controller { long dummy; };
  160727. struct jpeg_d_post_controller { long dummy; };
  160728. struct jpeg_input_controller { long dummy; };
  160729. struct jpeg_marker_reader { long dummy; };
  160730. struct jpeg_entropy_decoder { long dummy; };
  160731. struct jpeg_inverse_dct { long dummy; };
  160732. struct jpeg_upsampler { long dummy; };
  160733. struct jpeg_color_deconverter { long dummy; };
  160734. struct jpeg_color_quantizer { long dummy; };
  160735. #endif /* JPEG_INTERNALS */
  160736. #endif /* INCOMPLETE_TYPES_BROKEN */
  160737. /*
  160738. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160739. * The internal structure declarations are read only when that is true.
  160740. * Applications using the library should not include jpegint.h, but may wish
  160741. * to include jerror.h.
  160742. */
  160743. #ifdef JPEG_INTERNALS
  160744. /*** Start of inlined file: jpegint.h ***/
  160745. /* Declarations for both compression & decompression */
  160746. typedef enum { /* Operating modes for buffer controllers */
  160747. JBUF_PASS_THRU, /* Plain stripwise operation */
  160748. /* Remaining modes require a full-image buffer to have been created */
  160749. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160750. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160751. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160752. } J_BUF_MODE;
  160753. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160754. #define CSTATE_START 100 /* after create_compress */
  160755. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160756. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160757. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160758. #define DSTATE_START 200 /* after create_decompress */
  160759. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160760. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160761. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160762. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160763. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160764. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160765. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160766. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160767. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160768. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160769. /* Declarations for compression modules */
  160770. /* Master control module */
  160771. struct jpeg_comp_master {
  160772. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160773. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160774. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160775. /* State variables made visible to other modules */
  160776. boolean call_pass_startup; /* True if pass_startup must be called */
  160777. boolean is_last_pass; /* True during last pass */
  160778. };
  160779. /* Main buffer control (downsampled-data buffer) */
  160780. struct jpeg_c_main_controller {
  160781. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160782. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160783. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160784. JDIMENSION in_rows_avail));
  160785. };
  160786. /* Compression preprocessing (downsampling input buffer control) */
  160787. struct jpeg_c_prep_controller {
  160788. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160789. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160790. JSAMPARRAY input_buf,
  160791. JDIMENSION *in_row_ctr,
  160792. JDIMENSION in_rows_avail,
  160793. JSAMPIMAGE output_buf,
  160794. JDIMENSION *out_row_group_ctr,
  160795. JDIMENSION out_row_groups_avail));
  160796. };
  160797. /* Coefficient buffer control */
  160798. struct jpeg_c_coef_controller {
  160799. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160800. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160801. JSAMPIMAGE input_buf));
  160802. };
  160803. /* Colorspace conversion */
  160804. struct jpeg_color_converter {
  160805. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160806. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160807. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160808. JDIMENSION output_row, int num_rows));
  160809. };
  160810. /* Downsampling */
  160811. struct jpeg_downsampler {
  160812. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160813. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160814. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160815. JSAMPIMAGE output_buf,
  160816. JDIMENSION out_row_group_index));
  160817. boolean need_context_rows; /* TRUE if need rows above & below */
  160818. };
  160819. /* Forward DCT (also controls coefficient quantization) */
  160820. struct jpeg_forward_dct {
  160821. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160822. /* perhaps this should be an array??? */
  160823. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160824. jpeg_component_info * compptr,
  160825. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160826. JDIMENSION start_row, JDIMENSION start_col,
  160827. JDIMENSION num_blocks));
  160828. };
  160829. /* Entropy encoding */
  160830. struct jpeg_entropy_encoder {
  160831. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160832. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160833. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160834. };
  160835. /* Marker writing */
  160836. struct jpeg_marker_writer {
  160837. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160838. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160839. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160840. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160841. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160842. /* These routines are exported to allow insertion of extra markers */
  160843. /* Probably only COM and APPn markers should be written this way */
  160844. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160845. unsigned int datalen));
  160846. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160847. };
  160848. /* Declarations for decompression modules */
  160849. /* Master control module */
  160850. struct jpeg_decomp_master {
  160851. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160852. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160853. /* State variables made visible to other modules */
  160854. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160855. };
  160856. /* Input control module */
  160857. struct jpeg_input_controller {
  160858. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160859. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160860. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160861. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160862. /* State variables made visible to other modules */
  160863. boolean has_multiple_scans; /* True if file has multiple scans */
  160864. boolean eoi_reached; /* True when EOI has been consumed */
  160865. };
  160866. /* Main buffer control (downsampled-data buffer) */
  160867. struct jpeg_d_main_controller {
  160868. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160869. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160870. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160871. JDIMENSION out_rows_avail));
  160872. };
  160873. /* Coefficient buffer control */
  160874. struct jpeg_d_coef_controller {
  160875. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160876. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160877. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160878. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160879. JSAMPIMAGE output_buf));
  160880. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160881. jvirt_barray_ptr *coef_arrays;
  160882. };
  160883. /* Decompression postprocessing (color quantization buffer control) */
  160884. struct jpeg_d_post_controller {
  160885. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160886. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160887. JSAMPIMAGE input_buf,
  160888. JDIMENSION *in_row_group_ctr,
  160889. JDIMENSION in_row_groups_avail,
  160890. JSAMPARRAY output_buf,
  160891. JDIMENSION *out_row_ctr,
  160892. JDIMENSION out_rows_avail));
  160893. };
  160894. /* Marker reading & parsing */
  160895. struct jpeg_marker_reader {
  160896. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160897. /* Read markers until SOS or EOI.
  160898. * Returns same codes as are defined for jpeg_consume_input:
  160899. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160900. */
  160901. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160902. /* Read a restart marker --- exported for use by entropy decoder only */
  160903. jpeg_marker_parser_method read_restart_marker;
  160904. /* State of marker reader --- nominally internal, but applications
  160905. * supplying COM or APPn handlers might like to know the state.
  160906. */
  160907. boolean saw_SOI; /* found SOI? */
  160908. boolean saw_SOF; /* found SOF? */
  160909. int next_restart_num; /* next restart number expected (0-7) */
  160910. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160911. };
  160912. /* Entropy decoding */
  160913. struct jpeg_entropy_decoder {
  160914. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160915. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160916. JBLOCKROW *MCU_data));
  160917. /* This is here to share code between baseline and progressive decoders; */
  160918. /* other modules probably should not use it */
  160919. boolean insufficient_data; /* set TRUE after emitting warning */
  160920. };
  160921. /* Inverse DCT (also performs dequantization) */
  160922. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160923. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160924. JCOEFPTR coef_block,
  160925. JSAMPARRAY output_buf, JDIMENSION output_col));
  160926. struct jpeg_inverse_dct {
  160927. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160928. /* It is useful to allow each component to have a separate IDCT method. */
  160929. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160930. };
  160931. /* Upsampling (note that upsampler must also call color converter) */
  160932. struct jpeg_upsampler {
  160933. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160934. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160935. JSAMPIMAGE input_buf,
  160936. JDIMENSION *in_row_group_ctr,
  160937. JDIMENSION in_row_groups_avail,
  160938. JSAMPARRAY output_buf,
  160939. JDIMENSION *out_row_ctr,
  160940. JDIMENSION out_rows_avail));
  160941. boolean need_context_rows; /* TRUE if need rows above & below */
  160942. };
  160943. /* Colorspace conversion */
  160944. struct jpeg_color_deconverter {
  160945. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160946. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160947. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160948. JSAMPARRAY output_buf, int num_rows));
  160949. };
  160950. /* Color quantization or color precision reduction */
  160951. struct jpeg_color_quantizer {
  160952. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160953. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160954. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160955. int num_rows));
  160956. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160957. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160958. };
  160959. /* Miscellaneous useful macros */
  160960. #undef MAX
  160961. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160962. #undef MIN
  160963. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160964. /* We assume that right shift corresponds to signed division by 2 with
  160965. * rounding towards minus infinity. This is correct for typical "arithmetic
  160966. * shift" instructions that shift in copies of the sign bit. But some
  160967. * C compilers implement >> with an unsigned shift. For these machines you
  160968. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160969. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160970. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160971. * included in the variables of any routine using RIGHT_SHIFT.
  160972. */
  160973. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160974. #define SHIFT_TEMPS INT32 shift_temp;
  160975. #define RIGHT_SHIFT(x,shft) \
  160976. ((shift_temp = (x)) < 0 ? \
  160977. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160978. (shift_temp >> (shft)))
  160979. #else
  160980. #define SHIFT_TEMPS
  160981. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160982. #endif
  160983. /* Short forms of external names for systems with brain-damaged linkers. */
  160984. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160985. #define jinit_compress_master jICompress
  160986. #define jinit_c_master_control jICMaster
  160987. #define jinit_c_main_controller jICMainC
  160988. #define jinit_c_prep_controller jICPrepC
  160989. #define jinit_c_coef_controller jICCoefC
  160990. #define jinit_color_converter jICColor
  160991. #define jinit_downsampler jIDownsampler
  160992. #define jinit_forward_dct jIFDCT
  160993. #define jinit_huff_encoder jIHEncoder
  160994. #define jinit_phuff_encoder jIPHEncoder
  160995. #define jinit_marker_writer jIMWriter
  160996. #define jinit_master_decompress jIDMaster
  160997. #define jinit_d_main_controller jIDMainC
  160998. #define jinit_d_coef_controller jIDCoefC
  160999. #define jinit_d_post_controller jIDPostC
  161000. #define jinit_input_controller jIInCtlr
  161001. #define jinit_marker_reader jIMReader
  161002. #define jinit_huff_decoder jIHDecoder
  161003. #define jinit_phuff_decoder jIPHDecoder
  161004. #define jinit_inverse_dct jIIDCT
  161005. #define jinit_upsampler jIUpsampler
  161006. #define jinit_color_deconverter jIDColor
  161007. #define jinit_1pass_quantizer jI1Quant
  161008. #define jinit_2pass_quantizer jI2Quant
  161009. #define jinit_merged_upsampler jIMUpsampler
  161010. #define jinit_memory_mgr jIMemMgr
  161011. #define jdiv_round_up jDivRound
  161012. #define jround_up jRound
  161013. #define jcopy_sample_rows jCopySamples
  161014. #define jcopy_block_row jCopyBlocks
  161015. #define jzero_far jZeroFar
  161016. #define jpeg_zigzag_order jZIGTable
  161017. #define jpeg_natural_order jZAGTable
  161018. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161019. /* Compression module initialization routines */
  161020. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161021. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161022. boolean transcode_only));
  161023. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161024. boolean need_full_buffer));
  161025. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161026. boolean need_full_buffer));
  161027. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161028. boolean need_full_buffer));
  161029. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161030. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161031. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161032. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161033. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161034. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161035. /* Decompression module initialization routines */
  161036. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161037. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161038. boolean need_full_buffer));
  161039. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161040. boolean need_full_buffer));
  161041. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161042. boolean need_full_buffer));
  161043. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161044. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161045. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161046. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161047. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161048. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161049. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161050. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161051. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161052. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161053. /* Memory manager initialization */
  161054. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161055. /* Utility routines in jutils.c */
  161056. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161057. EXTERN(long) jround_up JPP((long a, long b));
  161058. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161059. JSAMPARRAY output_array, int dest_row,
  161060. int num_rows, JDIMENSION num_cols));
  161061. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161062. JDIMENSION num_blocks));
  161063. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161064. /* Constant tables in jutils.c */
  161065. #if 0 /* This table is not actually needed in v6a */
  161066. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161067. #endif
  161068. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161069. /* Suppress undefined-structure complaints if necessary. */
  161070. #ifdef INCOMPLETE_TYPES_BROKEN
  161071. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161072. struct jvirt_sarray_control { long dummy; };
  161073. struct jvirt_barray_control { long dummy; };
  161074. #endif
  161075. #endif /* INCOMPLETE_TYPES_BROKEN */
  161076. /*** End of inlined file: jpegint.h ***/
  161077. /* fetch private declarations */
  161078. /*** Start of inlined file: jerror.h ***/
  161079. /*
  161080. * To define the enum list of message codes, include this file without
  161081. * defining macro JMESSAGE. To create a message string table, include it
  161082. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161083. */
  161084. #ifndef JMESSAGE
  161085. #ifndef JERROR_H
  161086. /* First time through, define the enum list */
  161087. #define JMAKE_ENUM_LIST
  161088. #else
  161089. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161090. #define JMESSAGE(code,string)
  161091. #endif /* JERROR_H */
  161092. #endif /* JMESSAGE */
  161093. #ifdef JMAKE_ENUM_LIST
  161094. typedef enum {
  161095. #define JMESSAGE(code,string) code ,
  161096. #endif /* JMAKE_ENUM_LIST */
  161097. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161098. /* For maintenance convenience, list is alphabetical by message code name */
  161099. JMESSAGE(JERR_ARITH_NOTIMPL,
  161100. "Sorry, there are legal restrictions on arithmetic coding")
  161101. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161102. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161103. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161104. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161105. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161106. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161107. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161108. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161109. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161110. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161111. JMESSAGE(JERR_BAD_LIB_VERSION,
  161112. "Wrong JPEG library version: library is %d, caller expects %d")
  161113. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161114. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161115. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161116. JMESSAGE(JERR_BAD_PROGRESSION,
  161117. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161118. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161119. "Invalid progressive parameters at scan script entry %d")
  161120. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161121. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161122. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161123. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161124. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161125. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161126. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161127. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161128. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161129. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161130. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161131. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161132. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161133. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161134. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161135. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161136. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161137. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161138. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161139. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161140. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161141. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161142. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161143. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161144. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161145. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161146. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161147. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161148. "Cannot transcode due to multiple use of quantization table %d")
  161149. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161150. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161151. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161152. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161153. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161154. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161155. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161156. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161157. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161158. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161159. JMESSAGE(JERR_QUANT_COMPONENTS,
  161160. "Cannot quantize more than %d color components")
  161161. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161162. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161163. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161164. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161165. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161166. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161167. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161168. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161169. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161170. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161171. JMESSAGE(JERR_TFILE_WRITE,
  161172. "Write failed on temporary file --- out of disk space?")
  161173. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161174. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161175. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161176. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161177. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161178. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161179. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161180. JMESSAGE(JMSG_VERSION, JVERSION)
  161181. JMESSAGE(JTRC_16BIT_TABLES,
  161182. "Caution: quantization tables are too coarse for baseline JPEG")
  161183. JMESSAGE(JTRC_ADOBE,
  161184. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161185. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161186. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161187. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161188. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161189. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161190. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161191. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161192. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161193. JMESSAGE(JTRC_EOI, "End Of Image")
  161194. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161195. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161196. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161197. "Warning: thumbnail image size does not match data length %u")
  161198. JMESSAGE(JTRC_JFIF_EXTENSION,
  161199. "JFIF extension marker: type 0x%02x, length %u")
  161200. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161201. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161202. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161203. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161204. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161205. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161206. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161207. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161208. JMESSAGE(JTRC_RST, "RST%d")
  161209. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161210. "Smoothing not supported with nonstandard sampling ratios")
  161211. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161212. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161213. JMESSAGE(JTRC_SOI, "Start of Image")
  161214. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161215. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161216. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161217. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161218. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161219. JMESSAGE(JTRC_THUMB_JPEG,
  161220. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161221. JMESSAGE(JTRC_THUMB_PALETTE,
  161222. "JFIF extension marker: palette thumbnail image, length %u")
  161223. JMESSAGE(JTRC_THUMB_RGB,
  161224. "JFIF extension marker: RGB thumbnail image, length %u")
  161225. JMESSAGE(JTRC_UNKNOWN_IDS,
  161226. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161227. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161228. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161229. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161230. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161231. "Inconsistent progression sequence for component %d coefficient %d")
  161232. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161233. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161234. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161235. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161236. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161237. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161238. JMESSAGE(JWRN_MUST_RESYNC,
  161239. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161240. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161241. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161242. #ifdef JMAKE_ENUM_LIST
  161243. JMSG_LASTMSGCODE
  161244. } J_MESSAGE_CODE;
  161245. #undef JMAKE_ENUM_LIST
  161246. #endif /* JMAKE_ENUM_LIST */
  161247. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161248. #undef JMESSAGE
  161249. #ifndef JERROR_H
  161250. #define JERROR_H
  161251. /* Macros to simplify using the error and trace message stuff */
  161252. /* The first parameter is either type of cinfo pointer */
  161253. /* Fatal errors (print message and exit) */
  161254. #define ERREXIT(cinfo,code) \
  161255. ((cinfo)->err->msg_code = (code), \
  161256. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161257. #define ERREXIT1(cinfo,code,p1) \
  161258. ((cinfo)->err->msg_code = (code), \
  161259. (cinfo)->err->msg_parm.i[0] = (p1), \
  161260. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161261. #define ERREXIT2(cinfo,code,p1,p2) \
  161262. ((cinfo)->err->msg_code = (code), \
  161263. (cinfo)->err->msg_parm.i[0] = (p1), \
  161264. (cinfo)->err->msg_parm.i[1] = (p2), \
  161265. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161266. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161267. ((cinfo)->err->msg_code = (code), \
  161268. (cinfo)->err->msg_parm.i[0] = (p1), \
  161269. (cinfo)->err->msg_parm.i[1] = (p2), \
  161270. (cinfo)->err->msg_parm.i[2] = (p3), \
  161271. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161272. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161273. ((cinfo)->err->msg_code = (code), \
  161274. (cinfo)->err->msg_parm.i[0] = (p1), \
  161275. (cinfo)->err->msg_parm.i[1] = (p2), \
  161276. (cinfo)->err->msg_parm.i[2] = (p3), \
  161277. (cinfo)->err->msg_parm.i[3] = (p4), \
  161278. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161279. #define ERREXITS(cinfo,code,str) \
  161280. ((cinfo)->err->msg_code = (code), \
  161281. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161282. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161283. #define MAKESTMT(stuff) do { stuff } while (0)
  161284. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161285. #define WARNMS(cinfo,code) \
  161286. ((cinfo)->err->msg_code = (code), \
  161287. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161288. #define WARNMS1(cinfo,code,p1) \
  161289. ((cinfo)->err->msg_code = (code), \
  161290. (cinfo)->err->msg_parm.i[0] = (p1), \
  161291. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161292. #define WARNMS2(cinfo,code,p1,p2) \
  161293. ((cinfo)->err->msg_code = (code), \
  161294. (cinfo)->err->msg_parm.i[0] = (p1), \
  161295. (cinfo)->err->msg_parm.i[1] = (p2), \
  161296. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161297. /* Informational/debugging messages */
  161298. #define TRACEMS(cinfo,lvl,code) \
  161299. ((cinfo)->err->msg_code = (code), \
  161300. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161301. #define TRACEMS1(cinfo,lvl,code,p1) \
  161302. ((cinfo)->err->msg_code = (code), \
  161303. (cinfo)->err->msg_parm.i[0] = (p1), \
  161304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161305. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161306. ((cinfo)->err->msg_code = (code), \
  161307. (cinfo)->err->msg_parm.i[0] = (p1), \
  161308. (cinfo)->err->msg_parm.i[1] = (p2), \
  161309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161310. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161311. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161312. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161313. (cinfo)->err->msg_code = (code); \
  161314. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161315. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161316. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161317. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161318. (cinfo)->err->msg_code = (code); \
  161319. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161320. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161321. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161322. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161323. _mp[4] = (p5); \
  161324. (cinfo)->err->msg_code = (code); \
  161325. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161326. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161327. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161328. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161329. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161330. (cinfo)->err->msg_code = (code); \
  161331. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161332. #define TRACEMSS(cinfo,lvl,code,str) \
  161333. ((cinfo)->err->msg_code = (code), \
  161334. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161335. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161336. #endif /* JERROR_H */
  161337. /*** End of inlined file: jerror.h ***/
  161338. /* fetch error codes too */
  161339. #endif
  161340. #endif /* JPEGLIB_H */
  161341. /*** End of inlined file: jpeglib.h ***/
  161342. /*** Start of inlined file: jcapimin.c ***/
  161343. #define JPEG_INTERNALS
  161344. /*** Start of inlined file: jinclude.h ***/
  161345. /* Include auto-config file to find out which system include files we need. */
  161346. #ifndef __jinclude_h__
  161347. #define __jinclude_h__
  161348. /*** Start of inlined file: jconfig.h ***/
  161349. /* see jconfig.doc for explanations */
  161350. // disable all the warnings under MSVC
  161351. #ifdef _MSC_VER
  161352. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161353. #endif
  161354. #ifdef __BORLANDC__
  161355. #pragma warn -8057
  161356. #pragma warn -8019
  161357. #pragma warn -8004
  161358. #pragma warn -8008
  161359. #endif
  161360. #define HAVE_PROTOTYPES
  161361. #define HAVE_UNSIGNED_CHAR
  161362. #define HAVE_UNSIGNED_SHORT
  161363. /* #define void char */
  161364. /* #define const */
  161365. #undef CHAR_IS_UNSIGNED
  161366. #define HAVE_STDDEF_H
  161367. #define HAVE_STDLIB_H
  161368. #undef NEED_BSD_STRINGS
  161369. #undef NEED_SYS_TYPES_H
  161370. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161371. #undef NEED_SHORT_EXTERNAL_NAMES
  161372. #undef INCOMPLETE_TYPES_BROKEN
  161373. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161374. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161375. typedef unsigned char boolean;
  161376. #endif
  161377. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161378. #ifdef JPEG_INTERNALS
  161379. #undef RIGHT_SHIFT_IS_UNSIGNED
  161380. #endif /* JPEG_INTERNALS */
  161381. #ifdef JPEG_CJPEG_DJPEG
  161382. #define BMP_SUPPORTED /* BMP image file format */
  161383. #define GIF_SUPPORTED /* GIF image file format */
  161384. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161385. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161386. #define TARGA_SUPPORTED /* Targa image file format */
  161387. #define TWO_FILE_COMMANDLINE /* optional */
  161388. #define USE_SETMODE /* Microsoft has setmode() */
  161389. #undef NEED_SIGNAL_CATCHER
  161390. #undef DONT_USE_B_MODE
  161391. #undef PROGRESS_REPORT /* optional */
  161392. #endif /* JPEG_CJPEG_DJPEG */
  161393. /*** End of inlined file: jconfig.h ***/
  161394. /* auto configuration options */
  161395. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161396. /*
  161397. * We need the NULL macro and size_t typedef.
  161398. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161399. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161400. * pull in <sys/types.h> as well.
  161401. * Note that the core JPEG library does not require <stdio.h>;
  161402. * only the default error handler and data source/destination modules do.
  161403. * But we must pull it in because of the references to FILE in jpeglib.h.
  161404. * You can remove those references if you want to compile without <stdio.h>.
  161405. */
  161406. #ifdef HAVE_STDDEF_H
  161407. #include <stddef.h>
  161408. #endif
  161409. #ifdef HAVE_STDLIB_H
  161410. #include <stdlib.h>
  161411. #endif
  161412. #ifdef NEED_SYS_TYPES_H
  161413. #include <sys/types.h>
  161414. #endif
  161415. #include <stdio.h>
  161416. /*
  161417. * We need memory copying and zeroing functions, plus strncpy().
  161418. * ANSI and System V implementations declare these in <string.h>.
  161419. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161420. * Some systems may declare memset and memcpy in <memory.h>.
  161421. *
  161422. * NOTE: we assume the size parameters to these functions are of type size_t.
  161423. * Change the casts in these macros if not!
  161424. */
  161425. #ifdef NEED_BSD_STRINGS
  161426. #include <strings.h>
  161427. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161428. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161429. #else /* not BSD, assume ANSI/SysV string lib */
  161430. #include <string.h>
  161431. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161432. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161433. #endif
  161434. /*
  161435. * In ANSI C, and indeed any rational implementation, size_t is also the
  161436. * type returned by sizeof(). However, it seems there are some irrational
  161437. * implementations out there, in which sizeof() returns an int even though
  161438. * size_t is defined as long or unsigned long. To ensure consistent results
  161439. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161440. */
  161441. #define SIZEOF(object) ((size_t) sizeof(object))
  161442. /*
  161443. * The modules that use fread() and fwrite() always invoke them through
  161444. * these macros. On some systems you may need to twiddle the argument casts.
  161445. * CAUTION: argument order is different from underlying functions!
  161446. */
  161447. #define JFREAD(file,buf,sizeofbuf) \
  161448. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161449. #define JFWRITE(file,buf,sizeofbuf) \
  161450. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161451. typedef enum { /* JPEG marker codes */
  161452. M_SOF0 = 0xc0,
  161453. M_SOF1 = 0xc1,
  161454. M_SOF2 = 0xc2,
  161455. M_SOF3 = 0xc3,
  161456. M_SOF5 = 0xc5,
  161457. M_SOF6 = 0xc6,
  161458. M_SOF7 = 0xc7,
  161459. M_JPG = 0xc8,
  161460. M_SOF9 = 0xc9,
  161461. M_SOF10 = 0xca,
  161462. M_SOF11 = 0xcb,
  161463. M_SOF13 = 0xcd,
  161464. M_SOF14 = 0xce,
  161465. M_SOF15 = 0xcf,
  161466. M_DHT = 0xc4,
  161467. M_DAC = 0xcc,
  161468. M_RST0 = 0xd0,
  161469. M_RST1 = 0xd1,
  161470. M_RST2 = 0xd2,
  161471. M_RST3 = 0xd3,
  161472. M_RST4 = 0xd4,
  161473. M_RST5 = 0xd5,
  161474. M_RST6 = 0xd6,
  161475. M_RST7 = 0xd7,
  161476. M_SOI = 0xd8,
  161477. M_EOI = 0xd9,
  161478. M_SOS = 0xda,
  161479. M_DQT = 0xdb,
  161480. M_DNL = 0xdc,
  161481. M_DRI = 0xdd,
  161482. M_DHP = 0xde,
  161483. M_EXP = 0xdf,
  161484. M_APP0 = 0xe0,
  161485. M_APP1 = 0xe1,
  161486. M_APP2 = 0xe2,
  161487. M_APP3 = 0xe3,
  161488. M_APP4 = 0xe4,
  161489. M_APP5 = 0xe5,
  161490. M_APP6 = 0xe6,
  161491. M_APP7 = 0xe7,
  161492. M_APP8 = 0xe8,
  161493. M_APP9 = 0xe9,
  161494. M_APP10 = 0xea,
  161495. M_APP11 = 0xeb,
  161496. M_APP12 = 0xec,
  161497. M_APP13 = 0xed,
  161498. M_APP14 = 0xee,
  161499. M_APP15 = 0xef,
  161500. M_JPG0 = 0xf0,
  161501. M_JPG13 = 0xfd,
  161502. M_COM = 0xfe,
  161503. M_TEM = 0x01,
  161504. M_ERROR = 0x100
  161505. } JPEG_MARKER;
  161506. /*
  161507. * Figure F.12: extend sign bit.
  161508. * On some machines, a shift and add will be faster than a table lookup.
  161509. */
  161510. #ifdef AVOID_TABLES
  161511. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161512. #else
  161513. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161514. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161515. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161516. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161517. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161518. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161519. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161520. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161521. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161522. #endif /* AVOID_TABLES */
  161523. #endif
  161524. /*** End of inlined file: jinclude.h ***/
  161525. /*
  161526. * Initialization of a JPEG compression object.
  161527. * The error manager must already be set up (in case memory manager fails).
  161528. */
  161529. GLOBAL(void)
  161530. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161531. {
  161532. int i;
  161533. /* Guard against version mismatches between library and caller. */
  161534. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161535. if (version != JPEG_LIB_VERSION)
  161536. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161537. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161538. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161539. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161540. /* For debugging purposes, we zero the whole master structure.
  161541. * But the application has already set the err pointer, and may have set
  161542. * client_data, so we have to save and restore those fields.
  161543. * Note: if application hasn't set client_data, tools like Purify may
  161544. * complain here.
  161545. */
  161546. {
  161547. struct jpeg_error_mgr * err = cinfo->err;
  161548. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161549. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161550. cinfo->err = err;
  161551. cinfo->client_data = client_data;
  161552. }
  161553. cinfo->is_decompressor = FALSE;
  161554. /* Initialize a memory manager instance for this object */
  161555. jinit_memory_mgr((j_common_ptr) cinfo);
  161556. /* Zero out pointers to permanent structures. */
  161557. cinfo->progress = NULL;
  161558. cinfo->dest = NULL;
  161559. cinfo->comp_info = NULL;
  161560. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161561. cinfo->quant_tbl_ptrs[i] = NULL;
  161562. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161563. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161564. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161565. }
  161566. cinfo->script_space = NULL;
  161567. cinfo->input_gamma = 1.0; /* in case application forgets */
  161568. /* OK, I'm ready */
  161569. cinfo->global_state = CSTATE_START;
  161570. }
  161571. /*
  161572. * Destruction of a JPEG compression object
  161573. */
  161574. GLOBAL(void)
  161575. jpeg_destroy_compress (j_compress_ptr cinfo)
  161576. {
  161577. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161578. }
  161579. /*
  161580. * Abort processing of a JPEG compression operation,
  161581. * but don't destroy the object itself.
  161582. */
  161583. GLOBAL(void)
  161584. jpeg_abort_compress (j_compress_ptr cinfo)
  161585. {
  161586. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161587. }
  161588. /*
  161589. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161590. * Marks all currently defined tables as already written (if suppress)
  161591. * or not written (if !suppress). This will control whether they get emitted
  161592. * by a subsequent jpeg_start_compress call.
  161593. *
  161594. * This routine is exported for use by applications that want to produce
  161595. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161596. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161597. * jcparam.o would be linked whether the application used it or not.
  161598. */
  161599. GLOBAL(void)
  161600. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161601. {
  161602. int i;
  161603. JQUANT_TBL * qtbl;
  161604. JHUFF_TBL * htbl;
  161605. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161606. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161607. qtbl->sent_table = suppress;
  161608. }
  161609. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161610. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161611. htbl->sent_table = suppress;
  161612. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161613. htbl->sent_table = suppress;
  161614. }
  161615. }
  161616. /*
  161617. * Finish JPEG compression.
  161618. *
  161619. * If a multipass operating mode was selected, this may do a great deal of
  161620. * work including most of the actual output.
  161621. */
  161622. GLOBAL(void)
  161623. jpeg_finish_compress (j_compress_ptr cinfo)
  161624. {
  161625. JDIMENSION iMCU_row;
  161626. if (cinfo->global_state == CSTATE_SCANNING ||
  161627. cinfo->global_state == CSTATE_RAW_OK) {
  161628. /* Terminate first pass */
  161629. if (cinfo->next_scanline < cinfo->image_height)
  161630. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161631. (*cinfo->master->finish_pass) (cinfo);
  161632. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161633. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161634. /* Perform any remaining passes */
  161635. while (! cinfo->master->is_last_pass) {
  161636. (*cinfo->master->prepare_for_pass) (cinfo);
  161637. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161638. if (cinfo->progress != NULL) {
  161639. cinfo->progress->pass_counter = (long) iMCU_row;
  161640. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161641. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161642. }
  161643. /* We bypass the main controller and invoke coef controller directly;
  161644. * all work is being done from the coefficient buffer.
  161645. */
  161646. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161647. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161648. }
  161649. (*cinfo->master->finish_pass) (cinfo);
  161650. }
  161651. /* Write EOI, do final cleanup */
  161652. (*cinfo->marker->write_file_trailer) (cinfo);
  161653. (*cinfo->dest->term_destination) (cinfo);
  161654. /* We can use jpeg_abort to release memory and reset global_state */
  161655. jpeg_abort((j_common_ptr) cinfo);
  161656. }
  161657. /*
  161658. * Write a special marker.
  161659. * This is only recommended for writing COM or APPn markers.
  161660. * Must be called after jpeg_start_compress() and before
  161661. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161662. */
  161663. GLOBAL(void)
  161664. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161665. const JOCTET *dataptr, unsigned int datalen)
  161666. {
  161667. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161668. if (cinfo->next_scanline != 0 ||
  161669. (cinfo->global_state != CSTATE_SCANNING &&
  161670. cinfo->global_state != CSTATE_RAW_OK &&
  161671. cinfo->global_state != CSTATE_WRCOEFS))
  161672. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161673. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161674. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161675. while (datalen--) {
  161676. (*write_marker_byte) (cinfo, *dataptr);
  161677. dataptr++;
  161678. }
  161679. }
  161680. /* Same, but piecemeal. */
  161681. GLOBAL(void)
  161682. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161683. {
  161684. if (cinfo->next_scanline != 0 ||
  161685. (cinfo->global_state != CSTATE_SCANNING &&
  161686. cinfo->global_state != CSTATE_RAW_OK &&
  161687. cinfo->global_state != CSTATE_WRCOEFS))
  161688. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161689. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161690. }
  161691. GLOBAL(void)
  161692. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161693. {
  161694. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161695. }
  161696. /*
  161697. * Alternate compression function: just write an abbreviated table file.
  161698. * Before calling this, all parameters and a data destination must be set up.
  161699. *
  161700. * To produce a pair of files containing abbreviated tables and abbreviated
  161701. * image data, one would proceed as follows:
  161702. *
  161703. * initialize JPEG object
  161704. * set JPEG parameters
  161705. * set destination to table file
  161706. * jpeg_write_tables(cinfo);
  161707. * set destination to image file
  161708. * jpeg_start_compress(cinfo, FALSE);
  161709. * write data...
  161710. * jpeg_finish_compress(cinfo);
  161711. *
  161712. * jpeg_write_tables has the side effect of marking all tables written
  161713. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161714. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161715. */
  161716. GLOBAL(void)
  161717. jpeg_write_tables (j_compress_ptr cinfo)
  161718. {
  161719. if (cinfo->global_state != CSTATE_START)
  161720. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161721. /* (Re)initialize error mgr and destination modules */
  161722. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161723. (*cinfo->dest->init_destination) (cinfo);
  161724. /* Initialize the marker writer ... bit of a crock to do it here. */
  161725. jinit_marker_writer(cinfo);
  161726. /* Write them tables! */
  161727. (*cinfo->marker->write_tables_only) (cinfo);
  161728. /* And clean up. */
  161729. (*cinfo->dest->term_destination) (cinfo);
  161730. /*
  161731. * In library releases up through v6a, we called jpeg_abort() here to free
  161732. * any working memory allocated by the destination manager and marker
  161733. * writer. Some applications had a problem with that: they allocated space
  161734. * of their own from the library memory manager, and didn't want it to go
  161735. * away during write_tables. So now we do nothing. This will cause a
  161736. * memory leak if an app calls write_tables repeatedly without doing a full
  161737. * compression cycle or otherwise resetting the JPEG object. However, that
  161738. * seems less bad than unexpectedly freeing memory in the normal case.
  161739. * An app that prefers the old behavior can call jpeg_abort for itself after
  161740. * each call to jpeg_write_tables().
  161741. */
  161742. }
  161743. /*** End of inlined file: jcapimin.c ***/
  161744. /*** Start of inlined file: jcapistd.c ***/
  161745. #define JPEG_INTERNALS
  161746. /*
  161747. * Compression initialization.
  161748. * Before calling this, all parameters and a data destination must be set up.
  161749. *
  161750. * We require a write_all_tables parameter as a failsafe check when writing
  161751. * multiple datastreams from the same compression object. Since prior runs
  161752. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161753. * would emit an abbreviated stream (no tables) by default. This may be what
  161754. * is wanted, but for safety's sake it should not be the default behavior:
  161755. * programmers should have to make a deliberate choice to emit abbreviated
  161756. * images. Therefore the documentation and examples should encourage people
  161757. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161758. * wrong thing.
  161759. */
  161760. GLOBAL(void)
  161761. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161762. {
  161763. if (cinfo->global_state != CSTATE_START)
  161764. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161765. if (write_all_tables)
  161766. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161767. /* (Re)initialize error mgr and destination modules */
  161768. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161769. (*cinfo->dest->init_destination) (cinfo);
  161770. /* Perform master selection of active modules */
  161771. jinit_compress_master(cinfo);
  161772. /* Set up for the first pass */
  161773. (*cinfo->master->prepare_for_pass) (cinfo);
  161774. /* Ready for application to drive first pass through jpeg_write_scanlines
  161775. * or jpeg_write_raw_data.
  161776. */
  161777. cinfo->next_scanline = 0;
  161778. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161779. }
  161780. /*
  161781. * Write some scanlines of data to the JPEG compressor.
  161782. *
  161783. * The return value will be the number of lines actually written.
  161784. * This should be less than the supplied num_lines only in case that
  161785. * the data destination module has requested suspension of the compressor,
  161786. * or if more than image_height scanlines are passed in.
  161787. *
  161788. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161789. * this likely signals an application programmer error. However,
  161790. * excess scanlines passed in the last valid call are *silently* ignored,
  161791. * so that the application need not adjust num_lines for end-of-image
  161792. * when using a multiple-scanline buffer.
  161793. */
  161794. GLOBAL(JDIMENSION)
  161795. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161796. JDIMENSION num_lines)
  161797. {
  161798. JDIMENSION row_ctr, rows_left;
  161799. if (cinfo->global_state != CSTATE_SCANNING)
  161800. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161801. if (cinfo->next_scanline >= cinfo->image_height)
  161802. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161803. /* Call progress monitor hook if present */
  161804. if (cinfo->progress != NULL) {
  161805. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161806. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161807. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161808. }
  161809. /* Give master control module another chance if this is first call to
  161810. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161811. * delayed so that application can write COM, etc, markers between
  161812. * jpeg_start_compress and jpeg_write_scanlines.
  161813. */
  161814. if (cinfo->master->call_pass_startup)
  161815. (*cinfo->master->pass_startup) (cinfo);
  161816. /* Ignore any extra scanlines at bottom of image. */
  161817. rows_left = cinfo->image_height - cinfo->next_scanline;
  161818. if (num_lines > rows_left)
  161819. num_lines = rows_left;
  161820. row_ctr = 0;
  161821. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161822. cinfo->next_scanline += row_ctr;
  161823. return row_ctr;
  161824. }
  161825. /*
  161826. * Alternate entry point to write raw data.
  161827. * Processes exactly one iMCU row per call, unless suspended.
  161828. */
  161829. GLOBAL(JDIMENSION)
  161830. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161831. JDIMENSION num_lines)
  161832. {
  161833. JDIMENSION lines_per_iMCU_row;
  161834. if (cinfo->global_state != CSTATE_RAW_OK)
  161835. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161836. if (cinfo->next_scanline >= cinfo->image_height) {
  161837. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161838. return 0;
  161839. }
  161840. /* Call progress monitor hook if present */
  161841. if (cinfo->progress != NULL) {
  161842. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161843. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161844. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161845. }
  161846. /* Give master control module another chance if this is first call to
  161847. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161848. * delayed so that application can write COM, etc, markers between
  161849. * jpeg_start_compress and jpeg_write_raw_data.
  161850. */
  161851. if (cinfo->master->call_pass_startup)
  161852. (*cinfo->master->pass_startup) (cinfo);
  161853. /* Verify that at least one iMCU row has been passed. */
  161854. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161855. if (num_lines < lines_per_iMCU_row)
  161856. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161857. /* Directly compress the row. */
  161858. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161859. /* If compressor did not consume the whole row, suspend processing. */
  161860. return 0;
  161861. }
  161862. /* OK, we processed one iMCU row. */
  161863. cinfo->next_scanline += lines_per_iMCU_row;
  161864. return lines_per_iMCU_row;
  161865. }
  161866. /*** End of inlined file: jcapistd.c ***/
  161867. /*** Start of inlined file: jccoefct.c ***/
  161868. #define JPEG_INTERNALS
  161869. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161870. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161871. * step is run during the first pass, and subsequent passes need only read
  161872. * the buffered coefficients.
  161873. */
  161874. #ifdef ENTROPY_OPT_SUPPORTED
  161875. #define FULL_COEF_BUFFER_SUPPORTED
  161876. #else
  161877. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161878. #define FULL_COEF_BUFFER_SUPPORTED
  161879. #endif
  161880. #endif
  161881. /* Private buffer controller object */
  161882. typedef struct {
  161883. struct jpeg_c_coef_controller pub; /* public fields */
  161884. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161885. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161886. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161887. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161888. /* For single-pass compression, it's sufficient to buffer just one MCU
  161889. * (although this may prove a bit slow in practice). We allocate a
  161890. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161891. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161892. * it's not really very big; this is to keep the module interfaces unchanged
  161893. * when a large coefficient buffer is necessary.)
  161894. * In multi-pass modes, this array points to the current MCU's blocks
  161895. * within the virtual arrays.
  161896. */
  161897. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161898. /* In multi-pass modes, we need a virtual block array for each component. */
  161899. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161900. } my_coef_controller;
  161901. typedef my_coef_controller * my_coef_ptr;
  161902. /* Forward declarations */
  161903. METHODDEF(boolean) compress_data
  161904. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161905. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161906. METHODDEF(boolean) compress_first_pass
  161907. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161908. METHODDEF(boolean) compress_output
  161909. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161910. #endif
  161911. LOCAL(void)
  161912. start_iMCU_row (j_compress_ptr cinfo)
  161913. /* Reset within-iMCU-row counters for a new row */
  161914. {
  161915. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161916. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161917. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161918. * But at the bottom of the image, process only what's left.
  161919. */
  161920. if (cinfo->comps_in_scan > 1) {
  161921. coef->MCU_rows_per_iMCU_row = 1;
  161922. } else {
  161923. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161924. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161925. else
  161926. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161927. }
  161928. coef->mcu_ctr = 0;
  161929. coef->MCU_vert_offset = 0;
  161930. }
  161931. /*
  161932. * Initialize for a processing pass.
  161933. */
  161934. METHODDEF(void)
  161935. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161936. {
  161937. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161938. coef->iMCU_row_num = 0;
  161939. start_iMCU_row(cinfo);
  161940. switch (pass_mode) {
  161941. case JBUF_PASS_THRU:
  161942. if (coef->whole_image[0] != NULL)
  161943. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161944. coef->pub.compress_data = compress_data;
  161945. break;
  161946. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161947. case JBUF_SAVE_AND_PASS:
  161948. if (coef->whole_image[0] == NULL)
  161949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161950. coef->pub.compress_data = compress_first_pass;
  161951. break;
  161952. case JBUF_CRANK_DEST:
  161953. if (coef->whole_image[0] == NULL)
  161954. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161955. coef->pub.compress_data = compress_output;
  161956. break;
  161957. #endif
  161958. default:
  161959. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161960. break;
  161961. }
  161962. }
  161963. /*
  161964. * Process some data in the single-pass case.
  161965. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161966. * per call, ie, v_samp_factor block rows for each component in the image.
  161967. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161968. *
  161969. * NB: input_buf contains a plane for each component in image,
  161970. * which we index according to the component's SOF position.
  161971. */
  161972. METHODDEF(boolean)
  161973. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161974. {
  161975. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161976. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161977. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161978. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161979. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161980. JDIMENSION ypos, xpos;
  161981. jpeg_component_info *compptr;
  161982. /* Loop to write as much as one whole iMCU row */
  161983. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161984. yoffset++) {
  161985. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161986. MCU_col_num++) {
  161987. /* Determine where data comes from in input_buf and do the DCT thing.
  161988. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161989. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161990. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161991. * specially. The data in them does not matter for image reconstruction,
  161992. * so we fill them with values that will encode to the smallest amount of
  161993. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161994. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161995. */
  161996. blkn = 0;
  161997. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161998. compptr = cinfo->cur_comp_info[ci];
  161999. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162000. : compptr->last_col_width;
  162001. xpos = MCU_col_num * compptr->MCU_sample_width;
  162002. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162003. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162004. if (coef->iMCU_row_num < last_iMCU_row ||
  162005. yoffset+yindex < compptr->last_row_height) {
  162006. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162007. input_buf[compptr->component_index],
  162008. coef->MCU_buffer[blkn],
  162009. ypos, xpos, (JDIMENSION) blockcnt);
  162010. if (blockcnt < compptr->MCU_width) {
  162011. /* Create some dummy blocks at the right edge of the image. */
  162012. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162013. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162014. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162015. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162016. }
  162017. }
  162018. } else {
  162019. /* Create a row of dummy blocks at the bottom of the image. */
  162020. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162021. compptr->MCU_width * SIZEOF(JBLOCK));
  162022. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162023. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162024. }
  162025. }
  162026. blkn += compptr->MCU_width;
  162027. ypos += DCTSIZE;
  162028. }
  162029. }
  162030. /* Try to write the MCU. In event of a suspension failure, we will
  162031. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162032. */
  162033. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162034. /* Suspension forced; update state counters and exit */
  162035. coef->MCU_vert_offset = yoffset;
  162036. coef->mcu_ctr = MCU_col_num;
  162037. return FALSE;
  162038. }
  162039. }
  162040. /* Completed an MCU row, but perhaps not an iMCU row */
  162041. coef->mcu_ctr = 0;
  162042. }
  162043. /* Completed the iMCU row, advance counters for next one */
  162044. coef->iMCU_row_num++;
  162045. start_iMCU_row(cinfo);
  162046. return TRUE;
  162047. }
  162048. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162049. /*
  162050. * Process some data in the first pass of a multi-pass case.
  162051. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162052. * per call, ie, v_samp_factor block rows for each component in the image.
  162053. * This amount of data is read from the source buffer, DCT'd and quantized,
  162054. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162055. * as needed at the right and lower edges. (The dummy blocks are constructed
  162056. * in the virtual arrays, which have been padded appropriately.) This makes
  162057. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162058. *
  162059. * We must also emit the data to the entropy encoder. This is conveniently
  162060. * done by calling compress_output() after we've loaded the current strip
  162061. * of the virtual arrays.
  162062. *
  162063. * NB: input_buf contains a plane for each component in image. All
  162064. * components are DCT'd and loaded into the virtual arrays in this pass.
  162065. * However, it may be that only a subset of the components are emitted to
  162066. * the entropy encoder during this first pass; be careful about looking
  162067. * at the scan-dependent variables (MCU dimensions, etc).
  162068. */
  162069. METHODDEF(boolean)
  162070. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162071. {
  162072. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162073. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162074. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162075. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162076. JCOEF lastDC;
  162077. jpeg_component_info *compptr;
  162078. JBLOCKARRAY buffer;
  162079. JBLOCKROW thisblockrow, lastblockrow;
  162080. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162081. ci++, compptr++) {
  162082. /* Align the virtual buffer for this component. */
  162083. buffer = (*cinfo->mem->access_virt_barray)
  162084. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162085. coef->iMCU_row_num * compptr->v_samp_factor,
  162086. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162087. /* Count non-dummy DCT block rows in this iMCU row. */
  162088. if (coef->iMCU_row_num < last_iMCU_row)
  162089. block_rows = compptr->v_samp_factor;
  162090. else {
  162091. /* NB: can't use last_row_height here, since may not be set! */
  162092. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162093. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162094. }
  162095. blocks_across = compptr->width_in_blocks;
  162096. h_samp_factor = compptr->h_samp_factor;
  162097. /* Count number of dummy blocks to be added at the right margin. */
  162098. ndummy = (int) (blocks_across % h_samp_factor);
  162099. if (ndummy > 0)
  162100. ndummy = h_samp_factor - ndummy;
  162101. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162102. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162103. */
  162104. for (block_row = 0; block_row < block_rows; block_row++) {
  162105. thisblockrow = buffer[block_row];
  162106. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162107. input_buf[ci], thisblockrow,
  162108. (JDIMENSION) (block_row * DCTSIZE),
  162109. (JDIMENSION) 0, blocks_across);
  162110. if (ndummy > 0) {
  162111. /* Create dummy blocks at the right edge of the image. */
  162112. thisblockrow += blocks_across; /* => first dummy block */
  162113. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162114. lastDC = thisblockrow[-1][0];
  162115. for (bi = 0; bi < ndummy; bi++) {
  162116. thisblockrow[bi][0] = lastDC;
  162117. }
  162118. }
  162119. }
  162120. /* If at end of image, create dummy block rows as needed.
  162121. * The tricky part here is that within each MCU, we want the DC values
  162122. * of the dummy blocks to match the last real block's DC value.
  162123. * This squeezes a few more bytes out of the resulting file...
  162124. */
  162125. if (coef->iMCU_row_num == last_iMCU_row) {
  162126. blocks_across += ndummy; /* include lower right corner */
  162127. MCUs_across = blocks_across / h_samp_factor;
  162128. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162129. block_row++) {
  162130. thisblockrow = buffer[block_row];
  162131. lastblockrow = buffer[block_row-1];
  162132. jzero_far((void FAR *) thisblockrow,
  162133. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162134. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162135. lastDC = lastblockrow[h_samp_factor-1][0];
  162136. for (bi = 0; bi < h_samp_factor; bi++) {
  162137. thisblockrow[bi][0] = lastDC;
  162138. }
  162139. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162140. lastblockrow += h_samp_factor;
  162141. }
  162142. }
  162143. }
  162144. }
  162145. /* NB: compress_output will increment iMCU_row_num if successful.
  162146. * A suspension return will result in redoing all the work above next time.
  162147. */
  162148. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162149. return compress_output(cinfo, input_buf);
  162150. }
  162151. /*
  162152. * Process some data in subsequent passes of a multi-pass case.
  162153. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162154. * per call, ie, v_samp_factor block rows for each component in the scan.
  162155. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162156. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162157. *
  162158. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162159. */
  162160. METHODDEF(boolean)
  162161. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162162. {
  162163. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162164. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162165. int blkn, ci, xindex, yindex, yoffset;
  162166. JDIMENSION start_col;
  162167. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162168. JBLOCKROW buffer_ptr;
  162169. jpeg_component_info *compptr;
  162170. /* Align the virtual buffers for the components used in this scan.
  162171. * NB: during first pass, this is safe only because the buffers will
  162172. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162173. */
  162174. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162175. compptr = cinfo->cur_comp_info[ci];
  162176. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162177. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162178. coef->iMCU_row_num * compptr->v_samp_factor,
  162179. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162180. }
  162181. /* Loop to process one whole iMCU row */
  162182. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162183. yoffset++) {
  162184. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162185. MCU_col_num++) {
  162186. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162187. blkn = 0; /* index of current DCT block within MCU */
  162188. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162189. compptr = cinfo->cur_comp_info[ci];
  162190. start_col = MCU_col_num * compptr->MCU_width;
  162191. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162192. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162193. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162194. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162195. }
  162196. }
  162197. }
  162198. /* Try to write the MCU. */
  162199. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162200. /* Suspension forced; update state counters and exit */
  162201. coef->MCU_vert_offset = yoffset;
  162202. coef->mcu_ctr = MCU_col_num;
  162203. return FALSE;
  162204. }
  162205. }
  162206. /* Completed an MCU row, but perhaps not an iMCU row */
  162207. coef->mcu_ctr = 0;
  162208. }
  162209. /* Completed the iMCU row, advance counters for next one */
  162210. coef->iMCU_row_num++;
  162211. start_iMCU_row(cinfo);
  162212. return TRUE;
  162213. }
  162214. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162215. /*
  162216. * Initialize coefficient buffer controller.
  162217. */
  162218. GLOBAL(void)
  162219. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162220. {
  162221. my_coef_ptr coef;
  162222. coef = (my_coef_ptr)
  162223. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162224. SIZEOF(my_coef_controller));
  162225. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162226. coef->pub.start_pass = start_pass_coef;
  162227. /* Create the coefficient buffer. */
  162228. if (need_full_buffer) {
  162229. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162230. /* Allocate a full-image virtual array for each component, */
  162231. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162232. int ci;
  162233. jpeg_component_info *compptr;
  162234. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162235. ci++, compptr++) {
  162236. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162237. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162238. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162239. (long) compptr->h_samp_factor),
  162240. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162241. (long) compptr->v_samp_factor),
  162242. (JDIMENSION) compptr->v_samp_factor);
  162243. }
  162244. #else
  162245. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162246. #endif
  162247. } else {
  162248. /* We only need a single-MCU buffer. */
  162249. JBLOCKROW buffer;
  162250. int i;
  162251. buffer = (JBLOCKROW)
  162252. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162253. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162254. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162255. coef->MCU_buffer[i] = buffer + i;
  162256. }
  162257. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162258. }
  162259. }
  162260. /*** End of inlined file: jccoefct.c ***/
  162261. /*** Start of inlined file: jccolor.c ***/
  162262. #define JPEG_INTERNALS
  162263. /* Private subobject */
  162264. typedef struct {
  162265. struct jpeg_color_converter pub; /* public fields */
  162266. /* Private state for RGB->YCC conversion */
  162267. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162268. } my_color_converter;
  162269. typedef my_color_converter * my_cconvert_ptr;
  162270. /**************** RGB -> YCbCr conversion: most common case **************/
  162271. /*
  162272. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162273. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162274. * The conversion equations to be implemented are therefore
  162275. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162276. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162277. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162278. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162279. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162280. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162281. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162282. * were not represented exactly. Now we sacrifice exact representation of
  162283. * maximum red and maximum blue in order to get exact grayscales.
  162284. *
  162285. * To avoid floating-point arithmetic, we represent the fractional constants
  162286. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162287. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162288. *
  162289. * For even more speed, we avoid doing any multiplications in the inner loop
  162290. * by precalculating the constants times R,G,B for all possible values.
  162291. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162292. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162293. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162294. * colorspace anyway.
  162295. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162296. * in the tables to save adding them separately in the inner loop.
  162297. */
  162298. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162299. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162300. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162301. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162302. /* We allocate one big table and divide it up into eight parts, instead of
  162303. * doing eight alloc_small requests. This lets us use a single table base
  162304. * address, which can be held in a register in the inner loops on many
  162305. * machines (more than can hold all eight addresses, anyway).
  162306. */
  162307. #define R_Y_OFF 0 /* offset to R => Y section */
  162308. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162309. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162310. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162311. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162312. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162313. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162314. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162315. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162316. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162317. /*
  162318. * Initialize for RGB->YCC colorspace conversion.
  162319. */
  162320. METHODDEF(void)
  162321. rgb_ycc_start (j_compress_ptr cinfo)
  162322. {
  162323. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162324. INT32 * rgb_ycc_tab;
  162325. INT32 i;
  162326. /* Allocate and fill in the conversion tables. */
  162327. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162329. (TABLE_SIZE * SIZEOF(INT32)));
  162330. for (i = 0; i <= MAXJSAMPLE; i++) {
  162331. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162332. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162333. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162334. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162335. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162336. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162337. * This ensures that the maximum output will round to MAXJSAMPLE
  162338. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162339. */
  162340. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162341. /* B=>Cb and R=>Cr tables are the same
  162342. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162343. */
  162344. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162345. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162346. }
  162347. }
  162348. /*
  162349. * Convert some rows of samples to the JPEG colorspace.
  162350. *
  162351. * Note that we change from the application's interleaved-pixel format
  162352. * to our internal noninterleaved, one-plane-per-component format.
  162353. * The input buffer is therefore three times as wide as the output buffer.
  162354. *
  162355. * A starting row offset is provided only for the output buffer. The caller
  162356. * can easily adjust the passed input_buf value to accommodate any row
  162357. * offset required on that side.
  162358. */
  162359. METHODDEF(void)
  162360. rgb_ycc_convert (j_compress_ptr cinfo,
  162361. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162362. JDIMENSION output_row, int num_rows)
  162363. {
  162364. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162365. register int r, g, b;
  162366. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162367. register JSAMPROW inptr;
  162368. register JSAMPROW outptr0, outptr1, outptr2;
  162369. register JDIMENSION col;
  162370. JDIMENSION num_cols = cinfo->image_width;
  162371. while (--num_rows >= 0) {
  162372. inptr = *input_buf++;
  162373. outptr0 = output_buf[0][output_row];
  162374. outptr1 = output_buf[1][output_row];
  162375. outptr2 = output_buf[2][output_row];
  162376. output_row++;
  162377. for (col = 0; col < num_cols; col++) {
  162378. r = GETJSAMPLE(inptr[RGB_RED]);
  162379. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162380. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162381. inptr += RGB_PIXELSIZE;
  162382. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162383. * must be too; we do not need an explicit range-limiting operation.
  162384. * Hence the value being shifted is never negative, and we don't
  162385. * need the general RIGHT_SHIFT macro.
  162386. */
  162387. /* Y */
  162388. outptr0[col] = (JSAMPLE)
  162389. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162390. >> SCALEBITS);
  162391. /* Cb */
  162392. outptr1[col] = (JSAMPLE)
  162393. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162394. >> SCALEBITS);
  162395. /* Cr */
  162396. outptr2[col] = (JSAMPLE)
  162397. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162398. >> SCALEBITS);
  162399. }
  162400. }
  162401. }
  162402. /**************** Cases other than RGB -> YCbCr **************/
  162403. /*
  162404. * Convert some rows of samples to the JPEG colorspace.
  162405. * This version handles RGB->grayscale conversion, which is the same
  162406. * as the RGB->Y portion of RGB->YCbCr.
  162407. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162408. */
  162409. METHODDEF(void)
  162410. rgb_gray_convert (j_compress_ptr cinfo,
  162411. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162412. JDIMENSION output_row, int num_rows)
  162413. {
  162414. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162415. register int r, g, b;
  162416. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162417. register JSAMPROW inptr;
  162418. register JSAMPROW outptr;
  162419. register JDIMENSION col;
  162420. JDIMENSION num_cols = cinfo->image_width;
  162421. while (--num_rows >= 0) {
  162422. inptr = *input_buf++;
  162423. outptr = output_buf[0][output_row];
  162424. output_row++;
  162425. for (col = 0; col < num_cols; col++) {
  162426. r = GETJSAMPLE(inptr[RGB_RED]);
  162427. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162428. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162429. inptr += RGB_PIXELSIZE;
  162430. /* Y */
  162431. outptr[col] = (JSAMPLE)
  162432. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162433. >> SCALEBITS);
  162434. }
  162435. }
  162436. }
  162437. /*
  162438. * Convert some rows of samples to the JPEG colorspace.
  162439. * This version handles Adobe-style CMYK->YCCK conversion,
  162440. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162441. * conversion as above, while passing K (black) unchanged.
  162442. * We assume rgb_ycc_start has been called.
  162443. */
  162444. METHODDEF(void)
  162445. cmyk_ycck_convert (j_compress_ptr cinfo,
  162446. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162447. JDIMENSION output_row, int num_rows)
  162448. {
  162449. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162450. register int r, g, b;
  162451. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162452. register JSAMPROW inptr;
  162453. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162454. register JDIMENSION col;
  162455. JDIMENSION num_cols = cinfo->image_width;
  162456. while (--num_rows >= 0) {
  162457. inptr = *input_buf++;
  162458. outptr0 = output_buf[0][output_row];
  162459. outptr1 = output_buf[1][output_row];
  162460. outptr2 = output_buf[2][output_row];
  162461. outptr3 = output_buf[3][output_row];
  162462. output_row++;
  162463. for (col = 0; col < num_cols; col++) {
  162464. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162465. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162466. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162467. /* K passes through as-is */
  162468. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162469. inptr += 4;
  162470. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162471. * must be too; we do not need an explicit range-limiting operation.
  162472. * Hence the value being shifted is never negative, and we don't
  162473. * need the general RIGHT_SHIFT macro.
  162474. */
  162475. /* Y */
  162476. outptr0[col] = (JSAMPLE)
  162477. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162478. >> SCALEBITS);
  162479. /* Cb */
  162480. outptr1[col] = (JSAMPLE)
  162481. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162482. >> SCALEBITS);
  162483. /* Cr */
  162484. outptr2[col] = (JSAMPLE)
  162485. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162486. >> SCALEBITS);
  162487. }
  162488. }
  162489. }
  162490. /*
  162491. * Convert some rows of samples to the JPEG colorspace.
  162492. * This version handles grayscale output with no conversion.
  162493. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162494. */
  162495. METHODDEF(void)
  162496. grayscale_convert (j_compress_ptr cinfo,
  162497. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162498. JDIMENSION output_row, int num_rows)
  162499. {
  162500. register JSAMPROW inptr;
  162501. register JSAMPROW outptr;
  162502. register JDIMENSION col;
  162503. JDIMENSION num_cols = cinfo->image_width;
  162504. int instride = cinfo->input_components;
  162505. while (--num_rows >= 0) {
  162506. inptr = *input_buf++;
  162507. outptr = output_buf[0][output_row];
  162508. output_row++;
  162509. for (col = 0; col < num_cols; col++) {
  162510. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162511. inptr += instride;
  162512. }
  162513. }
  162514. }
  162515. /*
  162516. * Convert some rows of samples to the JPEG colorspace.
  162517. * This version handles multi-component colorspaces without conversion.
  162518. * We assume input_components == num_components.
  162519. */
  162520. METHODDEF(void)
  162521. null_convert (j_compress_ptr cinfo,
  162522. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162523. JDIMENSION output_row, int num_rows)
  162524. {
  162525. register JSAMPROW inptr;
  162526. register JSAMPROW outptr;
  162527. register JDIMENSION col;
  162528. register int ci;
  162529. int nc = cinfo->num_components;
  162530. JDIMENSION num_cols = cinfo->image_width;
  162531. while (--num_rows >= 0) {
  162532. /* It seems fastest to make a separate pass for each component. */
  162533. for (ci = 0; ci < nc; ci++) {
  162534. inptr = *input_buf;
  162535. outptr = output_buf[ci][output_row];
  162536. for (col = 0; col < num_cols; col++) {
  162537. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162538. inptr += nc;
  162539. }
  162540. }
  162541. input_buf++;
  162542. output_row++;
  162543. }
  162544. }
  162545. /*
  162546. * Empty method for start_pass.
  162547. */
  162548. METHODDEF(void)
  162549. null_method (j_compress_ptr)
  162550. {
  162551. /* no work needed */
  162552. }
  162553. /*
  162554. * Module initialization routine for input colorspace conversion.
  162555. */
  162556. GLOBAL(void)
  162557. jinit_color_converter (j_compress_ptr cinfo)
  162558. {
  162559. my_cconvert_ptr cconvert;
  162560. cconvert = (my_cconvert_ptr)
  162561. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162562. SIZEOF(my_color_converter));
  162563. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162564. /* set start_pass to null method until we find out differently */
  162565. cconvert->pub.start_pass = null_method;
  162566. /* Make sure input_components agrees with in_color_space */
  162567. switch (cinfo->in_color_space) {
  162568. case JCS_GRAYSCALE:
  162569. if (cinfo->input_components != 1)
  162570. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162571. break;
  162572. case JCS_RGB:
  162573. #if RGB_PIXELSIZE != 3
  162574. if (cinfo->input_components != RGB_PIXELSIZE)
  162575. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162576. break;
  162577. #endif /* else share code with YCbCr */
  162578. case JCS_YCbCr:
  162579. if (cinfo->input_components != 3)
  162580. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162581. break;
  162582. case JCS_CMYK:
  162583. case JCS_YCCK:
  162584. if (cinfo->input_components != 4)
  162585. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162586. break;
  162587. default: /* JCS_UNKNOWN can be anything */
  162588. if (cinfo->input_components < 1)
  162589. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162590. break;
  162591. }
  162592. /* Check num_components, set conversion method based on requested space */
  162593. switch (cinfo->jpeg_color_space) {
  162594. case JCS_GRAYSCALE:
  162595. if (cinfo->num_components != 1)
  162596. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162597. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162598. cconvert->pub.color_convert = grayscale_convert;
  162599. else if (cinfo->in_color_space == JCS_RGB) {
  162600. cconvert->pub.start_pass = rgb_ycc_start;
  162601. cconvert->pub.color_convert = rgb_gray_convert;
  162602. } else if (cinfo->in_color_space == JCS_YCbCr)
  162603. cconvert->pub.color_convert = grayscale_convert;
  162604. else
  162605. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162606. break;
  162607. case JCS_RGB:
  162608. if (cinfo->num_components != 3)
  162609. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162610. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162611. cconvert->pub.color_convert = null_convert;
  162612. else
  162613. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162614. break;
  162615. case JCS_YCbCr:
  162616. if (cinfo->num_components != 3)
  162617. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162618. if (cinfo->in_color_space == JCS_RGB) {
  162619. cconvert->pub.start_pass = rgb_ycc_start;
  162620. cconvert->pub.color_convert = rgb_ycc_convert;
  162621. } else if (cinfo->in_color_space == JCS_YCbCr)
  162622. cconvert->pub.color_convert = null_convert;
  162623. else
  162624. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162625. break;
  162626. case JCS_CMYK:
  162627. if (cinfo->num_components != 4)
  162628. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162629. if (cinfo->in_color_space == JCS_CMYK)
  162630. cconvert->pub.color_convert = null_convert;
  162631. else
  162632. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162633. break;
  162634. case JCS_YCCK:
  162635. if (cinfo->num_components != 4)
  162636. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162637. if (cinfo->in_color_space == JCS_CMYK) {
  162638. cconvert->pub.start_pass = rgb_ycc_start;
  162639. cconvert->pub.color_convert = cmyk_ycck_convert;
  162640. } else if (cinfo->in_color_space == JCS_YCCK)
  162641. cconvert->pub.color_convert = null_convert;
  162642. else
  162643. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162644. break;
  162645. default: /* allow null conversion of JCS_UNKNOWN */
  162646. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162647. cinfo->num_components != cinfo->input_components)
  162648. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162649. cconvert->pub.color_convert = null_convert;
  162650. break;
  162651. }
  162652. }
  162653. /*** End of inlined file: jccolor.c ***/
  162654. #undef FIX
  162655. /*** Start of inlined file: jcdctmgr.c ***/
  162656. #define JPEG_INTERNALS
  162657. /*** Start of inlined file: jdct.h ***/
  162658. /*
  162659. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162660. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162661. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162662. * implementations use an array of type FAST_FLOAT, instead.)
  162663. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162664. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162665. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162666. * convention improves accuracy in integer implementations and saves some
  162667. * work in floating-point ones.
  162668. * Quantization of the output coefficients is done by jcdctmgr.c.
  162669. */
  162670. #ifndef __jdct_h__
  162671. #define __jdct_h__
  162672. #if BITS_IN_JSAMPLE == 8
  162673. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162674. #else
  162675. typedef INT32 DCTELEM; /* must have 32 bits */
  162676. #endif
  162677. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162678. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162679. /*
  162680. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162681. * to an output sample array. The routine must dequantize the input data as
  162682. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162683. * pointed to by compptr->dct_table. The output data is to be placed into the
  162684. * sample array starting at a specified column. (Any row offset needed will
  162685. * be applied to the array pointer before it is passed to the IDCT code.)
  162686. * Note that the number of samples emitted by the IDCT routine is
  162687. * DCT_scaled_size * DCT_scaled_size.
  162688. */
  162689. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162690. /*
  162691. * Each IDCT routine has its own ideas about the best dct_table element type.
  162692. */
  162693. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162694. #if BITS_IN_JSAMPLE == 8
  162695. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162696. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162697. #else
  162698. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162699. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162700. #endif
  162701. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162702. /*
  162703. * Each IDCT routine is responsible for range-limiting its results and
  162704. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162705. * be quite far out of range if the input data is corrupt, so a bulletproof
  162706. * range-limiting step is required. We use a mask-and-table-lookup method
  162707. * to do the combined operations quickly. See the comments with
  162708. * prepare_range_limit_table (in jdmaster.c) for more info.
  162709. */
  162710. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162711. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162712. /* Short forms of external names for systems with brain-damaged linkers. */
  162713. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162714. #define jpeg_fdct_islow jFDislow
  162715. #define jpeg_fdct_ifast jFDifast
  162716. #define jpeg_fdct_float jFDfloat
  162717. #define jpeg_idct_islow jRDislow
  162718. #define jpeg_idct_ifast jRDifast
  162719. #define jpeg_idct_float jRDfloat
  162720. #define jpeg_idct_4x4 jRD4x4
  162721. #define jpeg_idct_2x2 jRD2x2
  162722. #define jpeg_idct_1x1 jRD1x1
  162723. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162724. /* Extern declarations for the forward and inverse DCT routines. */
  162725. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162726. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162727. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162728. EXTERN(void) jpeg_idct_islow
  162729. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162730. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162731. EXTERN(void) jpeg_idct_ifast
  162732. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162733. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162734. EXTERN(void) jpeg_idct_float
  162735. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162736. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162737. EXTERN(void) jpeg_idct_4x4
  162738. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162739. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162740. EXTERN(void) jpeg_idct_2x2
  162741. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162742. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162743. EXTERN(void) jpeg_idct_1x1
  162744. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162745. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162746. /*
  162747. * Macros for handling fixed-point arithmetic; these are used by many
  162748. * but not all of the DCT/IDCT modules.
  162749. *
  162750. * All values are expected to be of type INT32.
  162751. * Fractional constants are scaled left by CONST_BITS bits.
  162752. * CONST_BITS is defined within each module using these macros,
  162753. * and may differ from one module to the next.
  162754. */
  162755. #define ONE ((INT32) 1)
  162756. #define CONST_SCALE (ONE << CONST_BITS)
  162757. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162758. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162759. * thus causing a lot of useless floating-point operations at run time.
  162760. */
  162761. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162762. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162763. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162764. * the fudge factor is correct for either sign of X.
  162765. */
  162766. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162767. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162768. * This macro is used only when the two inputs will actually be no more than
  162769. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162770. * full 32x32 multiply. This provides a useful speedup on many machines.
  162771. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162772. * in C, but some C compilers will do the right thing if you provide the
  162773. * correct combination of casts.
  162774. */
  162775. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162776. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162777. #endif
  162778. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162779. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162780. #endif
  162781. #ifndef MULTIPLY16C16 /* default definition */
  162782. #define MULTIPLY16C16(var,const) ((var) * (const))
  162783. #endif
  162784. /* Same except both inputs are variables. */
  162785. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162786. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162787. #endif
  162788. #ifndef MULTIPLY16V16 /* default definition */
  162789. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162790. #endif
  162791. #endif
  162792. /*** End of inlined file: jdct.h ***/
  162793. /* Private declarations for DCT subsystem */
  162794. /* Private subobject for this module */
  162795. typedef struct {
  162796. struct jpeg_forward_dct pub; /* public fields */
  162797. /* Pointer to the DCT routine actually in use */
  162798. forward_DCT_method_ptr do_dct;
  162799. /* The actual post-DCT divisors --- not identical to the quant table
  162800. * entries, because of scaling (especially for an unnormalized DCT).
  162801. * Each table is given in normal array order.
  162802. */
  162803. DCTELEM * divisors[NUM_QUANT_TBLS];
  162804. #ifdef DCT_FLOAT_SUPPORTED
  162805. /* Same as above for the floating-point case. */
  162806. float_DCT_method_ptr do_float_dct;
  162807. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162808. #endif
  162809. } my_fdct_controller;
  162810. typedef my_fdct_controller * my_fdct_ptr;
  162811. /*
  162812. * Initialize for a processing pass.
  162813. * Verify that all referenced Q-tables are present, and set up
  162814. * the divisor table for each one.
  162815. * In the current implementation, DCT of all components is done during
  162816. * the first pass, even if only some components will be output in the
  162817. * first scan. Hence all components should be examined here.
  162818. */
  162819. METHODDEF(void)
  162820. start_pass_fdctmgr (j_compress_ptr cinfo)
  162821. {
  162822. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162823. int ci, qtblno, i;
  162824. jpeg_component_info *compptr;
  162825. JQUANT_TBL * qtbl;
  162826. DCTELEM * dtbl;
  162827. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162828. ci++, compptr++) {
  162829. qtblno = compptr->quant_tbl_no;
  162830. /* Make sure specified quantization table is present */
  162831. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162832. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162833. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162834. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162835. /* Compute divisors for this quant table */
  162836. /* We may do this more than once for same table, but it's not a big deal */
  162837. switch (cinfo->dct_method) {
  162838. #ifdef DCT_ISLOW_SUPPORTED
  162839. case JDCT_ISLOW:
  162840. /* For LL&M IDCT method, divisors are equal to raw quantization
  162841. * coefficients multiplied by 8 (to counteract scaling).
  162842. */
  162843. if (fdct->divisors[qtblno] == NULL) {
  162844. fdct->divisors[qtblno] = (DCTELEM *)
  162845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162846. DCTSIZE2 * SIZEOF(DCTELEM));
  162847. }
  162848. dtbl = fdct->divisors[qtblno];
  162849. for (i = 0; i < DCTSIZE2; i++) {
  162850. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162851. }
  162852. break;
  162853. #endif
  162854. #ifdef DCT_IFAST_SUPPORTED
  162855. case JDCT_IFAST:
  162856. {
  162857. /* For AA&N IDCT method, divisors are equal to quantization
  162858. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162859. * scalefactor[0] = 1
  162860. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162861. * We apply a further scale factor of 8.
  162862. */
  162863. #define CONST_BITS 14
  162864. static const INT16 aanscales[DCTSIZE2] = {
  162865. /* precomputed values scaled up by 14 bits */
  162866. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162867. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162868. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162869. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162870. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162871. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162872. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162873. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162874. };
  162875. SHIFT_TEMPS
  162876. if (fdct->divisors[qtblno] == NULL) {
  162877. fdct->divisors[qtblno] = (DCTELEM *)
  162878. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162879. DCTSIZE2 * SIZEOF(DCTELEM));
  162880. }
  162881. dtbl = fdct->divisors[qtblno];
  162882. for (i = 0; i < DCTSIZE2; i++) {
  162883. dtbl[i] = (DCTELEM)
  162884. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162885. (INT32) aanscales[i]),
  162886. CONST_BITS-3);
  162887. }
  162888. }
  162889. break;
  162890. #endif
  162891. #ifdef DCT_FLOAT_SUPPORTED
  162892. case JDCT_FLOAT:
  162893. {
  162894. /* For float AA&N IDCT method, divisors are equal to quantization
  162895. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162896. * scalefactor[0] = 1
  162897. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162898. * We apply a further scale factor of 8.
  162899. * What's actually stored is 1/divisor so that the inner loop can
  162900. * use a multiplication rather than a division.
  162901. */
  162902. FAST_FLOAT * fdtbl;
  162903. int row, col;
  162904. static const double aanscalefactor[DCTSIZE] = {
  162905. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162906. 1.0, 0.785694958, 0.541196100, 0.275899379
  162907. };
  162908. if (fdct->float_divisors[qtblno] == NULL) {
  162909. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162910. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162911. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162912. }
  162913. fdtbl = fdct->float_divisors[qtblno];
  162914. i = 0;
  162915. for (row = 0; row < DCTSIZE; row++) {
  162916. for (col = 0; col < DCTSIZE; col++) {
  162917. fdtbl[i] = (FAST_FLOAT)
  162918. (1.0 / (((double) qtbl->quantval[i] *
  162919. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162920. i++;
  162921. }
  162922. }
  162923. }
  162924. break;
  162925. #endif
  162926. default:
  162927. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162928. break;
  162929. }
  162930. }
  162931. }
  162932. /*
  162933. * Perform forward DCT on one or more blocks of a component.
  162934. *
  162935. * The input samples are taken from the sample_data[] array starting at
  162936. * position start_row/start_col, and moving to the right for any additional
  162937. * blocks. The quantized coefficients are returned in coef_blocks[].
  162938. */
  162939. METHODDEF(void)
  162940. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162941. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162942. JDIMENSION start_row, JDIMENSION start_col,
  162943. JDIMENSION num_blocks)
  162944. /* This version is used for integer DCT implementations. */
  162945. {
  162946. /* This routine is heavily used, so it's worth coding it tightly. */
  162947. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162948. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162949. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162950. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162951. JDIMENSION bi;
  162952. sample_data += start_row; /* fold in the vertical offset once */
  162953. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162954. /* Load data into workspace, applying unsigned->signed conversion */
  162955. { register DCTELEM *workspaceptr;
  162956. register JSAMPROW elemptr;
  162957. register int elemr;
  162958. workspaceptr = workspace;
  162959. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162960. elemptr = sample_data[elemr] + start_col;
  162961. #if DCTSIZE == 8 /* unroll the inner loop */
  162962. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162963. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162964. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162965. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162966. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162967. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162968. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162969. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162970. #else
  162971. { register int elemc;
  162972. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162973. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162974. }
  162975. }
  162976. #endif
  162977. }
  162978. }
  162979. /* Perform the DCT */
  162980. (*do_dct) (workspace);
  162981. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162982. { register DCTELEM temp, qval;
  162983. register int i;
  162984. register JCOEFPTR output_ptr = coef_blocks[bi];
  162985. for (i = 0; i < DCTSIZE2; i++) {
  162986. qval = divisors[i];
  162987. temp = workspace[i];
  162988. /* Divide the coefficient value by qval, ensuring proper rounding.
  162989. * Since C does not specify the direction of rounding for negative
  162990. * quotients, we have to force the dividend positive for portability.
  162991. *
  162992. * In most files, at least half of the output values will be zero
  162993. * (at default quantization settings, more like three-quarters...)
  162994. * so we should ensure that this case is fast. On many machines,
  162995. * a comparison is enough cheaper than a divide to make a special test
  162996. * a win. Since both inputs will be nonnegative, we need only test
  162997. * for a < b to discover whether a/b is 0.
  162998. * If your machine's division is fast enough, define FAST_DIVIDE.
  162999. */
  163000. #ifdef FAST_DIVIDE
  163001. #define DIVIDE_BY(a,b) a /= b
  163002. #else
  163003. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163004. #endif
  163005. if (temp < 0) {
  163006. temp = -temp;
  163007. temp += qval>>1; /* for rounding */
  163008. DIVIDE_BY(temp, qval);
  163009. temp = -temp;
  163010. } else {
  163011. temp += qval>>1; /* for rounding */
  163012. DIVIDE_BY(temp, qval);
  163013. }
  163014. output_ptr[i] = (JCOEF) temp;
  163015. }
  163016. }
  163017. }
  163018. }
  163019. #ifdef DCT_FLOAT_SUPPORTED
  163020. METHODDEF(void)
  163021. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163022. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163023. JDIMENSION start_row, JDIMENSION start_col,
  163024. JDIMENSION num_blocks)
  163025. /* This version is used for floating-point DCT implementations. */
  163026. {
  163027. /* This routine is heavily used, so it's worth coding it tightly. */
  163028. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163029. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163030. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163031. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163032. JDIMENSION bi;
  163033. sample_data += start_row; /* fold in the vertical offset once */
  163034. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163035. /* Load data into workspace, applying unsigned->signed conversion */
  163036. { register FAST_FLOAT *workspaceptr;
  163037. register JSAMPROW elemptr;
  163038. register int elemr;
  163039. workspaceptr = workspace;
  163040. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163041. elemptr = sample_data[elemr] + start_col;
  163042. #if DCTSIZE == 8 /* unroll the inner loop */
  163043. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163044. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163045. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163046. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163047. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163048. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163049. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163050. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163051. #else
  163052. { register int elemc;
  163053. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163054. *workspaceptr++ = (FAST_FLOAT)
  163055. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163056. }
  163057. }
  163058. #endif
  163059. }
  163060. }
  163061. /* Perform the DCT */
  163062. (*do_dct) (workspace);
  163063. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163064. { register FAST_FLOAT temp;
  163065. register int i;
  163066. register JCOEFPTR output_ptr = coef_blocks[bi];
  163067. for (i = 0; i < DCTSIZE2; i++) {
  163068. /* Apply the quantization and scaling factor */
  163069. temp = workspace[i] * divisors[i];
  163070. /* Round to nearest integer.
  163071. * Since C does not specify the direction of rounding for negative
  163072. * quotients, we have to force the dividend positive for portability.
  163073. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163074. * code should work for either 16-bit or 32-bit ints.
  163075. */
  163076. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163077. }
  163078. }
  163079. }
  163080. }
  163081. #endif /* DCT_FLOAT_SUPPORTED */
  163082. /*
  163083. * Initialize FDCT manager.
  163084. */
  163085. GLOBAL(void)
  163086. jinit_forward_dct (j_compress_ptr cinfo)
  163087. {
  163088. my_fdct_ptr fdct;
  163089. int i;
  163090. fdct = (my_fdct_ptr)
  163091. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163092. SIZEOF(my_fdct_controller));
  163093. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163094. fdct->pub.start_pass = start_pass_fdctmgr;
  163095. switch (cinfo->dct_method) {
  163096. #ifdef DCT_ISLOW_SUPPORTED
  163097. case JDCT_ISLOW:
  163098. fdct->pub.forward_DCT = forward_DCT;
  163099. fdct->do_dct = jpeg_fdct_islow;
  163100. break;
  163101. #endif
  163102. #ifdef DCT_IFAST_SUPPORTED
  163103. case JDCT_IFAST:
  163104. fdct->pub.forward_DCT = forward_DCT;
  163105. fdct->do_dct = jpeg_fdct_ifast;
  163106. break;
  163107. #endif
  163108. #ifdef DCT_FLOAT_SUPPORTED
  163109. case JDCT_FLOAT:
  163110. fdct->pub.forward_DCT = forward_DCT_float;
  163111. fdct->do_float_dct = jpeg_fdct_float;
  163112. break;
  163113. #endif
  163114. default:
  163115. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163116. break;
  163117. }
  163118. /* Mark divisor tables unallocated */
  163119. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163120. fdct->divisors[i] = NULL;
  163121. #ifdef DCT_FLOAT_SUPPORTED
  163122. fdct->float_divisors[i] = NULL;
  163123. #endif
  163124. }
  163125. }
  163126. /*** End of inlined file: jcdctmgr.c ***/
  163127. #undef CONST_BITS
  163128. /*** Start of inlined file: jchuff.c ***/
  163129. #define JPEG_INTERNALS
  163130. /*** Start of inlined file: jchuff.h ***/
  163131. /* The legal range of a DCT coefficient is
  163132. * -1024 .. +1023 for 8-bit data;
  163133. * -16384 .. +16383 for 12-bit data.
  163134. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163135. */
  163136. #ifndef _jchuff_h_
  163137. #define _jchuff_h_
  163138. #if BITS_IN_JSAMPLE == 8
  163139. #define MAX_COEF_BITS 10
  163140. #else
  163141. #define MAX_COEF_BITS 14
  163142. #endif
  163143. /* Derived data constructed for each Huffman table */
  163144. typedef struct {
  163145. unsigned int ehufco[256]; /* code for each symbol */
  163146. char ehufsi[256]; /* length of code for each symbol */
  163147. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163148. } c_derived_tbl;
  163149. /* Short forms of external names for systems with brain-damaged linkers. */
  163150. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163151. #define jpeg_make_c_derived_tbl jMkCDerived
  163152. #define jpeg_gen_optimal_table jGenOptTbl
  163153. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163154. /* Expand a Huffman table definition into the derived format */
  163155. EXTERN(void) jpeg_make_c_derived_tbl
  163156. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163157. c_derived_tbl ** pdtbl));
  163158. /* Generate an optimal table definition given the specified counts */
  163159. EXTERN(void) jpeg_gen_optimal_table
  163160. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163161. #endif
  163162. /*** End of inlined file: jchuff.h ***/
  163163. /* Declarations shared with jcphuff.c */
  163164. /* Expanded entropy encoder object for Huffman encoding.
  163165. *
  163166. * The savable_state subrecord contains fields that change within an MCU,
  163167. * but must not be updated permanently until we complete the MCU.
  163168. */
  163169. typedef struct {
  163170. INT32 put_buffer; /* current bit-accumulation buffer */
  163171. int put_bits; /* # of bits now in it */
  163172. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163173. } savable_state;
  163174. /* This macro is to work around compilers with missing or broken
  163175. * structure assignment. You'll need to fix this code if you have
  163176. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163177. */
  163178. #ifndef NO_STRUCT_ASSIGN
  163179. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163180. #else
  163181. #if MAX_COMPS_IN_SCAN == 4
  163182. #define ASSIGN_STATE(dest,src) \
  163183. ((dest).put_buffer = (src).put_buffer, \
  163184. (dest).put_bits = (src).put_bits, \
  163185. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163186. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163187. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163188. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163189. #endif
  163190. #endif
  163191. typedef struct {
  163192. struct jpeg_entropy_encoder pub; /* public fields */
  163193. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163194. /* These fields are NOT loaded into local working state. */
  163195. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163196. int next_restart_num; /* next restart number to write (0-7) */
  163197. /* Pointers to derived tables (these workspaces have image lifespan) */
  163198. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163199. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163200. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163201. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163202. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163203. #endif
  163204. } huff_entropy_encoder;
  163205. typedef huff_entropy_encoder * huff_entropy_ptr;
  163206. /* Working state while writing an MCU.
  163207. * This struct contains all the fields that are needed by subroutines.
  163208. */
  163209. typedef struct {
  163210. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163211. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163212. savable_state cur; /* Current bit buffer & DC state */
  163213. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163214. } working_state;
  163215. /* Forward declarations */
  163216. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163217. JBLOCKROW *MCU_data));
  163218. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163219. #ifdef ENTROPY_OPT_SUPPORTED
  163220. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163221. JBLOCKROW *MCU_data));
  163222. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163223. #endif
  163224. /*
  163225. * Initialize for a Huffman-compressed scan.
  163226. * If gather_statistics is TRUE, we do not output anything during the scan,
  163227. * just count the Huffman symbols used and generate Huffman code tables.
  163228. */
  163229. METHODDEF(void)
  163230. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163231. {
  163232. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163233. int ci, dctbl, actbl;
  163234. jpeg_component_info * compptr;
  163235. if (gather_statistics) {
  163236. #ifdef ENTROPY_OPT_SUPPORTED
  163237. entropy->pub.encode_mcu = encode_mcu_gather;
  163238. entropy->pub.finish_pass = finish_pass_gather;
  163239. #else
  163240. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163241. #endif
  163242. } else {
  163243. entropy->pub.encode_mcu = encode_mcu_huff;
  163244. entropy->pub.finish_pass = finish_pass_huff;
  163245. }
  163246. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163247. compptr = cinfo->cur_comp_info[ci];
  163248. dctbl = compptr->dc_tbl_no;
  163249. actbl = compptr->ac_tbl_no;
  163250. if (gather_statistics) {
  163251. #ifdef ENTROPY_OPT_SUPPORTED
  163252. /* Check for invalid table indexes */
  163253. /* (make_c_derived_tbl does this in the other path) */
  163254. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163255. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163256. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163257. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163258. /* Allocate and zero the statistics tables */
  163259. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163260. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163261. entropy->dc_count_ptrs[dctbl] = (long *)
  163262. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163263. 257 * SIZEOF(long));
  163264. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163265. if (entropy->ac_count_ptrs[actbl] == NULL)
  163266. entropy->ac_count_ptrs[actbl] = (long *)
  163267. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163268. 257 * SIZEOF(long));
  163269. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163270. #endif
  163271. } else {
  163272. /* Compute derived values for Huffman tables */
  163273. /* We may do this more than once for a table, but it's not expensive */
  163274. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163275. & entropy->dc_derived_tbls[dctbl]);
  163276. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163277. & entropy->ac_derived_tbls[actbl]);
  163278. }
  163279. /* Initialize DC predictions to 0 */
  163280. entropy->saved.last_dc_val[ci] = 0;
  163281. }
  163282. /* Initialize bit buffer to empty */
  163283. entropy->saved.put_buffer = 0;
  163284. entropy->saved.put_bits = 0;
  163285. /* Initialize restart stuff */
  163286. entropy->restarts_to_go = cinfo->restart_interval;
  163287. entropy->next_restart_num = 0;
  163288. }
  163289. /*
  163290. * Compute the derived values for a Huffman table.
  163291. * This routine also performs some validation checks on the table.
  163292. *
  163293. * Note this is also used by jcphuff.c.
  163294. */
  163295. GLOBAL(void)
  163296. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163297. c_derived_tbl ** pdtbl)
  163298. {
  163299. JHUFF_TBL *htbl;
  163300. c_derived_tbl *dtbl;
  163301. int p, i, l, lastp, si, maxsymbol;
  163302. char huffsize[257];
  163303. unsigned int huffcode[257];
  163304. unsigned int code;
  163305. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163306. * paralleling the order of the symbols themselves in htbl->huffval[].
  163307. */
  163308. /* Find the input Huffman table */
  163309. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163310. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163311. htbl =
  163312. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163313. if (htbl == NULL)
  163314. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163315. /* Allocate a workspace if we haven't already done so. */
  163316. if (*pdtbl == NULL)
  163317. *pdtbl = (c_derived_tbl *)
  163318. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163319. SIZEOF(c_derived_tbl));
  163320. dtbl = *pdtbl;
  163321. /* Figure C.1: make table of Huffman code length for each symbol */
  163322. p = 0;
  163323. for (l = 1; l <= 16; l++) {
  163324. i = (int) htbl->bits[l];
  163325. if (i < 0 || p + i > 256) /* protect against table overrun */
  163326. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163327. while (i--)
  163328. huffsize[p++] = (char) l;
  163329. }
  163330. huffsize[p] = 0;
  163331. lastp = p;
  163332. /* Figure C.2: generate the codes themselves */
  163333. /* We also validate that the counts represent a legal Huffman code tree. */
  163334. code = 0;
  163335. si = huffsize[0];
  163336. p = 0;
  163337. while (huffsize[p]) {
  163338. while (((int) huffsize[p]) == si) {
  163339. huffcode[p++] = code;
  163340. code++;
  163341. }
  163342. /* code is now 1 more than the last code used for codelength si; but
  163343. * it must still fit in si bits, since no code is allowed to be all ones.
  163344. */
  163345. if (((INT32) code) >= (((INT32) 1) << si))
  163346. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163347. code <<= 1;
  163348. si++;
  163349. }
  163350. /* Figure C.3: generate encoding tables */
  163351. /* These are code and size indexed by symbol value */
  163352. /* Set all codeless symbols to have code length 0;
  163353. * this lets us detect duplicate VAL entries here, and later
  163354. * allows emit_bits to detect any attempt to emit such symbols.
  163355. */
  163356. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163357. /* This is also a convenient place to check for out-of-range
  163358. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163359. * but only 0..15 for DC. (We could constrain them further
  163360. * based on data depth and mode, but this seems enough.)
  163361. */
  163362. maxsymbol = isDC ? 15 : 255;
  163363. for (p = 0; p < lastp; p++) {
  163364. i = htbl->huffval[p];
  163365. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163366. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163367. dtbl->ehufco[i] = huffcode[p];
  163368. dtbl->ehufsi[i] = huffsize[p];
  163369. }
  163370. }
  163371. /* Outputting bytes to the file */
  163372. /* Emit a byte, taking 'action' if must suspend. */
  163373. #define emit_byte(state,val,action) \
  163374. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163375. if (--(state)->free_in_buffer == 0) \
  163376. if (! dump_buffer(state)) \
  163377. { action; } }
  163378. LOCAL(boolean)
  163379. dump_buffer (working_state * state)
  163380. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163381. {
  163382. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163383. if (! (*dest->empty_output_buffer) (state->cinfo))
  163384. return FALSE;
  163385. /* After a successful buffer dump, must reset buffer pointers */
  163386. state->next_output_byte = dest->next_output_byte;
  163387. state->free_in_buffer = dest->free_in_buffer;
  163388. return TRUE;
  163389. }
  163390. /* Outputting bits to the file */
  163391. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163392. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163393. * in one call, and we never retain more than 7 bits in put_buffer
  163394. * between calls, so 24 bits are sufficient.
  163395. */
  163396. INLINE
  163397. LOCAL(boolean)
  163398. emit_bits (working_state * state, unsigned int code, int size)
  163399. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163400. {
  163401. /* This routine is heavily used, so it's worth coding tightly. */
  163402. register INT32 put_buffer = (INT32) code;
  163403. register int put_bits = state->cur.put_bits;
  163404. /* if size is 0, caller used an invalid Huffman table entry */
  163405. if (size == 0)
  163406. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163407. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163408. put_bits += size; /* new number of bits in buffer */
  163409. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163410. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163411. while (put_bits >= 8) {
  163412. int c = (int) ((put_buffer >> 16) & 0xFF);
  163413. emit_byte(state, c, return FALSE);
  163414. if (c == 0xFF) { /* need to stuff a zero byte? */
  163415. emit_byte(state, 0, return FALSE);
  163416. }
  163417. put_buffer <<= 8;
  163418. put_bits -= 8;
  163419. }
  163420. state->cur.put_buffer = put_buffer; /* update state variables */
  163421. state->cur.put_bits = put_bits;
  163422. return TRUE;
  163423. }
  163424. LOCAL(boolean)
  163425. flush_bits (working_state * state)
  163426. {
  163427. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163428. return FALSE;
  163429. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163430. state->cur.put_bits = 0;
  163431. return TRUE;
  163432. }
  163433. /* Encode a single block's worth of coefficients */
  163434. LOCAL(boolean)
  163435. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163436. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163437. {
  163438. register int temp, temp2;
  163439. register int nbits;
  163440. register int k, r, i;
  163441. /* Encode the DC coefficient difference per section F.1.2.1 */
  163442. temp = temp2 = block[0] - last_dc_val;
  163443. if (temp < 0) {
  163444. temp = -temp; /* temp is abs value of input */
  163445. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163446. /* This code assumes we are on a two's complement machine */
  163447. temp2--;
  163448. }
  163449. /* Find the number of bits needed for the magnitude of the coefficient */
  163450. nbits = 0;
  163451. while (temp) {
  163452. nbits++;
  163453. temp >>= 1;
  163454. }
  163455. /* Check for out-of-range coefficient values.
  163456. * Since we're encoding a difference, the range limit is twice as much.
  163457. */
  163458. if (nbits > MAX_COEF_BITS+1)
  163459. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163460. /* Emit the Huffman-coded symbol for the number of bits */
  163461. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163462. return FALSE;
  163463. /* Emit that number of bits of the value, if positive, */
  163464. /* or the complement of its magnitude, if negative. */
  163465. if (nbits) /* emit_bits rejects calls with size 0 */
  163466. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163467. return FALSE;
  163468. /* Encode the AC coefficients per section F.1.2.2 */
  163469. r = 0; /* r = run length of zeros */
  163470. for (k = 1; k < DCTSIZE2; k++) {
  163471. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163472. r++;
  163473. } else {
  163474. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163475. while (r > 15) {
  163476. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163477. return FALSE;
  163478. r -= 16;
  163479. }
  163480. temp2 = temp;
  163481. if (temp < 0) {
  163482. temp = -temp; /* temp is abs value of input */
  163483. /* This code assumes we are on a two's complement machine */
  163484. temp2--;
  163485. }
  163486. /* Find the number of bits needed for the magnitude of the coefficient */
  163487. nbits = 1; /* there must be at least one 1 bit */
  163488. while ((temp >>= 1))
  163489. nbits++;
  163490. /* Check for out-of-range coefficient values */
  163491. if (nbits > MAX_COEF_BITS)
  163492. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163493. /* Emit Huffman symbol for run length / number of bits */
  163494. i = (r << 4) + nbits;
  163495. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163496. return FALSE;
  163497. /* Emit that number of bits of the value, if positive, */
  163498. /* or the complement of its magnitude, if negative. */
  163499. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163500. return FALSE;
  163501. r = 0;
  163502. }
  163503. }
  163504. /* If the last coef(s) were zero, emit an end-of-block code */
  163505. if (r > 0)
  163506. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163507. return FALSE;
  163508. return TRUE;
  163509. }
  163510. /*
  163511. * Emit a restart marker & resynchronize predictions.
  163512. */
  163513. LOCAL(boolean)
  163514. emit_restart (working_state * state, int restart_num)
  163515. {
  163516. int ci;
  163517. if (! flush_bits(state))
  163518. return FALSE;
  163519. emit_byte(state, 0xFF, return FALSE);
  163520. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163521. /* Re-initialize DC predictions to 0 */
  163522. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163523. state->cur.last_dc_val[ci] = 0;
  163524. /* The restart counter is not updated until we successfully write the MCU. */
  163525. return TRUE;
  163526. }
  163527. /*
  163528. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163529. */
  163530. METHODDEF(boolean)
  163531. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163532. {
  163533. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163534. working_state state;
  163535. int blkn, ci;
  163536. jpeg_component_info * compptr;
  163537. /* Load up working state */
  163538. state.next_output_byte = cinfo->dest->next_output_byte;
  163539. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163540. ASSIGN_STATE(state.cur, entropy->saved);
  163541. state.cinfo = cinfo;
  163542. /* Emit restart marker if needed */
  163543. if (cinfo->restart_interval) {
  163544. if (entropy->restarts_to_go == 0)
  163545. if (! emit_restart(&state, entropy->next_restart_num))
  163546. return FALSE;
  163547. }
  163548. /* Encode the MCU data blocks */
  163549. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163550. ci = cinfo->MCU_membership[blkn];
  163551. compptr = cinfo->cur_comp_info[ci];
  163552. if (! encode_one_block(&state,
  163553. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163554. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163555. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163556. return FALSE;
  163557. /* Update last_dc_val */
  163558. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163559. }
  163560. /* Completed MCU, so update state */
  163561. cinfo->dest->next_output_byte = state.next_output_byte;
  163562. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163563. ASSIGN_STATE(entropy->saved, state.cur);
  163564. /* Update restart-interval state too */
  163565. if (cinfo->restart_interval) {
  163566. if (entropy->restarts_to_go == 0) {
  163567. entropy->restarts_to_go = cinfo->restart_interval;
  163568. entropy->next_restart_num++;
  163569. entropy->next_restart_num &= 7;
  163570. }
  163571. entropy->restarts_to_go--;
  163572. }
  163573. return TRUE;
  163574. }
  163575. /*
  163576. * Finish up at the end of a Huffman-compressed scan.
  163577. */
  163578. METHODDEF(void)
  163579. finish_pass_huff (j_compress_ptr cinfo)
  163580. {
  163581. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163582. working_state state;
  163583. /* Load up working state ... flush_bits needs it */
  163584. state.next_output_byte = cinfo->dest->next_output_byte;
  163585. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163586. ASSIGN_STATE(state.cur, entropy->saved);
  163587. state.cinfo = cinfo;
  163588. /* Flush out the last data */
  163589. if (! flush_bits(&state))
  163590. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163591. /* Update state */
  163592. cinfo->dest->next_output_byte = state.next_output_byte;
  163593. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163594. ASSIGN_STATE(entropy->saved, state.cur);
  163595. }
  163596. /*
  163597. * Huffman coding optimization.
  163598. *
  163599. * We first scan the supplied data and count the number of uses of each symbol
  163600. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163601. * Then we build a Huffman coding tree for the observed counts.
  163602. * Symbols which are not needed at all for the particular image are not
  163603. * assigned any code, which saves space in the DHT marker as well as in
  163604. * the compressed data.
  163605. */
  163606. #ifdef ENTROPY_OPT_SUPPORTED
  163607. /* Process a single block's worth of coefficients */
  163608. LOCAL(void)
  163609. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163610. long dc_counts[], long ac_counts[])
  163611. {
  163612. register int temp;
  163613. register int nbits;
  163614. register int k, r;
  163615. /* Encode the DC coefficient difference per section F.1.2.1 */
  163616. temp = block[0] - last_dc_val;
  163617. if (temp < 0)
  163618. temp = -temp;
  163619. /* Find the number of bits needed for the magnitude of the coefficient */
  163620. nbits = 0;
  163621. while (temp) {
  163622. nbits++;
  163623. temp >>= 1;
  163624. }
  163625. /* Check for out-of-range coefficient values.
  163626. * Since we're encoding a difference, the range limit is twice as much.
  163627. */
  163628. if (nbits > MAX_COEF_BITS+1)
  163629. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163630. /* Count the Huffman symbol for the number of bits */
  163631. dc_counts[nbits]++;
  163632. /* Encode the AC coefficients per section F.1.2.2 */
  163633. r = 0; /* r = run length of zeros */
  163634. for (k = 1; k < DCTSIZE2; k++) {
  163635. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163636. r++;
  163637. } else {
  163638. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163639. while (r > 15) {
  163640. ac_counts[0xF0]++;
  163641. r -= 16;
  163642. }
  163643. /* Find the number of bits needed for the magnitude of the coefficient */
  163644. if (temp < 0)
  163645. temp = -temp;
  163646. /* Find the number of bits needed for the magnitude of the coefficient */
  163647. nbits = 1; /* there must be at least one 1 bit */
  163648. while ((temp >>= 1))
  163649. nbits++;
  163650. /* Check for out-of-range coefficient values */
  163651. if (nbits > MAX_COEF_BITS)
  163652. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163653. /* Count Huffman symbol for run length / number of bits */
  163654. ac_counts[(r << 4) + nbits]++;
  163655. r = 0;
  163656. }
  163657. }
  163658. /* If the last coef(s) were zero, emit an end-of-block code */
  163659. if (r > 0)
  163660. ac_counts[0]++;
  163661. }
  163662. /*
  163663. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163664. * No data is actually output, so no suspension return is possible.
  163665. */
  163666. METHODDEF(boolean)
  163667. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163668. {
  163669. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163670. int blkn, ci;
  163671. jpeg_component_info * compptr;
  163672. /* Take care of restart intervals if needed */
  163673. if (cinfo->restart_interval) {
  163674. if (entropy->restarts_to_go == 0) {
  163675. /* Re-initialize DC predictions to 0 */
  163676. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163677. entropy->saved.last_dc_val[ci] = 0;
  163678. /* Update restart state */
  163679. entropy->restarts_to_go = cinfo->restart_interval;
  163680. }
  163681. entropy->restarts_to_go--;
  163682. }
  163683. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163684. ci = cinfo->MCU_membership[blkn];
  163685. compptr = cinfo->cur_comp_info[ci];
  163686. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163687. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163688. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163689. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163690. }
  163691. return TRUE;
  163692. }
  163693. /*
  163694. * Generate the best Huffman code table for the given counts, fill htbl.
  163695. * Note this is also used by jcphuff.c.
  163696. *
  163697. * The JPEG standard requires that no symbol be assigned a codeword of all
  163698. * one bits (so that padding bits added at the end of a compressed segment
  163699. * can't look like a valid code). Because of the canonical ordering of
  163700. * codewords, this just means that there must be an unused slot in the
  163701. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163702. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163703. * with count 1. In theory that's not optimal; giving it count zero but
  163704. * including it in the symbol set anyway should give a better Huffman code.
  163705. * But the theoretically better code actually seems to come out worse in
  163706. * practice, because it produces more all-ones bytes (which incur stuffed
  163707. * zero bytes in the final file). In any case the difference is tiny.
  163708. *
  163709. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163710. * If some symbols have a very small but nonzero probability, the Huffman tree
  163711. * must be adjusted to meet the code length restriction. We currently use
  163712. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163713. * optimal; it may not choose the best possible limited-length code. But
  163714. * typically only very-low-frequency symbols will be given less-than-optimal
  163715. * lengths, so the code is almost optimal. Experimental comparisons against
  163716. * an optimal limited-length-code algorithm indicate that the difference is
  163717. * microscopic --- usually less than a hundredth of a percent of total size.
  163718. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163719. */
  163720. GLOBAL(void)
  163721. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163722. {
  163723. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163724. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163725. int codesize[257]; /* codesize[k] = code length of symbol k */
  163726. int others[257]; /* next symbol in current branch of tree */
  163727. int c1, c2;
  163728. int p, i, j;
  163729. long v;
  163730. /* This algorithm is explained in section K.2 of the JPEG standard */
  163731. MEMZERO(bits, SIZEOF(bits));
  163732. MEMZERO(codesize, SIZEOF(codesize));
  163733. for (i = 0; i < 257; i++)
  163734. others[i] = -1; /* init links to empty */
  163735. freq[256] = 1; /* make sure 256 has a nonzero count */
  163736. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163737. * that no real symbol is given code-value of all ones, because 256
  163738. * will be placed last in the largest codeword category.
  163739. */
  163740. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163741. for (;;) {
  163742. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163743. /* In case of ties, take the larger symbol number */
  163744. c1 = -1;
  163745. v = 1000000000L;
  163746. for (i = 0; i <= 256; i++) {
  163747. if (freq[i] && freq[i] <= v) {
  163748. v = freq[i];
  163749. c1 = i;
  163750. }
  163751. }
  163752. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163753. /* In case of ties, take the larger symbol number */
  163754. c2 = -1;
  163755. v = 1000000000L;
  163756. for (i = 0; i <= 256; i++) {
  163757. if (freq[i] && freq[i] <= v && i != c1) {
  163758. v = freq[i];
  163759. c2 = i;
  163760. }
  163761. }
  163762. /* Done if we've merged everything into one frequency */
  163763. if (c2 < 0)
  163764. break;
  163765. /* Else merge the two counts/trees */
  163766. freq[c1] += freq[c2];
  163767. freq[c2] = 0;
  163768. /* Increment the codesize of everything in c1's tree branch */
  163769. codesize[c1]++;
  163770. while (others[c1] >= 0) {
  163771. c1 = others[c1];
  163772. codesize[c1]++;
  163773. }
  163774. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163775. /* Increment the codesize of everything in c2's tree branch */
  163776. codesize[c2]++;
  163777. while (others[c2] >= 0) {
  163778. c2 = others[c2];
  163779. codesize[c2]++;
  163780. }
  163781. }
  163782. /* Now count the number of symbols of each code length */
  163783. for (i = 0; i <= 256; i++) {
  163784. if (codesize[i]) {
  163785. /* The JPEG standard seems to think that this can't happen, */
  163786. /* but I'm paranoid... */
  163787. if (codesize[i] > MAX_CLEN)
  163788. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163789. bits[codesize[i]]++;
  163790. }
  163791. }
  163792. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163793. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163794. * Here is what the JPEG spec says about how this next bit works:
  163795. * Since symbols are paired for the longest Huffman code, the symbols are
  163796. * removed from this length category two at a time. The prefix for the pair
  163797. * (which is one bit shorter) is allocated to one of the pair; then,
  163798. * skipping the BITS entry for that prefix length, a code word from the next
  163799. * shortest nonzero BITS entry is converted into a prefix for two code words
  163800. * one bit longer.
  163801. */
  163802. for (i = MAX_CLEN; i > 16; i--) {
  163803. while (bits[i] > 0) {
  163804. j = i - 2; /* find length of new prefix to be used */
  163805. while (bits[j] == 0)
  163806. j--;
  163807. bits[i] -= 2; /* remove two symbols */
  163808. bits[i-1]++; /* one goes in this length */
  163809. bits[j+1] += 2; /* two new symbols in this length */
  163810. bits[j]--; /* symbol of this length is now a prefix */
  163811. }
  163812. }
  163813. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163814. while (bits[i] == 0) /* find largest codelength still in use */
  163815. i--;
  163816. bits[i]--;
  163817. /* Return final symbol counts (only for lengths 0..16) */
  163818. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163819. /* Return a list of the symbols sorted by code length */
  163820. /* It's not real clear to me why we don't need to consider the codelength
  163821. * changes made above, but the JPEG spec seems to think this works.
  163822. */
  163823. p = 0;
  163824. for (i = 1; i <= MAX_CLEN; i++) {
  163825. for (j = 0; j <= 255; j++) {
  163826. if (codesize[j] == i) {
  163827. htbl->huffval[p] = (UINT8) j;
  163828. p++;
  163829. }
  163830. }
  163831. }
  163832. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163833. htbl->sent_table = FALSE;
  163834. }
  163835. /*
  163836. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163837. */
  163838. METHODDEF(void)
  163839. finish_pass_gather (j_compress_ptr cinfo)
  163840. {
  163841. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163842. int ci, dctbl, actbl;
  163843. jpeg_component_info * compptr;
  163844. JHUFF_TBL **htblptr;
  163845. boolean did_dc[NUM_HUFF_TBLS];
  163846. boolean did_ac[NUM_HUFF_TBLS];
  163847. /* It's important not to apply jpeg_gen_optimal_table more than once
  163848. * per table, because it clobbers the input frequency counts!
  163849. */
  163850. MEMZERO(did_dc, SIZEOF(did_dc));
  163851. MEMZERO(did_ac, SIZEOF(did_ac));
  163852. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163853. compptr = cinfo->cur_comp_info[ci];
  163854. dctbl = compptr->dc_tbl_no;
  163855. actbl = compptr->ac_tbl_no;
  163856. if (! did_dc[dctbl]) {
  163857. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163858. if (*htblptr == NULL)
  163859. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163860. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163861. did_dc[dctbl] = TRUE;
  163862. }
  163863. if (! did_ac[actbl]) {
  163864. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163865. if (*htblptr == NULL)
  163866. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163867. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163868. did_ac[actbl] = TRUE;
  163869. }
  163870. }
  163871. }
  163872. #endif /* ENTROPY_OPT_SUPPORTED */
  163873. /*
  163874. * Module initialization routine for Huffman entropy encoding.
  163875. */
  163876. GLOBAL(void)
  163877. jinit_huff_encoder (j_compress_ptr cinfo)
  163878. {
  163879. huff_entropy_ptr entropy;
  163880. int i;
  163881. entropy = (huff_entropy_ptr)
  163882. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163883. SIZEOF(huff_entropy_encoder));
  163884. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163885. entropy->pub.start_pass = start_pass_huff;
  163886. /* Mark tables unallocated */
  163887. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163888. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163889. #ifdef ENTROPY_OPT_SUPPORTED
  163890. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163891. #endif
  163892. }
  163893. }
  163894. /*** End of inlined file: jchuff.c ***/
  163895. #undef emit_byte
  163896. /*** Start of inlined file: jcinit.c ***/
  163897. #define JPEG_INTERNALS
  163898. /*
  163899. * Master selection of compression modules.
  163900. * This is done once at the start of processing an image. We determine
  163901. * which modules will be used and give them appropriate initialization calls.
  163902. */
  163903. GLOBAL(void)
  163904. jinit_compress_master (j_compress_ptr cinfo)
  163905. {
  163906. /* Initialize master control (includes parameter checking/processing) */
  163907. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163908. /* Preprocessing */
  163909. if (! cinfo->raw_data_in) {
  163910. jinit_color_converter(cinfo);
  163911. jinit_downsampler(cinfo);
  163912. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163913. }
  163914. /* Forward DCT */
  163915. jinit_forward_dct(cinfo);
  163916. /* Entropy encoding: either Huffman or arithmetic coding. */
  163917. if (cinfo->arith_code) {
  163918. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163919. } else {
  163920. if (cinfo->progressive_mode) {
  163921. #ifdef C_PROGRESSIVE_SUPPORTED
  163922. jinit_phuff_encoder(cinfo);
  163923. #else
  163924. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163925. #endif
  163926. } else
  163927. jinit_huff_encoder(cinfo);
  163928. }
  163929. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163930. jinit_c_coef_controller(cinfo,
  163931. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163932. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163933. jinit_marker_writer(cinfo);
  163934. /* We can now tell the memory manager to allocate virtual arrays. */
  163935. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163936. /* Write the datastream header (SOI) immediately.
  163937. * Frame and scan headers are postponed till later.
  163938. * This lets application insert special markers after the SOI.
  163939. */
  163940. (*cinfo->marker->write_file_header) (cinfo);
  163941. }
  163942. /*** End of inlined file: jcinit.c ***/
  163943. /*** Start of inlined file: jcmainct.c ***/
  163944. #define JPEG_INTERNALS
  163945. /* Note: currently, there is no operating mode in which a full-image buffer
  163946. * is needed at this step. If there were, that mode could not be used with
  163947. * "raw data" input, since this module is bypassed in that case. However,
  163948. * we've left the code here for possible use in special applications.
  163949. */
  163950. #undef FULL_MAIN_BUFFER_SUPPORTED
  163951. /* Private buffer controller object */
  163952. typedef struct {
  163953. struct jpeg_c_main_controller pub; /* public fields */
  163954. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163955. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163956. boolean suspended; /* remember if we suspended output */
  163957. J_BUF_MODE pass_mode; /* current operating mode */
  163958. /* If using just a strip buffer, this points to the entire set of buffers
  163959. * (we allocate one for each component). In the full-image case, this
  163960. * points to the currently accessible strips of the virtual arrays.
  163961. */
  163962. JSAMPARRAY buffer[MAX_COMPONENTS];
  163963. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163964. /* If using full-image storage, this array holds pointers to virtual-array
  163965. * control blocks for each component. Unused if not full-image storage.
  163966. */
  163967. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163968. #endif
  163969. } my_main_controller;
  163970. typedef my_main_controller * my_main_ptr;
  163971. /* Forward declarations */
  163972. METHODDEF(void) process_data_simple_main
  163973. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163974. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163975. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163976. METHODDEF(void) process_data_buffer_main
  163977. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163978. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163979. #endif
  163980. /*
  163981. * Initialize for a processing pass.
  163982. */
  163983. METHODDEF(void)
  163984. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163985. {
  163986. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163987. /* Do nothing in raw-data mode. */
  163988. if (cinfo->raw_data_in)
  163989. return;
  163990. main_->cur_iMCU_row = 0; /* initialize counters */
  163991. main_->rowgroup_ctr = 0;
  163992. main_->suspended = FALSE;
  163993. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163994. switch (pass_mode) {
  163995. case JBUF_PASS_THRU:
  163996. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163997. if (main_->whole_image[0] != NULL)
  163998. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163999. #endif
  164000. main_->pub.process_data = process_data_simple_main;
  164001. break;
  164002. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164003. case JBUF_SAVE_SOURCE:
  164004. case JBUF_CRANK_DEST:
  164005. case JBUF_SAVE_AND_PASS:
  164006. if (main_->whole_image[0] == NULL)
  164007. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164008. main_->pub.process_data = process_data_buffer_main;
  164009. break;
  164010. #endif
  164011. default:
  164012. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164013. break;
  164014. }
  164015. }
  164016. /*
  164017. * Process some data.
  164018. * This routine handles the simple pass-through mode,
  164019. * where we have only a strip buffer.
  164020. */
  164021. METHODDEF(void)
  164022. process_data_simple_main (j_compress_ptr cinfo,
  164023. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164024. JDIMENSION in_rows_avail)
  164025. {
  164026. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164027. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164028. /* Read input data if we haven't filled the main buffer yet */
  164029. if (main_->rowgroup_ctr < DCTSIZE)
  164030. (*cinfo->prep->pre_process_data) (cinfo,
  164031. input_buf, in_row_ctr, in_rows_avail,
  164032. main_->buffer, &main_->rowgroup_ctr,
  164033. (JDIMENSION) DCTSIZE);
  164034. /* If we don't have a full iMCU row buffered, return to application for
  164035. * more data. Note that preprocessor will always pad to fill the iMCU row
  164036. * at the bottom of the image.
  164037. */
  164038. if (main_->rowgroup_ctr != DCTSIZE)
  164039. return;
  164040. /* Send the completed row to the compressor */
  164041. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164042. /* If compressor did not consume the whole row, then we must need to
  164043. * suspend processing and return to the application. In this situation
  164044. * we pretend we didn't yet consume the last input row; otherwise, if
  164045. * it happened to be the last row of the image, the application would
  164046. * think we were done.
  164047. */
  164048. if (! main_->suspended) {
  164049. (*in_row_ctr)--;
  164050. main_->suspended = TRUE;
  164051. }
  164052. return;
  164053. }
  164054. /* We did finish the row. Undo our little suspension hack if a previous
  164055. * call suspended; then mark the main buffer empty.
  164056. */
  164057. if (main_->suspended) {
  164058. (*in_row_ctr)++;
  164059. main_->suspended = FALSE;
  164060. }
  164061. main_->rowgroup_ctr = 0;
  164062. main_->cur_iMCU_row++;
  164063. }
  164064. }
  164065. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164066. /*
  164067. * Process some data.
  164068. * This routine handles all of the modes that use a full-size buffer.
  164069. */
  164070. METHODDEF(void)
  164071. process_data_buffer_main (j_compress_ptr cinfo,
  164072. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164073. JDIMENSION in_rows_avail)
  164074. {
  164075. my_main_ptr main = (my_main_ptr) cinfo->main;
  164076. int ci;
  164077. jpeg_component_info *compptr;
  164078. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164079. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164080. /* Realign the virtual buffers if at the start of an iMCU row. */
  164081. if (main->rowgroup_ctr == 0) {
  164082. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164083. ci++, compptr++) {
  164084. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164085. ((j_common_ptr) cinfo, main->whole_image[ci],
  164086. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164087. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164088. }
  164089. /* In a read pass, pretend we just read some source data. */
  164090. if (! writing) {
  164091. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164092. main->rowgroup_ctr = DCTSIZE;
  164093. }
  164094. }
  164095. /* If a write pass, read input data until the current iMCU row is full. */
  164096. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164097. if (writing) {
  164098. (*cinfo->prep->pre_process_data) (cinfo,
  164099. input_buf, in_row_ctr, in_rows_avail,
  164100. main->buffer, &main->rowgroup_ctr,
  164101. (JDIMENSION) DCTSIZE);
  164102. /* Return to application if we need more data to fill the iMCU row. */
  164103. if (main->rowgroup_ctr < DCTSIZE)
  164104. return;
  164105. }
  164106. /* Emit data, unless this is a sink-only pass. */
  164107. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164108. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164109. /* If compressor did not consume the whole row, then we must need to
  164110. * suspend processing and return to the application. In this situation
  164111. * we pretend we didn't yet consume the last input row; otherwise, if
  164112. * it happened to be the last row of the image, the application would
  164113. * think we were done.
  164114. */
  164115. if (! main->suspended) {
  164116. (*in_row_ctr)--;
  164117. main->suspended = TRUE;
  164118. }
  164119. return;
  164120. }
  164121. /* We did finish the row. Undo our little suspension hack if a previous
  164122. * call suspended; then mark the main buffer empty.
  164123. */
  164124. if (main->suspended) {
  164125. (*in_row_ctr)++;
  164126. main->suspended = FALSE;
  164127. }
  164128. }
  164129. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164130. main->rowgroup_ctr = 0;
  164131. main->cur_iMCU_row++;
  164132. }
  164133. }
  164134. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164135. /*
  164136. * Initialize main buffer controller.
  164137. */
  164138. GLOBAL(void)
  164139. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164140. {
  164141. my_main_ptr main_;
  164142. int ci;
  164143. jpeg_component_info *compptr;
  164144. main_ = (my_main_ptr)
  164145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164146. SIZEOF(my_main_controller));
  164147. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164148. main_->pub.start_pass = start_pass_main;
  164149. /* We don't need to create a buffer in raw-data mode. */
  164150. if (cinfo->raw_data_in)
  164151. return;
  164152. /* Create the buffer. It holds downsampled data, so each component
  164153. * may be of a different size.
  164154. */
  164155. if (need_full_buffer) {
  164156. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164157. /* Allocate a full-image virtual array for each component */
  164158. /* Note we pad the bottom to a multiple of the iMCU height */
  164159. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164160. ci++, compptr++) {
  164161. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164162. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164163. compptr->width_in_blocks * DCTSIZE,
  164164. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164165. (long) compptr->v_samp_factor) * DCTSIZE,
  164166. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164167. }
  164168. #else
  164169. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164170. #endif
  164171. } else {
  164172. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164173. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164174. #endif
  164175. /* Allocate a strip buffer for each component */
  164176. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164177. ci++, compptr++) {
  164178. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164179. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164180. compptr->width_in_blocks * DCTSIZE,
  164181. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164182. }
  164183. }
  164184. }
  164185. /*** End of inlined file: jcmainct.c ***/
  164186. /*** Start of inlined file: jcmarker.c ***/
  164187. #define JPEG_INTERNALS
  164188. /* Private state */
  164189. typedef struct {
  164190. struct jpeg_marker_writer pub; /* public fields */
  164191. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164192. } my_marker_writer;
  164193. typedef my_marker_writer * my_marker_ptr;
  164194. /*
  164195. * Basic output routines.
  164196. *
  164197. * Note that we do not support suspension while writing a marker.
  164198. * Therefore, an application using suspension must ensure that there is
  164199. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164200. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164201. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164202. * modes are not supported at all with suspension, so those two are the only
  164203. * points where markers will be written.
  164204. */
  164205. LOCAL(void)
  164206. emit_byte (j_compress_ptr cinfo, int val)
  164207. /* Emit a byte */
  164208. {
  164209. struct jpeg_destination_mgr * dest = cinfo->dest;
  164210. *(dest->next_output_byte)++ = (JOCTET) val;
  164211. if (--dest->free_in_buffer == 0) {
  164212. if (! (*dest->empty_output_buffer) (cinfo))
  164213. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164214. }
  164215. }
  164216. LOCAL(void)
  164217. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164218. /* Emit a marker code */
  164219. {
  164220. emit_byte(cinfo, 0xFF);
  164221. emit_byte(cinfo, (int) mark);
  164222. }
  164223. LOCAL(void)
  164224. emit_2bytes (j_compress_ptr cinfo, int value)
  164225. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164226. {
  164227. emit_byte(cinfo, (value >> 8) & 0xFF);
  164228. emit_byte(cinfo, value & 0xFF);
  164229. }
  164230. /*
  164231. * Routines to write specific marker types.
  164232. */
  164233. LOCAL(int)
  164234. emit_dqt (j_compress_ptr cinfo, int index)
  164235. /* Emit a DQT marker */
  164236. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164237. {
  164238. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164239. int prec;
  164240. int i;
  164241. if (qtbl == NULL)
  164242. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164243. prec = 0;
  164244. for (i = 0; i < DCTSIZE2; i++) {
  164245. if (qtbl->quantval[i] > 255)
  164246. prec = 1;
  164247. }
  164248. if (! qtbl->sent_table) {
  164249. emit_marker(cinfo, M_DQT);
  164250. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164251. emit_byte(cinfo, index + (prec<<4));
  164252. for (i = 0; i < DCTSIZE2; i++) {
  164253. /* The table entries must be emitted in zigzag order. */
  164254. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164255. if (prec)
  164256. emit_byte(cinfo, (int) (qval >> 8));
  164257. emit_byte(cinfo, (int) (qval & 0xFF));
  164258. }
  164259. qtbl->sent_table = TRUE;
  164260. }
  164261. return prec;
  164262. }
  164263. LOCAL(void)
  164264. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164265. /* Emit a DHT marker */
  164266. {
  164267. JHUFF_TBL * htbl;
  164268. int length, i;
  164269. if (is_ac) {
  164270. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164271. index += 0x10; /* output index has AC bit set */
  164272. } else {
  164273. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164274. }
  164275. if (htbl == NULL)
  164276. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164277. if (! htbl->sent_table) {
  164278. emit_marker(cinfo, M_DHT);
  164279. length = 0;
  164280. for (i = 1; i <= 16; i++)
  164281. length += htbl->bits[i];
  164282. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164283. emit_byte(cinfo, index);
  164284. for (i = 1; i <= 16; i++)
  164285. emit_byte(cinfo, htbl->bits[i]);
  164286. for (i = 0; i < length; i++)
  164287. emit_byte(cinfo, htbl->huffval[i]);
  164288. htbl->sent_table = TRUE;
  164289. }
  164290. }
  164291. LOCAL(void)
  164292. emit_dac (j_compress_ptr)
  164293. /* Emit a DAC marker */
  164294. /* Since the useful info is so small, we want to emit all the tables in */
  164295. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164296. {
  164297. #ifdef C_ARITH_CODING_SUPPORTED
  164298. char dc_in_use[NUM_ARITH_TBLS];
  164299. char ac_in_use[NUM_ARITH_TBLS];
  164300. int length, i;
  164301. jpeg_component_info *compptr;
  164302. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164303. dc_in_use[i] = ac_in_use[i] = 0;
  164304. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164305. compptr = cinfo->cur_comp_info[i];
  164306. dc_in_use[compptr->dc_tbl_no] = 1;
  164307. ac_in_use[compptr->ac_tbl_no] = 1;
  164308. }
  164309. length = 0;
  164310. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164311. length += dc_in_use[i] + ac_in_use[i];
  164312. emit_marker(cinfo, M_DAC);
  164313. emit_2bytes(cinfo, length*2 + 2);
  164314. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164315. if (dc_in_use[i]) {
  164316. emit_byte(cinfo, i);
  164317. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164318. }
  164319. if (ac_in_use[i]) {
  164320. emit_byte(cinfo, i + 0x10);
  164321. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164322. }
  164323. }
  164324. #endif /* C_ARITH_CODING_SUPPORTED */
  164325. }
  164326. LOCAL(void)
  164327. emit_dri (j_compress_ptr cinfo)
  164328. /* Emit a DRI marker */
  164329. {
  164330. emit_marker(cinfo, M_DRI);
  164331. emit_2bytes(cinfo, 4); /* fixed length */
  164332. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164333. }
  164334. LOCAL(void)
  164335. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164336. /* Emit a SOF marker */
  164337. {
  164338. int ci;
  164339. jpeg_component_info *compptr;
  164340. emit_marker(cinfo, code);
  164341. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164342. /* Make sure image isn't bigger than SOF field can handle */
  164343. if ((long) cinfo->image_height > 65535L ||
  164344. (long) cinfo->image_width > 65535L)
  164345. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164346. emit_byte(cinfo, cinfo->data_precision);
  164347. emit_2bytes(cinfo, (int) cinfo->image_height);
  164348. emit_2bytes(cinfo, (int) cinfo->image_width);
  164349. emit_byte(cinfo, cinfo->num_components);
  164350. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164351. ci++, compptr++) {
  164352. emit_byte(cinfo, compptr->component_id);
  164353. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164354. emit_byte(cinfo, compptr->quant_tbl_no);
  164355. }
  164356. }
  164357. LOCAL(void)
  164358. emit_sos (j_compress_ptr cinfo)
  164359. /* Emit a SOS marker */
  164360. {
  164361. int i, td, ta;
  164362. jpeg_component_info *compptr;
  164363. emit_marker(cinfo, M_SOS);
  164364. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164365. emit_byte(cinfo, cinfo->comps_in_scan);
  164366. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164367. compptr = cinfo->cur_comp_info[i];
  164368. emit_byte(cinfo, compptr->component_id);
  164369. td = compptr->dc_tbl_no;
  164370. ta = compptr->ac_tbl_no;
  164371. if (cinfo->progressive_mode) {
  164372. /* Progressive mode: only DC or only AC tables are used in one scan;
  164373. * furthermore, Huffman coding of DC refinement uses no table at all.
  164374. * We emit 0 for unused field(s); this is recommended by the P&M text
  164375. * but does not seem to be specified in the standard.
  164376. */
  164377. if (cinfo->Ss == 0) {
  164378. ta = 0; /* DC scan */
  164379. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164380. td = 0; /* no DC table either */
  164381. } else {
  164382. td = 0; /* AC scan */
  164383. }
  164384. }
  164385. emit_byte(cinfo, (td << 4) + ta);
  164386. }
  164387. emit_byte(cinfo, cinfo->Ss);
  164388. emit_byte(cinfo, cinfo->Se);
  164389. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164390. }
  164391. LOCAL(void)
  164392. emit_jfif_app0 (j_compress_ptr cinfo)
  164393. /* Emit a JFIF-compliant APP0 marker */
  164394. {
  164395. /*
  164396. * Length of APP0 block (2 bytes)
  164397. * Block ID (4 bytes - ASCII "JFIF")
  164398. * Zero byte (1 byte to terminate the ID string)
  164399. * Version Major, Minor (2 bytes - major first)
  164400. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164401. * Xdpu (2 bytes - dots per unit horizontal)
  164402. * Ydpu (2 bytes - dots per unit vertical)
  164403. * Thumbnail X size (1 byte)
  164404. * Thumbnail Y size (1 byte)
  164405. */
  164406. emit_marker(cinfo, M_APP0);
  164407. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164408. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164409. emit_byte(cinfo, 0x46);
  164410. emit_byte(cinfo, 0x49);
  164411. emit_byte(cinfo, 0x46);
  164412. emit_byte(cinfo, 0);
  164413. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164414. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164415. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164416. emit_2bytes(cinfo, (int) cinfo->X_density);
  164417. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164418. emit_byte(cinfo, 0); /* No thumbnail image */
  164419. emit_byte(cinfo, 0);
  164420. }
  164421. LOCAL(void)
  164422. emit_adobe_app14 (j_compress_ptr cinfo)
  164423. /* Emit an Adobe APP14 marker */
  164424. {
  164425. /*
  164426. * Length of APP14 block (2 bytes)
  164427. * Block ID (5 bytes - ASCII "Adobe")
  164428. * Version Number (2 bytes - currently 100)
  164429. * Flags0 (2 bytes - currently 0)
  164430. * Flags1 (2 bytes - currently 0)
  164431. * Color transform (1 byte)
  164432. *
  164433. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164434. * now in circulation seem to use Version = 100, so that's what we write.
  164435. *
  164436. * We write the color transform byte as 1 if the JPEG color space is
  164437. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164438. * whether the encoder performed a transformation, which is pretty useless.
  164439. */
  164440. emit_marker(cinfo, M_APP14);
  164441. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164442. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164443. emit_byte(cinfo, 0x64);
  164444. emit_byte(cinfo, 0x6F);
  164445. emit_byte(cinfo, 0x62);
  164446. emit_byte(cinfo, 0x65);
  164447. emit_2bytes(cinfo, 100); /* Version */
  164448. emit_2bytes(cinfo, 0); /* Flags0 */
  164449. emit_2bytes(cinfo, 0); /* Flags1 */
  164450. switch (cinfo->jpeg_color_space) {
  164451. case JCS_YCbCr:
  164452. emit_byte(cinfo, 1); /* Color transform = 1 */
  164453. break;
  164454. case JCS_YCCK:
  164455. emit_byte(cinfo, 2); /* Color transform = 2 */
  164456. break;
  164457. default:
  164458. emit_byte(cinfo, 0); /* Color transform = 0 */
  164459. break;
  164460. }
  164461. }
  164462. /*
  164463. * These routines allow writing an arbitrary marker with parameters.
  164464. * The only intended use is to emit COM or APPn markers after calling
  164465. * write_file_header and before calling write_frame_header.
  164466. * Other uses are not guaranteed to produce desirable results.
  164467. * Counting the parameter bytes properly is the caller's responsibility.
  164468. */
  164469. METHODDEF(void)
  164470. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164471. /* Emit an arbitrary marker header */
  164472. {
  164473. if (datalen > (unsigned int) 65533) /* safety check */
  164474. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164475. emit_marker(cinfo, (JPEG_MARKER) marker);
  164476. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164477. }
  164478. METHODDEF(void)
  164479. write_marker_byte (j_compress_ptr cinfo, int val)
  164480. /* Emit one byte of marker parameters following write_marker_header */
  164481. {
  164482. emit_byte(cinfo, val);
  164483. }
  164484. /*
  164485. * Write datastream header.
  164486. * This consists of an SOI and optional APPn markers.
  164487. * We recommend use of the JFIF marker, but not the Adobe marker,
  164488. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164489. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164490. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164491. * Note that an application can write additional header markers after
  164492. * jpeg_start_compress returns.
  164493. */
  164494. METHODDEF(void)
  164495. write_file_header (j_compress_ptr cinfo)
  164496. {
  164497. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164498. emit_marker(cinfo, M_SOI); /* first the SOI */
  164499. /* SOI is defined to reset restart interval to 0 */
  164500. marker->last_restart_interval = 0;
  164501. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164502. emit_jfif_app0(cinfo);
  164503. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164504. emit_adobe_app14(cinfo);
  164505. }
  164506. /*
  164507. * Write frame header.
  164508. * This consists of DQT and SOFn markers.
  164509. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164510. * This avoids compatibility problems with incorrect implementations that
  164511. * try to error-check the quant table numbers as soon as they see the SOF.
  164512. */
  164513. METHODDEF(void)
  164514. write_frame_header (j_compress_ptr cinfo)
  164515. {
  164516. int ci, prec;
  164517. boolean is_baseline;
  164518. jpeg_component_info *compptr;
  164519. /* Emit DQT for each quantization table.
  164520. * Note that emit_dqt() suppresses any duplicate tables.
  164521. */
  164522. prec = 0;
  164523. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164524. ci++, compptr++) {
  164525. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164526. }
  164527. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164528. /* Check for a non-baseline specification.
  164529. * Note we assume that Huffman table numbers won't be changed later.
  164530. */
  164531. if (cinfo->arith_code || cinfo->progressive_mode ||
  164532. cinfo->data_precision != 8) {
  164533. is_baseline = FALSE;
  164534. } else {
  164535. is_baseline = TRUE;
  164536. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164537. ci++, compptr++) {
  164538. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164539. is_baseline = FALSE;
  164540. }
  164541. if (prec && is_baseline) {
  164542. is_baseline = FALSE;
  164543. /* If it's baseline except for quantizer size, warn the user */
  164544. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164545. }
  164546. }
  164547. /* Emit the proper SOF marker */
  164548. if (cinfo->arith_code) {
  164549. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164550. } else {
  164551. if (cinfo->progressive_mode)
  164552. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164553. else if (is_baseline)
  164554. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164555. else
  164556. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164557. }
  164558. }
  164559. /*
  164560. * Write scan header.
  164561. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164562. * Compressed data will be written following the SOS.
  164563. */
  164564. METHODDEF(void)
  164565. write_scan_header (j_compress_ptr cinfo)
  164566. {
  164567. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164568. int i;
  164569. jpeg_component_info *compptr;
  164570. if (cinfo->arith_code) {
  164571. /* Emit arith conditioning info. We may have some duplication
  164572. * if the file has multiple scans, but it's so small it's hardly
  164573. * worth worrying about.
  164574. */
  164575. emit_dac(cinfo);
  164576. } else {
  164577. /* Emit Huffman tables.
  164578. * Note that emit_dht() suppresses any duplicate tables.
  164579. */
  164580. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164581. compptr = cinfo->cur_comp_info[i];
  164582. if (cinfo->progressive_mode) {
  164583. /* Progressive mode: only DC or only AC tables are used in one scan */
  164584. if (cinfo->Ss == 0) {
  164585. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164586. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164587. } else {
  164588. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164589. }
  164590. } else {
  164591. /* Sequential mode: need both DC and AC tables */
  164592. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164593. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164594. }
  164595. }
  164596. }
  164597. /* Emit DRI if required --- note that DRI value could change for each scan.
  164598. * We avoid wasting space with unnecessary DRIs, however.
  164599. */
  164600. if (cinfo->restart_interval != marker->last_restart_interval) {
  164601. emit_dri(cinfo);
  164602. marker->last_restart_interval = cinfo->restart_interval;
  164603. }
  164604. emit_sos(cinfo);
  164605. }
  164606. /*
  164607. * Write datastream trailer.
  164608. */
  164609. METHODDEF(void)
  164610. write_file_trailer (j_compress_ptr cinfo)
  164611. {
  164612. emit_marker(cinfo, M_EOI);
  164613. }
  164614. /*
  164615. * Write an abbreviated table-specification datastream.
  164616. * This consists of SOI, DQT and DHT tables, and EOI.
  164617. * Any table that is defined and not marked sent_table = TRUE will be
  164618. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164619. */
  164620. METHODDEF(void)
  164621. write_tables_only (j_compress_ptr cinfo)
  164622. {
  164623. int i;
  164624. emit_marker(cinfo, M_SOI);
  164625. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164626. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164627. (void) emit_dqt(cinfo, i);
  164628. }
  164629. if (! cinfo->arith_code) {
  164630. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164631. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164632. emit_dht(cinfo, i, FALSE);
  164633. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164634. emit_dht(cinfo, i, TRUE);
  164635. }
  164636. }
  164637. emit_marker(cinfo, M_EOI);
  164638. }
  164639. /*
  164640. * Initialize the marker writer module.
  164641. */
  164642. GLOBAL(void)
  164643. jinit_marker_writer (j_compress_ptr cinfo)
  164644. {
  164645. my_marker_ptr marker;
  164646. /* Create the subobject */
  164647. marker = (my_marker_ptr)
  164648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164649. SIZEOF(my_marker_writer));
  164650. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164651. /* Initialize method pointers */
  164652. marker->pub.write_file_header = write_file_header;
  164653. marker->pub.write_frame_header = write_frame_header;
  164654. marker->pub.write_scan_header = write_scan_header;
  164655. marker->pub.write_file_trailer = write_file_trailer;
  164656. marker->pub.write_tables_only = write_tables_only;
  164657. marker->pub.write_marker_header = write_marker_header;
  164658. marker->pub.write_marker_byte = write_marker_byte;
  164659. /* Initialize private state */
  164660. marker->last_restart_interval = 0;
  164661. }
  164662. /*** End of inlined file: jcmarker.c ***/
  164663. /*** Start of inlined file: jcmaster.c ***/
  164664. #define JPEG_INTERNALS
  164665. /* Private state */
  164666. typedef enum {
  164667. main_pass, /* input data, also do first output step */
  164668. huff_opt_pass, /* Huffman code optimization pass */
  164669. output_pass /* data output pass */
  164670. } c_pass_type;
  164671. typedef struct {
  164672. struct jpeg_comp_master pub; /* public fields */
  164673. c_pass_type pass_type; /* the type of the current pass */
  164674. int pass_number; /* # of passes completed */
  164675. int total_passes; /* total # of passes needed */
  164676. int scan_number; /* current index in scan_info[] */
  164677. } my_comp_master;
  164678. typedef my_comp_master * my_master_ptr;
  164679. /*
  164680. * Support routines that do various essential calculations.
  164681. */
  164682. LOCAL(void)
  164683. initial_setup (j_compress_ptr cinfo)
  164684. /* Do computations that are needed before master selection phase */
  164685. {
  164686. int ci;
  164687. jpeg_component_info *compptr;
  164688. long samplesperrow;
  164689. JDIMENSION jd_samplesperrow;
  164690. /* Sanity check on image dimensions */
  164691. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164692. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164693. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164694. /* Make sure image isn't bigger than I can handle */
  164695. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164696. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164697. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164698. /* Width of an input scanline must be representable as JDIMENSION. */
  164699. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164700. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164701. if ((long) jd_samplesperrow != samplesperrow)
  164702. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164703. /* For now, precision must match compiled-in value... */
  164704. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164705. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164706. /* Check that number of components won't exceed internal array sizes */
  164707. if (cinfo->num_components > MAX_COMPONENTS)
  164708. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164709. MAX_COMPONENTS);
  164710. /* Compute maximum sampling factors; check factor validity */
  164711. cinfo->max_h_samp_factor = 1;
  164712. cinfo->max_v_samp_factor = 1;
  164713. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164714. ci++, compptr++) {
  164715. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164716. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164717. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164718. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164719. compptr->h_samp_factor);
  164720. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164721. compptr->v_samp_factor);
  164722. }
  164723. /* Compute dimensions of components */
  164724. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164725. ci++, compptr++) {
  164726. /* Fill in the correct component_index value; don't rely on application */
  164727. compptr->component_index = ci;
  164728. /* For compression, we never do DCT scaling. */
  164729. compptr->DCT_scaled_size = DCTSIZE;
  164730. /* Size in DCT blocks */
  164731. compptr->width_in_blocks = (JDIMENSION)
  164732. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164733. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164734. compptr->height_in_blocks = (JDIMENSION)
  164735. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164736. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164737. /* Size in samples */
  164738. compptr->downsampled_width = (JDIMENSION)
  164739. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164740. (long) cinfo->max_h_samp_factor);
  164741. compptr->downsampled_height = (JDIMENSION)
  164742. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164743. (long) cinfo->max_v_samp_factor);
  164744. /* Mark component needed (this flag isn't actually used for compression) */
  164745. compptr->component_needed = TRUE;
  164746. }
  164747. /* Compute number of fully interleaved MCU rows (number of times that
  164748. * main controller will call coefficient controller).
  164749. */
  164750. cinfo->total_iMCU_rows = (JDIMENSION)
  164751. jdiv_round_up((long) cinfo->image_height,
  164752. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164753. }
  164754. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164755. LOCAL(void)
  164756. validate_script (j_compress_ptr cinfo)
  164757. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164758. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164759. */
  164760. {
  164761. const jpeg_scan_info * scanptr;
  164762. int scanno, ncomps, ci, coefi, thisi;
  164763. int Ss, Se, Ah, Al;
  164764. boolean component_sent[MAX_COMPONENTS];
  164765. #ifdef C_PROGRESSIVE_SUPPORTED
  164766. int * last_bitpos_ptr;
  164767. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164768. /* -1 until that coefficient has been seen; then last Al for it */
  164769. #endif
  164770. if (cinfo->num_scans <= 0)
  164771. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164772. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164773. * for progressive JPEG, no scan can have this.
  164774. */
  164775. scanptr = cinfo->scan_info;
  164776. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164777. #ifdef C_PROGRESSIVE_SUPPORTED
  164778. cinfo->progressive_mode = TRUE;
  164779. last_bitpos_ptr = & last_bitpos[0][0];
  164780. for (ci = 0; ci < cinfo->num_components; ci++)
  164781. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164782. *last_bitpos_ptr++ = -1;
  164783. #else
  164784. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164785. #endif
  164786. } else {
  164787. cinfo->progressive_mode = FALSE;
  164788. for (ci = 0; ci < cinfo->num_components; ci++)
  164789. component_sent[ci] = FALSE;
  164790. }
  164791. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164792. /* Validate component indexes */
  164793. ncomps = scanptr->comps_in_scan;
  164794. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164795. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164796. for (ci = 0; ci < ncomps; ci++) {
  164797. thisi = scanptr->component_index[ci];
  164798. if (thisi < 0 || thisi >= cinfo->num_components)
  164799. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164800. /* Components must appear in SOF order within each scan */
  164801. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164802. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164803. }
  164804. /* Validate progression parameters */
  164805. Ss = scanptr->Ss;
  164806. Se = scanptr->Se;
  164807. Ah = scanptr->Ah;
  164808. Al = scanptr->Al;
  164809. if (cinfo->progressive_mode) {
  164810. #ifdef C_PROGRESSIVE_SUPPORTED
  164811. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164812. * seems wrong: the upper bound ought to depend on data precision.
  164813. * Perhaps they really meant 0..N+1 for N-bit precision.
  164814. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164815. * out-of-range reconstructed DC values during the first DC scan,
  164816. * which might cause problems for some decoders.
  164817. */
  164818. #if BITS_IN_JSAMPLE == 8
  164819. #define MAX_AH_AL 10
  164820. #else
  164821. #define MAX_AH_AL 13
  164822. #endif
  164823. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164824. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164825. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164826. if (Ss == 0) {
  164827. if (Se != 0) /* DC and AC together not OK */
  164828. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164829. } else {
  164830. if (ncomps != 1) /* AC scans must be for only one component */
  164831. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164832. }
  164833. for (ci = 0; ci < ncomps; ci++) {
  164834. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164835. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164836. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164837. for (coefi = Ss; coefi <= Se; coefi++) {
  164838. if (last_bitpos_ptr[coefi] < 0) {
  164839. /* first scan of this coefficient */
  164840. if (Ah != 0)
  164841. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164842. } else {
  164843. /* not first scan */
  164844. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164845. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164846. }
  164847. last_bitpos_ptr[coefi] = Al;
  164848. }
  164849. }
  164850. #endif
  164851. } else {
  164852. /* For sequential JPEG, all progression parameters must be these: */
  164853. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164854. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164855. /* Make sure components are not sent twice */
  164856. for (ci = 0; ci < ncomps; ci++) {
  164857. thisi = scanptr->component_index[ci];
  164858. if (component_sent[thisi])
  164859. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164860. component_sent[thisi] = TRUE;
  164861. }
  164862. }
  164863. }
  164864. /* Now verify that everything got sent. */
  164865. if (cinfo->progressive_mode) {
  164866. #ifdef C_PROGRESSIVE_SUPPORTED
  164867. /* For progressive mode, we only check that at least some DC data
  164868. * got sent for each component; the spec does not require that all bits
  164869. * of all coefficients be transmitted. Would it be wiser to enforce
  164870. * transmission of all coefficient bits??
  164871. */
  164872. for (ci = 0; ci < cinfo->num_components; ci++) {
  164873. if (last_bitpos[ci][0] < 0)
  164874. ERREXIT(cinfo, JERR_MISSING_DATA);
  164875. }
  164876. #endif
  164877. } else {
  164878. for (ci = 0; ci < cinfo->num_components; ci++) {
  164879. if (! component_sent[ci])
  164880. ERREXIT(cinfo, JERR_MISSING_DATA);
  164881. }
  164882. }
  164883. }
  164884. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164885. LOCAL(void)
  164886. select_scan_parameters (j_compress_ptr cinfo)
  164887. /* Set up the scan parameters for the current scan */
  164888. {
  164889. int ci;
  164890. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164891. if (cinfo->scan_info != NULL) {
  164892. /* Prepare for current scan --- the script is already validated */
  164893. my_master_ptr master = (my_master_ptr) cinfo->master;
  164894. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164895. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164896. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164897. cinfo->cur_comp_info[ci] =
  164898. &cinfo->comp_info[scanptr->component_index[ci]];
  164899. }
  164900. cinfo->Ss = scanptr->Ss;
  164901. cinfo->Se = scanptr->Se;
  164902. cinfo->Ah = scanptr->Ah;
  164903. cinfo->Al = scanptr->Al;
  164904. }
  164905. else
  164906. #endif
  164907. {
  164908. /* Prepare for single sequential-JPEG scan containing all components */
  164909. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164910. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164911. MAX_COMPS_IN_SCAN);
  164912. cinfo->comps_in_scan = cinfo->num_components;
  164913. for (ci = 0; ci < cinfo->num_components; ci++) {
  164914. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164915. }
  164916. cinfo->Ss = 0;
  164917. cinfo->Se = DCTSIZE2-1;
  164918. cinfo->Ah = 0;
  164919. cinfo->Al = 0;
  164920. }
  164921. }
  164922. LOCAL(void)
  164923. per_scan_setup (j_compress_ptr cinfo)
  164924. /* Do computations that are needed before processing a JPEG scan */
  164925. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164926. {
  164927. int ci, mcublks, tmp;
  164928. jpeg_component_info *compptr;
  164929. if (cinfo->comps_in_scan == 1) {
  164930. /* Noninterleaved (single-component) scan */
  164931. compptr = cinfo->cur_comp_info[0];
  164932. /* Overall image size in MCUs */
  164933. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164934. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164935. /* For noninterleaved scan, always one block per MCU */
  164936. compptr->MCU_width = 1;
  164937. compptr->MCU_height = 1;
  164938. compptr->MCU_blocks = 1;
  164939. compptr->MCU_sample_width = DCTSIZE;
  164940. compptr->last_col_width = 1;
  164941. /* For noninterleaved scans, it is convenient to define last_row_height
  164942. * as the number of block rows present in the last iMCU row.
  164943. */
  164944. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164945. if (tmp == 0) tmp = compptr->v_samp_factor;
  164946. compptr->last_row_height = tmp;
  164947. /* Prepare array describing MCU composition */
  164948. cinfo->blocks_in_MCU = 1;
  164949. cinfo->MCU_membership[0] = 0;
  164950. } else {
  164951. /* Interleaved (multi-component) scan */
  164952. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164953. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164954. MAX_COMPS_IN_SCAN);
  164955. /* Overall image size in MCUs */
  164956. cinfo->MCUs_per_row = (JDIMENSION)
  164957. jdiv_round_up((long) cinfo->image_width,
  164958. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164959. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164960. jdiv_round_up((long) cinfo->image_height,
  164961. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164962. cinfo->blocks_in_MCU = 0;
  164963. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164964. compptr = cinfo->cur_comp_info[ci];
  164965. /* Sampling factors give # of blocks of component in each MCU */
  164966. compptr->MCU_width = compptr->h_samp_factor;
  164967. compptr->MCU_height = compptr->v_samp_factor;
  164968. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164969. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164970. /* Figure number of non-dummy blocks in last MCU column & row */
  164971. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164972. if (tmp == 0) tmp = compptr->MCU_width;
  164973. compptr->last_col_width = tmp;
  164974. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164975. if (tmp == 0) tmp = compptr->MCU_height;
  164976. compptr->last_row_height = tmp;
  164977. /* Prepare array describing MCU composition */
  164978. mcublks = compptr->MCU_blocks;
  164979. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164980. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164981. while (mcublks-- > 0) {
  164982. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164983. }
  164984. }
  164985. }
  164986. /* Convert restart specified in rows to actual MCU count. */
  164987. /* Note that count must fit in 16 bits, so we provide limiting. */
  164988. if (cinfo->restart_in_rows > 0) {
  164989. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164990. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164991. }
  164992. }
  164993. /*
  164994. * Per-pass setup.
  164995. * This is called at the beginning of each pass. We determine which modules
  164996. * will be active during this pass and give them appropriate start_pass calls.
  164997. * We also set is_last_pass to indicate whether any more passes will be
  164998. * required.
  164999. */
  165000. METHODDEF(void)
  165001. prepare_for_pass (j_compress_ptr cinfo)
  165002. {
  165003. my_master_ptr master = (my_master_ptr) cinfo->master;
  165004. switch (master->pass_type) {
  165005. case main_pass:
  165006. /* Initial pass: will collect input data, and do either Huffman
  165007. * optimization or data output for the first scan.
  165008. */
  165009. select_scan_parameters(cinfo);
  165010. per_scan_setup(cinfo);
  165011. if (! cinfo->raw_data_in) {
  165012. (*cinfo->cconvert->start_pass) (cinfo);
  165013. (*cinfo->downsample->start_pass) (cinfo);
  165014. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165015. }
  165016. (*cinfo->fdct->start_pass) (cinfo);
  165017. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165018. (*cinfo->coef->start_pass) (cinfo,
  165019. (master->total_passes > 1 ?
  165020. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165021. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165022. if (cinfo->optimize_coding) {
  165023. /* No immediate data output; postpone writing frame/scan headers */
  165024. master->pub.call_pass_startup = FALSE;
  165025. } else {
  165026. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165027. master->pub.call_pass_startup = TRUE;
  165028. }
  165029. break;
  165030. #ifdef ENTROPY_OPT_SUPPORTED
  165031. case huff_opt_pass:
  165032. /* Do Huffman optimization for a scan after the first one. */
  165033. select_scan_parameters(cinfo);
  165034. per_scan_setup(cinfo);
  165035. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165036. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165037. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165038. master->pub.call_pass_startup = FALSE;
  165039. break;
  165040. }
  165041. /* Special case: Huffman DC refinement scans need no Huffman table
  165042. * and therefore we can skip the optimization pass for them.
  165043. */
  165044. master->pass_type = output_pass;
  165045. master->pass_number++;
  165046. /*FALLTHROUGH*/
  165047. #endif
  165048. case output_pass:
  165049. /* Do a data-output pass. */
  165050. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165051. if (! cinfo->optimize_coding) {
  165052. select_scan_parameters(cinfo);
  165053. per_scan_setup(cinfo);
  165054. }
  165055. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165056. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165057. /* We emit frame/scan headers now */
  165058. if (master->scan_number == 0)
  165059. (*cinfo->marker->write_frame_header) (cinfo);
  165060. (*cinfo->marker->write_scan_header) (cinfo);
  165061. master->pub.call_pass_startup = FALSE;
  165062. break;
  165063. default:
  165064. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165065. }
  165066. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165067. /* Set up progress monitor's pass info if present */
  165068. if (cinfo->progress != NULL) {
  165069. cinfo->progress->completed_passes = master->pass_number;
  165070. cinfo->progress->total_passes = master->total_passes;
  165071. }
  165072. }
  165073. /*
  165074. * Special start-of-pass hook.
  165075. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165076. * In single-pass processing, we need this hook because we don't want to
  165077. * write frame/scan headers during jpeg_start_compress; we want to let the
  165078. * application write COM markers etc. between jpeg_start_compress and the
  165079. * jpeg_write_scanlines loop.
  165080. * In multi-pass processing, this routine is not used.
  165081. */
  165082. METHODDEF(void)
  165083. pass_startup (j_compress_ptr cinfo)
  165084. {
  165085. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165086. (*cinfo->marker->write_frame_header) (cinfo);
  165087. (*cinfo->marker->write_scan_header) (cinfo);
  165088. }
  165089. /*
  165090. * Finish up at end of pass.
  165091. */
  165092. METHODDEF(void)
  165093. finish_pass_master (j_compress_ptr cinfo)
  165094. {
  165095. my_master_ptr master = (my_master_ptr) cinfo->master;
  165096. /* The entropy coder always needs an end-of-pass call,
  165097. * either to analyze statistics or to flush its output buffer.
  165098. */
  165099. (*cinfo->entropy->finish_pass) (cinfo);
  165100. /* Update state for next pass */
  165101. switch (master->pass_type) {
  165102. case main_pass:
  165103. /* next pass is either output of scan 0 (after optimization)
  165104. * or output of scan 1 (if no optimization).
  165105. */
  165106. master->pass_type = output_pass;
  165107. if (! cinfo->optimize_coding)
  165108. master->scan_number++;
  165109. break;
  165110. case huff_opt_pass:
  165111. /* next pass is always output of current scan */
  165112. master->pass_type = output_pass;
  165113. break;
  165114. case output_pass:
  165115. /* next pass is either optimization or output of next scan */
  165116. if (cinfo->optimize_coding)
  165117. master->pass_type = huff_opt_pass;
  165118. master->scan_number++;
  165119. break;
  165120. }
  165121. master->pass_number++;
  165122. }
  165123. /*
  165124. * Initialize master compression control.
  165125. */
  165126. GLOBAL(void)
  165127. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165128. {
  165129. my_master_ptr master;
  165130. master = (my_master_ptr)
  165131. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165132. SIZEOF(my_comp_master));
  165133. cinfo->master = (struct jpeg_comp_master *) master;
  165134. master->pub.prepare_for_pass = prepare_for_pass;
  165135. master->pub.pass_startup = pass_startup;
  165136. master->pub.finish_pass = finish_pass_master;
  165137. master->pub.is_last_pass = FALSE;
  165138. /* Validate parameters, determine derived values */
  165139. initial_setup(cinfo);
  165140. if (cinfo->scan_info != NULL) {
  165141. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165142. validate_script(cinfo);
  165143. #else
  165144. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165145. #endif
  165146. } else {
  165147. cinfo->progressive_mode = FALSE;
  165148. cinfo->num_scans = 1;
  165149. }
  165150. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165151. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165152. /* Initialize my private state */
  165153. if (transcode_only) {
  165154. /* no main pass in transcoding */
  165155. if (cinfo->optimize_coding)
  165156. master->pass_type = huff_opt_pass;
  165157. else
  165158. master->pass_type = output_pass;
  165159. } else {
  165160. /* for normal compression, first pass is always this type: */
  165161. master->pass_type = main_pass;
  165162. }
  165163. master->scan_number = 0;
  165164. master->pass_number = 0;
  165165. if (cinfo->optimize_coding)
  165166. master->total_passes = cinfo->num_scans * 2;
  165167. else
  165168. master->total_passes = cinfo->num_scans;
  165169. }
  165170. /*** End of inlined file: jcmaster.c ***/
  165171. /*** Start of inlined file: jcomapi.c ***/
  165172. #define JPEG_INTERNALS
  165173. /*
  165174. * Abort processing of a JPEG compression or decompression operation,
  165175. * but don't destroy the object itself.
  165176. *
  165177. * For this, we merely clean up all the nonpermanent memory pools.
  165178. * Note that temp files (virtual arrays) are not allowed to belong to
  165179. * the permanent pool, so we will be able to close all temp files here.
  165180. * Closing a data source or destination, if necessary, is the application's
  165181. * responsibility.
  165182. */
  165183. GLOBAL(void)
  165184. jpeg_abort (j_common_ptr cinfo)
  165185. {
  165186. int pool;
  165187. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165188. if (cinfo->mem == NULL)
  165189. return;
  165190. /* Releasing pools in reverse order might help avoid fragmentation
  165191. * with some (brain-damaged) malloc libraries.
  165192. */
  165193. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165194. (*cinfo->mem->free_pool) (cinfo, pool);
  165195. }
  165196. /* Reset overall state for possible reuse of object */
  165197. if (cinfo->is_decompressor) {
  165198. cinfo->global_state = DSTATE_START;
  165199. /* Try to keep application from accessing now-deleted marker list.
  165200. * A bit kludgy to do it here, but this is the most central place.
  165201. */
  165202. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165203. } else {
  165204. cinfo->global_state = CSTATE_START;
  165205. }
  165206. }
  165207. /*
  165208. * Destruction of a JPEG object.
  165209. *
  165210. * Everything gets deallocated except the master jpeg_compress_struct itself
  165211. * and the error manager struct. Both of these are supplied by the application
  165212. * and must be freed, if necessary, by the application. (Often they are on
  165213. * the stack and so don't need to be freed anyway.)
  165214. * Closing a data source or destination, if necessary, is the application's
  165215. * responsibility.
  165216. */
  165217. GLOBAL(void)
  165218. jpeg_destroy (j_common_ptr cinfo)
  165219. {
  165220. /* We need only tell the memory manager to release everything. */
  165221. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165222. if (cinfo->mem != NULL)
  165223. (*cinfo->mem->self_destruct) (cinfo);
  165224. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165225. cinfo->global_state = 0; /* mark it destroyed */
  165226. }
  165227. /*
  165228. * Convenience routines for allocating quantization and Huffman tables.
  165229. * (Would jutils.c be a more reasonable place to put these?)
  165230. */
  165231. GLOBAL(JQUANT_TBL *)
  165232. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165233. {
  165234. JQUANT_TBL *tbl;
  165235. tbl = (JQUANT_TBL *)
  165236. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165237. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165238. return tbl;
  165239. }
  165240. GLOBAL(JHUFF_TBL *)
  165241. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165242. {
  165243. JHUFF_TBL *tbl;
  165244. tbl = (JHUFF_TBL *)
  165245. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165246. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165247. return tbl;
  165248. }
  165249. /*** End of inlined file: jcomapi.c ***/
  165250. /*** Start of inlined file: jcparam.c ***/
  165251. #define JPEG_INTERNALS
  165252. /*
  165253. * Quantization table setup routines
  165254. */
  165255. GLOBAL(void)
  165256. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165257. const unsigned int *basic_table,
  165258. int scale_factor, boolean force_baseline)
  165259. /* Define a quantization table equal to the basic_table times
  165260. * a scale factor (given as a percentage).
  165261. * If force_baseline is TRUE, the computed quantization table entries
  165262. * are limited to 1..255 for JPEG baseline compatibility.
  165263. */
  165264. {
  165265. JQUANT_TBL ** qtblptr;
  165266. int i;
  165267. long temp;
  165268. /* Safety check to ensure start_compress not called yet. */
  165269. if (cinfo->global_state != CSTATE_START)
  165270. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165271. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165272. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165273. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165274. if (*qtblptr == NULL)
  165275. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165276. for (i = 0; i < DCTSIZE2; i++) {
  165277. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165278. /* limit the values to the valid range */
  165279. if (temp <= 0L) temp = 1L;
  165280. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165281. if (force_baseline && temp > 255L)
  165282. temp = 255L; /* limit to baseline range if requested */
  165283. (*qtblptr)->quantval[i] = (UINT16) temp;
  165284. }
  165285. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165286. (*qtblptr)->sent_table = FALSE;
  165287. }
  165288. GLOBAL(void)
  165289. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165290. boolean force_baseline)
  165291. /* Set or change the 'quality' (quantization) setting, using default tables
  165292. * and a straight percentage-scaling quality scale. In most cases it's better
  165293. * to use jpeg_set_quality (below); this entry point is provided for
  165294. * applications that insist on a linear percentage scaling.
  165295. */
  165296. {
  165297. /* These are the sample quantization tables given in JPEG spec section K.1.
  165298. * The spec says that the values given produce "good" quality, and
  165299. * when divided by 2, "very good" quality.
  165300. */
  165301. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165302. 16, 11, 10, 16, 24, 40, 51, 61,
  165303. 12, 12, 14, 19, 26, 58, 60, 55,
  165304. 14, 13, 16, 24, 40, 57, 69, 56,
  165305. 14, 17, 22, 29, 51, 87, 80, 62,
  165306. 18, 22, 37, 56, 68, 109, 103, 77,
  165307. 24, 35, 55, 64, 81, 104, 113, 92,
  165308. 49, 64, 78, 87, 103, 121, 120, 101,
  165309. 72, 92, 95, 98, 112, 100, 103, 99
  165310. };
  165311. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165312. 17, 18, 24, 47, 99, 99, 99, 99,
  165313. 18, 21, 26, 66, 99, 99, 99, 99,
  165314. 24, 26, 56, 99, 99, 99, 99, 99,
  165315. 47, 66, 99, 99, 99, 99, 99, 99,
  165316. 99, 99, 99, 99, 99, 99, 99, 99,
  165317. 99, 99, 99, 99, 99, 99, 99, 99,
  165318. 99, 99, 99, 99, 99, 99, 99, 99,
  165319. 99, 99, 99, 99, 99, 99, 99, 99
  165320. };
  165321. /* Set up two quantization tables using the specified scaling */
  165322. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165323. scale_factor, force_baseline);
  165324. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165325. scale_factor, force_baseline);
  165326. }
  165327. GLOBAL(int)
  165328. jpeg_quality_scaling (int quality)
  165329. /* Convert a user-specified quality rating to a percentage scaling factor
  165330. * for an underlying quantization table, using our recommended scaling curve.
  165331. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165332. */
  165333. {
  165334. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165335. if (quality <= 0) quality = 1;
  165336. if (quality > 100) quality = 100;
  165337. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165338. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165339. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165340. * to make all the table entries 1 (hence, minimum quantization loss).
  165341. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165342. */
  165343. if (quality < 50)
  165344. quality = 5000 / quality;
  165345. else
  165346. quality = 200 - quality*2;
  165347. return quality;
  165348. }
  165349. GLOBAL(void)
  165350. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165351. /* Set or change the 'quality' (quantization) setting, using default tables.
  165352. * This is the standard quality-adjusting entry point for typical user
  165353. * interfaces; only those who want detailed control over quantization tables
  165354. * would use the preceding three routines directly.
  165355. */
  165356. {
  165357. /* Convert user 0-100 rating to percentage scaling */
  165358. quality = jpeg_quality_scaling(quality);
  165359. /* Set up standard quality tables */
  165360. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165361. }
  165362. /*
  165363. * Huffman table setup routines
  165364. */
  165365. LOCAL(void)
  165366. add_huff_table (j_compress_ptr cinfo,
  165367. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165368. /* Define a Huffman table */
  165369. {
  165370. int nsymbols, len;
  165371. if (*htblptr == NULL)
  165372. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165373. /* Copy the number-of-symbols-of-each-code-length counts */
  165374. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165375. /* Validate the counts. We do this here mainly so we can copy the right
  165376. * number of symbols from the val[] array, without risking marching off
  165377. * the end of memory. jchuff.c will do a more thorough test later.
  165378. */
  165379. nsymbols = 0;
  165380. for (len = 1; len <= 16; len++)
  165381. nsymbols += bits[len];
  165382. if (nsymbols < 1 || nsymbols > 256)
  165383. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165384. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165385. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165386. (*htblptr)->sent_table = FALSE;
  165387. }
  165388. LOCAL(void)
  165389. std_huff_tables (j_compress_ptr cinfo)
  165390. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165391. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165392. {
  165393. static const UINT8 bits_dc_luminance[17] =
  165394. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165395. static const UINT8 val_dc_luminance[] =
  165396. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165397. static const UINT8 bits_dc_chrominance[17] =
  165398. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165399. static const UINT8 val_dc_chrominance[] =
  165400. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165401. static const UINT8 bits_ac_luminance[17] =
  165402. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165403. static const UINT8 val_ac_luminance[] =
  165404. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165405. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165406. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165407. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165408. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165409. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165410. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165411. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165412. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165413. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165414. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165415. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165416. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165417. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165418. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165419. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165420. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165421. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165422. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165423. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165424. 0xf9, 0xfa };
  165425. static const UINT8 bits_ac_chrominance[17] =
  165426. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165427. static const UINT8 val_ac_chrominance[] =
  165428. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165429. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165430. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165431. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165432. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165433. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165434. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165435. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165436. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165437. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165438. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165439. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165440. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165441. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165442. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165443. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165444. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165445. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165446. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165447. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165448. 0xf9, 0xfa };
  165449. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165450. bits_dc_luminance, val_dc_luminance);
  165451. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165452. bits_ac_luminance, val_ac_luminance);
  165453. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165454. bits_dc_chrominance, val_dc_chrominance);
  165455. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165456. bits_ac_chrominance, val_ac_chrominance);
  165457. }
  165458. /*
  165459. * Default parameter setup for compression.
  165460. *
  165461. * Applications that don't choose to use this routine must do their
  165462. * own setup of all these parameters. Alternately, you can call this
  165463. * to establish defaults and then alter parameters selectively. This
  165464. * is the recommended approach since, if we add any new parameters,
  165465. * your code will still work (they'll be set to reasonable defaults).
  165466. */
  165467. GLOBAL(void)
  165468. jpeg_set_defaults (j_compress_ptr cinfo)
  165469. {
  165470. int i;
  165471. /* Safety check to ensure start_compress not called yet. */
  165472. if (cinfo->global_state != CSTATE_START)
  165473. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165474. /* Allocate comp_info array large enough for maximum component count.
  165475. * Array is made permanent in case application wants to compress
  165476. * multiple images at same param settings.
  165477. */
  165478. if (cinfo->comp_info == NULL)
  165479. cinfo->comp_info = (jpeg_component_info *)
  165480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165481. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165482. /* Initialize everything not dependent on the color space */
  165483. cinfo->data_precision = BITS_IN_JSAMPLE;
  165484. /* Set up two quantization tables using default quality of 75 */
  165485. jpeg_set_quality(cinfo, 75, TRUE);
  165486. /* Set up two Huffman tables */
  165487. std_huff_tables(cinfo);
  165488. /* Initialize default arithmetic coding conditioning */
  165489. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165490. cinfo->arith_dc_L[i] = 0;
  165491. cinfo->arith_dc_U[i] = 1;
  165492. cinfo->arith_ac_K[i] = 5;
  165493. }
  165494. /* Default is no multiple-scan output */
  165495. cinfo->scan_info = NULL;
  165496. cinfo->num_scans = 0;
  165497. /* Expect normal source image, not raw downsampled data */
  165498. cinfo->raw_data_in = FALSE;
  165499. /* Use Huffman coding, not arithmetic coding, by default */
  165500. cinfo->arith_code = FALSE;
  165501. /* By default, don't do extra passes to optimize entropy coding */
  165502. cinfo->optimize_coding = FALSE;
  165503. /* The standard Huffman tables are only valid for 8-bit data precision.
  165504. * If the precision is higher, force optimization on so that usable
  165505. * tables will be computed. This test can be removed if default tables
  165506. * are supplied that are valid for the desired precision.
  165507. */
  165508. if (cinfo->data_precision > 8)
  165509. cinfo->optimize_coding = TRUE;
  165510. /* By default, use the simpler non-cosited sampling alignment */
  165511. cinfo->CCIR601_sampling = FALSE;
  165512. /* No input smoothing */
  165513. cinfo->smoothing_factor = 0;
  165514. /* DCT algorithm preference */
  165515. cinfo->dct_method = JDCT_DEFAULT;
  165516. /* No restart markers */
  165517. cinfo->restart_interval = 0;
  165518. cinfo->restart_in_rows = 0;
  165519. /* Fill in default JFIF marker parameters. Note that whether the marker
  165520. * will actually be written is determined by jpeg_set_colorspace.
  165521. *
  165522. * By default, the library emits JFIF version code 1.01.
  165523. * An application that wants to emit JFIF 1.02 extension markers should set
  165524. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165525. * to 1.02, but there may still be some decoders in use that will complain
  165526. * about that; saying 1.01 should minimize compatibility problems.
  165527. */
  165528. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165529. cinfo->JFIF_minor_version = 1;
  165530. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165531. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165532. cinfo->Y_density = 1;
  165533. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165534. jpeg_default_colorspace(cinfo);
  165535. }
  165536. /*
  165537. * Select an appropriate JPEG colorspace for in_color_space.
  165538. */
  165539. GLOBAL(void)
  165540. jpeg_default_colorspace (j_compress_ptr cinfo)
  165541. {
  165542. switch (cinfo->in_color_space) {
  165543. case JCS_GRAYSCALE:
  165544. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165545. break;
  165546. case JCS_RGB:
  165547. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165548. break;
  165549. case JCS_YCbCr:
  165550. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165551. break;
  165552. case JCS_CMYK:
  165553. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165554. break;
  165555. case JCS_YCCK:
  165556. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165557. break;
  165558. case JCS_UNKNOWN:
  165559. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165560. break;
  165561. default:
  165562. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165563. }
  165564. }
  165565. /*
  165566. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165567. */
  165568. GLOBAL(void)
  165569. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165570. {
  165571. jpeg_component_info * compptr;
  165572. int ci;
  165573. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165574. (compptr = &cinfo->comp_info[index], \
  165575. compptr->component_id = (id), \
  165576. compptr->h_samp_factor = (hsamp), \
  165577. compptr->v_samp_factor = (vsamp), \
  165578. compptr->quant_tbl_no = (quant), \
  165579. compptr->dc_tbl_no = (dctbl), \
  165580. compptr->ac_tbl_no = (actbl) )
  165581. /* Safety check to ensure start_compress not called yet. */
  165582. if (cinfo->global_state != CSTATE_START)
  165583. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165584. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165585. * tables 1 for chrominance components.
  165586. */
  165587. cinfo->jpeg_color_space = colorspace;
  165588. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165589. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165590. switch (colorspace) {
  165591. case JCS_GRAYSCALE:
  165592. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165593. cinfo->num_components = 1;
  165594. /* JFIF specifies component ID 1 */
  165595. SET_COMP(0, 1, 1,1, 0, 0,0);
  165596. break;
  165597. case JCS_RGB:
  165598. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165599. cinfo->num_components = 3;
  165600. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165601. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165602. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165603. break;
  165604. case JCS_YCbCr:
  165605. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165606. cinfo->num_components = 3;
  165607. /* JFIF specifies component IDs 1,2,3 */
  165608. /* We default to 2x2 subsamples of chrominance */
  165609. SET_COMP(0, 1, 2,2, 0, 0,0);
  165610. SET_COMP(1, 2, 1,1, 1, 1,1);
  165611. SET_COMP(2, 3, 1,1, 1, 1,1);
  165612. break;
  165613. case JCS_CMYK:
  165614. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165615. cinfo->num_components = 4;
  165616. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165617. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165618. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165619. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165620. break;
  165621. case JCS_YCCK:
  165622. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165623. cinfo->num_components = 4;
  165624. SET_COMP(0, 1, 2,2, 0, 0,0);
  165625. SET_COMP(1, 2, 1,1, 1, 1,1);
  165626. SET_COMP(2, 3, 1,1, 1, 1,1);
  165627. SET_COMP(3, 4, 2,2, 0, 0,0);
  165628. break;
  165629. case JCS_UNKNOWN:
  165630. cinfo->num_components = cinfo->input_components;
  165631. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165632. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165633. MAX_COMPONENTS);
  165634. for (ci = 0; ci < cinfo->num_components; ci++) {
  165635. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165636. }
  165637. break;
  165638. default:
  165639. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165640. }
  165641. }
  165642. #ifdef C_PROGRESSIVE_SUPPORTED
  165643. LOCAL(jpeg_scan_info *)
  165644. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165645. int Ss, int Se, int Ah, int Al)
  165646. /* Support routine: generate one scan for specified component */
  165647. {
  165648. scanptr->comps_in_scan = 1;
  165649. scanptr->component_index[0] = ci;
  165650. scanptr->Ss = Ss;
  165651. scanptr->Se = Se;
  165652. scanptr->Ah = Ah;
  165653. scanptr->Al = Al;
  165654. scanptr++;
  165655. return scanptr;
  165656. }
  165657. LOCAL(jpeg_scan_info *)
  165658. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165659. int Ss, int Se, int Ah, int Al)
  165660. /* Support routine: generate one scan for each component */
  165661. {
  165662. int ci;
  165663. for (ci = 0; ci < ncomps; ci++) {
  165664. scanptr->comps_in_scan = 1;
  165665. scanptr->component_index[0] = ci;
  165666. scanptr->Ss = Ss;
  165667. scanptr->Se = Se;
  165668. scanptr->Ah = Ah;
  165669. scanptr->Al = Al;
  165670. scanptr++;
  165671. }
  165672. return scanptr;
  165673. }
  165674. LOCAL(jpeg_scan_info *)
  165675. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165676. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165677. {
  165678. int ci;
  165679. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165680. /* Single interleaved DC scan */
  165681. scanptr->comps_in_scan = ncomps;
  165682. for (ci = 0; ci < ncomps; ci++)
  165683. scanptr->component_index[ci] = ci;
  165684. scanptr->Ss = scanptr->Se = 0;
  165685. scanptr->Ah = Ah;
  165686. scanptr->Al = Al;
  165687. scanptr++;
  165688. } else {
  165689. /* Noninterleaved DC scan for each component */
  165690. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165691. }
  165692. return scanptr;
  165693. }
  165694. /*
  165695. * Create a recommended progressive-JPEG script.
  165696. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165697. */
  165698. GLOBAL(void)
  165699. jpeg_simple_progression (j_compress_ptr cinfo)
  165700. {
  165701. int ncomps = cinfo->num_components;
  165702. int nscans;
  165703. jpeg_scan_info * scanptr;
  165704. /* Safety check to ensure start_compress not called yet. */
  165705. if (cinfo->global_state != CSTATE_START)
  165706. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165707. /* Figure space needed for script. Calculation must match code below! */
  165708. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165709. /* Custom script for YCbCr color images. */
  165710. nscans = 10;
  165711. } else {
  165712. /* All-purpose script for other color spaces. */
  165713. if (ncomps > MAX_COMPS_IN_SCAN)
  165714. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165715. else
  165716. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165717. }
  165718. /* Allocate space for script.
  165719. * We need to put it in the permanent pool in case the application performs
  165720. * multiple compressions without changing the settings. To avoid a memory
  165721. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165722. * object, we try to re-use previously allocated space, and we allocate
  165723. * enough space to handle YCbCr even if initially asked for grayscale.
  165724. */
  165725. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165726. cinfo->script_space_size = MAX(nscans, 10);
  165727. cinfo->script_space = (jpeg_scan_info *)
  165728. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165729. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165730. }
  165731. scanptr = cinfo->script_space;
  165732. cinfo->scan_info = scanptr;
  165733. cinfo->num_scans = nscans;
  165734. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165735. /* Custom script for YCbCr color images. */
  165736. /* Initial DC scan */
  165737. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165738. /* Initial AC scan: get some luma data out in a hurry */
  165739. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165740. /* Chroma data is too small to be worth expending many scans on */
  165741. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165742. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165743. /* Complete spectral selection for luma AC */
  165744. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165745. /* Refine next bit of luma AC */
  165746. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165747. /* Finish DC successive approximation */
  165748. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165749. /* Finish AC successive approximation */
  165750. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165751. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165752. /* Luma bottom bit comes last since it's usually largest scan */
  165753. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165754. } else {
  165755. /* All-purpose script for other color spaces. */
  165756. /* Successive approximation first pass */
  165757. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165758. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165759. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165760. /* Successive approximation second pass */
  165761. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165762. /* Successive approximation final pass */
  165763. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165764. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165765. }
  165766. }
  165767. #endif /* C_PROGRESSIVE_SUPPORTED */
  165768. /*** End of inlined file: jcparam.c ***/
  165769. /*** Start of inlined file: jcphuff.c ***/
  165770. #define JPEG_INTERNALS
  165771. #ifdef C_PROGRESSIVE_SUPPORTED
  165772. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165773. typedef struct {
  165774. struct jpeg_entropy_encoder pub; /* public fields */
  165775. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165776. boolean gather_statistics;
  165777. /* Bit-level coding status.
  165778. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165779. */
  165780. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165781. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165782. INT32 put_buffer; /* current bit-accumulation buffer */
  165783. int put_bits; /* # of bits now in it */
  165784. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165785. /* Coding status for DC components */
  165786. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165787. /* Coding status for AC components */
  165788. int ac_tbl_no; /* the table number of the single component */
  165789. unsigned int EOBRUN; /* run length of EOBs */
  165790. unsigned int BE; /* # of buffered correction bits before MCU */
  165791. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165792. /* packing correction bits tightly would save some space but cost time... */
  165793. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165794. int next_restart_num; /* next restart number to write (0-7) */
  165795. /* Pointers to derived tables (these workspaces have image lifespan).
  165796. * Since any one scan codes only DC or only AC, we only need one set
  165797. * of tables, not one for DC and one for AC.
  165798. */
  165799. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165800. /* Statistics tables for optimization; again, one set is enough */
  165801. long * count_ptrs[NUM_HUFF_TBLS];
  165802. } phuff_entropy_encoder;
  165803. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165804. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165805. * buffer can hold. Larger sizes may slightly improve compression, but
  165806. * 1000 is already well into the realm of overkill.
  165807. * The minimum safe size is 64 bits.
  165808. */
  165809. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165810. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165811. * We assume that int right shift is unsigned if INT32 right shift is,
  165812. * which should be safe.
  165813. */
  165814. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165815. #define ISHIFT_TEMPS int ishift_temp;
  165816. #define IRIGHT_SHIFT(x,shft) \
  165817. ((ishift_temp = (x)) < 0 ? \
  165818. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165819. (ishift_temp >> (shft)))
  165820. #else
  165821. #define ISHIFT_TEMPS
  165822. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165823. #endif
  165824. /* Forward declarations */
  165825. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165826. JBLOCKROW *MCU_data));
  165827. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165828. JBLOCKROW *MCU_data));
  165829. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165830. JBLOCKROW *MCU_data));
  165831. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165832. JBLOCKROW *MCU_data));
  165833. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165834. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165835. /*
  165836. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165837. */
  165838. METHODDEF(void)
  165839. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165840. {
  165841. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165842. boolean is_DC_band;
  165843. int ci, tbl;
  165844. jpeg_component_info * compptr;
  165845. entropy->cinfo = cinfo;
  165846. entropy->gather_statistics = gather_statistics;
  165847. is_DC_band = (cinfo->Ss == 0);
  165848. /* We assume jcmaster.c already validated the scan parameters. */
  165849. /* Select execution routines */
  165850. if (cinfo->Ah == 0) {
  165851. if (is_DC_band)
  165852. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165853. else
  165854. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165855. } else {
  165856. if (is_DC_band)
  165857. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165858. else {
  165859. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165860. /* AC refinement needs a correction bit buffer */
  165861. if (entropy->bit_buffer == NULL)
  165862. entropy->bit_buffer = (char *)
  165863. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165864. MAX_CORR_BITS * SIZEOF(char));
  165865. }
  165866. }
  165867. if (gather_statistics)
  165868. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165869. else
  165870. entropy->pub.finish_pass = finish_pass_phuff;
  165871. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165872. * for AC coefficients.
  165873. */
  165874. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165875. compptr = cinfo->cur_comp_info[ci];
  165876. /* Initialize DC predictions to 0 */
  165877. entropy->last_dc_val[ci] = 0;
  165878. /* Get table index */
  165879. if (is_DC_band) {
  165880. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165881. continue;
  165882. tbl = compptr->dc_tbl_no;
  165883. } else {
  165884. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165885. }
  165886. if (gather_statistics) {
  165887. /* Check for invalid table index */
  165888. /* (make_c_derived_tbl does this in the other path) */
  165889. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165890. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165891. /* Allocate and zero the statistics tables */
  165892. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165893. if (entropy->count_ptrs[tbl] == NULL)
  165894. entropy->count_ptrs[tbl] = (long *)
  165895. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165896. 257 * SIZEOF(long));
  165897. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165898. } else {
  165899. /* Compute derived values for Huffman table */
  165900. /* We may do this more than once for a table, but it's not expensive */
  165901. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165902. & entropy->derived_tbls[tbl]);
  165903. }
  165904. }
  165905. /* Initialize AC stuff */
  165906. entropy->EOBRUN = 0;
  165907. entropy->BE = 0;
  165908. /* Initialize bit buffer to empty */
  165909. entropy->put_buffer = 0;
  165910. entropy->put_bits = 0;
  165911. /* Initialize restart stuff */
  165912. entropy->restarts_to_go = cinfo->restart_interval;
  165913. entropy->next_restart_num = 0;
  165914. }
  165915. /* Outputting bytes to the file.
  165916. * NB: these must be called only when actually outputting,
  165917. * that is, entropy->gather_statistics == FALSE.
  165918. */
  165919. /* Emit a byte */
  165920. #define emit_byte(entropy,val) \
  165921. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165922. if (--(entropy)->free_in_buffer == 0) \
  165923. dump_buffer_p(entropy); }
  165924. LOCAL(void)
  165925. dump_buffer_p (phuff_entropy_ptr entropy)
  165926. /* Empty the output buffer; we do not support suspension in this module. */
  165927. {
  165928. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165929. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165930. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165931. /* After a successful buffer dump, must reset buffer pointers */
  165932. entropy->next_output_byte = dest->next_output_byte;
  165933. entropy->free_in_buffer = dest->free_in_buffer;
  165934. }
  165935. /* Outputting bits to the file */
  165936. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165937. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165938. * in one call, and we never retain more than 7 bits in put_buffer
  165939. * between calls, so 24 bits are sufficient.
  165940. */
  165941. INLINE
  165942. LOCAL(void)
  165943. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165944. /* Emit some bits, unless we are in gather mode */
  165945. {
  165946. /* This routine is heavily used, so it's worth coding tightly. */
  165947. register INT32 put_buffer = (INT32) code;
  165948. register int put_bits = entropy->put_bits;
  165949. /* if size is 0, caller used an invalid Huffman table entry */
  165950. if (size == 0)
  165951. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165952. if (entropy->gather_statistics)
  165953. return; /* do nothing if we're only getting stats */
  165954. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165955. put_bits += size; /* new number of bits in buffer */
  165956. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165957. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165958. while (put_bits >= 8) {
  165959. int c = (int) ((put_buffer >> 16) & 0xFF);
  165960. emit_byte(entropy, c);
  165961. if (c == 0xFF) { /* need to stuff a zero byte? */
  165962. emit_byte(entropy, 0);
  165963. }
  165964. put_buffer <<= 8;
  165965. put_bits -= 8;
  165966. }
  165967. entropy->put_buffer = put_buffer; /* update variables */
  165968. entropy->put_bits = put_bits;
  165969. }
  165970. LOCAL(void)
  165971. flush_bits_p (phuff_entropy_ptr entropy)
  165972. {
  165973. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165974. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165975. entropy->put_bits = 0;
  165976. }
  165977. /*
  165978. * Emit (or just count) a Huffman symbol.
  165979. */
  165980. INLINE
  165981. LOCAL(void)
  165982. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165983. {
  165984. if (entropy->gather_statistics)
  165985. entropy->count_ptrs[tbl_no][symbol]++;
  165986. else {
  165987. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165988. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165989. }
  165990. }
  165991. /*
  165992. * Emit bits from a correction bit buffer.
  165993. */
  165994. LOCAL(void)
  165995. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165996. unsigned int nbits)
  165997. {
  165998. if (entropy->gather_statistics)
  165999. return; /* no real work */
  166000. while (nbits > 0) {
  166001. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166002. bufstart++;
  166003. nbits--;
  166004. }
  166005. }
  166006. /*
  166007. * Emit any pending EOBRUN symbol.
  166008. */
  166009. LOCAL(void)
  166010. emit_eobrun (phuff_entropy_ptr entropy)
  166011. {
  166012. register int temp, nbits;
  166013. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166014. temp = entropy->EOBRUN;
  166015. nbits = 0;
  166016. while ((temp >>= 1))
  166017. nbits++;
  166018. /* safety check: shouldn't happen given limited correction-bit buffer */
  166019. if (nbits > 14)
  166020. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166021. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166022. if (nbits)
  166023. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166024. entropy->EOBRUN = 0;
  166025. /* Emit any buffered correction bits */
  166026. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166027. entropy->BE = 0;
  166028. }
  166029. }
  166030. /*
  166031. * Emit a restart marker & resynchronize predictions.
  166032. */
  166033. LOCAL(void)
  166034. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166035. {
  166036. int ci;
  166037. emit_eobrun(entropy);
  166038. if (! entropy->gather_statistics) {
  166039. flush_bits_p(entropy);
  166040. emit_byte(entropy, 0xFF);
  166041. emit_byte(entropy, JPEG_RST0 + restart_num);
  166042. }
  166043. if (entropy->cinfo->Ss == 0) {
  166044. /* Re-initialize DC predictions to 0 */
  166045. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166046. entropy->last_dc_val[ci] = 0;
  166047. } else {
  166048. /* Re-initialize all AC-related fields to 0 */
  166049. entropy->EOBRUN = 0;
  166050. entropy->BE = 0;
  166051. }
  166052. }
  166053. /*
  166054. * MCU encoding for DC initial scan (either spectral selection,
  166055. * or first pass of successive approximation).
  166056. */
  166057. METHODDEF(boolean)
  166058. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166059. {
  166060. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166061. register int temp, temp2;
  166062. register int nbits;
  166063. int blkn, ci;
  166064. int Al = cinfo->Al;
  166065. JBLOCKROW block;
  166066. jpeg_component_info * compptr;
  166067. ISHIFT_TEMPS
  166068. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166069. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166070. /* Emit restart marker if needed */
  166071. if (cinfo->restart_interval)
  166072. if (entropy->restarts_to_go == 0)
  166073. emit_restart_p(entropy, entropy->next_restart_num);
  166074. /* Encode the MCU data blocks */
  166075. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166076. block = MCU_data[blkn];
  166077. ci = cinfo->MCU_membership[blkn];
  166078. compptr = cinfo->cur_comp_info[ci];
  166079. /* Compute the DC value after the required point transform by Al.
  166080. * This is simply an arithmetic right shift.
  166081. */
  166082. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166083. /* DC differences are figured on the point-transformed values. */
  166084. temp = temp2 - entropy->last_dc_val[ci];
  166085. entropy->last_dc_val[ci] = temp2;
  166086. /* Encode the DC coefficient difference per section G.1.2.1 */
  166087. temp2 = temp;
  166088. if (temp < 0) {
  166089. temp = -temp; /* temp is abs value of input */
  166090. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166091. /* This code assumes we are on a two's complement machine */
  166092. temp2--;
  166093. }
  166094. /* Find the number of bits needed for the magnitude of the coefficient */
  166095. nbits = 0;
  166096. while (temp) {
  166097. nbits++;
  166098. temp >>= 1;
  166099. }
  166100. /* Check for out-of-range coefficient values.
  166101. * Since we're encoding a difference, the range limit is twice as much.
  166102. */
  166103. if (nbits > MAX_COEF_BITS+1)
  166104. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166105. /* Count/emit the Huffman-coded symbol for the number of bits */
  166106. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166107. /* Emit that number of bits of the value, if positive, */
  166108. /* or the complement of its magnitude, if negative. */
  166109. if (nbits) /* emit_bits rejects calls with size 0 */
  166110. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166111. }
  166112. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166113. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166114. /* Update restart-interval state too */
  166115. if (cinfo->restart_interval) {
  166116. if (entropy->restarts_to_go == 0) {
  166117. entropy->restarts_to_go = cinfo->restart_interval;
  166118. entropy->next_restart_num++;
  166119. entropy->next_restart_num &= 7;
  166120. }
  166121. entropy->restarts_to_go--;
  166122. }
  166123. return TRUE;
  166124. }
  166125. /*
  166126. * MCU encoding for AC initial scan (either spectral selection,
  166127. * or first pass of successive approximation).
  166128. */
  166129. METHODDEF(boolean)
  166130. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166131. {
  166132. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166133. register int temp, temp2;
  166134. register int nbits;
  166135. register int r, k;
  166136. int Se = cinfo->Se;
  166137. int Al = cinfo->Al;
  166138. JBLOCKROW block;
  166139. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166140. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166141. /* Emit restart marker if needed */
  166142. if (cinfo->restart_interval)
  166143. if (entropy->restarts_to_go == 0)
  166144. emit_restart_p(entropy, entropy->next_restart_num);
  166145. /* Encode the MCU data block */
  166146. block = MCU_data[0];
  166147. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166148. r = 0; /* r = run length of zeros */
  166149. for (k = cinfo->Ss; k <= Se; k++) {
  166150. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166151. r++;
  166152. continue;
  166153. }
  166154. /* We must apply the point transform by Al. For AC coefficients this
  166155. * is an integer division with rounding towards 0. To do this portably
  166156. * in C, we shift after obtaining the absolute value; so the code is
  166157. * interwoven with finding the abs value (temp) and output bits (temp2).
  166158. */
  166159. if (temp < 0) {
  166160. temp = -temp; /* temp is abs value of input */
  166161. temp >>= Al; /* apply the point transform */
  166162. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166163. temp2 = ~temp;
  166164. } else {
  166165. temp >>= Al; /* apply the point transform */
  166166. temp2 = temp;
  166167. }
  166168. /* Watch out for case that nonzero coef is zero after point transform */
  166169. if (temp == 0) {
  166170. r++;
  166171. continue;
  166172. }
  166173. /* Emit any pending EOBRUN */
  166174. if (entropy->EOBRUN > 0)
  166175. emit_eobrun(entropy);
  166176. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166177. while (r > 15) {
  166178. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166179. r -= 16;
  166180. }
  166181. /* Find the number of bits needed for the magnitude of the coefficient */
  166182. nbits = 1; /* there must be at least one 1 bit */
  166183. while ((temp >>= 1))
  166184. nbits++;
  166185. /* Check for out-of-range coefficient values */
  166186. if (nbits > MAX_COEF_BITS)
  166187. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166188. /* Count/emit Huffman symbol for run length / number of bits */
  166189. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166190. /* Emit that number of bits of the value, if positive, */
  166191. /* or the complement of its magnitude, if negative. */
  166192. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166193. r = 0; /* reset zero run length */
  166194. }
  166195. if (r > 0) { /* If there are trailing zeroes, */
  166196. entropy->EOBRUN++; /* count an EOB */
  166197. if (entropy->EOBRUN == 0x7FFF)
  166198. emit_eobrun(entropy); /* force it out to avoid overflow */
  166199. }
  166200. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166201. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166202. /* Update restart-interval state too */
  166203. if (cinfo->restart_interval) {
  166204. if (entropy->restarts_to_go == 0) {
  166205. entropy->restarts_to_go = cinfo->restart_interval;
  166206. entropy->next_restart_num++;
  166207. entropy->next_restart_num &= 7;
  166208. }
  166209. entropy->restarts_to_go--;
  166210. }
  166211. return TRUE;
  166212. }
  166213. /*
  166214. * MCU encoding for DC successive approximation refinement scan.
  166215. * Note: we assume such scans can be multi-component, although the spec
  166216. * is not very clear on the point.
  166217. */
  166218. METHODDEF(boolean)
  166219. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166220. {
  166221. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166222. register int temp;
  166223. int blkn;
  166224. int Al = cinfo->Al;
  166225. JBLOCKROW block;
  166226. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166227. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166228. /* Emit restart marker if needed */
  166229. if (cinfo->restart_interval)
  166230. if (entropy->restarts_to_go == 0)
  166231. emit_restart_p(entropy, entropy->next_restart_num);
  166232. /* Encode the MCU data blocks */
  166233. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166234. block = MCU_data[blkn];
  166235. /* We simply emit the Al'th bit of the DC coefficient value. */
  166236. temp = (*block)[0];
  166237. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166238. }
  166239. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166240. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166241. /* Update restart-interval state too */
  166242. if (cinfo->restart_interval) {
  166243. if (entropy->restarts_to_go == 0) {
  166244. entropy->restarts_to_go = cinfo->restart_interval;
  166245. entropy->next_restart_num++;
  166246. entropy->next_restart_num &= 7;
  166247. }
  166248. entropy->restarts_to_go--;
  166249. }
  166250. return TRUE;
  166251. }
  166252. /*
  166253. * MCU encoding for AC successive approximation refinement scan.
  166254. */
  166255. METHODDEF(boolean)
  166256. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166257. {
  166258. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166259. register int temp;
  166260. register int r, k;
  166261. int EOB;
  166262. char *BR_buffer;
  166263. unsigned int BR;
  166264. int Se = cinfo->Se;
  166265. int Al = cinfo->Al;
  166266. JBLOCKROW block;
  166267. int absvalues[DCTSIZE2];
  166268. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166269. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166270. /* Emit restart marker if needed */
  166271. if (cinfo->restart_interval)
  166272. if (entropy->restarts_to_go == 0)
  166273. emit_restart_p(entropy, entropy->next_restart_num);
  166274. /* Encode the MCU data block */
  166275. block = MCU_data[0];
  166276. /* It is convenient to make a pre-pass to determine the transformed
  166277. * coefficients' absolute values and the EOB position.
  166278. */
  166279. EOB = 0;
  166280. for (k = cinfo->Ss; k <= Se; k++) {
  166281. temp = (*block)[jpeg_natural_order[k]];
  166282. /* We must apply the point transform by Al. For AC coefficients this
  166283. * is an integer division with rounding towards 0. To do this portably
  166284. * in C, we shift after obtaining the absolute value.
  166285. */
  166286. if (temp < 0)
  166287. temp = -temp; /* temp is abs value of input */
  166288. temp >>= Al; /* apply the point transform */
  166289. absvalues[k] = temp; /* save abs value for main pass */
  166290. if (temp == 1)
  166291. EOB = k; /* EOB = index of last newly-nonzero coef */
  166292. }
  166293. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166294. r = 0; /* r = run length of zeros */
  166295. BR = 0; /* BR = count of buffered bits added now */
  166296. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166297. for (k = cinfo->Ss; k <= Se; k++) {
  166298. if ((temp = absvalues[k]) == 0) {
  166299. r++;
  166300. continue;
  166301. }
  166302. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166303. while (r > 15 && k <= EOB) {
  166304. /* emit any pending EOBRUN and the BE correction bits */
  166305. emit_eobrun(entropy);
  166306. /* Emit ZRL */
  166307. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166308. r -= 16;
  166309. /* Emit buffered correction bits that must be associated with ZRL */
  166310. emit_buffered_bits(entropy, BR_buffer, BR);
  166311. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166312. BR = 0;
  166313. }
  166314. /* If the coef was previously nonzero, it only needs a correction bit.
  166315. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166316. * that we also need to test r > 15. But if r > 15, we can only get here
  166317. * if k > EOB, which implies that this coefficient is not 1.
  166318. */
  166319. if (temp > 1) {
  166320. /* The correction bit is the next bit of the absolute value. */
  166321. BR_buffer[BR++] = (char) (temp & 1);
  166322. continue;
  166323. }
  166324. /* Emit any pending EOBRUN and the BE correction bits */
  166325. emit_eobrun(entropy);
  166326. /* Count/emit Huffman symbol for run length / number of bits */
  166327. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166328. /* Emit output bit for newly-nonzero coef */
  166329. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166330. emit_bits_p(entropy, (unsigned int) temp, 1);
  166331. /* Emit buffered correction bits that must be associated with this code */
  166332. emit_buffered_bits(entropy, BR_buffer, BR);
  166333. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166334. BR = 0;
  166335. r = 0; /* reset zero run length */
  166336. }
  166337. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166338. entropy->EOBRUN++; /* count an EOB */
  166339. entropy->BE += BR; /* concat my correction bits to older ones */
  166340. /* We force out the EOB if we risk either:
  166341. * 1. overflow of the EOB counter;
  166342. * 2. overflow of the correction bit buffer during the next MCU.
  166343. */
  166344. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166345. emit_eobrun(entropy);
  166346. }
  166347. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166348. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166349. /* Update restart-interval state too */
  166350. if (cinfo->restart_interval) {
  166351. if (entropy->restarts_to_go == 0) {
  166352. entropy->restarts_to_go = cinfo->restart_interval;
  166353. entropy->next_restart_num++;
  166354. entropy->next_restart_num &= 7;
  166355. }
  166356. entropy->restarts_to_go--;
  166357. }
  166358. return TRUE;
  166359. }
  166360. /*
  166361. * Finish up at the end of a Huffman-compressed progressive scan.
  166362. */
  166363. METHODDEF(void)
  166364. finish_pass_phuff (j_compress_ptr cinfo)
  166365. {
  166366. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166367. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166368. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166369. /* Flush out any buffered data */
  166370. emit_eobrun(entropy);
  166371. flush_bits_p(entropy);
  166372. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166373. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166374. }
  166375. /*
  166376. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166377. */
  166378. METHODDEF(void)
  166379. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166380. {
  166381. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166382. boolean is_DC_band;
  166383. int ci, tbl;
  166384. jpeg_component_info * compptr;
  166385. JHUFF_TBL **htblptr;
  166386. boolean did[NUM_HUFF_TBLS];
  166387. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166388. emit_eobrun(entropy);
  166389. is_DC_band = (cinfo->Ss == 0);
  166390. /* It's important not to apply jpeg_gen_optimal_table more than once
  166391. * per table, because it clobbers the input frequency counts!
  166392. */
  166393. MEMZERO(did, SIZEOF(did));
  166394. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166395. compptr = cinfo->cur_comp_info[ci];
  166396. if (is_DC_band) {
  166397. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166398. continue;
  166399. tbl = compptr->dc_tbl_no;
  166400. } else {
  166401. tbl = compptr->ac_tbl_no;
  166402. }
  166403. if (! did[tbl]) {
  166404. if (is_DC_band)
  166405. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166406. else
  166407. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166408. if (*htblptr == NULL)
  166409. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166410. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166411. did[tbl] = TRUE;
  166412. }
  166413. }
  166414. }
  166415. /*
  166416. * Module initialization routine for progressive Huffman entropy encoding.
  166417. */
  166418. GLOBAL(void)
  166419. jinit_phuff_encoder (j_compress_ptr cinfo)
  166420. {
  166421. phuff_entropy_ptr entropy;
  166422. int i;
  166423. entropy = (phuff_entropy_ptr)
  166424. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166425. SIZEOF(phuff_entropy_encoder));
  166426. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166427. entropy->pub.start_pass = start_pass_phuff;
  166428. /* Mark tables unallocated */
  166429. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166430. entropy->derived_tbls[i] = NULL;
  166431. entropy->count_ptrs[i] = NULL;
  166432. }
  166433. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166434. }
  166435. #endif /* C_PROGRESSIVE_SUPPORTED */
  166436. /*** End of inlined file: jcphuff.c ***/
  166437. /*** Start of inlined file: jcprepct.c ***/
  166438. #define JPEG_INTERNALS
  166439. /* At present, jcsample.c can request context rows only for smoothing.
  166440. * In the future, we might also need context rows for CCIR601 sampling
  166441. * or other more-complex downsampling procedures. The code to support
  166442. * context rows should be compiled only if needed.
  166443. */
  166444. #ifdef INPUT_SMOOTHING_SUPPORTED
  166445. #define CONTEXT_ROWS_SUPPORTED
  166446. #endif
  166447. /*
  166448. * For the simple (no-context-row) case, we just need to buffer one
  166449. * row group's worth of pixels for the downsampling step. At the bottom of
  166450. * the image, we pad to a full row group by replicating the last pixel row.
  166451. * The downsampler's last output row is then replicated if needed to pad
  166452. * out to a full iMCU row.
  166453. *
  166454. * When providing context rows, we must buffer three row groups' worth of
  166455. * pixels. Three row groups are physically allocated, but the row pointer
  166456. * arrays are made five row groups high, with the extra pointers above and
  166457. * below "wrapping around" to point to the last and first real row groups.
  166458. * This allows the downsampler to access the proper context rows.
  166459. * At the top and bottom of the image, we create dummy context rows by
  166460. * copying the first or last real pixel row. This copying could be avoided
  166461. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166462. * trouble on the compression side.
  166463. */
  166464. /* Private buffer controller object */
  166465. typedef struct {
  166466. struct jpeg_c_prep_controller pub; /* public fields */
  166467. /* Downsampling input buffer. This buffer holds color-converted data
  166468. * until we have enough to do a downsample step.
  166469. */
  166470. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166471. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166472. int next_buf_row; /* index of next row to store in color_buf */
  166473. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166474. int this_row_group; /* starting row index of group to process */
  166475. int next_buf_stop; /* downsample when we reach this index */
  166476. #endif
  166477. } my_prep_controller;
  166478. typedef my_prep_controller * my_prep_ptr;
  166479. /*
  166480. * Initialize for a processing pass.
  166481. */
  166482. METHODDEF(void)
  166483. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166484. {
  166485. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166486. if (pass_mode != JBUF_PASS_THRU)
  166487. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166488. /* Initialize total-height counter for detecting bottom of image */
  166489. prep->rows_to_go = cinfo->image_height;
  166490. /* Mark the conversion buffer empty */
  166491. prep->next_buf_row = 0;
  166492. #ifdef CONTEXT_ROWS_SUPPORTED
  166493. /* Preset additional state variables for context mode.
  166494. * These aren't used in non-context mode, so we needn't test which mode.
  166495. */
  166496. prep->this_row_group = 0;
  166497. /* Set next_buf_stop to stop after two row groups have been read in. */
  166498. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166499. #endif
  166500. }
  166501. /*
  166502. * Expand an image vertically from height input_rows to height output_rows,
  166503. * by duplicating the bottom row.
  166504. */
  166505. LOCAL(void)
  166506. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166507. int input_rows, int output_rows)
  166508. {
  166509. register int row;
  166510. for (row = input_rows; row < output_rows; row++) {
  166511. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166512. 1, num_cols);
  166513. }
  166514. }
  166515. /*
  166516. * Process some data in the simple no-context case.
  166517. *
  166518. * Preprocessor output data is counted in "row groups". A row group
  166519. * is defined to be v_samp_factor sample rows of each component.
  166520. * Downsampling will produce this much data from each max_v_samp_factor
  166521. * input rows.
  166522. */
  166523. METHODDEF(void)
  166524. pre_process_data (j_compress_ptr cinfo,
  166525. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166526. JDIMENSION in_rows_avail,
  166527. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166528. JDIMENSION out_row_groups_avail)
  166529. {
  166530. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166531. int numrows, ci;
  166532. JDIMENSION inrows;
  166533. jpeg_component_info * compptr;
  166534. while (*in_row_ctr < in_rows_avail &&
  166535. *out_row_group_ctr < out_row_groups_avail) {
  166536. /* Do color conversion to fill the conversion buffer. */
  166537. inrows = in_rows_avail - *in_row_ctr;
  166538. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166539. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166540. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166541. prep->color_buf,
  166542. (JDIMENSION) prep->next_buf_row,
  166543. numrows);
  166544. *in_row_ctr += numrows;
  166545. prep->next_buf_row += numrows;
  166546. prep->rows_to_go -= numrows;
  166547. /* If at bottom of image, pad to fill the conversion buffer. */
  166548. if (prep->rows_to_go == 0 &&
  166549. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166550. for (ci = 0; ci < cinfo->num_components; ci++) {
  166551. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166552. prep->next_buf_row, cinfo->max_v_samp_factor);
  166553. }
  166554. prep->next_buf_row = cinfo->max_v_samp_factor;
  166555. }
  166556. /* If we've filled the conversion buffer, empty it. */
  166557. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166558. (*cinfo->downsample->downsample) (cinfo,
  166559. prep->color_buf, (JDIMENSION) 0,
  166560. output_buf, *out_row_group_ctr);
  166561. prep->next_buf_row = 0;
  166562. (*out_row_group_ctr)++;
  166563. }
  166564. /* If at bottom of image, pad the output to a full iMCU height.
  166565. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166566. */
  166567. if (prep->rows_to_go == 0 &&
  166568. *out_row_group_ctr < out_row_groups_avail) {
  166569. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166570. ci++, compptr++) {
  166571. expand_bottom_edge(output_buf[ci],
  166572. compptr->width_in_blocks * DCTSIZE,
  166573. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166574. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166575. }
  166576. *out_row_group_ctr = out_row_groups_avail;
  166577. break; /* can exit outer loop without test */
  166578. }
  166579. }
  166580. }
  166581. #ifdef CONTEXT_ROWS_SUPPORTED
  166582. /*
  166583. * Process some data in the context case.
  166584. */
  166585. METHODDEF(void)
  166586. pre_process_context (j_compress_ptr cinfo,
  166587. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166588. JDIMENSION in_rows_avail,
  166589. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166590. JDIMENSION out_row_groups_avail)
  166591. {
  166592. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166593. int numrows, ci;
  166594. int buf_height = cinfo->max_v_samp_factor * 3;
  166595. JDIMENSION inrows;
  166596. while (*out_row_group_ctr < out_row_groups_avail) {
  166597. if (*in_row_ctr < in_rows_avail) {
  166598. /* Do color conversion to fill the conversion buffer. */
  166599. inrows = in_rows_avail - *in_row_ctr;
  166600. numrows = prep->next_buf_stop - prep->next_buf_row;
  166601. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166602. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166603. prep->color_buf,
  166604. (JDIMENSION) prep->next_buf_row,
  166605. numrows);
  166606. /* Pad at top of image, if first time through */
  166607. if (prep->rows_to_go == cinfo->image_height) {
  166608. for (ci = 0; ci < cinfo->num_components; ci++) {
  166609. int row;
  166610. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166611. jcopy_sample_rows(prep->color_buf[ci], 0,
  166612. prep->color_buf[ci], -row,
  166613. 1, cinfo->image_width);
  166614. }
  166615. }
  166616. }
  166617. *in_row_ctr += numrows;
  166618. prep->next_buf_row += numrows;
  166619. prep->rows_to_go -= numrows;
  166620. } else {
  166621. /* Return for more data, unless we are at the bottom of the image. */
  166622. if (prep->rows_to_go != 0)
  166623. break;
  166624. /* When at bottom of image, pad to fill the conversion buffer. */
  166625. if (prep->next_buf_row < prep->next_buf_stop) {
  166626. for (ci = 0; ci < cinfo->num_components; ci++) {
  166627. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166628. prep->next_buf_row, prep->next_buf_stop);
  166629. }
  166630. prep->next_buf_row = prep->next_buf_stop;
  166631. }
  166632. }
  166633. /* If we've gotten enough data, downsample a row group. */
  166634. if (prep->next_buf_row == prep->next_buf_stop) {
  166635. (*cinfo->downsample->downsample) (cinfo,
  166636. prep->color_buf,
  166637. (JDIMENSION) prep->this_row_group,
  166638. output_buf, *out_row_group_ctr);
  166639. (*out_row_group_ctr)++;
  166640. /* Advance pointers with wraparound as necessary. */
  166641. prep->this_row_group += cinfo->max_v_samp_factor;
  166642. if (prep->this_row_group >= buf_height)
  166643. prep->this_row_group = 0;
  166644. if (prep->next_buf_row >= buf_height)
  166645. prep->next_buf_row = 0;
  166646. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166647. }
  166648. }
  166649. }
  166650. /*
  166651. * Create the wrapped-around downsampling input buffer needed for context mode.
  166652. */
  166653. LOCAL(void)
  166654. create_context_buffer (j_compress_ptr cinfo)
  166655. {
  166656. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166657. int rgroup_height = cinfo->max_v_samp_factor;
  166658. int ci, i;
  166659. jpeg_component_info * compptr;
  166660. JSAMPARRAY true_buffer, fake_buffer;
  166661. /* Grab enough space for fake row pointers for all the components;
  166662. * we need five row groups' worth of pointers for each component.
  166663. */
  166664. fake_buffer = (JSAMPARRAY)
  166665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166666. (cinfo->num_components * 5 * rgroup_height) *
  166667. SIZEOF(JSAMPROW));
  166668. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166669. ci++, compptr++) {
  166670. /* Allocate the actual buffer space (3 row groups) for this component.
  166671. * We make the buffer wide enough to allow the downsampler to edge-expand
  166672. * horizontally within the buffer, if it so chooses.
  166673. */
  166674. true_buffer = (*cinfo->mem->alloc_sarray)
  166675. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166676. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166677. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166678. (JDIMENSION) (3 * rgroup_height));
  166679. /* Copy true buffer row pointers into the middle of the fake row array */
  166680. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166681. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166682. /* Fill in the above and below wraparound pointers */
  166683. for (i = 0; i < rgroup_height; i++) {
  166684. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166685. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166686. }
  166687. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166688. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166689. }
  166690. }
  166691. #endif /* CONTEXT_ROWS_SUPPORTED */
  166692. /*
  166693. * Initialize preprocessing controller.
  166694. */
  166695. GLOBAL(void)
  166696. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166697. {
  166698. my_prep_ptr prep;
  166699. int ci;
  166700. jpeg_component_info * compptr;
  166701. if (need_full_buffer) /* safety check */
  166702. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166703. prep = (my_prep_ptr)
  166704. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166705. SIZEOF(my_prep_controller));
  166706. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166707. prep->pub.start_pass = start_pass_prep;
  166708. /* Allocate the color conversion buffer.
  166709. * We make the buffer wide enough to allow the downsampler to edge-expand
  166710. * horizontally within the buffer, if it so chooses.
  166711. */
  166712. if (cinfo->downsample->need_context_rows) {
  166713. /* Set up to provide context rows */
  166714. #ifdef CONTEXT_ROWS_SUPPORTED
  166715. prep->pub.pre_process_data = pre_process_context;
  166716. create_context_buffer(cinfo);
  166717. #else
  166718. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166719. #endif
  166720. } else {
  166721. /* No context, just make it tall enough for one row group */
  166722. prep->pub.pre_process_data = pre_process_data;
  166723. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166724. ci++, compptr++) {
  166725. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166726. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166727. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166728. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166729. (JDIMENSION) cinfo->max_v_samp_factor);
  166730. }
  166731. }
  166732. }
  166733. /*** End of inlined file: jcprepct.c ***/
  166734. /*** Start of inlined file: jcsample.c ***/
  166735. #define JPEG_INTERNALS
  166736. /* Pointer to routine to downsample a single component */
  166737. typedef JMETHOD(void, downsample1_ptr,
  166738. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166739. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166740. /* Private subobject */
  166741. typedef struct {
  166742. struct jpeg_downsampler pub; /* public fields */
  166743. /* Downsampling method pointers, one per component */
  166744. downsample1_ptr methods[MAX_COMPONENTS];
  166745. } my_downsampler;
  166746. typedef my_downsampler * my_downsample_ptr;
  166747. /*
  166748. * Initialize for a downsampling pass.
  166749. */
  166750. METHODDEF(void)
  166751. start_pass_downsample (j_compress_ptr)
  166752. {
  166753. /* no work for now */
  166754. }
  166755. /*
  166756. * Expand a component horizontally from width input_cols to width output_cols,
  166757. * by duplicating the rightmost samples.
  166758. */
  166759. LOCAL(void)
  166760. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166761. JDIMENSION input_cols, JDIMENSION output_cols)
  166762. {
  166763. register JSAMPROW ptr;
  166764. register JSAMPLE pixval;
  166765. register int count;
  166766. int row;
  166767. int numcols = (int) (output_cols - input_cols);
  166768. if (numcols > 0) {
  166769. for (row = 0; row < num_rows; row++) {
  166770. ptr = image_data[row] + input_cols;
  166771. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166772. for (count = numcols; count > 0; count--)
  166773. *ptr++ = pixval;
  166774. }
  166775. }
  166776. }
  166777. /*
  166778. * Do downsampling for a whole row group (all components).
  166779. *
  166780. * In this version we simply downsample each component independently.
  166781. */
  166782. METHODDEF(void)
  166783. sep_downsample (j_compress_ptr cinfo,
  166784. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166785. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166786. {
  166787. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166788. int ci;
  166789. jpeg_component_info * compptr;
  166790. JSAMPARRAY in_ptr, out_ptr;
  166791. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166792. ci++, compptr++) {
  166793. in_ptr = input_buf[ci] + in_row_index;
  166794. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166795. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166796. }
  166797. }
  166798. /*
  166799. * Downsample pixel values of a single component.
  166800. * One row group is processed per call.
  166801. * This version handles arbitrary integral sampling ratios, without smoothing.
  166802. * Note that this version is not actually used for customary sampling ratios.
  166803. */
  166804. METHODDEF(void)
  166805. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166806. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166807. {
  166808. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166809. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166810. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166811. JSAMPROW inptr, outptr;
  166812. INT32 outvalue;
  166813. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166814. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166815. numpix = h_expand * v_expand;
  166816. numpix2 = numpix/2;
  166817. /* Expand input data enough to let all the output samples be generated
  166818. * by the standard loop. Special-casing padded output would be more
  166819. * efficient.
  166820. */
  166821. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166822. cinfo->image_width, output_cols * h_expand);
  166823. inrow = 0;
  166824. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166825. outptr = output_data[outrow];
  166826. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166827. outcol++, outcol_h += h_expand) {
  166828. outvalue = 0;
  166829. for (v = 0; v < v_expand; v++) {
  166830. inptr = input_data[inrow+v] + outcol_h;
  166831. for (h = 0; h < h_expand; h++) {
  166832. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166833. }
  166834. }
  166835. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166836. }
  166837. inrow += v_expand;
  166838. }
  166839. }
  166840. /*
  166841. * Downsample pixel values of a single component.
  166842. * This version handles the special case of a full-size component,
  166843. * without smoothing.
  166844. */
  166845. METHODDEF(void)
  166846. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166847. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166848. {
  166849. /* Copy the data */
  166850. jcopy_sample_rows(input_data, 0, output_data, 0,
  166851. cinfo->max_v_samp_factor, cinfo->image_width);
  166852. /* Edge-expand */
  166853. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166854. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166855. }
  166856. /*
  166857. * Downsample pixel values of a single component.
  166858. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166859. * without smoothing.
  166860. *
  166861. * A note about the "bias" calculations: when rounding fractional values to
  166862. * integer, we do not want to always round 0.5 up to the next integer.
  166863. * If we did that, we'd introduce a noticeable bias towards larger values.
  166864. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166865. * alternate pixel locations (a simple ordered dither pattern).
  166866. */
  166867. METHODDEF(void)
  166868. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166869. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166870. {
  166871. int outrow;
  166872. JDIMENSION outcol;
  166873. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166874. register JSAMPROW inptr, outptr;
  166875. register int bias;
  166876. /* Expand input data enough to let all the output samples be generated
  166877. * by the standard loop. Special-casing padded output would be more
  166878. * efficient.
  166879. */
  166880. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166881. cinfo->image_width, output_cols * 2);
  166882. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166883. outptr = output_data[outrow];
  166884. inptr = input_data[outrow];
  166885. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166886. for (outcol = 0; outcol < output_cols; outcol++) {
  166887. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166888. + bias) >> 1);
  166889. bias ^= 1; /* 0=>1, 1=>0 */
  166890. inptr += 2;
  166891. }
  166892. }
  166893. }
  166894. /*
  166895. * Downsample pixel values of a single component.
  166896. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166897. * without smoothing.
  166898. */
  166899. METHODDEF(void)
  166900. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166901. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166902. {
  166903. int inrow, outrow;
  166904. JDIMENSION outcol;
  166905. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166906. register JSAMPROW inptr0, inptr1, outptr;
  166907. register int bias;
  166908. /* Expand input data enough to let all the output samples be generated
  166909. * by the standard loop. Special-casing padded output would be more
  166910. * efficient.
  166911. */
  166912. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166913. cinfo->image_width, output_cols * 2);
  166914. inrow = 0;
  166915. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166916. outptr = output_data[outrow];
  166917. inptr0 = input_data[inrow];
  166918. inptr1 = input_data[inrow+1];
  166919. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166920. for (outcol = 0; outcol < output_cols; outcol++) {
  166921. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166922. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166923. + bias) >> 2);
  166924. bias ^= 3; /* 1=>2, 2=>1 */
  166925. inptr0 += 2; inptr1 += 2;
  166926. }
  166927. inrow += 2;
  166928. }
  166929. }
  166930. #ifdef INPUT_SMOOTHING_SUPPORTED
  166931. /*
  166932. * Downsample pixel values of a single component.
  166933. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166934. * with smoothing. One row of context is required.
  166935. */
  166936. METHODDEF(void)
  166937. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166938. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166939. {
  166940. int inrow, outrow;
  166941. JDIMENSION colctr;
  166942. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166943. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166944. INT32 membersum, neighsum, memberscale, neighscale;
  166945. /* Expand input data enough to let all the output samples be generated
  166946. * by the standard loop. Special-casing padded output would be more
  166947. * efficient.
  166948. */
  166949. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166950. cinfo->image_width, output_cols * 2);
  166951. /* We don't bother to form the individual "smoothed" input pixel values;
  166952. * we can directly compute the output which is the average of the four
  166953. * smoothed values. Each of the four member pixels contributes a fraction
  166954. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166955. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166956. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166957. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166958. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166959. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166960. * factors are scaled by 2^16 = 65536.
  166961. * Also recall that SF = smoothing_factor / 1024.
  166962. */
  166963. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166964. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166965. inrow = 0;
  166966. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166967. outptr = output_data[outrow];
  166968. inptr0 = input_data[inrow];
  166969. inptr1 = input_data[inrow+1];
  166970. above_ptr = input_data[inrow-1];
  166971. below_ptr = input_data[inrow+2];
  166972. /* Special case for first column: pretend column -1 is same as column 0 */
  166973. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166974. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166975. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166976. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166977. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166978. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166979. neighsum += neighsum;
  166980. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166981. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166982. membersum = membersum * memberscale + neighsum * neighscale;
  166983. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166984. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166985. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166986. /* sum of pixels directly mapped to this output element */
  166987. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166988. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166989. /* sum of edge-neighbor pixels */
  166990. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166991. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166992. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166993. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166994. /* The edge-neighbors count twice as much as corner-neighbors */
  166995. neighsum += neighsum;
  166996. /* Add in the corner-neighbors */
  166997. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166998. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166999. /* form final output scaled up by 2^16 */
  167000. membersum = membersum * memberscale + neighsum * neighscale;
  167001. /* round, descale and output it */
  167002. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167003. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167004. }
  167005. /* Special case for last column */
  167006. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167007. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167008. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167009. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167010. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167011. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167012. neighsum += neighsum;
  167013. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167014. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167015. membersum = membersum * memberscale + neighsum * neighscale;
  167016. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167017. inrow += 2;
  167018. }
  167019. }
  167020. /*
  167021. * Downsample pixel values of a single component.
  167022. * This version handles the special case of a full-size component,
  167023. * with smoothing. One row of context is required.
  167024. */
  167025. METHODDEF(void)
  167026. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167027. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167028. {
  167029. int outrow;
  167030. JDIMENSION colctr;
  167031. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167032. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167033. INT32 membersum, neighsum, memberscale, neighscale;
  167034. int colsum, lastcolsum, nextcolsum;
  167035. /* Expand input data enough to let all the output samples be generated
  167036. * by the standard loop. Special-casing padded output would be more
  167037. * efficient.
  167038. */
  167039. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167040. cinfo->image_width, output_cols);
  167041. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167042. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167043. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167044. * Also recall that SF = smoothing_factor / 1024.
  167045. */
  167046. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167047. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167048. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167049. outptr = output_data[outrow];
  167050. inptr = input_data[outrow];
  167051. above_ptr = input_data[outrow-1];
  167052. below_ptr = input_data[outrow+1];
  167053. /* Special case for first column */
  167054. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167055. GETJSAMPLE(*inptr);
  167056. membersum = GETJSAMPLE(*inptr++);
  167057. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167058. GETJSAMPLE(*inptr);
  167059. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167060. membersum = membersum * memberscale + neighsum * neighscale;
  167061. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167062. lastcolsum = colsum; colsum = nextcolsum;
  167063. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167064. membersum = GETJSAMPLE(*inptr++);
  167065. above_ptr++; below_ptr++;
  167066. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167067. GETJSAMPLE(*inptr);
  167068. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167069. membersum = membersum * memberscale + neighsum * neighscale;
  167070. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167071. lastcolsum = colsum; colsum = nextcolsum;
  167072. }
  167073. /* Special case for last column */
  167074. membersum = GETJSAMPLE(*inptr);
  167075. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167076. membersum = membersum * memberscale + neighsum * neighscale;
  167077. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167078. }
  167079. }
  167080. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167081. /*
  167082. * Module initialization routine for downsampling.
  167083. * Note that we must select a routine for each component.
  167084. */
  167085. GLOBAL(void)
  167086. jinit_downsampler (j_compress_ptr cinfo)
  167087. {
  167088. my_downsample_ptr downsample;
  167089. int ci;
  167090. jpeg_component_info * compptr;
  167091. boolean smoothok = TRUE;
  167092. downsample = (my_downsample_ptr)
  167093. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167094. SIZEOF(my_downsampler));
  167095. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167096. downsample->pub.start_pass = start_pass_downsample;
  167097. downsample->pub.downsample = sep_downsample;
  167098. downsample->pub.need_context_rows = FALSE;
  167099. if (cinfo->CCIR601_sampling)
  167100. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167101. /* Verify we can handle the sampling factors, and set up method pointers */
  167102. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167103. ci++, compptr++) {
  167104. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167105. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167106. #ifdef INPUT_SMOOTHING_SUPPORTED
  167107. if (cinfo->smoothing_factor) {
  167108. downsample->methods[ci] = fullsize_smooth_downsample;
  167109. downsample->pub.need_context_rows = TRUE;
  167110. } else
  167111. #endif
  167112. downsample->methods[ci] = fullsize_downsample;
  167113. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167114. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167115. smoothok = FALSE;
  167116. downsample->methods[ci] = h2v1_downsample;
  167117. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167118. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167119. #ifdef INPUT_SMOOTHING_SUPPORTED
  167120. if (cinfo->smoothing_factor) {
  167121. downsample->methods[ci] = h2v2_smooth_downsample;
  167122. downsample->pub.need_context_rows = TRUE;
  167123. } else
  167124. #endif
  167125. downsample->methods[ci] = h2v2_downsample;
  167126. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167127. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167128. smoothok = FALSE;
  167129. downsample->methods[ci] = int_downsample;
  167130. } else
  167131. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167132. }
  167133. #ifdef INPUT_SMOOTHING_SUPPORTED
  167134. if (cinfo->smoothing_factor && !smoothok)
  167135. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167136. #endif
  167137. }
  167138. /*** End of inlined file: jcsample.c ***/
  167139. /*** Start of inlined file: jctrans.c ***/
  167140. #define JPEG_INTERNALS
  167141. /* Forward declarations */
  167142. LOCAL(void) transencode_master_selection
  167143. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167144. LOCAL(void) transencode_coef_controller
  167145. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167146. /*
  167147. * Compression initialization for writing raw-coefficient data.
  167148. * Before calling this, all parameters and a data destination must be set up.
  167149. * Call jpeg_finish_compress() to actually write the data.
  167150. *
  167151. * The number of passed virtual arrays must match cinfo->num_components.
  167152. * Note that the virtual arrays need not be filled or even realized at
  167153. * the time write_coefficients is called; indeed, if the virtual arrays
  167154. * were requested from this compression object's memory manager, they
  167155. * typically will be realized during this routine and filled afterwards.
  167156. */
  167157. GLOBAL(void)
  167158. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167159. {
  167160. if (cinfo->global_state != CSTATE_START)
  167161. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167162. /* Mark all tables to be written */
  167163. jpeg_suppress_tables(cinfo, FALSE);
  167164. /* (Re)initialize error mgr and destination modules */
  167165. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167166. (*cinfo->dest->init_destination) (cinfo);
  167167. /* Perform master selection of active modules */
  167168. transencode_master_selection(cinfo, coef_arrays);
  167169. /* Wait for jpeg_finish_compress() call */
  167170. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167171. cinfo->global_state = CSTATE_WRCOEFS;
  167172. }
  167173. /*
  167174. * Initialize the compression object with default parameters,
  167175. * then copy from the source object all parameters needed for lossless
  167176. * transcoding. Parameters that can be varied without loss (such as
  167177. * scan script and Huffman optimization) are left in their default states.
  167178. */
  167179. GLOBAL(void)
  167180. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167181. j_compress_ptr dstinfo)
  167182. {
  167183. JQUANT_TBL ** qtblptr;
  167184. jpeg_component_info *incomp, *outcomp;
  167185. JQUANT_TBL *c_quant, *slot_quant;
  167186. int tblno, ci, coefi;
  167187. /* Safety check to ensure start_compress not called yet. */
  167188. if (dstinfo->global_state != CSTATE_START)
  167189. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167190. /* Copy fundamental image dimensions */
  167191. dstinfo->image_width = srcinfo->image_width;
  167192. dstinfo->image_height = srcinfo->image_height;
  167193. dstinfo->input_components = srcinfo->num_components;
  167194. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167195. /* Initialize all parameters to default values */
  167196. jpeg_set_defaults(dstinfo);
  167197. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167198. * Fix it to get the right header markers for the image colorspace.
  167199. */
  167200. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167201. dstinfo->data_precision = srcinfo->data_precision;
  167202. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167203. /* Copy the source's quantization tables. */
  167204. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167205. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167206. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167207. if (*qtblptr == NULL)
  167208. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167209. MEMCOPY((*qtblptr)->quantval,
  167210. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167211. SIZEOF((*qtblptr)->quantval));
  167212. (*qtblptr)->sent_table = FALSE;
  167213. }
  167214. }
  167215. /* Copy the source's per-component info.
  167216. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167217. */
  167218. dstinfo->num_components = srcinfo->num_components;
  167219. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167220. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167221. MAX_COMPONENTS);
  167222. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167223. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167224. outcomp->component_id = incomp->component_id;
  167225. outcomp->h_samp_factor = incomp->h_samp_factor;
  167226. outcomp->v_samp_factor = incomp->v_samp_factor;
  167227. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167228. /* Make sure saved quantization table for component matches the qtable
  167229. * slot. If not, the input file re-used this qtable slot.
  167230. * IJG encoder currently cannot duplicate this.
  167231. */
  167232. tblno = outcomp->quant_tbl_no;
  167233. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167234. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167235. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167236. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167237. c_quant = incomp->quant_table;
  167238. if (c_quant != NULL) {
  167239. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167240. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167241. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167242. }
  167243. }
  167244. /* Note: we do not copy the source's Huffman table assignments;
  167245. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167246. */
  167247. }
  167248. /* Also copy JFIF version and resolution information, if available.
  167249. * Strictly speaking this isn't "critical" info, but it's nearly
  167250. * always appropriate to copy it if available. In particular,
  167251. * if the application chooses to copy JFIF 1.02 extension markers from
  167252. * the source file, we need to copy the version to make sure we don't
  167253. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167254. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167255. */
  167256. if (srcinfo->saw_JFIF_marker) {
  167257. if (srcinfo->JFIF_major_version == 1) {
  167258. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167259. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167260. }
  167261. dstinfo->density_unit = srcinfo->density_unit;
  167262. dstinfo->X_density = srcinfo->X_density;
  167263. dstinfo->Y_density = srcinfo->Y_density;
  167264. }
  167265. }
  167266. /*
  167267. * Master selection of compression modules for transcoding.
  167268. * This substitutes for jcinit.c's initialization of the full compressor.
  167269. */
  167270. LOCAL(void)
  167271. transencode_master_selection (j_compress_ptr cinfo,
  167272. jvirt_barray_ptr * coef_arrays)
  167273. {
  167274. /* Although we don't actually use input_components for transcoding,
  167275. * jcmaster.c's initial_setup will complain if input_components is 0.
  167276. */
  167277. cinfo->input_components = 1;
  167278. /* Initialize master control (includes parameter checking/processing) */
  167279. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167280. /* Entropy encoding: either Huffman or arithmetic coding. */
  167281. if (cinfo->arith_code) {
  167282. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167283. } else {
  167284. if (cinfo->progressive_mode) {
  167285. #ifdef C_PROGRESSIVE_SUPPORTED
  167286. jinit_phuff_encoder(cinfo);
  167287. #else
  167288. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167289. #endif
  167290. } else
  167291. jinit_huff_encoder(cinfo);
  167292. }
  167293. /* We need a special coefficient buffer controller. */
  167294. transencode_coef_controller(cinfo, coef_arrays);
  167295. jinit_marker_writer(cinfo);
  167296. /* We can now tell the memory manager to allocate virtual arrays. */
  167297. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167298. /* Write the datastream header (SOI, JFIF) immediately.
  167299. * Frame and scan headers are postponed till later.
  167300. * This lets application insert special markers after the SOI.
  167301. */
  167302. (*cinfo->marker->write_file_header) (cinfo);
  167303. }
  167304. /*
  167305. * The rest of this file is a special implementation of the coefficient
  167306. * buffer controller. This is similar to jccoefct.c, but it handles only
  167307. * output from presupplied virtual arrays. Furthermore, we generate any
  167308. * dummy padding blocks on-the-fly rather than expecting them to be present
  167309. * in the arrays.
  167310. */
  167311. /* Private buffer controller object */
  167312. typedef struct {
  167313. struct jpeg_c_coef_controller pub; /* public fields */
  167314. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167315. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167316. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167317. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167318. /* Virtual block array for each component. */
  167319. jvirt_barray_ptr * whole_image;
  167320. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167321. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167322. } my_coef_controller2;
  167323. typedef my_coef_controller2 * my_coef_ptr2;
  167324. LOCAL(void)
  167325. start_iMCU_row2 (j_compress_ptr cinfo)
  167326. /* Reset within-iMCU-row counters for a new row */
  167327. {
  167328. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167329. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167330. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167331. * But at the bottom of the image, process only what's left.
  167332. */
  167333. if (cinfo->comps_in_scan > 1) {
  167334. coef->MCU_rows_per_iMCU_row = 1;
  167335. } else {
  167336. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167337. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167338. else
  167339. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167340. }
  167341. coef->mcu_ctr = 0;
  167342. coef->MCU_vert_offset = 0;
  167343. }
  167344. /*
  167345. * Initialize for a processing pass.
  167346. */
  167347. METHODDEF(void)
  167348. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167349. {
  167350. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167351. if (pass_mode != JBUF_CRANK_DEST)
  167352. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167353. coef->iMCU_row_num = 0;
  167354. start_iMCU_row2(cinfo);
  167355. }
  167356. /*
  167357. * Process some data.
  167358. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167359. * per call, ie, v_samp_factor block rows for each component in the scan.
  167360. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167361. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167362. *
  167363. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167364. */
  167365. METHODDEF(boolean)
  167366. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167367. {
  167368. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167369. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167370. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167371. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167372. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167373. JDIMENSION start_col;
  167374. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167375. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167376. JBLOCKROW buffer_ptr;
  167377. jpeg_component_info *compptr;
  167378. /* Align the virtual buffers for the components used in this scan. */
  167379. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167380. compptr = cinfo->cur_comp_info[ci];
  167381. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167382. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167383. coef->iMCU_row_num * compptr->v_samp_factor,
  167384. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167385. }
  167386. /* Loop to process one whole iMCU row */
  167387. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167388. yoffset++) {
  167389. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167390. MCU_col_num++) {
  167391. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167392. blkn = 0; /* index of current DCT block within MCU */
  167393. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167394. compptr = cinfo->cur_comp_info[ci];
  167395. start_col = MCU_col_num * compptr->MCU_width;
  167396. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167397. : compptr->last_col_width;
  167398. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167399. if (coef->iMCU_row_num < last_iMCU_row ||
  167400. yindex+yoffset < compptr->last_row_height) {
  167401. /* Fill in pointers to real blocks in this row */
  167402. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167403. for (xindex = 0; xindex < blockcnt; xindex++)
  167404. MCU_buffer[blkn++] = buffer_ptr++;
  167405. } else {
  167406. /* At bottom of image, need a whole row of dummy blocks */
  167407. xindex = 0;
  167408. }
  167409. /* Fill in any dummy blocks needed in this row.
  167410. * Dummy blocks are filled in the same way as in jccoefct.c:
  167411. * all zeroes in the AC entries, DC entries equal to previous
  167412. * block's DC value. The init routine has already zeroed the
  167413. * AC entries, so we need only set the DC entries correctly.
  167414. */
  167415. for (; xindex < compptr->MCU_width; xindex++) {
  167416. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167417. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167418. blkn++;
  167419. }
  167420. }
  167421. }
  167422. /* Try to write the MCU. */
  167423. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167424. /* Suspension forced; update state counters and exit */
  167425. coef->MCU_vert_offset = yoffset;
  167426. coef->mcu_ctr = MCU_col_num;
  167427. return FALSE;
  167428. }
  167429. }
  167430. /* Completed an MCU row, but perhaps not an iMCU row */
  167431. coef->mcu_ctr = 0;
  167432. }
  167433. /* Completed the iMCU row, advance counters for next one */
  167434. coef->iMCU_row_num++;
  167435. start_iMCU_row2(cinfo);
  167436. return TRUE;
  167437. }
  167438. /*
  167439. * Initialize coefficient buffer controller.
  167440. *
  167441. * Each passed coefficient array must be the right size for that
  167442. * coefficient: width_in_blocks wide and height_in_blocks high,
  167443. * with unitheight at least v_samp_factor.
  167444. */
  167445. LOCAL(void)
  167446. transencode_coef_controller (j_compress_ptr cinfo,
  167447. jvirt_barray_ptr * coef_arrays)
  167448. {
  167449. my_coef_ptr2 coef;
  167450. JBLOCKROW buffer;
  167451. int i;
  167452. coef = (my_coef_ptr2)
  167453. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167454. SIZEOF(my_coef_controller2));
  167455. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167456. coef->pub.start_pass = start_pass_coef2;
  167457. coef->pub.compress_data = compress_output2;
  167458. /* Save pointer to virtual arrays */
  167459. coef->whole_image = coef_arrays;
  167460. /* Allocate and pre-zero space for dummy DCT blocks. */
  167461. buffer = (JBLOCKROW)
  167462. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167463. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167464. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167465. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167466. coef->dummy_buffer[i] = buffer + i;
  167467. }
  167468. }
  167469. /*** End of inlined file: jctrans.c ***/
  167470. /*** Start of inlined file: jdapistd.c ***/
  167471. #define JPEG_INTERNALS
  167472. /* Forward declarations */
  167473. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167474. /*
  167475. * Decompression initialization.
  167476. * jpeg_read_header must be completed before calling this.
  167477. *
  167478. * If a multipass operating mode was selected, this will do all but the
  167479. * last pass, and thus may take a great deal of time.
  167480. *
  167481. * Returns FALSE if suspended. The return value need be inspected only if
  167482. * a suspending data source is used.
  167483. */
  167484. GLOBAL(boolean)
  167485. jpeg_start_decompress (j_decompress_ptr cinfo)
  167486. {
  167487. if (cinfo->global_state == DSTATE_READY) {
  167488. /* First call: initialize master control, select active modules */
  167489. jinit_master_decompress(cinfo);
  167490. if (cinfo->buffered_image) {
  167491. /* No more work here; expecting jpeg_start_output next */
  167492. cinfo->global_state = DSTATE_BUFIMAGE;
  167493. return TRUE;
  167494. }
  167495. cinfo->global_state = DSTATE_PRELOAD;
  167496. }
  167497. if (cinfo->global_state == DSTATE_PRELOAD) {
  167498. /* If file has multiple scans, absorb them all into the coef buffer */
  167499. if (cinfo->inputctl->has_multiple_scans) {
  167500. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167501. for (;;) {
  167502. int retcode;
  167503. /* Call progress monitor hook if present */
  167504. if (cinfo->progress != NULL)
  167505. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167506. /* Absorb some more input */
  167507. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167508. if (retcode == JPEG_SUSPENDED)
  167509. return FALSE;
  167510. if (retcode == JPEG_REACHED_EOI)
  167511. break;
  167512. /* Advance progress counter if appropriate */
  167513. if (cinfo->progress != NULL &&
  167514. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167515. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167516. /* jdmaster underestimated number of scans; ratchet up one scan */
  167517. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167518. }
  167519. }
  167520. }
  167521. #else
  167522. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167523. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167524. }
  167525. cinfo->output_scan_number = cinfo->input_scan_number;
  167526. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167527. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167528. /* Perform any dummy output passes, and set up for the final pass */
  167529. return output_pass_setup(cinfo);
  167530. }
  167531. /*
  167532. * Set up for an output pass, and perform any dummy pass(es) needed.
  167533. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167534. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167535. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167536. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167537. */
  167538. LOCAL(boolean)
  167539. output_pass_setup (j_decompress_ptr cinfo)
  167540. {
  167541. if (cinfo->global_state != DSTATE_PRESCAN) {
  167542. /* First call: do pass setup */
  167543. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167544. cinfo->output_scanline = 0;
  167545. cinfo->global_state = DSTATE_PRESCAN;
  167546. }
  167547. /* Loop over any required dummy passes */
  167548. while (cinfo->master->is_dummy_pass) {
  167549. #ifdef QUANT_2PASS_SUPPORTED
  167550. /* Crank through the dummy pass */
  167551. while (cinfo->output_scanline < cinfo->output_height) {
  167552. JDIMENSION last_scanline;
  167553. /* Call progress monitor hook if present */
  167554. if (cinfo->progress != NULL) {
  167555. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167556. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167557. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167558. }
  167559. /* Process some data */
  167560. last_scanline = cinfo->output_scanline;
  167561. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167562. &cinfo->output_scanline, (JDIMENSION) 0);
  167563. if (cinfo->output_scanline == last_scanline)
  167564. return FALSE; /* No progress made, must suspend */
  167565. }
  167566. /* Finish up dummy pass, and set up for another one */
  167567. (*cinfo->master->finish_output_pass) (cinfo);
  167568. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167569. cinfo->output_scanline = 0;
  167570. #else
  167571. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167572. #endif /* QUANT_2PASS_SUPPORTED */
  167573. }
  167574. /* Ready for application to drive output pass through
  167575. * jpeg_read_scanlines or jpeg_read_raw_data.
  167576. */
  167577. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167578. return TRUE;
  167579. }
  167580. /*
  167581. * Read some scanlines of data from the JPEG decompressor.
  167582. *
  167583. * The return value will be the number of lines actually read.
  167584. * This may be less than the number requested in several cases,
  167585. * including bottom of image, data source suspension, and operating
  167586. * modes that emit multiple scanlines at a time.
  167587. *
  167588. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167589. * this likely signals an application programmer error. However,
  167590. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167591. */
  167592. GLOBAL(JDIMENSION)
  167593. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167594. JDIMENSION max_lines)
  167595. {
  167596. JDIMENSION row_ctr;
  167597. if (cinfo->global_state != DSTATE_SCANNING)
  167598. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167599. if (cinfo->output_scanline >= cinfo->output_height) {
  167600. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167601. return 0;
  167602. }
  167603. /* Call progress monitor hook if present */
  167604. if (cinfo->progress != NULL) {
  167605. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167606. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167607. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167608. }
  167609. /* Process some data */
  167610. row_ctr = 0;
  167611. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167612. cinfo->output_scanline += row_ctr;
  167613. return row_ctr;
  167614. }
  167615. /*
  167616. * Alternate entry point to read raw data.
  167617. * Processes exactly one iMCU row per call, unless suspended.
  167618. */
  167619. GLOBAL(JDIMENSION)
  167620. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167621. JDIMENSION max_lines)
  167622. {
  167623. JDIMENSION lines_per_iMCU_row;
  167624. if (cinfo->global_state != DSTATE_RAW_OK)
  167625. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167626. if (cinfo->output_scanline >= cinfo->output_height) {
  167627. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167628. return 0;
  167629. }
  167630. /* Call progress monitor hook if present */
  167631. if (cinfo->progress != NULL) {
  167632. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167633. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167634. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167635. }
  167636. /* Verify that at least one iMCU row can be returned. */
  167637. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167638. if (max_lines < lines_per_iMCU_row)
  167639. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167640. /* Decompress directly into user's buffer. */
  167641. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167642. return 0; /* suspension forced, can do nothing more */
  167643. /* OK, we processed one iMCU row. */
  167644. cinfo->output_scanline += lines_per_iMCU_row;
  167645. return lines_per_iMCU_row;
  167646. }
  167647. /* Additional entry points for buffered-image mode. */
  167648. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167649. /*
  167650. * Initialize for an output pass in buffered-image mode.
  167651. */
  167652. GLOBAL(boolean)
  167653. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167654. {
  167655. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167656. cinfo->global_state != DSTATE_PRESCAN)
  167657. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167658. /* Limit scan number to valid range */
  167659. if (scan_number <= 0)
  167660. scan_number = 1;
  167661. if (cinfo->inputctl->eoi_reached &&
  167662. scan_number > cinfo->input_scan_number)
  167663. scan_number = cinfo->input_scan_number;
  167664. cinfo->output_scan_number = scan_number;
  167665. /* Perform any dummy output passes, and set up for the real pass */
  167666. return output_pass_setup(cinfo);
  167667. }
  167668. /*
  167669. * Finish up after an output pass in buffered-image mode.
  167670. *
  167671. * Returns FALSE if suspended. The return value need be inspected only if
  167672. * a suspending data source is used.
  167673. */
  167674. GLOBAL(boolean)
  167675. jpeg_finish_output (j_decompress_ptr cinfo)
  167676. {
  167677. if ((cinfo->global_state == DSTATE_SCANNING ||
  167678. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167679. /* Terminate this pass. */
  167680. /* We do not require the whole pass to have been completed. */
  167681. (*cinfo->master->finish_output_pass) (cinfo);
  167682. cinfo->global_state = DSTATE_BUFPOST;
  167683. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167684. /* BUFPOST = repeat call after a suspension, anything else is error */
  167685. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167686. }
  167687. /* Read markers looking for SOS or EOI */
  167688. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167689. ! cinfo->inputctl->eoi_reached) {
  167690. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167691. return FALSE; /* Suspend, come back later */
  167692. }
  167693. cinfo->global_state = DSTATE_BUFIMAGE;
  167694. return TRUE;
  167695. }
  167696. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167697. /*** End of inlined file: jdapistd.c ***/
  167698. /*** Start of inlined file: jdapimin.c ***/
  167699. #define JPEG_INTERNALS
  167700. /*
  167701. * Initialization of a JPEG decompression object.
  167702. * The error manager must already be set up (in case memory manager fails).
  167703. */
  167704. GLOBAL(void)
  167705. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167706. {
  167707. int i;
  167708. /* Guard against version mismatches between library and caller. */
  167709. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167710. if (version != JPEG_LIB_VERSION)
  167711. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167712. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167713. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167714. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167715. /* For debugging purposes, we zero the whole master structure.
  167716. * But the application has already set the err pointer, and may have set
  167717. * client_data, so we have to save and restore those fields.
  167718. * Note: if application hasn't set client_data, tools like Purify may
  167719. * complain here.
  167720. */
  167721. {
  167722. struct jpeg_error_mgr * err = cinfo->err;
  167723. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167724. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167725. cinfo->err = err;
  167726. cinfo->client_data = client_data;
  167727. }
  167728. cinfo->is_decompressor = TRUE;
  167729. /* Initialize a memory manager instance for this object */
  167730. jinit_memory_mgr((j_common_ptr) cinfo);
  167731. /* Zero out pointers to permanent structures. */
  167732. cinfo->progress = NULL;
  167733. cinfo->src = NULL;
  167734. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167735. cinfo->quant_tbl_ptrs[i] = NULL;
  167736. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167737. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167738. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167739. }
  167740. /* Initialize marker processor so application can override methods
  167741. * for COM, APPn markers before calling jpeg_read_header.
  167742. */
  167743. cinfo->marker_list = NULL;
  167744. jinit_marker_reader(cinfo);
  167745. /* And initialize the overall input controller. */
  167746. jinit_input_controller(cinfo);
  167747. /* OK, I'm ready */
  167748. cinfo->global_state = DSTATE_START;
  167749. }
  167750. /*
  167751. * Destruction of a JPEG decompression object
  167752. */
  167753. GLOBAL(void)
  167754. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167755. {
  167756. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167757. }
  167758. /*
  167759. * Abort processing of a JPEG decompression operation,
  167760. * but don't destroy the object itself.
  167761. */
  167762. GLOBAL(void)
  167763. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167764. {
  167765. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167766. }
  167767. /*
  167768. * Set default decompression parameters.
  167769. */
  167770. LOCAL(void)
  167771. default_decompress_parms (j_decompress_ptr cinfo)
  167772. {
  167773. /* Guess the input colorspace, and set output colorspace accordingly. */
  167774. /* (Wish JPEG committee had provided a real way to specify this...) */
  167775. /* Note application may override our guesses. */
  167776. switch (cinfo->num_components) {
  167777. case 1:
  167778. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167779. cinfo->out_color_space = JCS_GRAYSCALE;
  167780. break;
  167781. case 3:
  167782. if (cinfo->saw_JFIF_marker) {
  167783. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167784. } else if (cinfo->saw_Adobe_marker) {
  167785. switch (cinfo->Adobe_transform) {
  167786. case 0:
  167787. cinfo->jpeg_color_space = JCS_RGB;
  167788. break;
  167789. case 1:
  167790. cinfo->jpeg_color_space = JCS_YCbCr;
  167791. break;
  167792. default:
  167793. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167794. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167795. break;
  167796. }
  167797. } else {
  167798. /* Saw no special markers, try to guess from the component IDs */
  167799. int cid0 = cinfo->comp_info[0].component_id;
  167800. int cid1 = cinfo->comp_info[1].component_id;
  167801. int cid2 = cinfo->comp_info[2].component_id;
  167802. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167803. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167804. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167805. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167806. else {
  167807. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167808. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167809. }
  167810. }
  167811. /* Always guess RGB is proper output colorspace. */
  167812. cinfo->out_color_space = JCS_RGB;
  167813. break;
  167814. case 4:
  167815. if (cinfo->saw_Adobe_marker) {
  167816. switch (cinfo->Adobe_transform) {
  167817. case 0:
  167818. cinfo->jpeg_color_space = JCS_CMYK;
  167819. break;
  167820. case 2:
  167821. cinfo->jpeg_color_space = JCS_YCCK;
  167822. break;
  167823. default:
  167824. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167825. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167826. break;
  167827. }
  167828. } else {
  167829. /* No special markers, assume straight CMYK. */
  167830. cinfo->jpeg_color_space = JCS_CMYK;
  167831. }
  167832. cinfo->out_color_space = JCS_CMYK;
  167833. break;
  167834. default:
  167835. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167836. cinfo->out_color_space = JCS_UNKNOWN;
  167837. break;
  167838. }
  167839. /* Set defaults for other decompression parameters. */
  167840. cinfo->scale_num = 1; /* 1:1 scaling */
  167841. cinfo->scale_denom = 1;
  167842. cinfo->output_gamma = 1.0;
  167843. cinfo->buffered_image = FALSE;
  167844. cinfo->raw_data_out = FALSE;
  167845. cinfo->dct_method = JDCT_DEFAULT;
  167846. cinfo->do_fancy_upsampling = TRUE;
  167847. cinfo->do_block_smoothing = TRUE;
  167848. cinfo->quantize_colors = FALSE;
  167849. /* We set these in case application only sets quantize_colors. */
  167850. cinfo->dither_mode = JDITHER_FS;
  167851. #ifdef QUANT_2PASS_SUPPORTED
  167852. cinfo->two_pass_quantize = TRUE;
  167853. #else
  167854. cinfo->two_pass_quantize = FALSE;
  167855. #endif
  167856. cinfo->desired_number_of_colors = 256;
  167857. cinfo->colormap = NULL;
  167858. /* Initialize for no mode change in buffered-image mode. */
  167859. cinfo->enable_1pass_quant = FALSE;
  167860. cinfo->enable_external_quant = FALSE;
  167861. cinfo->enable_2pass_quant = FALSE;
  167862. }
  167863. /*
  167864. * Decompression startup: read start of JPEG datastream to see what's there.
  167865. * Need only initialize JPEG object and supply a data source before calling.
  167866. *
  167867. * This routine will read as far as the first SOS marker (ie, actual start of
  167868. * compressed data), and will save all tables and parameters in the JPEG
  167869. * object. It will also initialize the decompression parameters to default
  167870. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167871. * adjust the decompression parameters and then call jpeg_start_decompress.
  167872. * (Or, if the application only wanted to determine the image parameters,
  167873. * the data need not be decompressed. In that case, call jpeg_abort or
  167874. * jpeg_destroy to release any temporary space.)
  167875. * If an abbreviated (tables only) datastream is presented, the routine will
  167876. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167877. * re-use the JPEG object to read the abbreviated image datastream(s).
  167878. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167879. * The JPEG_SUSPENDED return code only occurs if the data source module
  167880. * requests suspension of the decompressor. In this case the application
  167881. * should load more source data and then re-call jpeg_read_header to resume
  167882. * processing.
  167883. * If a non-suspending data source is used and require_image is TRUE, then the
  167884. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167885. *
  167886. * This routine is now just a front end to jpeg_consume_input, with some
  167887. * extra error checking.
  167888. */
  167889. GLOBAL(int)
  167890. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167891. {
  167892. int retcode;
  167893. if (cinfo->global_state != DSTATE_START &&
  167894. cinfo->global_state != DSTATE_INHEADER)
  167895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167896. retcode = jpeg_consume_input(cinfo);
  167897. switch (retcode) {
  167898. case JPEG_REACHED_SOS:
  167899. retcode = JPEG_HEADER_OK;
  167900. break;
  167901. case JPEG_REACHED_EOI:
  167902. if (require_image) /* Complain if application wanted an image */
  167903. ERREXIT(cinfo, JERR_NO_IMAGE);
  167904. /* Reset to start state; it would be safer to require the application to
  167905. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167906. * A side effect is to free any temporary memory (there shouldn't be any).
  167907. */
  167908. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167909. retcode = JPEG_HEADER_TABLES_ONLY;
  167910. break;
  167911. case JPEG_SUSPENDED:
  167912. /* no work */
  167913. break;
  167914. }
  167915. return retcode;
  167916. }
  167917. /*
  167918. * Consume data in advance of what the decompressor requires.
  167919. * This can be called at any time once the decompressor object has
  167920. * been created and a data source has been set up.
  167921. *
  167922. * This routine is essentially a state machine that handles a couple
  167923. * of critical state-transition actions, namely initial setup and
  167924. * transition from header scanning to ready-for-start_decompress.
  167925. * All the actual input is done via the input controller's consume_input
  167926. * method.
  167927. */
  167928. GLOBAL(int)
  167929. jpeg_consume_input (j_decompress_ptr cinfo)
  167930. {
  167931. int retcode = JPEG_SUSPENDED;
  167932. /* NB: every possible DSTATE value should be listed in this switch */
  167933. switch (cinfo->global_state) {
  167934. case DSTATE_START:
  167935. /* Start-of-datastream actions: reset appropriate modules */
  167936. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167937. /* Initialize application's data source module */
  167938. (*cinfo->src->init_source) (cinfo);
  167939. cinfo->global_state = DSTATE_INHEADER;
  167940. /*FALLTHROUGH*/
  167941. case DSTATE_INHEADER:
  167942. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167943. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167944. /* Set up default parameters based on header data */
  167945. default_decompress_parms(cinfo);
  167946. /* Set global state: ready for start_decompress */
  167947. cinfo->global_state = DSTATE_READY;
  167948. }
  167949. break;
  167950. case DSTATE_READY:
  167951. /* Can't advance past first SOS until start_decompress is called */
  167952. retcode = JPEG_REACHED_SOS;
  167953. break;
  167954. case DSTATE_PRELOAD:
  167955. case DSTATE_PRESCAN:
  167956. case DSTATE_SCANNING:
  167957. case DSTATE_RAW_OK:
  167958. case DSTATE_BUFIMAGE:
  167959. case DSTATE_BUFPOST:
  167960. case DSTATE_STOPPING:
  167961. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167962. break;
  167963. default:
  167964. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167965. }
  167966. return retcode;
  167967. }
  167968. /*
  167969. * Have we finished reading the input file?
  167970. */
  167971. GLOBAL(boolean)
  167972. jpeg_input_complete (j_decompress_ptr cinfo)
  167973. {
  167974. /* Check for valid jpeg object */
  167975. if (cinfo->global_state < DSTATE_START ||
  167976. cinfo->global_state > DSTATE_STOPPING)
  167977. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167978. return cinfo->inputctl->eoi_reached;
  167979. }
  167980. /*
  167981. * Is there more than one scan?
  167982. */
  167983. GLOBAL(boolean)
  167984. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167985. {
  167986. /* Only valid after jpeg_read_header completes */
  167987. if (cinfo->global_state < DSTATE_READY ||
  167988. cinfo->global_state > DSTATE_STOPPING)
  167989. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167990. return cinfo->inputctl->has_multiple_scans;
  167991. }
  167992. /*
  167993. * Finish JPEG decompression.
  167994. *
  167995. * This will normally just verify the file trailer and release temp storage.
  167996. *
  167997. * Returns FALSE if suspended. The return value need be inspected only if
  167998. * a suspending data source is used.
  167999. */
  168000. GLOBAL(boolean)
  168001. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168002. {
  168003. if ((cinfo->global_state == DSTATE_SCANNING ||
  168004. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168005. /* Terminate final pass of non-buffered mode */
  168006. if (cinfo->output_scanline < cinfo->output_height)
  168007. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168008. (*cinfo->master->finish_output_pass) (cinfo);
  168009. cinfo->global_state = DSTATE_STOPPING;
  168010. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168011. /* Finishing after a buffered-image operation */
  168012. cinfo->global_state = DSTATE_STOPPING;
  168013. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168014. /* STOPPING = repeat call after a suspension, anything else is error */
  168015. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168016. }
  168017. /* Read until EOI */
  168018. while (! cinfo->inputctl->eoi_reached) {
  168019. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168020. return FALSE; /* Suspend, come back later */
  168021. }
  168022. /* Do final cleanup */
  168023. (*cinfo->src->term_source) (cinfo);
  168024. /* We can use jpeg_abort to release memory and reset global_state */
  168025. jpeg_abort((j_common_ptr) cinfo);
  168026. return TRUE;
  168027. }
  168028. /*** End of inlined file: jdapimin.c ***/
  168029. /*** Start of inlined file: jdatasrc.c ***/
  168030. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168031. /*** Start of inlined file: jerror.h ***/
  168032. /*
  168033. * To define the enum list of message codes, include this file without
  168034. * defining macro JMESSAGE. To create a message string table, include it
  168035. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168036. */
  168037. #ifndef JMESSAGE
  168038. #ifndef JERROR_H
  168039. /* First time through, define the enum list */
  168040. #define JMAKE_ENUM_LIST
  168041. #else
  168042. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168043. #define JMESSAGE(code,string)
  168044. #endif /* JERROR_H */
  168045. #endif /* JMESSAGE */
  168046. #ifdef JMAKE_ENUM_LIST
  168047. typedef enum {
  168048. #define JMESSAGE(code,string) code ,
  168049. #endif /* JMAKE_ENUM_LIST */
  168050. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168051. /* For maintenance convenience, list is alphabetical by message code name */
  168052. JMESSAGE(JERR_ARITH_NOTIMPL,
  168053. "Sorry, there are legal restrictions on arithmetic coding")
  168054. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168055. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168056. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168057. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168058. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168059. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168060. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168061. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168062. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168063. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168064. JMESSAGE(JERR_BAD_LIB_VERSION,
  168065. "Wrong JPEG library version: library is %d, caller expects %d")
  168066. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168067. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168068. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168069. JMESSAGE(JERR_BAD_PROGRESSION,
  168070. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168071. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168072. "Invalid progressive parameters at scan script entry %d")
  168073. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168074. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168075. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168076. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168077. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168078. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168079. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168080. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168081. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168082. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168083. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168084. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168085. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168086. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168087. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168088. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168089. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168090. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168091. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168092. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168093. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168094. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168095. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168096. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168097. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168098. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168099. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168100. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168101. "Cannot transcode due to multiple use of quantization table %d")
  168102. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168103. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168104. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168105. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168106. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168107. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168108. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168109. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168110. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168111. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168112. JMESSAGE(JERR_QUANT_COMPONENTS,
  168113. "Cannot quantize more than %d color components")
  168114. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168115. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168116. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168117. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168118. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168119. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168120. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168121. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168122. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168123. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168124. JMESSAGE(JERR_TFILE_WRITE,
  168125. "Write failed on temporary file --- out of disk space?")
  168126. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168127. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168128. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168129. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168130. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168131. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168132. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168133. JMESSAGE(JMSG_VERSION, JVERSION)
  168134. JMESSAGE(JTRC_16BIT_TABLES,
  168135. "Caution: quantization tables are too coarse for baseline JPEG")
  168136. JMESSAGE(JTRC_ADOBE,
  168137. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168138. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168139. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168140. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168141. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168142. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168143. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168144. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168145. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168146. JMESSAGE(JTRC_EOI, "End Of Image")
  168147. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168148. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168149. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168150. "Warning: thumbnail image size does not match data length %u")
  168151. JMESSAGE(JTRC_JFIF_EXTENSION,
  168152. "JFIF extension marker: type 0x%02x, length %u")
  168153. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168154. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168155. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168156. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168157. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168158. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168159. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168160. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168161. JMESSAGE(JTRC_RST, "RST%d")
  168162. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168163. "Smoothing not supported with nonstandard sampling ratios")
  168164. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168165. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168166. JMESSAGE(JTRC_SOI, "Start of Image")
  168167. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168168. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168169. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168170. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168171. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168172. JMESSAGE(JTRC_THUMB_JPEG,
  168173. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168174. JMESSAGE(JTRC_THUMB_PALETTE,
  168175. "JFIF extension marker: palette thumbnail image, length %u")
  168176. JMESSAGE(JTRC_THUMB_RGB,
  168177. "JFIF extension marker: RGB thumbnail image, length %u")
  168178. JMESSAGE(JTRC_UNKNOWN_IDS,
  168179. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168180. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168181. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168182. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168183. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168184. "Inconsistent progression sequence for component %d coefficient %d")
  168185. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168186. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168187. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168188. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168189. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168190. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168191. JMESSAGE(JWRN_MUST_RESYNC,
  168192. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168193. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168194. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168195. #ifdef JMAKE_ENUM_LIST
  168196. JMSG_LASTMSGCODE
  168197. } J_MESSAGE_CODE;
  168198. #undef JMAKE_ENUM_LIST
  168199. #endif /* JMAKE_ENUM_LIST */
  168200. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168201. #undef JMESSAGE
  168202. #ifndef JERROR_H
  168203. #define JERROR_H
  168204. /* Macros to simplify using the error and trace message stuff */
  168205. /* The first parameter is either type of cinfo pointer */
  168206. /* Fatal errors (print message and exit) */
  168207. #define ERREXIT(cinfo,code) \
  168208. ((cinfo)->err->msg_code = (code), \
  168209. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168210. #define ERREXIT1(cinfo,code,p1) \
  168211. ((cinfo)->err->msg_code = (code), \
  168212. (cinfo)->err->msg_parm.i[0] = (p1), \
  168213. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168214. #define ERREXIT2(cinfo,code,p1,p2) \
  168215. ((cinfo)->err->msg_code = (code), \
  168216. (cinfo)->err->msg_parm.i[0] = (p1), \
  168217. (cinfo)->err->msg_parm.i[1] = (p2), \
  168218. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168219. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168220. ((cinfo)->err->msg_code = (code), \
  168221. (cinfo)->err->msg_parm.i[0] = (p1), \
  168222. (cinfo)->err->msg_parm.i[1] = (p2), \
  168223. (cinfo)->err->msg_parm.i[2] = (p3), \
  168224. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168225. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168226. ((cinfo)->err->msg_code = (code), \
  168227. (cinfo)->err->msg_parm.i[0] = (p1), \
  168228. (cinfo)->err->msg_parm.i[1] = (p2), \
  168229. (cinfo)->err->msg_parm.i[2] = (p3), \
  168230. (cinfo)->err->msg_parm.i[3] = (p4), \
  168231. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168232. #define ERREXITS(cinfo,code,str) \
  168233. ((cinfo)->err->msg_code = (code), \
  168234. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168235. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168236. #define MAKESTMT(stuff) do { stuff } while (0)
  168237. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168238. #define WARNMS(cinfo,code) \
  168239. ((cinfo)->err->msg_code = (code), \
  168240. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168241. #define WARNMS1(cinfo,code,p1) \
  168242. ((cinfo)->err->msg_code = (code), \
  168243. (cinfo)->err->msg_parm.i[0] = (p1), \
  168244. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168245. #define WARNMS2(cinfo,code,p1,p2) \
  168246. ((cinfo)->err->msg_code = (code), \
  168247. (cinfo)->err->msg_parm.i[0] = (p1), \
  168248. (cinfo)->err->msg_parm.i[1] = (p2), \
  168249. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168250. /* Informational/debugging messages */
  168251. #define TRACEMS(cinfo,lvl,code) \
  168252. ((cinfo)->err->msg_code = (code), \
  168253. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168254. #define TRACEMS1(cinfo,lvl,code,p1) \
  168255. ((cinfo)->err->msg_code = (code), \
  168256. (cinfo)->err->msg_parm.i[0] = (p1), \
  168257. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168258. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168259. ((cinfo)->err->msg_code = (code), \
  168260. (cinfo)->err->msg_parm.i[0] = (p1), \
  168261. (cinfo)->err->msg_parm.i[1] = (p2), \
  168262. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168263. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168264. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168265. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168266. (cinfo)->err->msg_code = (code); \
  168267. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168268. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168269. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168270. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168271. (cinfo)->err->msg_code = (code); \
  168272. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168273. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168274. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168275. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168276. _mp[4] = (p5); \
  168277. (cinfo)->err->msg_code = (code); \
  168278. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168279. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168280. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168281. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168282. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168283. (cinfo)->err->msg_code = (code); \
  168284. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168285. #define TRACEMSS(cinfo,lvl,code,str) \
  168286. ((cinfo)->err->msg_code = (code), \
  168287. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168288. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168289. #endif /* JERROR_H */
  168290. /*** End of inlined file: jerror.h ***/
  168291. /* Expanded data source object for stdio input */
  168292. typedef struct {
  168293. struct jpeg_source_mgr pub; /* public fields */
  168294. FILE * infile; /* source stream */
  168295. JOCTET * buffer; /* start of buffer */
  168296. boolean start_of_file; /* have we gotten any data yet? */
  168297. } my_source_mgr;
  168298. typedef my_source_mgr * my_src_ptr;
  168299. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168300. /*
  168301. * Initialize source --- called by jpeg_read_header
  168302. * before any data is actually read.
  168303. */
  168304. METHODDEF(void)
  168305. init_source (j_decompress_ptr cinfo)
  168306. {
  168307. my_src_ptr src = (my_src_ptr) cinfo->src;
  168308. /* We reset the empty-input-file flag for each image,
  168309. * but we don't clear the input buffer.
  168310. * This is correct behavior for reading a series of images from one source.
  168311. */
  168312. src->start_of_file = TRUE;
  168313. }
  168314. /*
  168315. * Fill the input buffer --- called whenever buffer is emptied.
  168316. *
  168317. * In typical applications, this should read fresh data into the buffer
  168318. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168319. * reset the pointer & count to the start of the buffer, and return TRUE
  168320. * indicating that the buffer has been reloaded. It is not necessary to
  168321. * fill the buffer entirely, only to obtain at least one more byte.
  168322. *
  168323. * There is no such thing as an EOF return. If the end of the file has been
  168324. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168325. * the buffer. In most cases, generating a warning message and inserting a
  168326. * fake EOI marker is the best course of action --- this will allow the
  168327. * decompressor to output however much of the image is there. However,
  168328. * the resulting error message is misleading if the real problem is an empty
  168329. * input file, so we handle that case specially.
  168330. *
  168331. * In applications that need to be able to suspend compression due to input
  168332. * not being available yet, a FALSE return indicates that no more data can be
  168333. * obtained right now, but more may be forthcoming later. In this situation,
  168334. * the decompressor will return to its caller (with an indication of the
  168335. * number of scanlines it has read, if any). The application should resume
  168336. * decompression after it has loaded more data into the input buffer. Note
  168337. * that there are substantial restrictions on the use of suspension --- see
  168338. * the documentation.
  168339. *
  168340. * When suspending, the decompressor will back up to a convenient restart point
  168341. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168342. * indicate where the restart point will be if the current call returns FALSE.
  168343. * Data beyond this point must be rescanned after resumption, so move it to
  168344. * the front of the buffer rather than discarding it.
  168345. */
  168346. METHODDEF(boolean)
  168347. fill_input_buffer (j_decompress_ptr cinfo)
  168348. {
  168349. my_src_ptr src = (my_src_ptr) cinfo->src;
  168350. size_t nbytes;
  168351. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168352. if (nbytes <= 0) {
  168353. if (src->start_of_file) /* Treat empty input file as fatal error */
  168354. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168355. WARNMS(cinfo, JWRN_JPEG_EOF);
  168356. /* Insert a fake EOI marker */
  168357. src->buffer[0] = (JOCTET) 0xFF;
  168358. src->buffer[1] = (JOCTET) JPEG_EOI;
  168359. nbytes = 2;
  168360. }
  168361. src->pub.next_input_byte = src->buffer;
  168362. src->pub.bytes_in_buffer = nbytes;
  168363. src->start_of_file = FALSE;
  168364. return TRUE;
  168365. }
  168366. /*
  168367. * Skip data --- used to skip over a potentially large amount of
  168368. * uninteresting data (such as an APPn marker).
  168369. *
  168370. * Writers of suspendable-input applications must note that skip_input_data
  168371. * is not granted the right to give a suspension return. If the skip extends
  168372. * beyond the data currently in the buffer, the buffer can be marked empty so
  168373. * that the next read will cause a fill_input_buffer call that can suspend.
  168374. * Arranging for additional bytes to be discarded before reloading the input
  168375. * buffer is the application writer's problem.
  168376. */
  168377. METHODDEF(void)
  168378. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168379. {
  168380. my_src_ptr src = (my_src_ptr) cinfo->src;
  168381. /* Just a dumb implementation for now. Could use fseek() except
  168382. * it doesn't work on pipes. Not clear that being smart is worth
  168383. * any trouble anyway --- large skips are infrequent.
  168384. */
  168385. if (num_bytes > 0) {
  168386. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168387. num_bytes -= (long) src->pub.bytes_in_buffer;
  168388. (void) fill_input_buffer(cinfo);
  168389. /* note we assume that fill_input_buffer will never return FALSE,
  168390. * so suspension need not be handled.
  168391. */
  168392. }
  168393. src->pub.next_input_byte += (size_t) num_bytes;
  168394. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168395. }
  168396. }
  168397. /*
  168398. * An additional method that can be provided by data source modules is the
  168399. * resync_to_restart method for error recovery in the presence of RST markers.
  168400. * For the moment, this source module just uses the default resync method
  168401. * provided by the JPEG library. That method assumes that no backtracking
  168402. * is possible.
  168403. */
  168404. /*
  168405. * Terminate source --- called by jpeg_finish_decompress
  168406. * after all data has been read. Often a no-op.
  168407. *
  168408. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168409. * application must deal with any cleanup that should happen even
  168410. * for error exit.
  168411. */
  168412. METHODDEF(void)
  168413. term_source (j_decompress_ptr)
  168414. {
  168415. /* no work necessary here */
  168416. }
  168417. /*
  168418. * Prepare for input from a stdio stream.
  168419. * The caller must have already opened the stream, and is responsible
  168420. * for closing it after finishing decompression.
  168421. */
  168422. GLOBAL(void)
  168423. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168424. {
  168425. my_src_ptr src;
  168426. /* The source object and input buffer are made permanent so that a series
  168427. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168428. * only before the first one. (If we discarded the buffer at the end of
  168429. * one image, we'd likely lose the start of the next one.)
  168430. * This makes it unsafe to use this manager and a different source
  168431. * manager serially with the same JPEG object. Caveat programmer.
  168432. */
  168433. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168434. cinfo->src = (struct jpeg_source_mgr *)
  168435. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168436. SIZEOF(my_source_mgr));
  168437. src = (my_src_ptr) cinfo->src;
  168438. src->buffer = (JOCTET *)
  168439. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168440. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168441. }
  168442. src = (my_src_ptr) cinfo->src;
  168443. src->pub.init_source = init_source;
  168444. src->pub.fill_input_buffer = fill_input_buffer;
  168445. src->pub.skip_input_data = skip_input_data;
  168446. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168447. src->pub.term_source = term_source;
  168448. src->infile = infile;
  168449. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168450. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168451. }
  168452. /*** End of inlined file: jdatasrc.c ***/
  168453. /*** Start of inlined file: jdcoefct.c ***/
  168454. #define JPEG_INTERNALS
  168455. /* Block smoothing is only applicable for progressive JPEG, so: */
  168456. #ifndef D_PROGRESSIVE_SUPPORTED
  168457. #undef BLOCK_SMOOTHING_SUPPORTED
  168458. #endif
  168459. /* Private buffer controller object */
  168460. typedef struct {
  168461. struct jpeg_d_coef_controller pub; /* public fields */
  168462. /* These variables keep track of the current location of the input side. */
  168463. /* cinfo->input_iMCU_row is also used for this. */
  168464. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168465. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168466. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168467. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168468. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168469. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168470. * and let the entropy decoder write into that workspace each time.
  168471. * (On 80x86, the workspace is FAR even though it's not really very big;
  168472. * this is to keep the module interfaces unchanged when a large coefficient
  168473. * buffer is necessary.)
  168474. * In multi-pass modes, this array points to the current MCU's blocks
  168475. * within the virtual arrays; it is used only by the input side.
  168476. */
  168477. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168478. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168479. /* In multi-pass modes, we need a virtual block array for each component. */
  168480. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168481. #endif
  168482. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168483. /* When doing block smoothing, we latch coefficient Al values here */
  168484. int * coef_bits_latch;
  168485. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168486. #endif
  168487. } my_coef_controller3;
  168488. typedef my_coef_controller3 * my_coef_ptr3;
  168489. /* Forward declarations */
  168490. METHODDEF(int) decompress_onepass
  168491. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168492. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168493. METHODDEF(int) decompress_data
  168494. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168495. #endif
  168496. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168497. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168498. METHODDEF(int) decompress_smooth_data
  168499. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168500. #endif
  168501. LOCAL(void)
  168502. start_iMCU_row3 (j_decompress_ptr cinfo)
  168503. /* Reset within-iMCU-row counters for a new row (input side) */
  168504. {
  168505. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168506. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168507. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168508. * But at the bottom of the image, process only what's left.
  168509. */
  168510. if (cinfo->comps_in_scan > 1) {
  168511. coef->MCU_rows_per_iMCU_row = 1;
  168512. } else {
  168513. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168514. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168515. else
  168516. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168517. }
  168518. coef->MCU_ctr = 0;
  168519. coef->MCU_vert_offset = 0;
  168520. }
  168521. /*
  168522. * Initialize for an input processing pass.
  168523. */
  168524. METHODDEF(void)
  168525. start_input_pass (j_decompress_ptr cinfo)
  168526. {
  168527. cinfo->input_iMCU_row = 0;
  168528. start_iMCU_row3(cinfo);
  168529. }
  168530. /*
  168531. * Initialize for an output processing pass.
  168532. */
  168533. METHODDEF(void)
  168534. start_output_pass (j_decompress_ptr cinfo)
  168535. {
  168536. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168537. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168538. /* If multipass, check to see whether to use block smoothing on this pass */
  168539. if (coef->pub.coef_arrays != NULL) {
  168540. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168541. coef->pub.decompress_data = decompress_smooth_data;
  168542. else
  168543. coef->pub.decompress_data = decompress_data;
  168544. }
  168545. #endif
  168546. cinfo->output_iMCU_row = 0;
  168547. }
  168548. /*
  168549. * Decompress and return some data in the single-pass case.
  168550. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168551. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168552. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168553. *
  168554. * NB: output_buf contains a plane for each component in image,
  168555. * which we index according to the component's SOF position.
  168556. */
  168557. METHODDEF(int)
  168558. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168559. {
  168560. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168561. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168562. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168563. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168564. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168565. JSAMPARRAY output_ptr;
  168566. JDIMENSION start_col, output_col;
  168567. jpeg_component_info *compptr;
  168568. inverse_DCT_method_ptr inverse_DCT;
  168569. /* Loop to process as much as one whole iMCU row */
  168570. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168571. yoffset++) {
  168572. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168573. MCU_col_num++) {
  168574. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168575. jzero_far((void FAR *) coef->MCU_buffer[0],
  168576. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168577. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168578. /* Suspension forced; update state counters and exit */
  168579. coef->MCU_vert_offset = yoffset;
  168580. coef->MCU_ctr = MCU_col_num;
  168581. return JPEG_SUSPENDED;
  168582. }
  168583. /* Determine where data should go in output_buf and do the IDCT thing.
  168584. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168585. * incremented past them!). Note the inner loop relies on having
  168586. * allocated the MCU_buffer[] blocks sequentially.
  168587. */
  168588. blkn = 0; /* index of current DCT block within MCU */
  168589. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168590. compptr = cinfo->cur_comp_info[ci];
  168591. /* Don't bother to IDCT an uninteresting component. */
  168592. if (! compptr->component_needed) {
  168593. blkn += compptr->MCU_blocks;
  168594. continue;
  168595. }
  168596. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168597. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168598. : compptr->last_col_width;
  168599. output_ptr = output_buf[compptr->component_index] +
  168600. yoffset * compptr->DCT_scaled_size;
  168601. start_col = MCU_col_num * compptr->MCU_sample_width;
  168602. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168603. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168604. yoffset+yindex < compptr->last_row_height) {
  168605. output_col = start_col;
  168606. for (xindex = 0; xindex < useful_width; xindex++) {
  168607. (*inverse_DCT) (cinfo, compptr,
  168608. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168609. output_ptr, output_col);
  168610. output_col += compptr->DCT_scaled_size;
  168611. }
  168612. }
  168613. blkn += compptr->MCU_width;
  168614. output_ptr += compptr->DCT_scaled_size;
  168615. }
  168616. }
  168617. }
  168618. /* Completed an MCU row, but perhaps not an iMCU row */
  168619. coef->MCU_ctr = 0;
  168620. }
  168621. /* Completed the iMCU row, advance counters for next one */
  168622. cinfo->output_iMCU_row++;
  168623. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168624. start_iMCU_row3(cinfo);
  168625. return JPEG_ROW_COMPLETED;
  168626. }
  168627. /* Completed the scan */
  168628. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168629. return JPEG_SCAN_COMPLETED;
  168630. }
  168631. /*
  168632. * Dummy consume-input routine for single-pass operation.
  168633. */
  168634. METHODDEF(int)
  168635. dummy_consume_data (j_decompress_ptr)
  168636. {
  168637. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168638. }
  168639. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168640. /*
  168641. * Consume input data and store it in the full-image coefficient buffer.
  168642. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168643. * ie, v_samp_factor block rows for each component in the scan.
  168644. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168645. */
  168646. METHODDEF(int)
  168647. consume_data (j_decompress_ptr cinfo)
  168648. {
  168649. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168650. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168651. int blkn, ci, xindex, yindex, yoffset;
  168652. JDIMENSION start_col;
  168653. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168654. JBLOCKROW buffer_ptr;
  168655. jpeg_component_info *compptr;
  168656. /* Align the virtual buffers for the components used in this scan. */
  168657. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168658. compptr = cinfo->cur_comp_info[ci];
  168659. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168660. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168661. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168662. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168663. /* Note: entropy decoder expects buffer to be zeroed,
  168664. * but this is handled automatically by the memory manager
  168665. * because we requested a pre-zeroed array.
  168666. */
  168667. }
  168668. /* Loop to process one whole iMCU row */
  168669. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168670. yoffset++) {
  168671. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168672. MCU_col_num++) {
  168673. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168674. blkn = 0; /* index of current DCT block within MCU */
  168675. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168676. compptr = cinfo->cur_comp_info[ci];
  168677. start_col = MCU_col_num * compptr->MCU_width;
  168678. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168679. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168680. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168681. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168682. }
  168683. }
  168684. }
  168685. /* Try to fetch the MCU. */
  168686. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168687. /* Suspension forced; update state counters and exit */
  168688. coef->MCU_vert_offset = yoffset;
  168689. coef->MCU_ctr = MCU_col_num;
  168690. return JPEG_SUSPENDED;
  168691. }
  168692. }
  168693. /* Completed an MCU row, but perhaps not an iMCU row */
  168694. coef->MCU_ctr = 0;
  168695. }
  168696. /* Completed the iMCU row, advance counters for next one */
  168697. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168698. start_iMCU_row3(cinfo);
  168699. return JPEG_ROW_COMPLETED;
  168700. }
  168701. /* Completed the scan */
  168702. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168703. return JPEG_SCAN_COMPLETED;
  168704. }
  168705. /*
  168706. * Decompress and return some data in the multi-pass case.
  168707. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168708. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168709. *
  168710. * NB: output_buf contains a plane for each component in image.
  168711. */
  168712. METHODDEF(int)
  168713. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168714. {
  168715. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168716. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168717. JDIMENSION block_num;
  168718. int ci, block_row, block_rows;
  168719. JBLOCKARRAY buffer;
  168720. JBLOCKROW buffer_ptr;
  168721. JSAMPARRAY output_ptr;
  168722. JDIMENSION output_col;
  168723. jpeg_component_info *compptr;
  168724. inverse_DCT_method_ptr inverse_DCT;
  168725. /* Force some input to be done if we are getting ahead of the input. */
  168726. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168727. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168728. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168729. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168730. return JPEG_SUSPENDED;
  168731. }
  168732. /* OK, output from the virtual arrays. */
  168733. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168734. ci++, compptr++) {
  168735. /* Don't bother to IDCT an uninteresting component. */
  168736. if (! compptr->component_needed)
  168737. continue;
  168738. /* Align the virtual buffer for this component. */
  168739. buffer = (*cinfo->mem->access_virt_barray)
  168740. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168741. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168742. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168743. /* Count non-dummy DCT block rows in this iMCU row. */
  168744. if (cinfo->output_iMCU_row < last_iMCU_row)
  168745. block_rows = compptr->v_samp_factor;
  168746. else {
  168747. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168748. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168749. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168750. }
  168751. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168752. output_ptr = output_buf[ci];
  168753. /* Loop over all DCT blocks to be processed. */
  168754. for (block_row = 0; block_row < block_rows; block_row++) {
  168755. buffer_ptr = buffer[block_row];
  168756. output_col = 0;
  168757. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168758. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168759. output_ptr, output_col);
  168760. buffer_ptr++;
  168761. output_col += compptr->DCT_scaled_size;
  168762. }
  168763. output_ptr += compptr->DCT_scaled_size;
  168764. }
  168765. }
  168766. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168767. return JPEG_ROW_COMPLETED;
  168768. return JPEG_SCAN_COMPLETED;
  168769. }
  168770. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168771. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168772. /*
  168773. * This code applies interblock smoothing as described by section K.8
  168774. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168775. * the DC values of a DCT block and its 8 neighboring blocks.
  168776. * We apply smoothing only for progressive JPEG decoding, and only if
  168777. * the coefficients it can estimate are not yet known to full precision.
  168778. */
  168779. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168780. #define Q01_POS 1
  168781. #define Q10_POS 8
  168782. #define Q20_POS 16
  168783. #define Q11_POS 9
  168784. #define Q02_POS 2
  168785. /*
  168786. * Determine whether block smoothing is applicable and safe.
  168787. * We also latch the current states of the coef_bits[] entries for the
  168788. * AC coefficients; otherwise, if the input side of the decompressor
  168789. * advances into a new scan, we might think the coefficients are known
  168790. * more accurately than they really are.
  168791. */
  168792. LOCAL(boolean)
  168793. smoothing_ok (j_decompress_ptr cinfo)
  168794. {
  168795. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168796. boolean smoothing_useful = FALSE;
  168797. int ci, coefi;
  168798. jpeg_component_info *compptr;
  168799. JQUANT_TBL * qtable;
  168800. int * coef_bits;
  168801. int * coef_bits_latch;
  168802. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168803. return FALSE;
  168804. /* Allocate latch area if not already done */
  168805. if (coef->coef_bits_latch == NULL)
  168806. coef->coef_bits_latch = (int *)
  168807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168808. cinfo->num_components *
  168809. (SAVED_COEFS * SIZEOF(int)));
  168810. coef_bits_latch = coef->coef_bits_latch;
  168811. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168812. ci++, compptr++) {
  168813. /* All components' quantization values must already be latched. */
  168814. if ((qtable = compptr->quant_table) == NULL)
  168815. return FALSE;
  168816. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168817. if (qtable->quantval[0] == 0 ||
  168818. qtable->quantval[Q01_POS] == 0 ||
  168819. qtable->quantval[Q10_POS] == 0 ||
  168820. qtable->quantval[Q20_POS] == 0 ||
  168821. qtable->quantval[Q11_POS] == 0 ||
  168822. qtable->quantval[Q02_POS] == 0)
  168823. return FALSE;
  168824. /* DC values must be at least partly known for all components. */
  168825. coef_bits = cinfo->coef_bits[ci];
  168826. if (coef_bits[0] < 0)
  168827. return FALSE;
  168828. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168829. for (coefi = 1; coefi <= 5; coefi++) {
  168830. coef_bits_latch[coefi] = coef_bits[coefi];
  168831. if (coef_bits[coefi] != 0)
  168832. smoothing_useful = TRUE;
  168833. }
  168834. coef_bits_latch += SAVED_COEFS;
  168835. }
  168836. return smoothing_useful;
  168837. }
  168838. /*
  168839. * Variant of decompress_data for use when doing block smoothing.
  168840. */
  168841. METHODDEF(int)
  168842. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168843. {
  168844. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168845. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168846. JDIMENSION block_num, last_block_column;
  168847. int ci, block_row, block_rows, access_rows;
  168848. JBLOCKARRAY buffer;
  168849. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168850. JSAMPARRAY output_ptr;
  168851. JDIMENSION output_col;
  168852. jpeg_component_info *compptr;
  168853. inverse_DCT_method_ptr inverse_DCT;
  168854. boolean first_row, last_row;
  168855. JBLOCK workspace;
  168856. int *coef_bits;
  168857. JQUANT_TBL *quanttbl;
  168858. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168859. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168860. int Al, pred;
  168861. /* Force some input to be done if we are getting ahead of the input. */
  168862. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168863. ! cinfo->inputctl->eoi_reached) {
  168864. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168865. /* If input is working on current scan, we ordinarily want it to
  168866. * have completed the current row. But if input scan is DC,
  168867. * we want it to keep one row ahead so that next block row's DC
  168868. * values are up to date.
  168869. */
  168870. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168871. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168872. break;
  168873. }
  168874. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168875. return JPEG_SUSPENDED;
  168876. }
  168877. /* OK, output from the virtual arrays. */
  168878. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168879. ci++, compptr++) {
  168880. /* Don't bother to IDCT an uninteresting component. */
  168881. if (! compptr->component_needed)
  168882. continue;
  168883. /* Count non-dummy DCT block rows in this iMCU row. */
  168884. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168885. block_rows = compptr->v_samp_factor;
  168886. access_rows = block_rows * 2; /* this and next iMCU row */
  168887. last_row = FALSE;
  168888. } else {
  168889. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168890. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168891. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168892. access_rows = block_rows; /* this iMCU row only */
  168893. last_row = TRUE;
  168894. }
  168895. /* Align the virtual buffer for this component. */
  168896. if (cinfo->output_iMCU_row > 0) {
  168897. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168898. buffer = (*cinfo->mem->access_virt_barray)
  168899. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168900. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168901. (JDIMENSION) access_rows, FALSE);
  168902. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168903. first_row = FALSE;
  168904. } else {
  168905. buffer = (*cinfo->mem->access_virt_barray)
  168906. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168907. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168908. first_row = TRUE;
  168909. }
  168910. /* Fetch component-dependent info */
  168911. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168912. quanttbl = compptr->quant_table;
  168913. Q00 = quanttbl->quantval[0];
  168914. Q01 = quanttbl->quantval[Q01_POS];
  168915. Q10 = quanttbl->quantval[Q10_POS];
  168916. Q20 = quanttbl->quantval[Q20_POS];
  168917. Q11 = quanttbl->quantval[Q11_POS];
  168918. Q02 = quanttbl->quantval[Q02_POS];
  168919. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168920. output_ptr = output_buf[ci];
  168921. /* Loop over all DCT blocks to be processed. */
  168922. for (block_row = 0; block_row < block_rows; block_row++) {
  168923. buffer_ptr = buffer[block_row];
  168924. if (first_row && block_row == 0)
  168925. prev_block_row = buffer_ptr;
  168926. else
  168927. prev_block_row = buffer[block_row-1];
  168928. if (last_row && block_row == block_rows-1)
  168929. next_block_row = buffer_ptr;
  168930. else
  168931. next_block_row = buffer[block_row+1];
  168932. /* We fetch the surrounding DC values using a sliding-register approach.
  168933. * Initialize all nine here so as to do the right thing on narrow pics.
  168934. */
  168935. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168936. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168937. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168938. output_col = 0;
  168939. last_block_column = compptr->width_in_blocks - 1;
  168940. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168941. /* Fetch current DCT block into workspace so we can modify it. */
  168942. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168943. /* Update DC values */
  168944. if (block_num < last_block_column) {
  168945. DC3 = (int) prev_block_row[1][0];
  168946. DC6 = (int) buffer_ptr[1][0];
  168947. DC9 = (int) next_block_row[1][0];
  168948. }
  168949. /* Compute coefficient estimates per K.8.
  168950. * An estimate is applied only if coefficient is still zero,
  168951. * and is not known to be fully accurate.
  168952. */
  168953. /* AC01 */
  168954. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168955. num = 36 * Q00 * (DC4 - DC6);
  168956. if (num >= 0) {
  168957. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168958. if (Al > 0 && pred >= (1<<Al))
  168959. pred = (1<<Al)-1;
  168960. } else {
  168961. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168962. if (Al > 0 && pred >= (1<<Al))
  168963. pred = (1<<Al)-1;
  168964. pred = -pred;
  168965. }
  168966. workspace[1] = (JCOEF) pred;
  168967. }
  168968. /* AC10 */
  168969. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168970. num = 36 * Q00 * (DC2 - DC8);
  168971. if (num >= 0) {
  168972. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168973. if (Al > 0 && pred >= (1<<Al))
  168974. pred = (1<<Al)-1;
  168975. } else {
  168976. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168977. if (Al > 0 && pred >= (1<<Al))
  168978. pred = (1<<Al)-1;
  168979. pred = -pred;
  168980. }
  168981. workspace[8] = (JCOEF) pred;
  168982. }
  168983. /* AC20 */
  168984. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168985. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168986. if (num >= 0) {
  168987. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168988. if (Al > 0 && pred >= (1<<Al))
  168989. pred = (1<<Al)-1;
  168990. } else {
  168991. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168992. if (Al > 0 && pred >= (1<<Al))
  168993. pred = (1<<Al)-1;
  168994. pred = -pred;
  168995. }
  168996. workspace[16] = (JCOEF) pred;
  168997. }
  168998. /* AC11 */
  168999. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169000. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169001. if (num >= 0) {
  169002. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169003. if (Al > 0 && pred >= (1<<Al))
  169004. pred = (1<<Al)-1;
  169005. } else {
  169006. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169007. if (Al > 0 && pred >= (1<<Al))
  169008. pred = (1<<Al)-1;
  169009. pred = -pred;
  169010. }
  169011. workspace[9] = (JCOEF) pred;
  169012. }
  169013. /* AC02 */
  169014. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169015. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169016. if (num >= 0) {
  169017. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169018. if (Al > 0 && pred >= (1<<Al))
  169019. pred = (1<<Al)-1;
  169020. } else {
  169021. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169022. if (Al > 0 && pred >= (1<<Al))
  169023. pred = (1<<Al)-1;
  169024. pred = -pred;
  169025. }
  169026. workspace[2] = (JCOEF) pred;
  169027. }
  169028. /* OK, do the IDCT */
  169029. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169030. output_ptr, output_col);
  169031. /* Advance for next column */
  169032. DC1 = DC2; DC2 = DC3;
  169033. DC4 = DC5; DC5 = DC6;
  169034. DC7 = DC8; DC8 = DC9;
  169035. buffer_ptr++, prev_block_row++, next_block_row++;
  169036. output_col += compptr->DCT_scaled_size;
  169037. }
  169038. output_ptr += compptr->DCT_scaled_size;
  169039. }
  169040. }
  169041. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169042. return JPEG_ROW_COMPLETED;
  169043. return JPEG_SCAN_COMPLETED;
  169044. }
  169045. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169046. /*
  169047. * Initialize coefficient buffer controller.
  169048. */
  169049. GLOBAL(void)
  169050. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169051. {
  169052. my_coef_ptr3 coef;
  169053. coef = (my_coef_ptr3)
  169054. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169055. SIZEOF(my_coef_controller3));
  169056. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169057. coef->pub.start_input_pass = start_input_pass;
  169058. coef->pub.start_output_pass = start_output_pass;
  169059. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169060. coef->coef_bits_latch = NULL;
  169061. #endif
  169062. /* Create the coefficient buffer. */
  169063. if (need_full_buffer) {
  169064. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169065. /* Allocate a full-image virtual array for each component, */
  169066. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169067. /* Note we ask for a pre-zeroed array. */
  169068. int ci, access_rows;
  169069. jpeg_component_info *compptr;
  169070. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169071. ci++, compptr++) {
  169072. access_rows = compptr->v_samp_factor;
  169073. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169074. /* If block smoothing could be used, need a bigger window */
  169075. if (cinfo->progressive_mode)
  169076. access_rows *= 3;
  169077. #endif
  169078. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169079. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169080. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169081. (long) compptr->h_samp_factor),
  169082. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169083. (long) compptr->v_samp_factor),
  169084. (JDIMENSION) access_rows);
  169085. }
  169086. coef->pub.consume_data = consume_data;
  169087. coef->pub.decompress_data = decompress_data;
  169088. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169089. #else
  169090. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169091. #endif
  169092. } else {
  169093. /* We only need a single-MCU buffer. */
  169094. JBLOCKROW buffer;
  169095. int i;
  169096. buffer = (JBLOCKROW)
  169097. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169098. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169099. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169100. coef->MCU_buffer[i] = buffer + i;
  169101. }
  169102. coef->pub.consume_data = dummy_consume_data;
  169103. coef->pub.decompress_data = decompress_onepass;
  169104. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169105. }
  169106. }
  169107. /*** End of inlined file: jdcoefct.c ***/
  169108. #undef FIX
  169109. /*** Start of inlined file: jdcolor.c ***/
  169110. #define JPEG_INTERNALS
  169111. /* Private subobject */
  169112. typedef struct {
  169113. struct jpeg_color_deconverter pub; /* public fields */
  169114. /* Private state for YCC->RGB conversion */
  169115. int * Cr_r_tab; /* => table for Cr to R conversion */
  169116. int * Cb_b_tab; /* => table for Cb to B conversion */
  169117. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169118. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169119. } my_color_deconverter2;
  169120. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169121. /**************** YCbCr -> RGB conversion: most common case **************/
  169122. /*
  169123. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169124. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169125. * The conversion equations to be implemented are therefore
  169126. * R = Y + 1.40200 * Cr
  169127. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169128. * B = Y + 1.77200 * Cb
  169129. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169130. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169131. *
  169132. * To avoid floating-point arithmetic, we represent the fractional constants
  169133. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169134. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169135. * Notice that Y, being an integral input, does not contribute any fraction
  169136. * so it need not participate in the rounding.
  169137. *
  169138. * For even more speed, we avoid doing any multiplications in the inner loop
  169139. * by precalculating the constants times Cb and Cr for all possible values.
  169140. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169141. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169142. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169143. * colorspace anyway.
  169144. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169145. * values for the G calculation are left scaled up, since we must add them
  169146. * together before rounding.
  169147. */
  169148. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169149. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169150. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169151. /*
  169152. * Initialize tables for YCC->RGB colorspace conversion.
  169153. */
  169154. LOCAL(void)
  169155. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169156. {
  169157. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169158. int i;
  169159. INT32 x;
  169160. SHIFT_TEMPS
  169161. cconvert->Cr_r_tab = (int *)
  169162. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169163. (MAXJSAMPLE+1) * SIZEOF(int));
  169164. cconvert->Cb_b_tab = (int *)
  169165. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169166. (MAXJSAMPLE+1) * SIZEOF(int));
  169167. cconvert->Cr_g_tab = (INT32 *)
  169168. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169169. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169170. cconvert->Cb_g_tab = (INT32 *)
  169171. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169172. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169173. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169174. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169175. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169176. /* Cr=>R value is nearest int to 1.40200 * x */
  169177. cconvert->Cr_r_tab[i] = (int)
  169178. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169179. /* Cb=>B value is nearest int to 1.77200 * x */
  169180. cconvert->Cb_b_tab[i] = (int)
  169181. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169182. /* Cr=>G value is scaled-up -0.71414 * x */
  169183. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169184. /* Cb=>G value is scaled-up -0.34414 * x */
  169185. /* We also add in ONE_HALF so that need not do it in inner loop */
  169186. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169187. }
  169188. }
  169189. /*
  169190. * Convert some rows of samples to the output colorspace.
  169191. *
  169192. * Note that we change from noninterleaved, one-plane-per-component format
  169193. * to interleaved-pixel format. The output buffer is therefore three times
  169194. * as wide as the input buffer.
  169195. * A starting row offset is provided only for the input buffer. The caller
  169196. * can easily adjust the passed output_buf value to accommodate any row
  169197. * offset required on that side.
  169198. */
  169199. METHODDEF(void)
  169200. ycc_rgb_convert (j_decompress_ptr cinfo,
  169201. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169202. JSAMPARRAY output_buf, int num_rows)
  169203. {
  169204. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169205. register int y, cb, cr;
  169206. register JSAMPROW outptr;
  169207. register JSAMPROW inptr0, inptr1, inptr2;
  169208. register JDIMENSION col;
  169209. JDIMENSION num_cols = cinfo->output_width;
  169210. /* copy these pointers into registers if possible */
  169211. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169212. register int * Crrtab = cconvert->Cr_r_tab;
  169213. register int * Cbbtab = cconvert->Cb_b_tab;
  169214. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169215. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169216. SHIFT_TEMPS
  169217. while (--num_rows >= 0) {
  169218. inptr0 = input_buf[0][input_row];
  169219. inptr1 = input_buf[1][input_row];
  169220. inptr2 = input_buf[2][input_row];
  169221. input_row++;
  169222. outptr = *output_buf++;
  169223. for (col = 0; col < num_cols; col++) {
  169224. y = GETJSAMPLE(inptr0[col]);
  169225. cb = GETJSAMPLE(inptr1[col]);
  169226. cr = GETJSAMPLE(inptr2[col]);
  169227. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169228. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169229. outptr[RGB_GREEN] = range_limit[y +
  169230. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169231. SCALEBITS))];
  169232. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169233. outptr += RGB_PIXELSIZE;
  169234. }
  169235. }
  169236. }
  169237. /**************** Cases other than YCbCr -> RGB **************/
  169238. /*
  169239. * Color conversion for no colorspace change: just copy the data,
  169240. * converting from separate-planes to interleaved representation.
  169241. */
  169242. METHODDEF(void)
  169243. null_convert2 (j_decompress_ptr cinfo,
  169244. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169245. JSAMPARRAY output_buf, int num_rows)
  169246. {
  169247. register JSAMPROW inptr, outptr;
  169248. register JDIMENSION count;
  169249. register int num_components = cinfo->num_components;
  169250. JDIMENSION num_cols = cinfo->output_width;
  169251. int ci;
  169252. while (--num_rows >= 0) {
  169253. for (ci = 0; ci < num_components; ci++) {
  169254. inptr = input_buf[ci][input_row];
  169255. outptr = output_buf[0] + ci;
  169256. for (count = num_cols; count > 0; count--) {
  169257. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169258. outptr += num_components;
  169259. }
  169260. }
  169261. input_row++;
  169262. output_buf++;
  169263. }
  169264. }
  169265. /*
  169266. * Color conversion for grayscale: just copy the data.
  169267. * This also works for YCbCr -> grayscale conversion, in which
  169268. * we just copy the Y (luminance) component and ignore chrominance.
  169269. */
  169270. METHODDEF(void)
  169271. grayscale_convert2 (j_decompress_ptr cinfo,
  169272. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169273. JSAMPARRAY output_buf, int num_rows)
  169274. {
  169275. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169276. num_rows, cinfo->output_width);
  169277. }
  169278. /*
  169279. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169280. * This is provided to support applications that don't want to cope
  169281. * with grayscale as a separate case.
  169282. */
  169283. METHODDEF(void)
  169284. gray_rgb_convert (j_decompress_ptr cinfo,
  169285. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169286. JSAMPARRAY output_buf, int num_rows)
  169287. {
  169288. register JSAMPROW inptr, outptr;
  169289. register JDIMENSION col;
  169290. JDIMENSION num_cols = cinfo->output_width;
  169291. while (--num_rows >= 0) {
  169292. inptr = input_buf[0][input_row++];
  169293. outptr = *output_buf++;
  169294. for (col = 0; col < num_cols; col++) {
  169295. /* We can dispense with GETJSAMPLE() here */
  169296. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169297. outptr += RGB_PIXELSIZE;
  169298. }
  169299. }
  169300. }
  169301. /*
  169302. * Adobe-style YCCK->CMYK conversion.
  169303. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169304. * conversion as above, while passing K (black) unchanged.
  169305. * We assume build_ycc_rgb_table has been called.
  169306. */
  169307. METHODDEF(void)
  169308. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169309. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169310. JSAMPARRAY output_buf, int num_rows)
  169311. {
  169312. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169313. register int y, cb, cr;
  169314. register JSAMPROW outptr;
  169315. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169316. register JDIMENSION col;
  169317. JDIMENSION num_cols = cinfo->output_width;
  169318. /* copy these pointers into registers if possible */
  169319. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169320. register int * Crrtab = cconvert->Cr_r_tab;
  169321. register int * Cbbtab = cconvert->Cb_b_tab;
  169322. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169323. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169324. SHIFT_TEMPS
  169325. while (--num_rows >= 0) {
  169326. inptr0 = input_buf[0][input_row];
  169327. inptr1 = input_buf[1][input_row];
  169328. inptr2 = input_buf[2][input_row];
  169329. inptr3 = input_buf[3][input_row];
  169330. input_row++;
  169331. outptr = *output_buf++;
  169332. for (col = 0; col < num_cols; col++) {
  169333. y = GETJSAMPLE(inptr0[col]);
  169334. cb = GETJSAMPLE(inptr1[col]);
  169335. cr = GETJSAMPLE(inptr2[col]);
  169336. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169337. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169338. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169339. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169340. SCALEBITS)))];
  169341. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169342. /* K passes through unchanged */
  169343. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169344. outptr += 4;
  169345. }
  169346. }
  169347. }
  169348. /*
  169349. * Empty method for start_pass.
  169350. */
  169351. METHODDEF(void)
  169352. start_pass_dcolor (j_decompress_ptr)
  169353. {
  169354. /* no work needed */
  169355. }
  169356. /*
  169357. * Module initialization routine for output colorspace conversion.
  169358. */
  169359. GLOBAL(void)
  169360. jinit_color_deconverter (j_decompress_ptr cinfo)
  169361. {
  169362. my_cconvert_ptr2 cconvert;
  169363. int ci;
  169364. cconvert = (my_cconvert_ptr2)
  169365. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169366. SIZEOF(my_color_deconverter2));
  169367. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169368. cconvert->pub.start_pass = start_pass_dcolor;
  169369. /* Make sure num_components agrees with jpeg_color_space */
  169370. switch (cinfo->jpeg_color_space) {
  169371. case JCS_GRAYSCALE:
  169372. if (cinfo->num_components != 1)
  169373. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169374. break;
  169375. case JCS_RGB:
  169376. case JCS_YCbCr:
  169377. if (cinfo->num_components != 3)
  169378. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169379. break;
  169380. case JCS_CMYK:
  169381. case JCS_YCCK:
  169382. if (cinfo->num_components != 4)
  169383. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169384. break;
  169385. default: /* JCS_UNKNOWN can be anything */
  169386. if (cinfo->num_components < 1)
  169387. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169388. break;
  169389. }
  169390. /* Set out_color_components and conversion method based on requested space.
  169391. * Also clear the component_needed flags for any unused components,
  169392. * so that earlier pipeline stages can avoid useless computation.
  169393. */
  169394. switch (cinfo->out_color_space) {
  169395. case JCS_GRAYSCALE:
  169396. cinfo->out_color_components = 1;
  169397. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169398. cinfo->jpeg_color_space == JCS_YCbCr) {
  169399. cconvert->pub.color_convert = grayscale_convert2;
  169400. /* For color->grayscale conversion, only the Y (0) component is needed */
  169401. for (ci = 1; ci < cinfo->num_components; ci++)
  169402. cinfo->comp_info[ci].component_needed = FALSE;
  169403. } else
  169404. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169405. break;
  169406. case JCS_RGB:
  169407. cinfo->out_color_components = RGB_PIXELSIZE;
  169408. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169409. cconvert->pub.color_convert = ycc_rgb_convert;
  169410. build_ycc_rgb_table(cinfo);
  169411. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169412. cconvert->pub.color_convert = gray_rgb_convert;
  169413. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169414. cconvert->pub.color_convert = null_convert2;
  169415. } else
  169416. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169417. break;
  169418. case JCS_CMYK:
  169419. cinfo->out_color_components = 4;
  169420. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169421. cconvert->pub.color_convert = ycck_cmyk_convert;
  169422. build_ycc_rgb_table(cinfo);
  169423. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169424. cconvert->pub.color_convert = null_convert2;
  169425. } else
  169426. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169427. break;
  169428. default:
  169429. /* Permit null conversion to same output space */
  169430. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169431. cinfo->out_color_components = cinfo->num_components;
  169432. cconvert->pub.color_convert = null_convert2;
  169433. } else /* unsupported non-null conversion */
  169434. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169435. break;
  169436. }
  169437. if (cinfo->quantize_colors)
  169438. cinfo->output_components = 1; /* single colormapped output component */
  169439. else
  169440. cinfo->output_components = cinfo->out_color_components;
  169441. }
  169442. /*** End of inlined file: jdcolor.c ***/
  169443. #undef FIX
  169444. /*** Start of inlined file: jddctmgr.c ***/
  169445. #define JPEG_INTERNALS
  169446. /*
  169447. * The decompressor input side (jdinput.c) saves away the appropriate
  169448. * quantization table for each component at the start of the first scan
  169449. * involving that component. (This is necessary in order to correctly
  169450. * decode files that reuse Q-table slots.)
  169451. * When we are ready to make an output pass, the saved Q-table is converted
  169452. * to a multiplier table that will actually be used by the IDCT routine.
  169453. * The multiplier table contents are IDCT-method-dependent. To support
  169454. * application changes in IDCT method between scans, we can remake the
  169455. * multiplier tables if necessary.
  169456. * In buffered-image mode, the first output pass may occur before any data
  169457. * has been seen for some components, and thus before their Q-tables have
  169458. * been saved away. To handle this case, multiplier tables are preset
  169459. * to zeroes; the result of the IDCT will be a neutral gray level.
  169460. */
  169461. /* Private subobject for this module */
  169462. typedef struct {
  169463. struct jpeg_inverse_dct pub; /* public fields */
  169464. /* This array contains the IDCT method code that each multiplier table
  169465. * is currently set up for, or -1 if it's not yet set up.
  169466. * The actual multiplier tables are pointed to by dct_table in the
  169467. * per-component comp_info structures.
  169468. */
  169469. int cur_method[MAX_COMPONENTS];
  169470. } my_idct_controller;
  169471. typedef my_idct_controller * my_idct_ptr;
  169472. /* Allocated multiplier tables: big enough for any supported variant */
  169473. typedef union {
  169474. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169475. #ifdef DCT_IFAST_SUPPORTED
  169476. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169477. #endif
  169478. #ifdef DCT_FLOAT_SUPPORTED
  169479. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169480. #endif
  169481. } multiplier_table;
  169482. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169483. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169484. */
  169485. #ifdef DCT_ISLOW_SUPPORTED
  169486. #define PROVIDE_ISLOW_TABLES
  169487. #else
  169488. #ifdef IDCT_SCALING_SUPPORTED
  169489. #define PROVIDE_ISLOW_TABLES
  169490. #endif
  169491. #endif
  169492. /*
  169493. * Prepare for an output pass.
  169494. * Here we select the proper IDCT routine for each component and build
  169495. * a matching multiplier table.
  169496. */
  169497. METHODDEF(void)
  169498. start_pass (j_decompress_ptr cinfo)
  169499. {
  169500. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169501. int ci, i;
  169502. jpeg_component_info *compptr;
  169503. int method = 0;
  169504. inverse_DCT_method_ptr method_ptr = NULL;
  169505. JQUANT_TBL * qtbl;
  169506. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169507. ci++, compptr++) {
  169508. /* Select the proper IDCT routine for this component's scaling */
  169509. switch (compptr->DCT_scaled_size) {
  169510. #ifdef IDCT_SCALING_SUPPORTED
  169511. case 1:
  169512. method_ptr = jpeg_idct_1x1;
  169513. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169514. break;
  169515. case 2:
  169516. method_ptr = jpeg_idct_2x2;
  169517. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169518. break;
  169519. case 4:
  169520. method_ptr = jpeg_idct_4x4;
  169521. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169522. break;
  169523. #endif
  169524. case DCTSIZE:
  169525. switch (cinfo->dct_method) {
  169526. #ifdef DCT_ISLOW_SUPPORTED
  169527. case JDCT_ISLOW:
  169528. method_ptr = jpeg_idct_islow;
  169529. method = JDCT_ISLOW;
  169530. break;
  169531. #endif
  169532. #ifdef DCT_IFAST_SUPPORTED
  169533. case JDCT_IFAST:
  169534. method_ptr = jpeg_idct_ifast;
  169535. method = JDCT_IFAST;
  169536. break;
  169537. #endif
  169538. #ifdef DCT_FLOAT_SUPPORTED
  169539. case JDCT_FLOAT:
  169540. method_ptr = jpeg_idct_float;
  169541. method = JDCT_FLOAT;
  169542. break;
  169543. #endif
  169544. default:
  169545. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169546. break;
  169547. }
  169548. break;
  169549. default:
  169550. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169551. break;
  169552. }
  169553. idct->pub.inverse_DCT[ci] = method_ptr;
  169554. /* Create multiplier table from quant table.
  169555. * However, we can skip this if the component is uninteresting
  169556. * or if we already built the table. Also, if no quant table
  169557. * has yet been saved for the component, we leave the
  169558. * multiplier table all-zero; we'll be reading zeroes from the
  169559. * coefficient controller's buffer anyway.
  169560. */
  169561. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169562. continue;
  169563. qtbl = compptr->quant_table;
  169564. if (qtbl == NULL) /* happens if no data yet for component */
  169565. continue;
  169566. idct->cur_method[ci] = method;
  169567. switch (method) {
  169568. #ifdef PROVIDE_ISLOW_TABLES
  169569. case JDCT_ISLOW:
  169570. {
  169571. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169572. * coefficients, but are stored as ints to ensure access efficiency.
  169573. */
  169574. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169575. for (i = 0; i < DCTSIZE2; i++) {
  169576. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169577. }
  169578. }
  169579. break;
  169580. #endif
  169581. #ifdef DCT_IFAST_SUPPORTED
  169582. case JDCT_IFAST:
  169583. {
  169584. /* For AA&N IDCT method, multipliers are equal to quantization
  169585. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169586. * scalefactor[0] = 1
  169587. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169588. * For integer operation, the multiplier table is to be scaled by
  169589. * IFAST_SCALE_BITS.
  169590. */
  169591. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169592. #define CONST_BITS 14
  169593. static const INT16 aanscales[DCTSIZE2] = {
  169594. /* precomputed values scaled up by 14 bits */
  169595. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169596. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169597. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169598. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169599. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169600. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169601. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169602. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169603. };
  169604. SHIFT_TEMPS
  169605. for (i = 0; i < DCTSIZE2; i++) {
  169606. ifmtbl[i] = (IFAST_MULT_TYPE)
  169607. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169608. (INT32) aanscales[i]),
  169609. CONST_BITS-IFAST_SCALE_BITS);
  169610. }
  169611. }
  169612. break;
  169613. #endif
  169614. #ifdef DCT_FLOAT_SUPPORTED
  169615. case JDCT_FLOAT:
  169616. {
  169617. /* For float AA&N IDCT method, multipliers are equal to quantization
  169618. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169619. * scalefactor[0] = 1
  169620. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169621. */
  169622. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169623. int row, col;
  169624. static const double aanscalefactor[DCTSIZE] = {
  169625. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169626. 1.0, 0.785694958, 0.541196100, 0.275899379
  169627. };
  169628. i = 0;
  169629. for (row = 0; row < DCTSIZE; row++) {
  169630. for (col = 0; col < DCTSIZE; col++) {
  169631. fmtbl[i] = (FLOAT_MULT_TYPE)
  169632. ((double) qtbl->quantval[i] *
  169633. aanscalefactor[row] * aanscalefactor[col]);
  169634. i++;
  169635. }
  169636. }
  169637. }
  169638. break;
  169639. #endif
  169640. default:
  169641. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169642. break;
  169643. }
  169644. }
  169645. }
  169646. /*
  169647. * Initialize IDCT manager.
  169648. */
  169649. GLOBAL(void)
  169650. jinit_inverse_dct (j_decompress_ptr cinfo)
  169651. {
  169652. my_idct_ptr idct;
  169653. int ci;
  169654. jpeg_component_info *compptr;
  169655. idct = (my_idct_ptr)
  169656. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169657. SIZEOF(my_idct_controller));
  169658. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169659. idct->pub.start_pass = start_pass;
  169660. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169661. ci++, compptr++) {
  169662. /* Allocate and pre-zero a multiplier table for each component */
  169663. compptr->dct_table =
  169664. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169665. SIZEOF(multiplier_table));
  169666. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169667. /* Mark multiplier table not yet set up for any method */
  169668. idct->cur_method[ci] = -1;
  169669. }
  169670. }
  169671. /*** End of inlined file: jddctmgr.c ***/
  169672. #undef CONST_BITS
  169673. #undef ASSIGN_STATE
  169674. /*** Start of inlined file: jdhuff.c ***/
  169675. #define JPEG_INTERNALS
  169676. /*** Start of inlined file: jdhuff.h ***/
  169677. /* Short forms of external names for systems with brain-damaged linkers. */
  169678. #ifndef __jdhuff_h__
  169679. #define __jdhuff_h__
  169680. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169681. #define jpeg_make_d_derived_tbl jMkDDerived
  169682. #define jpeg_fill_bit_buffer jFilBitBuf
  169683. #define jpeg_huff_decode jHufDecode
  169684. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169685. /* Derived data constructed for each Huffman table */
  169686. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169687. typedef struct {
  169688. /* Basic tables: (element [0] of each array is unused) */
  169689. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169690. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169691. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169692. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169693. * the smallest code of length k; so given a code of length k, the
  169694. * corresponding symbol is huffval[code + valoffset[k]]
  169695. */
  169696. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169697. JHUFF_TBL *pub;
  169698. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169699. * the input data stream. If the next Huffman code is no more
  169700. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169701. * the corresponding symbol directly from these tables.
  169702. */
  169703. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169704. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169705. } d_derived_tbl;
  169706. /* Expand a Huffman table definition into the derived format */
  169707. EXTERN(void) jpeg_make_d_derived_tbl
  169708. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169709. d_derived_tbl ** pdtbl));
  169710. /*
  169711. * Fetching the next N bits from the input stream is a time-critical operation
  169712. * for the Huffman decoders. We implement it with a combination of inline
  169713. * macros and out-of-line subroutines. Note that N (the number of bits
  169714. * demanded at one time) never exceeds 15 for JPEG use.
  169715. *
  169716. * We read source bytes into get_buffer and dole out bits as needed.
  169717. * If get_buffer already contains enough bits, they are fetched in-line
  169718. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169719. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169720. * as full as possible (not just to the number of bits needed; this
  169721. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169722. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169723. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169724. * at least the requested number of bits --- dummy zeroes are inserted if
  169725. * necessary.
  169726. */
  169727. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169728. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169729. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169730. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169731. * appropriately should be a win. Unfortunately we can't define the size
  169732. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169733. * because not all machines measure sizeof in 8-bit bytes.
  169734. */
  169735. typedef struct { /* Bitreading state saved across MCUs */
  169736. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169737. int bits_left; /* # of unused bits in it */
  169738. } bitread_perm_state;
  169739. typedef struct { /* Bitreading working state within an MCU */
  169740. /* Current data source location */
  169741. /* We need a copy, rather than munging the original, in case of suspension */
  169742. const JOCTET * next_input_byte; /* => next byte to read from source */
  169743. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169744. /* Bit input buffer --- note these values are kept in register variables,
  169745. * not in this struct, inside the inner loops.
  169746. */
  169747. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169748. int bits_left; /* # of unused bits in it */
  169749. /* Pointer needed by jpeg_fill_bit_buffer. */
  169750. j_decompress_ptr cinfo; /* back link to decompress master record */
  169751. } bitread_working_state;
  169752. /* Macros to declare and load/save bitread local variables. */
  169753. #define BITREAD_STATE_VARS \
  169754. register bit_buf_type get_buffer; \
  169755. register int bits_left; \
  169756. bitread_working_state br_state
  169757. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169758. br_state.cinfo = cinfop; \
  169759. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169760. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169761. get_buffer = permstate.get_buffer; \
  169762. bits_left = permstate.bits_left;
  169763. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169764. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169765. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169766. permstate.get_buffer = get_buffer; \
  169767. permstate.bits_left = bits_left
  169768. /*
  169769. * These macros provide the in-line portion of bit fetching.
  169770. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169771. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169772. * The variables get_buffer and bits_left are assumed to be locals,
  169773. * but the state struct might not be (jpeg_huff_decode needs this).
  169774. * CHECK_BIT_BUFFER(state,n,action);
  169775. * Ensure there are N bits in get_buffer; if suspend, take action.
  169776. * val = GET_BITS(n);
  169777. * Fetch next N bits.
  169778. * val = PEEK_BITS(n);
  169779. * Fetch next N bits without removing them from the buffer.
  169780. * DROP_BITS(n);
  169781. * Discard next N bits.
  169782. * The value N should be a simple variable, not an expression, because it
  169783. * is evaluated multiple times.
  169784. */
  169785. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169786. { if (bits_left < (nbits)) { \
  169787. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169788. { action; } \
  169789. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169790. #define GET_BITS(nbits) \
  169791. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169792. #define PEEK_BITS(nbits) \
  169793. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169794. #define DROP_BITS(nbits) \
  169795. (bits_left -= (nbits))
  169796. /* Load up the bit buffer to a depth of at least nbits */
  169797. EXTERN(boolean) jpeg_fill_bit_buffer
  169798. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169799. register int bits_left, int nbits));
  169800. /*
  169801. * Code for extracting next Huffman-coded symbol from input bit stream.
  169802. * Again, this is time-critical and we make the main paths be macros.
  169803. *
  169804. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169805. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169806. * or fewer bits long. The few overlength codes are handled with a loop,
  169807. * which need not be inline code.
  169808. *
  169809. * Notes about the HUFF_DECODE macro:
  169810. * 1. Near the end of the data segment, we may fail to get enough bits
  169811. * for a lookahead. In that case, we do it the hard way.
  169812. * 2. If the lookahead table contains no entry, the next code must be
  169813. * more than HUFF_LOOKAHEAD bits long.
  169814. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169815. */
  169816. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169817. { register int nb, look; \
  169818. if (bits_left < HUFF_LOOKAHEAD) { \
  169819. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169820. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169821. if (bits_left < HUFF_LOOKAHEAD) { \
  169822. nb = 1; goto slowlabel; \
  169823. } \
  169824. } \
  169825. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169826. if ((nb = htbl->look_nbits[look]) != 0) { \
  169827. DROP_BITS(nb); \
  169828. result = htbl->look_sym[look]; \
  169829. } else { \
  169830. nb = HUFF_LOOKAHEAD+1; \
  169831. slowlabel: \
  169832. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169833. { failaction; } \
  169834. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169835. } \
  169836. }
  169837. /* Out-of-line case for Huffman code fetching */
  169838. EXTERN(int) jpeg_huff_decode
  169839. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169840. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169841. #endif
  169842. /*** End of inlined file: jdhuff.h ***/
  169843. /* Declarations shared with jdphuff.c */
  169844. /*
  169845. * Expanded entropy decoder object for Huffman decoding.
  169846. *
  169847. * The savable_state subrecord contains fields that change within an MCU,
  169848. * but must not be updated permanently until we complete the MCU.
  169849. */
  169850. typedef struct {
  169851. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169852. } savable_state2;
  169853. /* This macro is to work around compilers with missing or broken
  169854. * structure assignment. You'll need to fix this code if you have
  169855. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169856. */
  169857. #ifndef NO_STRUCT_ASSIGN
  169858. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169859. #else
  169860. #if MAX_COMPS_IN_SCAN == 4
  169861. #define ASSIGN_STATE(dest,src) \
  169862. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169863. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169864. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169865. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169866. #endif
  169867. #endif
  169868. typedef struct {
  169869. struct jpeg_entropy_decoder pub; /* public fields */
  169870. /* These fields are loaded into local variables at start of each MCU.
  169871. * In case of suspension, we exit WITHOUT updating them.
  169872. */
  169873. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169874. savable_state2 saved; /* Other state at start of MCU */
  169875. /* These fields are NOT loaded into local working state. */
  169876. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169877. /* Pointers to derived tables (these workspaces have image lifespan) */
  169878. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169879. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169880. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169881. /* Pointers to derived tables to be used for each block within an MCU */
  169882. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169883. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169884. /* Whether we care about the DC and AC coefficient values for each block */
  169885. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169886. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169887. } huff_entropy_decoder2;
  169888. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169889. /*
  169890. * Initialize for a Huffman-compressed scan.
  169891. */
  169892. METHODDEF(void)
  169893. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169894. {
  169895. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169896. int ci, blkn, dctbl, actbl;
  169897. jpeg_component_info * compptr;
  169898. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169899. * This ought to be an error condition, but we make it a warning because
  169900. * there are some baseline files out there with all zeroes in these bytes.
  169901. */
  169902. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169903. cinfo->Ah != 0 || cinfo->Al != 0)
  169904. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169905. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169906. compptr = cinfo->cur_comp_info[ci];
  169907. dctbl = compptr->dc_tbl_no;
  169908. actbl = compptr->ac_tbl_no;
  169909. /* Compute derived values for Huffman tables */
  169910. /* We may do this more than once for a table, but it's not expensive */
  169911. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169912. & entropy->dc_derived_tbls[dctbl]);
  169913. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169914. & entropy->ac_derived_tbls[actbl]);
  169915. /* Initialize DC predictions to 0 */
  169916. entropy->saved.last_dc_val[ci] = 0;
  169917. }
  169918. /* Precalculate decoding info for each block in an MCU of this scan */
  169919. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169920. ci = cinfo->MCU_membership[blkn];
  169921. compptr = cinfo->cur_comp_info[ci];
  169922. /* Precalculate which table to use for each block */
  169923. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169924. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169925. /* Decide whether we really care about the coefficient values */
  169926. if (compptr->component_needed) {
  169927. entropy->dc_needed[blkn] = TRUE;
  169928. /* we don't need the ACs if producing a 1/8th-size image */
  169929. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169930. } else {
  169931. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169932. }
  169933. }
  169934. /* Initialize bitread state variables */
  169935. entropy->bitstate.bits_left = 0;
  169936. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169937. entropy->pub.insufficient_data = FALSE;
  169938. /* Initialize restart counter */
  169939. entropy->restarts_to_go = cinfo->restart_interval;
  169940. }
  169941. /*
  169942. * Compute the derived values for a Huffman table.
  169943. * This routine also performs some validation checks on the table.
  169944. *
  169945. * Note this is also used by jdphuff.c.
  169946. */
  169947. GLOBAL(void)
  169948. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169949. d_derived_tbl ** pdtbl)
  169950. {
  169951. JHUFF_TBL *htbl;
  169952. d_derived_tbl *dtbl;
  169953. int p, i, l, si, numsymbols;
  169954. int lookbits, ctr;
  169955. char huffsize[257];
  169956. unsigned int huffcode[257];
  169957. unsigned int code;
  169958. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169959. * paralleling the order of the symbols themselves in htbl->huffval[].
  169960. */
  169961. /* Find the input Huffman table */
  169962. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169963. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169964. htbl =
  169965. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169966. if (htbl == NULL)
  169967. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169968. /* Allocate a workspace if we haven't already done so. */
  169969. if (*pdtbl == NULL)
  169970. *pdtbl = (d_derived_tbl *)
  169971. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169972. SIZEOF(d_derived_tbl));
  169973. dtbl = *pdtbl;
  169974. dtbl->pub = htbl; /* fill in back link */
  169975. /* Figure C.1: make table of Huffman code length for each symbol */
  169976. p = 0;
  169977. for (l = 1; l <= 16; l++) {
  169978. i = (int) htbl->bits[l];
  169979. if (i < 0 || p + i > 256) /* protect against table overrun */
  169980. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169981. while (i--)
  169982. huffsize[p++] = (char) l;
  169983. }
  169984. huffsize[p] = 0;
  169985. numsymbols = p;
  169986. /* Figure C.2: generate the codes themselves */
  169987. /* We also validate that the counts represent a legal Huffman code tree. */
  169988. code = 0;
  169989. si = huffsize[0];
  169990. p = 0;
  169991. while (huffsize[p]) {
  169992. while (((int) huffsize[p]) == si) {
  169993. huffcode[p++] = code;
  169994. code++;
  169995. }
  169996. /* code is now 1 more than the last code used for codelength si; but
  169997. * it must still fit in si bits, since no code is allowed to be all ones.
  169998. */
  169999. if (((INT32) code) >= (((INT32) 1) << si))
  170000. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170001. code <<= 1;
  170002. si++;
  170003. }
  170004. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170005. p = 0;
  170006. for (l = 1; l <= 16; l++) {
  170007. if (htbl->bits[l]) {
  170008. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170009. * minus the minimum code of length l
  170010. */
  170011. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170012. p += htbl->bits[l];
  170013. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170014. } else {
  170015. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170016. }
  170017. }
  170018. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170019. /* Compute lookahead tables to speed up decoding.
  170020. * First we set all the table entries to 0, indicating "too long";
  170021. * then we iterate through the Huffman codes that are short enough and
  170022. * fill in all the entries that correspond to bit sequences starting
  170023. * with that code.
  170024. */
  170025. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170026. p = 0;
  170027. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170028. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170029. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170030. /* Generate left-justified code followed by all possible bit sequences */
  170031. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170032. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170033. dtbl->look_nbits[lookbits] = l;
  170034. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170035. lookbits++;
  170036. }
  170037. }
  170038. }
  170039. /* Validate symbols as being reasonable.
  170040. * For AC tables, we make no check, but accept all byte values 0..255.
  170041. * For DC tables, we require the symbols to be in range 0..15.
  170042. * (Tighter bounds could be applied depending on the data depth and mode,
  170043. * but this is sufficient to ensure safe decoding.)
  170044. */
  170045. if (isDC) {
  170046. for (i = 0; i < numsymbols; i++) {
  170047. int sym = htbl->huffval[i];
  170048. if (sym < 0 || sym > 15)
  170049. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170050. }
  170051. }
  170052. }
  170053. /*
  170054. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170055. * See jdhuff.h for info about usage.
  170056. * Note: current values of get_buffer and bits_left are passed as parameters,
  170057. * but are returned in the corresponding fields of the state struct.
  170058. *
  170059. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170060. * of get_buffer to be used. (On machines with wider words, an even larger
  170061. * buffer could be used.) However, on some machines 32-bit shifts are
  170062. * quite slow and take time proportional to the number of places shifted.
  170063. * (This is true with most PC compilers, for instance.) In this case it may
  170064. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170065. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170066. */
  170067. #ifdef SLOW_SHIFT_32
  170068. #define MIN_GET_BITS 15 /* minimum allowable value */
  170069. #else
  170070. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170071. #endif
  170072. GLOBAL(boolean)
  170073. jpeg_fill_bit_buffer (bitread_working_state * state,
  170074. register bit_buf_type get_buffer, register int bits_left,
  170075. int nbits)
  170076. /* Load up the bit buffer to a depth of at least nbits */
  170077. {
  170078. /* Copy heavily used state fields into locals (hopefully registers) */
  170079. register const JOCTET * next_input_byte = state->next_input_byte;
  170080. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170081. j_decompress_ptr cinfo = state->cinfo;
  170082. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170083. /* (It is assumed that no request will be for more than that many bits.) */
  170084. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170085. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170086. while (bits_left < MIN_GET_BITS) {
  170087. register int c;
  170088. /* Attempt to read a byte */
  170089. if (bytes_in_buffer == 0) {
  170090. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170091. return FALSE;
  170092. next_input_byte = cinfo->src->next_input_byte;
  170093. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170094. }
  170095. bytes_in_buffer--;
  170096. c = GETJOCTET(*next_input_byte++);
  170097. /* If it's 0xFF, check and discard stuffed zero byte */
  170098. if (c == 0xFF) {
  170099. /* Loop here to discard any padding FF's on terminating marker,
  170100. * so that we can save a valid unread_marker value. NOTE: we will
  170101. * accept multiple FF's followed by a 0 as meaning a single FF data
  170102. * byte. This data pattern is not valid according to the standard.
  170103. */
  170104. do {
  170105. if (bytes_in_buffer == 0) {
  170106. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170107. return FALSE;
  170108. next_input_byte = cinfo->src->next_input_byte;
  170109. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170110. }
  170111. bytes_in_buffer--;
  170112. c = GETJOCTET(*next_input_byte++);
  170113. } while (c == 0xFF);
  170114. if (c == 0) {
  170115. /* Found FF/00, which represents an FF data byte */
  170116. c = 0xFF;
  170117. } else {
  170118. /* Oops, it's actually a marker indicating end of compressed data.
  170119. * Save the marker code for later use.
  170120. * Fine point: it might appear that we should save the marker into
  170121. * bitread working state, not straight into permanent state. But
  170122. * once we have hit a marker, we cannot need to suspend within the
  170123. * current MCU, because we will read no more bytes from the data
  170124. * source. So it is OK to update permanent state right away.
  170125. */
  170126. cinfo->unread_marker = c;
  170127. /* See if we need to insert some fake zero bits. */
  170128. goto no_more_bytes;
  170129. }
  170130. }
  170131. /* OK, load c into get_buffer */
  170132. get_buffer = (get_buffer << 8) | c;
  170133. bits_left += 8;
  170134. } /* end while */
  170135. } else {
  170136. no_more_bytes:
  170137. /* We get here if we've read the marker that terminates the compressed
  170138. * data segment. There should be enough bits in the buffer register
  170139. * to satisfy the request; if so, no problem.
  170140. */
  170141. if (nbits > bits_left) {
  170142. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170143. * the data stream, so that we can produce some kind of image.
  170144. * We use a nonvolatile flag to ensure that only one warning message
  170145. * appears per data segment.
  170146. */
  170147. if (! cinfo->entropy->insufficient_data) {
  170148. WARNMS(cinfo, JWRN_HIT_MARKER);
  170149. cinfo->entropy->insufficient_data = TRUE;
  170150. }
  170151. /* Fill the buffer with zero bits */
  170152. get_buffer <<= MIN_GET_BITS - bits_left;
  170153. bits_left = MIN_GET_BITS;
  170154. }
  170155. }
  170156. /* Unload the local registers */
  170157. state->next_input_byte = next_input_byte;
  170158. state->bytes_in_buffer = bytes_in_buffer;
  170159. state->get_buffer = get_buffer;
  170160. state->bits_left = bits_left;
  170161. return TRUE;
  170162. }
  170163. /*
  170164. * Out-of-line code for Huffman code decoding.
  170165. * See jdhuff.h for info about usage.
  170166. */
  170167. GLOBAL(int)
  170168. jpeg_huff_decode (bitread_working_state * state,
  170169. register bit_buf_type get_buffer, register int bits_left,
  170170. d_derived_tbl * htbl, int min_bits)
  170171. {
  170172. register int l = min_bits;
  170173. register INT32 code;
  170174. /* HUFF_DECODE has determined that the code is at least min_bits */
  170175. /* bits long, so fetch that many bits in one swoop. */
  170176. CHECK_BIT_BUFFER(*state, l, return -1);
  170177. code = GET_BITS(l);
  170178. /* Collect the rest of the Huffman code one bit at a time. */
  170179. /* This is per Figure F.16 in the JPEG spec. */
  170180. while (code > htbl->maxcode[l]) {
  170181. code <<= 1;
  170182. CHECK_BIT_BUFFER(*state, 1, return -1);
  170183. code |= GET_BITS(1);
  170184. l++;
  170185. }
  170186. /* Unload the local registers */
  170187. state->get_buffer = get_buffer;
  170188. state->bits_left = bits_left;
  170189. /* With garbage input we may reach the sentinel value l = 17. */
  170190. if (l > 16) {
  170191. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170192. return 0; /* fake a zero as the safest result */
  170193. }
  170194. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170195. }
  170196. /*
  170197. * Check for a restart marker & resynchronize decoder.
  170198. * Returns FALSE if must suspend.
  170199. */
  170200. LOCAL(boolean)
  170201. process_restart (j_decompress_ptr cinfo)
  170202. {
  170203. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170204. int ci;
  170205. /* Throw away any unused bits remaining in bit buffer; */
  170206. /* include any full bytes in next_marker's count of discarded bytes */
  170207. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170208. entropy->bitstate.bits_left = 0;
  170209. /* Advance past the RSTn marker */
  170210. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170211. return FALSE;
  170212. /* Re-initialize DC predictions to 0 */
  170213. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170214. entropy->saved.last_dc_val[ci] = 0;
  170215. /* Reset restart counter */
  170216. entropy->restarts_to_go = cinfo->restart_interval;
  170217. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170218. * against a marker. In that case we will end up treating the next data
  170219. * segment as empty, and we can avoid producing bogus output pixels by
  170220. * leaving the flag set.
  170221. */
  170222. if (cinfo->unread_marker == 0)
  170223. entropy->pub.insufficient_data = FALSE;
  170224. return TRUE;
  170225. }
  170226. /*
  170227. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170228. * The coefficients are reordered from zigzag order into natural array order,
  170229. * but are not dequantized.
  170230. *
  170231. * The i'th block of the MCU is stored into the block pointed to by
  170232. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170233. * (Wholesale zeroing is usually a little faster than retail...)
  170234. *
  170235. * Returns FALSE if data source requested suspension. In that case no
  170236. * changes have been made to permanent state. (Exception: some output
  170237. * coefficients may already have been assigned. This is harmless for
  170238. * this module, since we'll just re-assign them on the next call.)
  170239. */
  170240. METHODDEF(boolean)
  170241. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170242. {
  170243. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170244. int blkn;
  170245. BITREAD_STATE_VARS;
  170246. savable_state2 state;
  170247. /* Process restart marker if needed; may have to suspend */
  170248. if (cinfo->restart_interval) {
  170249. if (entropy->restarts_to_go == 0)
  170250. if (! process_restart(cinfo))
  170251. return FALSE;
  170252. }
  170253. /* If we've run out of data, just leave the MCU set to zeroes.
  170254. * This way, we return uniform gray for the remainder of the segment.
  170255. */
  170256. if (! entropy->pub.insufficient_data) {
  170257. /* Load up working state */
  170258. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170259. ASSIGN_STATE(state, entropy->saved);
  170260. /* Outer loop handles each block in the MCU */
  170261. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170262. JBLOCKROW block = MCU_data[blkn];
  170263. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170264. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170265. register int s, k, r;
  170266. /* Decode a single block's worth of coefficients */
  170267. /* Section F.2.2.1: decode the DC coefficient difference */
  170268. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170269. if (s) {
  170270. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170271. r = GET_BITS(s);
  170272. s = HUFF_EXTEND(r, s);
  170273. }
  170274. if (entropy->dc_needed[blkn]) {
  170275. /* Convert DC difference to actual value, update last_dc_val */
  170276. int ci = cinfo->MCU_membership[blkn];
  170277. s += state.last_dc_val[ci];
  170278. state.last_dc_val[ci] = s;
  170279. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170280. (*block)[0] = (JCOEF) s;
  170281. }
  170282. if (entropy->ac_needed[blkn]) {
  170283. /* Section F.2.2.2: decode the AC coefficients */
  170284. /* Since zeroes are skipped, output area must be cleared beforehand */
  170285. for (k = 1; k < DCTSIZE2; k++) {
  170286. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170287. r = s >> 4;
  170288. s &= 15;
  170289. if (s) {
  170290. k += r;
  170291. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170292. r = GET_BITS(s);
  170293. s = HUFF_EXTEND(r, s);
  170294. /* Output coefficient in natural (dezigzagged) order.
  170295. * Note: the extra entries in jpeg_natural_order[] will save us
  170296. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170297. */
  170298. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170299. } else {
  170300. if (r != 15)
  170301. break;
  170302. k += 15;
  170303. }
  170304. }
  170305. } else {
  170306. /* Section F.2.2.2: decode the AC coefficients */
  170307. /* In this path we just discard the values */
  170308. for (k = 1; k < DCTSIZE2; k++) {
  170309. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170310. r = s >> 4;
  170311. s &= 15;
  170312. if (s) {
  170313. k += r;
  170314. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170315. DROP_BITS(s);
  170316. } else {
  170317. if (r != 15)
  170318. break;
  170319. k += 15;
  170320. }
  170321. }
  170322. }
  170323. }
  170324. /* Completed MCU, so update state */
  170325. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170326. ASSIGN_STATE(entropy->saved, state);
  170327. }
  170328. /* Account for restart interval (no-op if not using restarts) */
  170329. entropy->restarts_to_go--;
  170330. return TRUE;
  170331. }
  170332. /*
  170333. * Module initialization routine for Huffman entropy decoding.
  170334. */
  170335. GLOBAL(void)
  170336. jinit_huff_decoder (j_decompress_ptr cinfo)
  170337. {
  170338. huff_entropy_ptr2 entropy;
  170339. int i;
  170340. entropy = (huff_entropy_ptr2)
  170341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170342. SIZEOF(huff_entropy_decoder2));
  170343. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170344. entropy->pub.start_pass = start_pass_huff_decoder;
  170345. entropy->pub.decode_mcu = decode_mcu;
  170346. /* Mark tables unallocated */
  170347. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170348. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170349. }
  170350. }
  170351. /*** End of inlined file: jdhuff.c ***/
  170352. /*** Start of inlined file: jdinput.c ***/
  170353. #define JPEG_INTERNALS
  170354. /* Private state */
  170355. typedef struct {
  170356. struct jpeg_input_controller pub; /* public fields */
  170357. boolean inheaders; /* TRUE until first SOS is reached */
  170358. } my_input_controller;
  170359. typedef my_input_controller * my_inputctl_ptr;
  170360. /* Forward declarations */
  170361. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170362. /*
  170363. * Routines to calculate various quantities related to the size of the image.
  170364. */
  170365. LOCAL(void)
  170366. initial_setup2 (j_decompress_ptr cinfo)
  170367. /* Called once, when first SOS marker is reached */
  170368. {
  170369. int ci;
  170370. jpeg_component_info *compptr;
  170371. /* Make sure image isn't bigger than I can handle */
  170372. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170373. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170374. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170375. /* For now, precision must match compiled-in value... */
  170376. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170377. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170378. /* Check that number of components won't exceed internal array sizes */
  170379. if (cinfo->num_components > MAX_COMPONENTS)
  170380. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170381. MAX_COMPONENTS);
  170382. /* Compute maximum sampling factors; check factor validity */
  170383. cinfo->max_h_samp_factor = 1;
  170384. cinfo->max_v_samp_factor = 1;
  170385. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170386. ci++, compptr++) {
  170387. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170388. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170389. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170390. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170391. compptr->h_samp_factor);
  170392. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170393. compptr->v_samp_factor);
  170394. }
  170395. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170396. * In the full decompressor, this will be overridden by jdmaster.c;
  170397. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170398. */
  170399. cinfo->min_DCT_scaled_size = DCTSIZE;
  170400. /* Compute dimensions of components */
  170401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170402. ci++, compptr++) {
  170403. compptr->DCT_scaled_size = DCTSIZE;
  170404. /* Size in DCT blocks */
  170405. compptr->width_in_blocks = (JDIMENSION)
  170406. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170407. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170408. compptr->height_in_blocks = (JDIMENSION)
  170409. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170410. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170411. /* downsampled_width and downsampled_height will also be overridden by
  170412. * jdmaster.c if we are doing full decompression. The transcoder library
  170413. * doesn't use these values, but the calling application might.
  170414. */
  170415. /* Size in samples */
  170416. compptr->downsampled_width = (JDIMENSION)
  170417. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170418. (long) cinfo->max_h_samp_factor);
  170419. compptr->downsampled_height = (JDIMENSION)
  170420. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170421. (long) cinfo->max_v_samp_factor);
  170422. /* Mark component needed, until color conversion says otherwise */
  170423. compptr->component_needed = TRUE;
  170424. /* Mark no quantization table yet saved for component */
  170425. compptr->quant_table = NULL;
  170426. }
  170427. /* Compute number of fully interleaved MCU rows. */
  170428. cinfo->total_iMCU_rows = (JDIMENSION)
  170429. jdiv_round_up((long) cinfo->image_height,
  170430. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170431. /* Decide whether file contains multiple scans */
  170432. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170433. cinfo->inputctl->has_multiple_scans = TRUE;
  170434. else
  170435. cinfo->inputctl->has_multiple_scans = FALSE;
  170436. }
  170437. LOCAL(void)
  170438. per_scan_setup2 (j_decompress_ptr cinfo)
  170439. /* Do computations that are needed before processing a JPEG scan */
  170440. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170441. {
  170442. int ci, mcublks, tmp;
  170443. jpeg_component_info *compptr;
  170444. if (cinfo->comps_in_scan == 1) {
  170445. /* Noninterleaved (single-component) scan */
  170446. compptr = cinfo->cur_comp_info[0];
  170447. /* Overall image size in MCUs */
  170448. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170449. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170450. /* For noninterleaved scan, always one block per MCU */
  170451. compptr->MCU_width = 1;
  170452. compptr->MCU_height = 1;
  170453. compptr->MCU_blocks = 1;
  170454. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170455. compptr->last_col_width = 1;
  170456. /* For noninterleaved scans, it is convenient to define last_row_height
  170457. * as the number of block rows present in the last iMCU row.
  170458. */
  170459. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170460. if (tmp == 0) tmp = compptr->v_samp_factor;
  170461. compptr->last_row_height = tmp;
  170462. /* Prepare array describing MCU composition */
  170463. cinfo->blocks_in_MCU = 1;
  170464. cinfo->MCU_membership[0] = 0;
  170465. } else {
  170466. /* Interleaved (multi-component) scan */
  170467. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170468. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170469. MAX_COMPS_IN_SCAN);
  170470. /* Overall image size in MCUs */
  170471. cinfo->MCUs_per_row = (JDIMENSION)
  170472. jdiv_round_up((long) cinfo->image_width,
  170473. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170474. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170475. jdiv_round_up((long) cinfo->image_height,
  170476. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170477. cinfo->blocks_in_MCU = 0;
  170478. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170479. compptr = cinfo->cur_comp_info[ci];
  170480. /* Sampling factors give # of blocks of component in each MCU */
  170481. compptr->MCU_width = compptr->h_samp_factor;
  170482. compptr->MCU_height = compptr->v_samp_factor;
  170483. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170484. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170485. /* Figure number of non-dummy blocks in last MCU column & row */
  170486. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170487. if (tmp == 0) tmp = compptr->MCU_width;
  170488. compptr->last_col_width = tmp;
  170489. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170490. if (tmp == 0) tmp = compptr->MCU_height;
  170491. compptr->last_row_height = tmp;
  170492. /* Prepare array describing MCU composition */
  170493. mcublks = compptr->MCU_blocks;
  170494. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170495. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170496. while (mcublks-- > 0) {
  170497. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170498. }
  170499. }
  170500. }
  170501. }
  170502. /*
  170503. * Save away a copy of the Q-table referenced by each component present
  170504. * in the current scan, unless already saved during a prior scan.
  170505. *
  170506. * In a multiple-scan JPEG file, the encoder could assign different components
  170507. * the same Q-table slot number, but change table definitions between scans
  170508. * so that each component uses a different Q-table. (The IJG encoder is not
  170509. * currently capable of doing this, but other encoders might.) Since we want
  170510. * to be able to dequantize all the components at the end of the file, this
  170511. * means that we have to save away the table actually used for each component.
  170512. * We do this by copying the table at the start of the first scan containing
  170513. * the component.
  170514. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170515. * slot between scans of a component using that slot. If the encoder does so
  170516. * anyway, this decoder will simply use the Q-table values that were current
  170517. * at the start of the first scan for the component.
  170518. *
  170519. * The decompressor output side looks only at the saved quant tables,
  170520. * not at the current Q-table slots.
  170521. */
  170522. LOCAL(void)
  170523. latch_quant_tables (j_decompress_ptr cinfo)
  170524. {
  170525. int ci, qtblno;
  170526. jpeg_component_info *compptr;
  170527. JQUANT_TBL * qtbl;
  170528. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170529. compptr = cinfo->cur_comp_info[ci];
  170530. /* No work if we already saved Q-table for this component */
  170531. if (compptr->quant_table != NULL)
  170532. continue;
  170533. /* Make sure specified quantization table is present */
  170534. qtblno = compptr->quant_tbl_no;
  170535. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170536. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170537. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170538. /* OK, save away the quantization table */
  170539. qtbl = (JQUANT_TBL *)
  170540. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170541. SIZEOF(JQUANT_TBL));
  170542. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170543. compptr->quant_table = qtbl;
  170544. }
  170545. }
  170546. /*
  170547. * Initialize the input modules to read a scan of compressed data.
  170548. * The first call to this is done by jdmaster.c after initializing
  170549. * the entire decompressor (during jpeg_start_decompress).
  170550. * Subsequent calls come from consume_markers, below.
  170551. */
  170552. METHODDEF(void)
  170553. start_input_pass2 (j_decompress_ptr cinfo)
  170554. {
  170555. per_scan_setup2(cinfo);
  170556. latch_quant_tables(cinfo);
  170557. (*cinfo->entropy->start_pass) (cinfo);
  170558. (*cinfo->coef->start_input_pass) (cinfo);
  170559. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170560. }
  170561. /*
  170562. * Finish up after inputting a compressed-data scan.
  170563. * This is called by the coefficient controller after it's read all
  170564. * the expected data of the scan.
  170565. */
  170566. METHODDEF(void)
  170567. finish_input_pass (j_decompress_ptr cinfo)
  170568. {
  170569. cinfo->inputctl->consume_input = consume_markers;
  170570. }
  170571. /*
  170572. * Read JPEG markers before, between, or after compressed-data scans.
  170573. * Change state as necessary when a new scan is reached.
  170574. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170575. *
  170576. * The consume_input method pointer points either here or to the
  170577. * coefficient controller's consume_data routine, depending on whether
  170578. * we are reading a compressed data segment or inter-segment markers.
  170579. */
  170580. METHODDEF(int)
  170581. consume_markers (j_decompress_ptr cinfo)
  170582. {
  170583. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170584. int val;
  170585. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170586. return JPEG_REACHED_EOI;
  170587. val = (*cinfo->marker->read_markers) (cinfo);
  170588. switch (val) {
  170589. case JPEG_REACHED_SOS: /* Found SOS */
  170590. if (inputctl->inheaders) { /* 1st SOS */
  170591. initial_setup2(cinfo);
  170592. inputctl->inheaders = FALSE;
  170593. /* Note: start_input_pass must be called by jdmaster.c
  170594. * before any more input can be consumed. jdapimin.c is
  170595. * responsible for enforcing this sequencing.
  170596. */
  170597. } else { /* 2nd or later SOS marker */
  170598. if (! inputctl->pub.has_multiple_scans)
  170599. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170600. start_input_pass2(cinfo);
  170601. }
  170602. break;
  170603. case JPEG_REACHED_EOI: /* Found EOI */
  170604. inputctl->pub.eoi_reached = TRUE;
  170605. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170606. if (cinfo->marker->saw_SOF)
  170607. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170608. } else {
  170609. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170610. * if user set output_scan_number larger than number of scans.
  170611. */
  170612. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170613. cinfo->output_scan_number = cinfo->input_scan_number;
  170614. }
  170615. break;
  170616. case JPEG_SUSPENDED:
  170617. break;
  170618. }
  170619. return val;
  170620. }
  170621. /*
  170622. * Reset state to begin a fresh datastream.
  170623. */
  170624. METHODDEF(void)
  170625. reset_input_controller (j_decompress_ptr cinfo)
  170626. {
  170627. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170628. inputctl->pub.consume_input = consume_markers;
  170629. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170630. inputctl->pub.eoi_reached = FALSE;
  170631. inputctl->inheaders = TRUE;
  170632. /* Reset other modules */
  170633. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170634. (*cinfo->marker->reset_marker_reader) (cinfo);
  170635. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170636. cinfo->coef_bits = NULL;
  170637. }
  170638. /*
  170639. * Initialize the input controller module.
  170640. * This is called only once, when the decompression object is created.
  170641. */
  170642. GLOBAL(void)
  170643. jinit_input_controller (j_decompress_ptr cinfo)
  170644. {
  170645. my_inputctl_ptr inputctl;
  170646. /* Create subobject in permanent pool */
  170647. inputctl = (my_inputctl_ptr)
  170648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170649. SIZEOF(my_input_controller));
  170650. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170651. /* Initialize method pointers */
  170652. inputctl->pub.consume_input = consume_markers;
  170653. inputctl->pub.reset_input_controller = reset_input_controller;
  170654. inputctl->pub.start_input_pass = start_input_pass2;
  170655. inputctl->pub.finish_input_pass = finish_input_pass;
  170656. /* Initialize state: can't use reset_input_controller since we don't
  170657. * want to try to reset other modules yet.
  170658. */
  170659. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170660. inputctl->pub.eoi_reached = FALSE;
  170661. inputctl->inheaders = TRUE;
  170662. }
  170663. /*** End of inlined file: jdinput.c ***/
  170664. /*** Start of inlined file: jdmainct.c ***/
  170665. #define JPEG_INTERNALS
  170666. /*
  170667. * In the current system design, the main buffer need never be a full-image
  170668. * buffer; any full-height buffers will be found inside the coefficient or
  170669. * postprocessing controllers. Nonetheless, the main controller is not
  170670. * trivial. Its responsibility is to provide context rows for upsampling/
  170671. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170672. *
  170673. * Postprocessor input data is counted in "row groups". A row group
  170674. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170675. * sample rows of each component. (We require DCT_scaled_size values to be
  170676. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170677. * values will likely be powers of two, so we actually have the stronger
  170678. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170679. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170680. * row group (times any additional scale factor that the upsampler is
  170681. * applying).
  170682. *
  170683. * The coefficient controller will deliver data to us one iMCU row at a time;
  170684. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170685. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170686. * to one row of MCUs when the image is fully interleaved.) Note that the
  170687. * number of sample rows varies across components, but the number of row
  170688. * groups does not. Some garbage sample rows may be included in the last iMCU
  170689. * row at the bottom of the image.
  170690. *
  170691. * Depending on the vertical scaling algorithm used, the upsampler may need
  170692. * access to the sample row(s) above and below its current input row group.
  170693. * The upsampler is required to set need_context_rows TRUE at global selection
  170694. * time if so. When need_context_rows is FALSE, this controller can simply
  170695. * obtain one iMCU row at a time from the coefficient controller and dole it
  170696. * out as row groups to the postprocessor.
  170697. *
  170698. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170699. * passed to postprocessing contains at least one row group's worth of samples
  170700. * above and below the row group(s) being processed. Note that the context
  170701. * rows "above" the first passed row group appear at negative row offsets in
  170702. * the passed buffer. At the top and bottom of the image, the required
  170703. * context rows are manufactured by duplicating the first or last real sample
  170704. * row; this avoids having special cases in the upsampling inner loops.
  170705. *
  170706. * The amount of context is fixed at one row group just because that's a
  170707. * convenient number for this controller to work with. The existing
  170708. * upsamplers really only need one sample row of context. An upsampler
  170709. * supporting arbitrary output rescaling might wish for more than one row
  170710. * group of context when shrinking the image; tough, we don't handle that.
  170711. * (This is justified by the assumption that downsizing will be handled mostly
  170712. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170713. * the upsample step needn't be much less than one.)
  170714. *
  170715. * To provide the desired context, we have to retain the last two row groups
  170716. * of one iMCU row while reading in the next iMCU row. (The last row group
  170717. * can't be processed until we have another row group for its below-context,
  170718. * and so we have to save the next-to-last group too for its above-context.)
  170719. * We could do this most simply by copying data around in our buffer, but
  170720. * that'd be very slow. We can avoid copying any data by creating a rather
  170721. * strange pointer structure. Here's how it works. We allocate a workspace
  170722. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170723. * of row groups per iMCU row). We create two sets of redundant pointers to
  170724. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170725. * pointer lists look like this:
  170726. * M+1 M-1
  170727. * master pointer --> 0 master pointer --> 0
  170728. * 1 1
  170729. * ... ...
  170730. * M-3 M-3
  170731. * M-2 M
  170732. * M-1 M+1
  170733. * M M-2
  170734. * M+1 M-1
  170735. * 0 0
  170736. * We read alternate iMCU rows using each master pointer; thus the last two
  170737. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170738. * The pointer lists are set up so that the required context rows appear to
  170739. * be adjacent to the proper places when we pass the pointer lists to the
  170740. * upsampler.
  170741. *
  170742. * The above pictures describe the normal state of the pointer lists.
  170743. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170744. * the first or last sample row as necessary (this is cheaper than copying
  170745. * sample rows around).
  170746. *
  170747. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170748. * situation each iMCU row provides only one row group so the buffering logic
  170749. * must be different (eg, we must read two iMCU rows before we can emit the
  170750. * first row group). For now, we simply do not support providing context
  170751. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170752. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170753. * want it quick and dirty, so a context-free upsampler is sufficient.
  170754. */
  170755. /* Private buffer controller object */
  170756. typedef struct {
  170757. struct jpeg_d_main_controller pub; /* public fields */
  170758. /* Pointer to allocated workspace (M or M+2 row groups). */
  170759. JSAMPARRAY buffer[MAX_COMPONENTS];
  170760. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170761. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170762. /* Remaining fields are only used in the context case. */
  170763. /* These are the master pointers to the funny-order pointer lists. */
  170764. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170765. int whichptr; /* indicates which pointer set is now in use */
  170766. int context_state; /* process_data state machine status */
  170767. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170768. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170769. } my_main_controller4;
  170770. typedef my_main_controller4 * my_main_ptr4;
  170771. /* context_state values: */
  170772. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170773. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170774. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170775. /* Forward declarations */
  170776. METHODDEF(void) process_data_simple_main2
  170777. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170778. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170779. METHODDEF(void) process_data_context_main
  170780. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170781. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170782. #ifdef QUANT_2PASS_SUPPORTED
  170783. METHODDEF(void) process_data_crank_post
  170784. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170785. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170786. #endif
  170787. LOCAL(void)
  170788. alloc_funny_pointers (j_decompress_ptr cinfo)
  170789. /* Allocate space for the funny pointer lists.
  170790. * This is done only once, not once per pass.
  170791. */
  170792. {
  170793. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170794. int ci, rgroup;
  170795. int M = cinfo->min_DCT_scaled_size;
  170796. jpeg_component_info *compptr;
  170797. JSAMPARRAY xbuf;
  170798. /* Get top-level space for component array pointers.
  170799. * We alloc both arrays with one call to save a few cycles.
  170800. */
  170801. main_->xbuffer[0] = (JSAMPIMAGE)
  170802. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170803. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170804. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170805. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170806. ci++, compptr++) {
  170807. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170808. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170809. /* Get space for pointer lists --- M+4 row groups in each list.
  170810. * We alloc both pointer lists with one call to save a few cycles.
  170811. */
  170812. xbuf = (JSAMPARRAY)
  170813. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170814. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170815. xbuf += rgroup; /* want one row group at negative offsets */
  170816. main_->xbuffer[0][ci] = xbuf;
  170817. xbuf += rgroup * (M + 4);
  170818. main_->xbuffer[1][ci] = xbuf;
  170819. }
  170820. }
  170821. LOCAL(void)
  170822. make_funny_pointers (j_decompress_ptr cinfo)
  170823. /* Create the funny pointer lists discussed in the comments above.
  170824. * The actual workspace is already allocated (in main->buffer),
  170825. * and the space for the pointer lists is allocated too.
  170826. * This routine just fills in the curiously ordered lists.
  170827. * This will be repeated at the beginning of each pass.
  170828. */
  170829. {
  170830. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170831. int ci, i, rgroup;
  170832. int M = cinfo->min_DCT_scaled_size;
  170833. jpeg_component_info *compptr;
  170834. JSAMPARRAY buf, xbuf0, xbuf1;
  170835. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170836. ci++, compptr++) {
  170837. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170838. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170839. xbuf0 = main_->xbuffer[0][ci];
  170840. xbuf1 = main_->xbuffer[1][ci];
  170841. /* First copy the workspace pointers as-is */
  170842. buf = main_->buffer[ci];
  170843. for (i = 0; i < rgroup * (M + 2); i++) {
  170844. xbuf0[i] = xbuf1[i] = buf[i];
  170845. }
  170846. /* In the second list, put the last four row groups in swapped order */
  170847. for (i = 0; i < rgroup * 2; i++) {
  170848. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170849. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170850. }
  170851. /* The wraparound pointers at top and bottom will be filled later
  170852. * (see set_wraparound_pointers, below). Initially we want the "above"
  170853. * pointers to duplicate the first actual data line. This only needs
  170854. * to happen in xbuffer[0].
  170855. */
  170856. for (i = 0; i < rgroup; i++) {
  170857. xbuf0[i - rgroup] = xbuf0[0];
  170858. }
  170859. }
  170860. }
  170861. LOCAL(void)
  170862. set_wraparound_pointers (j_decompress_ptr cinfo)
  170863. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170864. * This changes the pointer list state from top-of-image to the normal state.
  170865. */
  170866. {
  170867. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170868. int ci, i, rgroup;
  170869. int M = cinfo->min_DCT_scaled_size;
  170870. jpeg_component_info *compptr;
  170871. JSAMPARRAY xbuf0, xbuf1;
  170872. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170873. ci++, compptr++) {
  170874. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170875. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170876. xbuf0 = main_->xbuffer[0][ci];
  170877. xbuf1 = main_->xbuffer[1][ci];
  170878. for (i = 0; i < rgroup; i++) {
  170879. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170880. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170881. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170882. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170883. }
  170884. }
  170885. }
  170886. LOCAL(void)
  170887. set_bottom_pointers (j_decompress_ptr cinfo)
  170888. /* Change the pointer lists to duplicate the last sample row at the bottom
  170889. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170890. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170891. */
  170892. {
  170893. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170894. int ci, i, rgroup, iMCUheight, rows_left;
  170895. jpeg_component_info *compptr;
  170896. JSAMPARRAY xbuf;
  170897. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170898. ci++, compptr++) {
  170899. /* Count sample rows in one iMCU row and in one row group */
  170900. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170901. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170902. /* Count nondummy sample rows remaining for this component */
  170903. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170904. if (rows_left == 0) rows_left = iMCUheight;
  170905. /* Count nondummy row groups. Should get same answer for each component,
  170906. * so we need only do it once.
  170907. */
  170908. if (ci == 0) {
  170909. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170910. }
  170911. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170912. * last partial rowgroup and ensures at least one full rowgroup of context.
  170913. */
  170914. xbuf = main_->xbuffer[main_->whichptr][ci];
  170915. for (i = 0; i < rgroup * 2; i++) {
  170916. xbuf[rows_left + i] = xbuf[rows_left-1];
  170917. }
  170918. }
  170919. }
  170920. /*
  170921. * Initialize for a processing pass.
  170922. */
  170923. METHODDEF(void)
  170924. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170925. {
  170926. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170927. switch (pass_mode) {
  170928. case JBUF_PASS_THRU:
  170929. if (cinfo->upsample->need_context_rows) {
  170930. main_->pub.process_data = process_data_context_main;
  170931. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170932. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170933. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170934. main_->iMCU_row_ctr = 0;
  170935. } else {
  170936. /* Simple case with no context needed */
  170937. main_->pub.process_data = process_data_simple_main2;
  170938. }
  170939. main_->buffer_full = FALSE; /* Mark buffer empty */
  170940. main_->rowgroup_ctr = 0;
  170941. break;
  170942. #ifdef QUANT_2PASS_SUPPORTED
  170943. case JBUF_CRANK_DEST:
  170944. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170945. main_->pub.process_data = process_data_crank_post;
  170946. break;
  170947. #endif
  170948. default:
  170949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170950. break;
  170951. }
  170952. }
  170953. /*
  170954. * Process some data.
  170955. * This handles the simple case where no context is required.
  170956. */
  170957. METHODDEF(void)
  170958. process_data_simple_main2 (j_decompress_ptr cinfo,
  170959. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170960. JDIMENSION out_rows_avail)
  170961. {
  170962. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170963. JDIMENSION rowgroups_avail;
  170964. /* Read input data if we haven't filled the main buffer yet */
  170965. if (! main_->buffer_full) {
  170966. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170967. return; /* suspension forced, can do nothing more */
  170968. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170969. }
  170970. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170971. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170972. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170973. * to the postprocessor. The postprocessor has to check for bottom
  170974. * of image anyway (at row resolution), so no point in us doing it too.
  170975. */
  170976. /* Feed the postprocessor */
  170977. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170978. &main_->rowgroup_ctr, rowgroups_avail,
  170979. output_buf, out_row_ctr, out_rows_avail);
  170980. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170981. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170982. main_->buffer_full = FALSE;
  170983. main_->rowgroup_ctr = 0;
  170984. }
  170985. }
  170986. /*
  170987. * Process some data.
  170988. * This handles the case where context rows must be provided.
  170989. */
  170990. METHODDEF(void)
  170991. process_data_context_main (j_decompress_ptr cinfo,
  170992. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170993. JDIMENSION out_rows_avail)
  170994. {
  170995. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170996. /* Read input data if we haven't filled the main buffer yet */
  170997. if (! main_->buffer_full) {
  170998. if (! (*cinfo->coef->decompress_data) (cinfo,
  170999. main_->xbuffer[main_->whichptr]))
  171000. return; /* suspension forced, can do nothing more */
  171001. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171002. main_->iMCU_row_ctr++; /* count rows received */
  171003. }
  171004. /* Postprocessor typically will not swallow all the input data it is handed
  171005. * in one call (due to filling the output buffer first). Must be prepared
  171006. * to exit and restart. This switch lets us keep track of how far we got.
  171007. * Note that each case falls through to the next on successful completion.
  171008. */
  171009. switch (main_->context_state) {
  171010. case CTX_POSTPONED_ROW:
  171011. /* Call postprocessor using previously set pointers for postponed row */
  171012. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171013. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171014. output_buf, out_row_ctr, out_rows_avail);
  171015. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171016. return; /* Need to suspend */
  171017. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171018. if (*out_row_ctr >= out_rows_avail)
  171019. return; /* Postprocessor exactly filled output buf */
  171020. /*FALLTHROUGH*/
  171021. case CTX_PREPARE_FOR_IMCU:
  171022. /* Prepare to process first M-1 row groups of this iMCU row */
  171023. main_->rowgroup_ctr = 0;
  171024. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171025. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171026. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171027. */
  171028. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171029. set_bottom_pointers(cinfo);
  171030. main_->context_state = CTX_PROCESS_IMCU;
  171031. /*FALLTHROUGH*/
  171032. case CTX_PROCESS_IMCU:
  171033. /* Call postprocessor using previously set pointers */
  171034. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171035. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171036. output_buf, out_row_ctr, out_rows_avail);
  171037. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171038. return; /* Need to suspend */
  171039. /* After the first iMCU, change wraparound pointers to normal state */
  171040. if (main_->iMCU_row_ctr == 1)
  171041. set_wraparound_pointers(cinfo);
  171042. /* Prepare to load new iMCU row using other xbuffer list */
  171043. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171044. main_->buffer_full = FALSE;
  171045. /* Still need to process last row group of this iMCU row, */
  171046. /* which is saved at index M+1 of the other xbuffer */
  171047. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171048. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171049. main_->context_state = CTX_POSTPONED_ROW;
  171050. }
  171051. }
  171052. /*
  171053. * Process some data.
  171054. * Final pass of two-pass quantization: just call the postprocessor.
  171055. * Source data will be the postprocessor controller's internal buffer.
  171056. */
  171057. #ifdef QUANT_2PASS_SUPPORTED
  171058. METHODDEF(void)
  171059. process_data_crank_post (j_decompress_ptr cinfo,
  171060. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171061. JDIMENSION out_rows_avail)
  171062. {
  171063. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171064. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171065. output_buf, out_row_ctr, out_rows_avail);
  171066. }
  171067. #endif /* QUANT_2PASS_SUPPORTED */
  171068. /*
  171069. * Initialize main buffer controller.
  171070. */
  171071. GLOBAL(void)
  171072. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171073. {
  171074. my_main_ptr4 main_;
  171075. int ci, rgroup, ngroups;
  171076. jpeg_component_info *compptr;
  171077. main_ = (my_main_ptr4)
  171078. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171079. SIZEOF(my_main_controller4));
  171080. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171081. main_->pub.start_pass = start_pass_main2;
  171082. if (need_full_buffer) /* shouldn't happen */
  171083. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171084. /* Allocate the workspace.
  171085. * ngroups is the number of row groups we need.
  171086. */
  171087. if (cinfo->upsample->need_context_rows) {
  171088. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171089. ERREXIT(cinfo, JERR_NOTIMPL);
  171090. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171091. ngroups = cinfo->min_DCT_scaled_size + 2;
  171092. } else {
  171093. ngroups = cinfo->min_DCT_scaled_size;
  171094. }
  171095. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171096. ci++, compptr++) {
  171097. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171098. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171099. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171100. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171101. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171102. (JDIMENSION) (rgroup * ngroups));
  171103. }
  171104. }
  171105. /*** End of inlined file: jdmainct.c ***/
  171106. /*** Start of inlined file: jdmarker.c ***/
  171107. #define JPEG_INTERNALS
  171108. /* Private state */
  171109. typedef struct {
  171110. struct jpeg_marker_reader pub; /* public fields */
  171111. /* Application-overridable marker processing methods */
  171112. jpeg_marker_parser_method process_COM;
  171113. jpeg_marker_parser_method process_APPn[16];
  171114. /* Limit on marker data length to save for each marker type */
  171115. unsigned int length_limit_COM;
  171116. unsigned int length_limit_APPn[16];
  171117. /* Status of COM/APPn marker saving */
  171118. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171119. unsigned int bytes_read; /* data bytes read so far in marker */
  171120. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171121. } my_marker_reader;
  171122. typedef my_marker_reader * my_marker_ptr2;
  171123. /*
  171124. * Macros for fetching data from the data source module.
  171125. *
  171126. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171127. * the current restart point; we update them only when we have reached a
  171128. * suitable place to restart if a suspension occurs.
  171129. */
  171130. /* Declare and initialize local copies of input pointer/count */
  171131. #define INPUT_VARS(cinfo) \
  171132. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171133. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171134. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171135. /* Unload the local copies --- do this only at a restart boundary */
  171136. #define INPUT_SYNC(cinfo) \
  171137. ( datasrc->next_input_byte = next_input_byte, \
  171138. datasrc->bytes_in_buffer = bytes_in_buffer )
  171139. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171140. #define INPUT_RELOAD(cinfo) \
  171141. ( next_input_byte = datasrc->next_input_byte, \
  171142. bytes_in_buffer = datasrc->bytes_in_buffer )
  171143. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171144. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171145. * but we must reload the local copies after a successful fill.
  171146. */
  171147. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171148. if (bytes_in_buffer == 0) { \
  171149. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171150. { action; } \
  171151. INPUT_RELOAD(cinfo); \
  171152. }
  171153. /* Read a byte into variable V.
  171154. * If must suspend, take the specified action (typically "return FALSE").
  171155. */
  171156. #define INPUT_BYTE(cinfo,V,action) \
  171157. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171158. bytes_in_buffer--; \
  171159. V = GETJOCTET(*next_input_byte++); )
  171160. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171161. * V should be declared unsigned int or perhaps INT32.
  171162. */
  171163. #define INPUT_2BYTES(cinfo,V,action) \
  171164. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171165. bytes_in_buffer--; \
  171166. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171167. MAKE_BYTE_AVAIL(cinfo,action); \
  171168. bytes_in_buffer--; \
  171169. V += GETJOCTET(*next_input_byte++); )
  171170. /*
  171171. * Routines to process JPEG markers.
  171172. *
  171173. * Entry condition: JPEG marker itself has been read and its code saved
  171174. * in cinfo->unread_marker; input restart point is just after the marker.
  171175. *
  171176. * Exit: if return TRUE, have read and processed any parameters, and have
  171177. * updated the restart point to point after the parameters.
  171178. * If return FALSE, was forced to suspend before reaching end of
  171179. * marker parameters; restart point has not been moved. Same routine
  171180. * will be called again after application supplies more input data.
  171181. *
  171182. * This approach to suspension assumes that all of a marker's parameters
  171183. * can fit into a single input bufferload. This should hold for "normal"
  171184. * markers. Some COM/APPn markers might have large parameter segments
  171185. * that might not fit. If we are simply dropping such a marker, we use
  171186. * skip_input_data to get past it, and thereby put the problem on the
  171187. * source manager's shoulders. If we are saving the marker's contents
  171188. * into memory, we use a slightly different convention: when forced to
  171189. * suspend, the marker processor updates the restart point to the end of
  171190. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171191. * On resumption, cinfo->unread_marker still contains the marker code,
  171192. * but the data source will point to the next chunk of marker data.
  171193. * The marker processor must retain internal state to deal with this.
  171194. *
  171195. * Note that we don't bother to avoid duplicate trace messages if a
  171196. * suspension occurs within marker parameters. Other side effects
  171197. * require more care.
  171198. */
  171199. LOCAL(boolean)
  171200. get_soi (j_decompress_ptr cinfo)
  171201. /* Process an SOI marker */
  171202. {
  171203. int i;
  171204. TRACEMS(cinfo, 1, JTRC_SOI);
  171205. if (cinfo->marker->saw_SOI)
  171206. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171207. /* Reset all parameters that are defined to be reset by SOI */
  171208. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171209. cinfo->arith_dc_L[i] = 0;
  171210. cinfo->arith_dc_U[i] = 1;
  171211. cinfo->arith_ac_K[i] = 5;
  171212. }
  171213. cinfo->restart_interval = 0;
  171214. /* Set initial assumptions for colorspace etc */
  171215. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171216. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171217. cinfo->saw_JFIF_marker = FALSE;
  171218. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171219. cinfo->JFIF_minor_version = 1;
  171220. cinfo->density_unit = 0;
  171221. cinfo->X_density = 1;
  171222. cinfo->Y_density = 1;
  171223. cinfo->saw_Adobe_marker = FALSE;
  171224. cinfo->Adobe_transform = 0;
  171225. cinfo->marker->saw_SOI = TRUE;
  171226. return TRUE;
  171227. }
  171228. LOCAL(boolean)
  171229. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171230. /* Process a SOFn marker */
  171231. {
  171232. INT32 length;
  171233. int c, ci;
  171234. jpeg_component_info * compptr;
  171235. INPUT_VARS(cinfo);
  171236. cinfo->progressive_mode = is_prog;
  171237. cinfo->arith_code = is_arith;
  171238. INPUT_2BYTES(cinfo, length, return FALSE);
  171239. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171240. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171241. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171242. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171243. length -= 8;
  171244. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171245. (int) cinfo->image_width, (int) cinfo->image_height,
  171246. cinfo->num_components);
  171247. if (cinfo->marker->saw_SOF)
  171248. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171249. /* We don't support files in which the image height is initially specified */
  171250. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171251. /* might as well have a general sanity check. */
  171252. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171253. || cinfo->num_components <= 0)
  171254. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171255. if (length != (cinfo->num_components * 3))
  171256. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171257. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171258. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171259. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171260. cinfo->num_components * SIZEOF(jpeg_component_info));
  171261. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171262. ci++, compptr++) {
  171263. compptr->component_index = ci;
  171264. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171265. INPUT_BYTE(cinfo, c, return FALSE);
  171266. compptr->h_samp_factor = (c >> 4) & 15;
  171267. compptr->v_samp_factor = (c ) & 15;
  171268. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171269. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171270. compptr->component_id, compptr->h_samp_factor,
  171271. compptr->v_samp_factor, compptr->quant_tbl_no);
  171272. }
  171273. cinfo->marker->saw_SOF = TRUE;
  171274. INPUT_SYNC(cinfo);
  171275. return TRUE;
  171276. }
  171277. LOCAL(boolean)
  171278. get_sos (j_decompress_ptr cinfo)
  171279. /* Process a SOS marker */
  171280. {
  171281. INT32 length;
  171282. int i, ci, n, c, cc;
  171283. jpeg_component_info * compptr;
  171284. INPUT_VARS(cinfo);
  171285. if (! cinfo->marker->saw_SOF)
  171286. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171287. INPUT_2BYTES(cinfo, length, return FALSE);
  171288. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171289. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171290. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171291. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171292. cinfo->comps_in_scan = n;
  171293. /* Collect the component-spec parameters */
  171294. for (i = 0; i < n; i++) {
  171295. INPUT_BYTE(cinfo, cc, return FALSE);
  171296. INPUT_BYTE(cinfo, c, return FALSE);
  171297. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171298. ci++, compptr++) {
  171299. if (cc == compptr->component_id)
  171300. goto id_found;
  171301. }
  171302. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171303. id_found:
  171304. cinfo->cur_comp_info[i] = compptr;
  171305. compptr->dc_tbl_no = (c >> 4) & 15;
  171306. compptr->ac_tbl_no = (c ) & 15;
  171307. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171308. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171309. }
  171310. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171311. INPUT_BYTE(cinfo, c, return FALSE);
  171312. cinfo->Ss = c;
  171313. INPUT_BYTE(cinfo, c, return FALSE);
  171314. cinfo->Se = c;
  171315. INPUT_BYTE(cinfo, c, return FALSE);
  171316. cinfo->Ah = (c >> 4) & 15;
  171317. cinfo->Al = (c ) & 15;
  171318. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171319. cinfo->Ah, cinfo->Al);
  171320. /* Prepare to scan data & restart markers */
  171321. cinfo->marker->next_restart_num = 0;
  171322. /* Count another SOS marker */
  171323. cinfo->input_scan_number++;
  171324. INPUT_SYNC(cinfo);
  171325. return TRUE;
  171326. }
  171327. #ifdef D_ARITH_CODING_SUPPORTED
  171328. LOCAL(boolean)
  171329. get_dac (j_decompress_ptr cinfo)
  171330. /* Process a DAC marker */
  171331. {
  171332. INT32 length;
  171333. int index, val;
  171334. INPUT_VARS(cinfo);
  171335. INPUT_2BYTES(cinfo, length, return FALSE);
  171336. length -= 2;
  171337. while (length > 0) {
  171338. INPUT_BYTE(cinfo, index, return FALSE);
  171339. INPUT_BYTE(cinfo, val, return FALSE);
  171340. length -= 2;
  171341. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171342. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171343. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171344. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171345. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171346. } else { /* define DC table */
  171347. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171348. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171349. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171350. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171351. }
  171352. }
  171353. if (length != 0)
  171354. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171355. INPUT_SYNC(cinfo);
  171356. return TRUE;
  171357. }
  171358. #else /* ! D_ARITH_CODING_SUPPORTED */
  171359. #define get_dac(cinfo) skip_variable(cinfo)
  171360. #endif /* D_ARITH_CODING_SUPPORTED */
  171361. LOCAL(boolean)
  171362. get_dht (j_decompress_ptr cinfo)
  171363. /* Process a DHT marker */
  171364. {
  171365. INT32 length;
  171366. UINT8 bits[17];
  171367. UINT8 huffval[256];
  171368. int i, index, count;
  171369. JHUFF_TBL **htblptr;
  171370. INPUT_VARS(cinfo);
  171371. INPUT_2BYTES(cinfo, length, return FALSE);
  171372. length -= 2;
  171373. while (length > 16) {
  171374. INPUT_BYTE(cinfo, index, return FALSE);
  171375. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171376. bits[0] = 0;
  171377. count = 0;
  171378. for (i = 1; i <= 16; i++) {
  171379. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171380. count += bits[i];
  171381. }
  171382. length -= 1 + 16;
  171383. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171384. bits[1], bits[2], bits[3], bits[4],
  171385. bits[5], bits[6], bits[7], bits[8]);
  171386. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171387. bits[9], bits[10], bits[11], bits[12],
  171388. bits[13], bits[14], bits[15], bits[16]);
  171389. /* Here we just do minimal validation of the counts to avoid walking
  171390. * off the end of our table space. jdhuff.c will check more carefully.
  171391. */
  171392. if (count > 256 || ((INT32) count) > length)
  171393. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171394. for (i = 0; i < count; i++)
  171395. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171396. length -= count;
  171397. if (index & 0x10) { /* AC table definition */
  171398. index -= 0x10;
  171399. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171400. } else { /* DC table definition */
  171401. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171402. }
  171403. if (index < 0 || index >= NUM_HUFF_TBLS)
  171404. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171405. if (*htblptr == NULL)
  171406. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171407. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171408. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171409. }
  171410. if (length != 0)
  171411. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171412. INPUT_SYNC(cinfo);
  171413. return TRUE;
  171414. }
  171415. LOCAL(boolean)
  171416. get_dqt (j_decompress_ptr cinfo)
  171417. /* Process a DQT marker */
  171418. {
  171419. INT32 length;
  171420. int n, i, prec;
  171421. unsigned int tmp;
  171422. JQUANT_TBL *quant_ptr;
  171423. INPUT_VARS(cinfo);
  171424. INPUT_2BYTES(cinfo, length, return FALSE);
  171425. length -= 2;
  171426. while (length > 0) {
  171427. INPUT_BYTE(cinfo, n, return FALSE);
  171428. prec = n >> 4;
  171429. n &= 0x0F;
  171430. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171431. if (n >= NUM_QUANT_TBLS)
  171432. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171433. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171434. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171435. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171436. for (i = 0; i < DCTSIZE2; i++) {
  171437. if (prec)
  171438. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171439. else
  171440. INPUT_BYTE(cinfo, tmp, return FALSE);
  171441. /* We convert the zigzag-order table to natural array order. */
  171442. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171443. }
  171444. if (cinfo->err->trace_level >= 2) {
  171445. for (i = 0; i < DCTSIZE2; i += 8) {
  171446. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171447. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171448. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171449. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171450. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171451. }
  171452. }
  171453. length -= DCTSIZE2+1;
  171454. if (prec) length -= DCTSIZE2;
  171455. }
  171456. if (length != 0)
  171457. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171458. INPUT_SYNC(cinfo);
  171459. return TRUE;
  171460. }
  171461. LOCAL(boolean)
  171462. get_dri (j_decompress_ptr cinfo)
  171463. /* Process a DRI marker */
  171464. {
  171465. INT32 length;
  171466. unsigned int tmp;
  171467. INPUT_VARS(cinfo);
  171468. INPUT_2BYTES(cinfo, length, return FALSE);
  171469. if (length != 4)
  171470. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171471. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171472. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171473. cinfo->restart_interval = tmp;
  171474. INPUT_SYNC(cinfo);
  171475. return TRUE;
  171476. }
  171477. /*
  171478. * Routines for processing APPn and COM markers.
  171479. * These are either saved in memory or discarded, per application request.
  171480. * APP0 and APP14 are specially checked to see if they are
  171481. * JFIF and Adobe markers, respectively.
  171482. */
  171483. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171484. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171485. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171486. LOCAL(void)
  171487. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171488. unsigned int datalen, INT32 remaining)
  171489. /* Examine first few bytes from an APP0.
  171490. * Take appropriate action if it is a JFIF marker.
  171491. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171492. */
  171493. {
  171494. INT32 totallen = (INT32) datalen + remaining;
  171495. if (datalen >= APP0_DATA_LEN &&
  171496. GETJOCTET(data[0]) == 0x4A &&
  171497. GETJOCTET(data[1]) == 0x46 &&
  171498. GETJOCTET(data[2]) == 0x49 &&
  171499. GETJOCTET(data[3]) == 0x46 &&
  171500. GETJOCTET(data[4]) == 0) {
  171501. /* Found JFIF APP0 marker: save info */
  171502. cinfo->saw_JFIF_marker = TRUE;
  171503. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171504. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171505. cinfo->density_unit = GETJOCTET(data[7]);
  171506. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171507. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171508. /* Check version.
  171509. * Major version must be 1, anything else signals an incompatible change.
  171510. * (We used to treat this as an error, but now it's a nonfatal warning,
  171511. * because some bozo at Hijaak couldn't read the spec.)
  171512. * Minor version should be 0..2, but process anyway if newer.
  171513. */
  171514. if (cinfo->JFIF_major_version != 1)
  171515. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171516. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171517. /* Generate trace messages */
  171518. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171519. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171520. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171521. /* Validate thumbnail dimensions and issue appropriate messages */
  171522. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171523. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171524. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171525. totallen -= APP0_DATA_LEN;
  171526. if (totallen !=
  171527. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171528. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171529. } else if (datalen >= 6 &&
  171530. GETJOCTET(data[0]) == 0x4A &&
  171531. GETJOCTET(data[1]) == 0x46 &&
  171532. GETJOCTET(data[2]) == 0x58 &&
  171533. GETJOCTET(data[3]) == 0x58 &&
  171534. GETJOCTET(data[4]) == 0) {
  171535. /* Found JFIF "JFXX" extension APP0 marker */
  171536. /* The library doesn't actually do anything with these,
  171537. * but we try to produce a helpful trace message.
  171538. */
  171539. switch (GETJOCTET(data[5])) {
  171540. case 0x10:
  171541. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171542. break;
  171543. case 0x11:
  171544. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171545. break;
  171546. case 0x13:
  171547. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171548. break;
  171549. default:
  171550. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171551. GETJOCTET(data[5]), (int) totallen);
  171552. break;
  171553. }
  171554. } else {
  171555. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171556. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171557. }
  171558. }
  171559. LOCAL(void)
  171560. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171561. unsigned int datalen, INT32 remaining)
  171562. /* Examine first few bytes from an APP14.
  171563. * Take appropriate action if it is an Adobe marker.
  171564. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171565. */
  171566. {
  171567. unsigned int version, flags0, flags1, transform;
  171568. if (datalen >= APP14_DATA_LEN &&
  171569. GETJOCTET(data[0]) == 0x41 &&
  171570. GETJOCTET(data[1]) == 0x64 &&
  171571. GETJOCTET(data[2]) == 0x6F &&
  171572. GETJOCTET(data[3]) == 0x62 &&
  171573. GETJOCTET(data[4]) == 0x65) {
  171574. /* Found Adobe APP14 marker */
  171575. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171576. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171577. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171578. transform = GETJOCTET(data[11]);
  171579. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171580. cinfo->saw_Adobe_marker = TRUE;
  171581. cinfo->Adobe_transform = (UINT8) transform;
  171582. } else {
  171583. /* Start of APP14 does not match "Adobe", or too short */
  171584. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171585. }
  171586. }
  171587. METHODDEF(boolean)
  171588. get_interesting_appn (j_decompress_ptr cinfo)
  171589. /* Process an APP0 or APP14 marker without saving it */
  171590. {
  171591. INT32 length;
  171592. JOCTET b[APPN_DATA_LEN];
  171593. unsigned int i, numtoread;
  171594. INPUT_VARS(cinfo);
  171595. INPUT_2BYTES(cinfo, length, return FALSE);
  171596. length -= 2;
  171597. /* get the interesting part of the marker data */
  171598. if (length >= APPN_DATA_LEN)
  171599. numtoread = APPN_DATA_LEN;
  171600. else if (length > 0)
  171601. numtoread = (unsigned int) length;
  171602. else
  171603. numtoread = 0;
  171604. for (i = 0; i < numtoread; i++)
  171605. INPUT_BYTE(cinfo, b[i], return FALSE);
  171606. length -= numtoread;
  171607. /* process it */
  171608. switch (cinfo->unread_marker) {
  171609. case M_APP0:
  171610. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171611. break;
  171612. case M_APP14:
  171613. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171614. break;
  171615. default:
  171616. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171617. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171618. break;
  171619. }
  171620. /* skip any remaining data -- could be lots */
  171621. INPUT_SYNC(cinfo);
  171622. if (length > 0)
  171623. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171624. return TRUE;
  171625. }
  171626. #ifdef SAVE_MARKERS_SUPPORTED
  171627. METHODDEF(boolean)
  171628. save_marker (j_decompress_ptr cinfo)
  171629. /* Save an APPn or COM marker into the marker list */
  171630. {
  171631. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171632. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171633. unsigned int bytes_read, data_length;
  171634. JOCTET FAR * data;
  171635. INT32 length = 0;
  171636. INPUT_VARS(cinfo);
  171637. if (cur_marker == NULL) {
  171638. /* begin reading a marker */
  171639. INPUT_2BYTES(cinfo, length, return FALSE);
  171640. length -= 2;
  171641. if (length >= 0) { /* watch out for bogus length word */
  171642. /* figure out how much we want to save */
  171643. unsigned int limit;
  171644. if (cinfo->unread_marker == (int) M_COM)
  171645. limit = marker->length_limit_COM;
  171646. else
  171647. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171648. if ((unsigned int) length < limit)
  171649. limit = (unsigned int) length;
  171650. /* allocate and initialize the marker item */
  171651. cur_marker = (jpeg_saved_marker_ptr)
  171652. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171653. SIZEOF(struct jpeg_marker_struct) + limit);
  171654. cur_marker->next = NULL;
  171655. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171656. cur_marker->original_length = (unsigned int) length;
  171657. cur_marker->data_length = limit;
  171658. /* data area is just beyond the jpeg_marker_struct */
  171659. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171660. marker->cur_marker = cur_marker;
  171661. marker->bytes_read = 0;
  171662. bytes_read = 0;
  171663. data_length = limit;
  171664. } else {
  171665. /* deal with bogus length word */
  171666. bytes_read = data_length = 0;
  171667. data = NULL;
  171668. }
  171669. } else {
  171670. /* resume reading a marker */
  171671. bytes_read = marker->bytes_read;
  171672. data_length = cur_marker->data_length;
  171673. data = cur_marker->data + bytes_read;
  171674. }
  171675. while (bytes_read < data_length) {
  171676. INPUT_SYNC(cinfo); /* move the restart point to here */
  171677. marker->bytes_read = bytes_read;
  171678. /* If there's not at least one byte in buffer, suspend */
  171679. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171680. /* Copy bytes with reasonable rapidity */
  171681. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171682. *data++ = *next_input_byte++;
  171683. bytes_in_buffer--;
  171684. bytes_read++;
  171685. }
  171686. }
  171687. /* Done reading what we want to read */
  171688. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171689. /* Add new marker to end of list */
  171690. if (cinfo->marker_list == NULL) {
  171691. cinfo->marker_list = cur_marker;
  171692. } else {
  171693. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171694. while (prev->next != NULL)
  171695. prev = prev->next;
  171696. prev->next = cur_marker;
  171697. }
  171698. /* Reset pointer & calc remaining data length */
  171699. data = cur_marker->data;
  171700. length = cur_marker->original_length - data_length;
  171701. }
  171702. /* Reset to initial state for next marker */
  171703. marker->cur_marker = NULL;
  171704. /* Process the marker if interesting; else just make a generic trace msg */
  171705. switch (cinfo->unread_marker) {
  171706. case M_APP0:
  171707. examine_app0(cinfo, data, data_length, length);
  171708. break;
  171709. case M_APP14:
  171710. examine_app14(cinfo, data, data_length, length);
  171711. break;
  171712. default:
  171713. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171714. (int) (data_length + length));
  171715. break;
  171716. }
  171717. /* skip any remaining data -- could be lots */
  171718. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171719. if (length > 0)
  171720. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171721. return TRUE;
  171722. }
  171723. #endif /* SAVE_MARKERS_SUPPORTED */
  171724. METHODDEF(boolean)
  171725. skip_variable (j_decompress_ptr cinfo)
  171726. /* Skip over an unknown or uninteresting variable-length marker */
  171727. {
  171728. INT32 length;
  171729. INPUT_VARS(cinfo);
  171730. INPUT_2BYTES(cinfo, length, return FALSE);
  171731. length -= 2;
  171732. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171733. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171734. if (length > 0)
  171735. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171736. return TRUE;
  171737. }
  171738. /*
  171739. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171740. * Returns FALSE if had to suspend before reaching a marker;
  171741. * in that case cinfo->unread_marker is unchanged.
  171742. *
  171743. * Note that the result might not be a valid marker code,
  171744. * but it will never be 0 or FF.
  171745. */
  171746. LOCAL(boolean)
  171747. next_marker (j_decompress_ptr cinfo)
  171748. {
  171749. int c;
  171750. INPUT_VARS(cinfo);
  171751. for (;;) {
  171752. INPUT_BYTE(cinfo, c, return FALSE);
  171753. /* Skip any non-FF bytes.
  171754. * This may look a bit inefficient, but it will not occur in a valid file.
  171755. * We sync after each discarded byte so that a suspending data source
  171756. * can discard the byte from its buffer.
  171757. */
  171758. while (c != 0xFF) {
  171759. cinfo->marker->discarded_bytes++;
  171760. INPUT_SYNC(cinfo);
  171761. INPUT_BYTE(cinfo, c, return FALSE);
  171762. }
  171763. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171764. * pad bytes, so don't count them in discarded_bytes. We assume there
  171765. * will not be so many consecutive FF bytes as to overflow a suspending
  171766. * data source's input buffer.
  171767. */
  171768. do {
  171769. INPUT_BYTE(cinfo, c, return FALSE);
  171770. } while (c == 0xFF);
  171771. if (c != 0)
  171772. break; /* found a valid marker, exit loop */
  171773. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171774. * Discard it and loop back to try again.
  171775. */
  171776. cinfo->marker->discarded_bytes += 2;
  171777. INPUT_SYNC(cinfo);
  171778. }
  171779. if (cinfo->marker->discarded_bytes != 0) {
  171780. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171781. cinfo->marker->discarded_bytes = 0;
  171782. }
  171783. cinfo->unread_marker = c;
  171784. INPUT_SYNC(cinfo);
  171785. return TRUE;
  171786. }
  171787. LOCAL(boolean)
  171788. first_marker (j_decompress_ptr cinfo)
  171789. /* Like next_marker, but used to obtain the initial SOI marker. */
  171790. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171791. * we might well scan an entire input file before realizing it ain't JPEG.
  171792. * If an application wants to process non-JFIF files, it must seek to the
  171793. * SOI before calling the JPEG library.
  171794. */
  171795. {
  171796. int c, c2;
  171797. INPUT_VARS(cinfo);
  171798. INPUT_BYTE(cinfo, c, return FALSE);
  171799. INPUT_BYTE(cinfo, c2, return FALSE);
  171800. if (c != 0xFF || c2 != (int) M_SOI)
  171801. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171802. cinfo->unread_marker = c2;
  171803. INPUT_SYNC(cinfo);
  171804. return TRUE;
  171805. }
  171806. /*
  171807. * Read markers until SOS or EOI.
  171808. *
  171809. * Returns same codes as are defined for jpeg_consume_input:
  171810. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171811. */
  171812. METHODDEF(int)
  171813. read_markers (j_decompress_ptr cinfo)
  171814. {
  171815. /* Outer loop repeats once for each marker. */
  171816. for (;;) {
  171817. /* Collect the marker proper, unless we already did. */
  171818. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171819. if (cinfo->unread_marker == 0) {
  171820. if (! cinfo->marker->saw_SOI) {
  171821. if (! first_marker(cinfo))
  171822. return JPEG_SUSPENDED;
  171823. } else {
  171824. if (! next_marker(cinfo))
  171825. return JPEG_SUSPENDED;
  171826. }
  171827. }
  171828. /* At this point cinfo->unread_marker contains the marker code and the
  171829. * input point is just past the marker proper, but before any parameters.
  171830. * A suspension will cause us to return with this state still true.
  171831. */
  171832. switch (cinfo->unread_marker) {
  171833. case M_SOI:
  171834. if (! get_soi(cinfo))
  171835. return JPEG_SUSPENDED;
  171836. break;
  171837. case M_SOF0: /* Baseline */
  171838. case M_SOF1: /* Extended sequential, Huffman */
  171839. if (! get_sof(cinfo, FALSE, FALSE))
  171840. return JPEG_SUSPENDED;
  171841. break;
  171842. case M_SOF2: /* Progressive, Huffman */
  171843. if (! get_sof(cinfo, TRUE, FALSE))
  171844. return JPEG_SUSPENDED;
  171845. break;
  171846. case M_SOF9: /* Extended sequential, arithmetic */
  171847. if (! get_sof(cinfo, FALSE, TRUE))
  171848. return JPEG_SUSPENDED;
  171849. break;
  171850. case M_SOF10: /* Progressive, arithmetic */
  171851. if (! get_sof(cinfo, TRUE, TRUE))
  171852. return JPEG_SUSPENDED;
  171853. break;
  171854. /* Currently unsupported SOFn types */
  171855. case M_SOF3: /* Lossless, Huffman */
  171856. case M_SOF5: /* Differential sequential, Huffman */
  171857. case M_SOF6: /* Differential progressive, Huffman */
  171858. case M_SOF7: /* Differential lossless, Huffman */
  171859. case M_JPG: /* Reserved for JPEG extensions */
  171860. case M_SOF11: /* Lossless, arithmetic */
  171861. case M_SOF13: /* Differential sequential, arithmetic */
  171862. case M_SOF14: /* Differential progressive, arithmetic */
  171863. case M_SOF15: /* Differential lossless, arithmetic */
  171864. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171865. break;
  171866. case M_SOS:
  171867. if (! get_sos(cinfo))
  171868. return JPEG_SUSPENDED;
  171869. cinfo->unread_marker = 0; /* processed the marker */
  171870. return JPEG_REACHED_SOS;
  171871. case M_EOI:
  171872. TRACEMS(cinfo, 1, JTRC_EOI);
  171873. cinfo->unread_marker = 0; /* processed the marker */
  171874. return JPEG_REACHED_EOI;
  171875. case M_DAC:
  171876. if (! get_dac(cinfo))
  171877. return JPEG_SUSPENDED;
  171878. break;
  171879. case M_DHT:
  171880. if (! get_dht(cinfo))
  171881. return JPEG_SUSPENDED;
  171882. break;
  171883. case M_DQT:
  171884. if (! get_dqt(cinfo))
  171885. return JPEG_SUSPENDED;
  171886. break;
  171887. case M_DRI:
  171888. if (! get_dri(cinfo))
  171889. return JPEG_SUSPENDED;
  171890. break;
  171891. case M_APP0:
  171892. case M_APP1:
  171893. case M_APP2:
  171894. case M_APP3:
  171895. case M_APP4:
  171896. case M_APP5:
  171897. case M_APP6:
  171898. case M_APP7:
  171899. case M_APP8:
  171900. case M_APP9:
  171901. case M_APP10:
  171902. case M_APP11:
  171903. case M_APP12:
  171904. case M_APP13:
  171905. case M_APP14:
  171906. case M_APP15:
  171907. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171908. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171909. return JPEG_SUSPENDED;
  171910. break;
  171911. case M_COM:
  171912. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171913. return JPEG_SUSPENDED;
  171914. break;
  171915. case M_RST0: /* these are all parameterless */
  171916. case M_RST1:
  171917. case M_RST2:
  171918. case M_RST3:
  171919. case M_RST4:
  171920. case M_RST5:
  171921. case M_RST6:
  171922. case M_RST7:
  171923. case M_TEM:
  171924. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171925. break;
  171926. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171927. if (! skip_variable(cinfo))
  171928. return JPEG_SUSPENDED;
  171929. break;
  171930. default: /* must be DHP, EXP, JPGn, or RESn */
  171931. /* For now, we treat the reserved markers as fatal errors since they are
  171932. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171933. * Once the JPEG 3 version-number marker is well defined, this code
  171934. * ought to change!
  171935. */
  171936. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171937. break;
  171938. }
  171939. /* Successfully processed marker, so reset state variable */
  171940. cinfo->unread_marker = 0;
  171941. } /* end loop */
  171942. }
  171943. /*
  171944. * Read a restart marker, which is expected to appear next in the datastream;
  171945. * if the marker is not there, take appropriate recovery action.
  171946. * Returns FALSE if suspension is required.
  171947. *
  171948. * This is called by the entropy decoder after it has read an appropriate
  171949. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171950. * has already read a marker from the data source. Under normal conditions
  171951. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171952. * it holds a marker which the decoder will be unable to read past.
  171953. */
  171954. METHODDEF(boolean)
  171955. read_restart_marker (j_decompress_ptr cinfo)
  171956. {
  171957. /* Obtain a marker unless we already did. */
  171958. /* Note that next_marker will complain if it skips any data. */
  171959. if (cinfo->unread_marker == 0) {
  171960. if (! next_marker(cinfo))
  171961. return FALSE;
  171962. }
  171963. if (cinfo->unread_marker ==
  171964. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171965. /* Normal case --- swallow the marker and let entropy decoder continue */
  171966. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171967. cinfo->unread_marker = 0;
  171968. } else {
  171969. /* Uh-oh, the restart markers have been messed up. */
  171970. /* Let the data source manager determine how to resync. */
  171971. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171972. cinfo->marker->next_restart_num))
  171973. return FALSE;
  171974. }
  171975. /* Update next-restart state */
  171976. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171977. return TRUE;
  171978. }
  171979. /*
  171980. * This is the default resync_to_restart method for data source managers
  171981. * to use if they don't have any better approach. Some data source managers
  171982. * may be able to back up, or may have additional knowledge about the data
  171983. * which permits a more intelligent recovery strategy; such managers would
  171984. * presumably supply their own resync method.
  171985. *
  171986. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171987. * the restart marker it was expecting. (This code is *not* used unless
  171988. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171989. * the marker code actually found (might be anything, except 0 or FF).
  171990. * The desired restart marker number (0..7) is passed as a parameter.
  171991. * This routine is supposed to apply whatever error recovery strategy seems
  171992. * appropriate in order to position the input stream to the next data segment.
  171993. * Note that cinfo->unread_marker is treated as a marker appearing before
  171994. * the current data-source input point; usually it should be reset to zero
  171995. * before returning.
  171996. * Returns FALSE if suspension is required.
  171997. *
  171998. * This implementation is substantially constrained by wanting to treat the
  171999. * input as a data stream; this means we can't back up. Therefore, we have
  172000. * only the following actions to work with:
  172001. * 1. Simply discard the marker and let the entropy decoder resume at next
  172002. * byte of file.
  172003. * 2. Read forward until we find another marker, discarding intervening
  172004. * data. (In theory we could look ahead within the current bufferload,
  172005. * without having to discard data if we don't find the desired marker.
  172006. * This idea is not implemented here, in part because it makes behavior
  172007. * dependent on buffer size and chance buffer-boundary positions.)
  172008. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172009. * This will cause the entropy decoder to process an empty data segment,
  172010. * inserting dummy zeroes, and then we will reprocess the marker.
  172011. *
  172012. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172013. * appropriate if the found marker is a future restart marker (indicating
  172014. * that we have missed the desired restart marker, probably because it got
  172015. * corrupted).
  172016. * We apply #2 or #3 if the found marker is a restart marker no more than
  172017. * two counts behind or ahead of the expected one. We also apply #2 if the
  172018. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172019. * If the found marker is a restart marker more than 2 counts away, we do #1
  172020. * (too much risk that the marker is erroneous; with luck we will be able to
  172021. * resync at some future point).
  172022. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172023. * overrunning the end of a scan. An implementation limited to single-scan
  172024. * files might find it better to apply #2 for markers other than EOI, since
  172025. * any other marker would have to be bogus data in that case.
  172026. */
  172027. GLOBAL(boolean)
  172028. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172029. {
  172030. int marker = cinfo->unread_marker;
  172031. int action = 1;
  172032. /* Always put up a warning. */
  172033. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172034. /* Outer loop handles repeated decision after scanning forward. */
  172035. for (;;) {
  172036. if (marker < (int) M_SOF0)
  172037. action = 2; /* invalid marker */
  172038. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172039. action = 3; /* valid non-restart marker */
  172040. else {
  172041. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172042. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172043. action = 3; /* one of the next two expected restarts */
  172044. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172045. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172046. action = 2; /* a prior restart, so advance */
  172047. else
  172048. action = 1; /* desired restart or too far away */
  172049. }
  172050. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172051. switch (action) {
  172052. case 1:
  172053. /* Discard marker and let entropy decoder resume processing. */
  172054. cinfo->unread_marker = 0;
  172055. return TRUE;
  172056. case 2:
  172057. /* Scan to the next marker, and repeat the decision loop. */
  172058. if (! next_marker(cinfo))
  172059. return FALSE;
  172060. marker = cinfo->unread_marker;
  172061. break;
  172062. case 3:
  172063. /* Return without advancing past this marker. */
  172064. /* Entropy decoder will be forced to process an empty segment. */
  172065. return TRUE;
  172066. }
  172067. } /* end loop */
  172068. }
  172069. /*
  172070. * Reset marker processing state to begin a fresh datastream.
  172071. */
  172072. METHODDEF(void)
  172073. reset_marker_reader (j_decompress_ptr cinfo)
  172074. {
  172075. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172076. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172077. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172078. cinfo->unread_marker = 0; /* no pending marker */
  172079. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172080. marker->pub.saw_SOF = FALSE;
  172081. marker->pub.discarded_bytes = 0;
  172082. marker->cur_marker = NULL;
  172083. }
  172084. /*
  172085. * Initialize the marker reader module.
  172086. * This is called only once, when the decompression object is created.
  172087. */
  172088. GLOBAL(void)
  172089. jinit_marker_reader (j_decompress_ptr cinfo)
  172090. {
  172091. my_marker_ptr2 marker;
  172092. int i;
  172093. /* Create subobject in permanent pool */
  172094. marker = (my_marker_ptr2)
  172095. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172096. SIZEOF(my_marker_reader));
  172097. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172098. /* Initialize public method pointers */
  172099. marker->pub.reset_marker_reader = reset_marker_reader;
  172100. marker->pub.read_markers = read_markers;
  172101. marker->pub.read_restart_marker = read_restart_marker;
  172102. /* Initialize COM/APPn processing.
  172103. * By default, we examine and then discard APP0 and APP14,
  172104. * but simply discard COM and all other APPn.
  172105. */
  172106. marker->process_COM = skip_variable;
  172107. marker->length_limit_COM = 0;
  172108. for (i = 0; i < 16; i++) {
  172109. marker->process_APPn[i] = skip_variable;
  172110. marker->length_limit_APPn[i] = 0;
  172111. }
  172112. marker->process_APPn[0] = get_interesting_appn;
  172113. marker->process_APPn[14] = get_interesting_appn;
  172114. /* Reset marker processing state */
  172115. reset_marker_reader(cinfo);
  172116. }
  172117. /*
  172118. * Control saving of COM and APPn markers into marker_list.
  172119. */
  172120. #ifdef SAVE_MARKERS_SUPPORTED
  172121. GLOBAL(void)
  172122. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172123. unsigned int length_limit)
  172124. {
  172125. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172126. long maxlength;
  172127. jpeg_marker_parser_method processor;
  172128. /* Length limit mustn't be larger than what we can allocate
  172129. * (should only be a concern in a 16-bit environment).
  172130. */
  172131. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172132. if (((long) length_limit) > maxlength)
  172133. length_limit = (unsigned int) maxlength;
  172134. /* Choose processor routine to use.
  172135. * APP0/APP14 have special requirements.
  172136. */
  172137. if (length_limit) {
  172138. processor = save_marker;
  172139. /* If saving APP0/APP14, save at least enough for our internal use. */
  172140. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172141. length_limit = APP0_DATA_LEN;
  172142. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172143. length_limit = APP14_DATA_LEN;
  172144. } else {
  172145. processor = skip_variable;
  172146. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172147. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172148. processor = get_interesting_appn;
  172149. }
  172150. if (marker_code == (int) M_COM) {
  172151. marker->process_COM = processor;
  172152. marker->length_limit_COM = length_limit;
  172153. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172154. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172155. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172156. } else
  172157. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172158. }
  172159. #endif /* SAVE_MARKERS_SUPPORTED */
  172160. /*
  172161. * Install a special processing method for COM or APPn markers.
  172162. */
  172163. GLOBAL(void)
  172164. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172165. jpeg_marker_parser_method routine)
  172166. {
  172167. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172168. if (marker_code == (int) M_COM)
  172169. marker->process_COM = routine;
  172170. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172171. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172172. else
  172173. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172174. }
  172175. /*** End of inlined file: jdmarker.c ***/
  172176. /*** Start of inlined file: jdmaster.c ***/
  172177. #define JPEG_INTERNALS
  172178. /* Private state */
  172179. typedef struct {
  172180. struct jpeg_decomp_master pub; /* public fields */
  172181. int pass_number; /* # of passes completed */
  172182. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172183. /* Saved references to initialized quantizer modules,
  172184. * in case we need to switch modes.
  172185. */
  172186. struct jpeg_color_quantizer * quantizer_1pass;
  172187. struct jpeg_color_quantizer * quantizer_2pass;
  172188. } my_decomp_master;
  172189. typedef my_decomp_master * my_master_ptr6;
  172190. /*
  172191. * Determine whether merged upsample/color conversion should be used.
  172192. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172193. */
  172194. LOCAL(boolean)
  172195. use_merged_upsample (j_decompress_ptr cinfo)
  172196. {
  172197. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172198. /* Merging is the equivalent of plain box-filter upsampling */
  172199. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172200. return FALSE;
  172201. /* jdmerge.c only supports YCC=>RGB color conversion */
  172202. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172203. cinfo->out_color_space != JCS_RGB ||
  172204. cinfo->out_color_components != RGB_PIXELSIZE)
  172205. return FALSE;
  172206. /* and it only handles 2h1v or 2h2v sampling ratios */
  172207. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172208. cinfo->comp_info[1].h_samp_factor != 1 ||
  172209. cinfo->comp_info[2].h_samp_factor != 1 ||
  172210. cinfo->comp_info[0].v_samp_factor > 2 ||
  172211. cinfo->comp_info[1].v_samp_factor != 1 ||
  172212. cinfo->comp_info[2].v_samp_factor != 1)
  172213. return FALSE;
  172214. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172215. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172216. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172217. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172218. return FALSE;
  172219. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172220. return TRUE; /* by golly, it'll work... */
  172221. #else
  172222. return FALSE;
  172223. #endif
  172224. }
  172225. /*
  172226. * Compute output image dimensions and related values.
  172227. * NOTE: this is exported for possible use by application.
  172228. * Hence it mustn't do anything that can't be done twice.
  172229. * Also note that it may be called before the master module is initialized!
  172230. */
  172231. GLOBAL(void)
  172232. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172233. /* Do computations that are needed before master selection phase */
  172234. {
  172235. #ifdef IDCT_SCALING_SUPPORTED
  172236. int ci;
  172237. jpeg_component_info *compptr;
  172238. #endif
  172239. /* Prevent application from calling me at wrong times */
  172240. if (cinfo->global_state != DSTATE_READY)
  172241. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172242. #ifdef IDCT_SCALING_SUPPORTED
  172243. /* Compute actual output image dimensions and DCT scaling choices. */
  172244. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172245. /* Provide 1/8 scaling */
  172246. cinfo->output_width = (JDIMENSION)
  172247. jdiv_round_up((long) cinfo->image_width, 8L);
  172248. cinfo->output_height = (JDIMENSION)
  172249. jdiv_round_up((long) cinfo->image_height, 8L);
  172250. cinfo->min_DCT_scaled_size = 1;
  172251. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172252. /* Provide 1/4 scaling */
  172253. cinfo->output_width = (JDIMENSION)
  172254. jdiv_round_up((long) cinfo->image_width, 4L);
  172255. cinfo->output_height = (JDIMENSION)
  172256. jdiv_round_up((long) cinfo->image_height, 4L);
  172257. cinfo->min_DCT_scaled_size = 2;
  172258. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172259. /* Provide 1/2 scaling */
  172260. cinfo->output_width = (JDIMENSION)
  172261. jdiv_round_up((long) cinfo->image_width, 2L);
  172262. cinfo->output_height = (JDIMENSION)
  172263. jdiv_round_up((long) cinfo->image_height, 2L);
  172264. cinfo->min_DCT_scaled_size = 4;
  172265. } else {
  172266. /* Provide 1/1 scaling */
  172267. cinfo->output_width = cinfo->image_width;
  172268. cinfo->output_height = cinfo->image_height;
  172269. cinfo->min_DCT_scaled_size = DCTSIZE;
  172270. }
  172271. /* In selecting the actual DCT scaling for each component, we try to
  172272. * scale up the chroma components via IDCT scaling rather than upsampling.
  172273. * This saves time if the upsampler gets to use 1:1 scaling.
  172274. * Note this code assumes that the supported DCT scalings are powers of 2.
  172275. */
  172276. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172277. ci++, compptr++) {
  172278. int ssize = cinfo->min_DCT_scaled_size;
  172279. while (ssize < DCTSIZE &&
  172280. (compptr->h_samp_factor * ssize * 2 <=
  172281. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172282. (compptr->v_samp_factor * ssize * 2 <=
  172283. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172284. ssize = ssize * 2;
  172285. }
  172286. compptr->DCT_scaled_size = ssize;
  172287. }
  172288. /* Recompute downsampled dimensions of components;
  172289. * application needs to know these if using raw downsampled data.
  172290. */
  172291. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172292. ci++, compptr++) {
  172293. /* Size in samples, after IDCT scaling */
  172294. compptr->downsampled_width = (JDIMENSION)
  172295. jdiv_round_up((long) cinfo->image_width *
  172296. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172297. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172298. compptr->downsampled_height = (JDIMENSION)
  172299. jdiv_round_up((long) cinfo->image_height *
  172300. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172301. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172302. }
  172303. #else /* !IDCT_SCALING_SUPPORTED */
  172304. /* Hardwire it to "no scaling" */
  172305. cinfo->output_width = cinfo->image_width;
  172306. cinfo->output_height = cinfo->image_height;
  172307. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172308. * and has computed unscaled downsampled_width and downsampled_height.
  172309. */
  172310. #endif /* IDCT_SCALING_SUPPORTED */
  172311. /* Report number of components in selected colorspace. */
  172312. /* Probably this should be in the color conversion module... */
  172313. switch (cinfo->out_color_space) {
  172314. case JCS_GRAYSCALE:
  172315. cinfo->out_color_components = 1;
  172316. break;
  172317. case JCS_RGB:
  172318. #if RGB_PIXELSIZE != 3
  172319. cinfo->out_color_components = RGB_PIXELSIZE;
  172320. break;
  172321. #endif /* else share code with YCbCr */
  172322. case JCS_YCbCr:
  172323. cinfo->out_color_components = 3;
  172324. break;
  172325. case JCS_CMYK:
  172326. case JCS_YCCK:
  172327. cinfo->out_color_components = 4;
  172328. break;
  172329. default: /* else must be same colorspace as in file */
  172330. cinfo->out_color_components = cinfo->num_components;
  172331. break;
  172332. }
  172333. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172334. cinfo->out_color_components);
  172335. /* See if upsampler will want to emit more than one row at a time */
  172336. if (use_merged_upsample(cinfo))
  172337. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172338. else
  172339. cinfo->rec_outbuf_height = 1;
  172340. }
  172341. /*
  172342. * Several decompression processes need to range-limit values to the range
  172343. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172344. * due to noise introduced by quantization, roundoff error, etc. These
  172345. * processes are inner loops and need to be as fast as possible. On most
  172346. * machines, particularly CPUs with pipelines or instruction prefetch,
  172347. * a (subscript-check-less) C table lookup
  172348. * x = sample_range_limit[x];
  172349. * is faster than explicit tests
  172350. * if (x < 0) x = 0;
  172351. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172352. * These processes all use a common table prepared by the routine below.
  172353. *
  172354. * For most steps we can mathematically guarantee that the initial value
  172355. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172356. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172357. * limiting step (just after the IDCT), a wildly out-of-range value is
  172358. * possible if the input data is corrupt. To avoid any chance of indexing
  172359. * off the end of memory and getting a bad-pointer trap, we perform the
  172360. * post-IDCT limiting thus:
  172361. * x = range_limit[x & MASK];
  172362. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172363. * samples. Under normal circumstances this is more than enough range and
  172364. * a correct output will be generated; with bogus input data the mask will
  172365. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172366. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172367. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172368. * So the post-IDCT limiting table ends up looking like this:
  172369. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172370. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172371. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172372. * 0,1,...,CENTERJSAMPLE-1
  172373. * Negative inputs select values from the upper half of the table after
  172374. * masking.
  172375. *
  172376. * We can save some space by overlapping the start of the post-IDCT table
  172377. * with the simpler range limiting table. The post-IDCT table begins at
  172378. * sample_range_limit + CENTERJSAMPLE.
  172379. *
  172380. * Note that the table is allocated in near data space on PCs; it's small
  172381. * enough and used often enough to justify this.
  172382. */
  172383. LOCAL(void)
  172384. prepare_range_limit_table (j_decompress_ptr cinfo)
  172385. /* Allocate and fill in the sample_range_limit table */
  172386. {
  172387. JSAMPLE * table;
  172388. int i;
  172389. table = (JSAMPLE *)
  172390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172391. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172392. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172393. cinfo->sample_range_limit = table;
  172394. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172395. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172396. /* Main part of "simple" table: limit[x] = x */
  172397. for (i = 0; i <= MAXJSAMPLE; i++)
  172398. table[i] = (JSAMPLE) i;
  172399. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172400. /* End of simple table, rest of first half of post-IDCT table */
  172401. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172402. table[i] = MAXJSAMPLE;
  172403. /* Second half of post-IDCT table */
  172404. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172405. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172406. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172407. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172408. }
  172409. /*
  172410. * Master selection of decompression modules.
  172411. * This is done once at jpeg_start_decompress time. We determine
  172412. * which modules will be used and give them appropriate initialization calls.
  172413. * We also initialize the decompressor input side to begin consuming data.
  172414. *
  172415. * Since jpeg_read_header has finished, we know what is in the SOF
  172416. * and (first) SOS markers. We also have all the application parameter
  172417. * settings.
  172418. */
  172419. LOCAL(void)
  172420. master_selection (j_decompress_ptr cinfo)
  172421. {
  172422. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172423. boolean use_c_buffer;
  172424. long samplesperrow;
  172425. JDIMENSION jd_samplesperrow;
  172426. /* Initialize dimensions and other stuff */
  172427. jpeg_calc_output_dimensions(cinfo);
  172428. prepare_range_limit_table(cinfo);
  172429. /* Width of an output scanline must be representable as JDIMENSION. */
  172430. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172431. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172432. if ((long) jd_samplesperrow != samplesperrow)
  172433. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172434. /* Initialize my private state */
  172435. master->pass_number = 0;
  172436. master->using_merged_upsample = use_merged_upsample(cinfo);
  172437. /* Color quantizer selection */
  172438. master->quantizer_1pass = NULL;
  172439. master->quantizer_2pass = NULL;
  172440. /* No mode changes if not using buffered-image mode. */
  172441. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172442. cinfo->enable_1pass_quant = FALSE;
  172443. cinfo->enable_external_quant = FALSE;
  172444. cinfo->enable_2pass_quant = FALSE;
  172445. }
  172446. if (cinfo->quantize_colors) {
  172447. if (cinfo->raw_data_out)
  172448. ERREXIT(cinfo, JERR_NOTIMPL);
  172449. /* 2-pass quantizer only works in 3-component color space. */
  172450. if (cinfo->out_color_components != 3) {
  172451. cinfo->enable_1pass_quant = TRUE;
  172452. cinfo->enable_external_quant = FALSE;
  172453. cinfo->enable_2pass_quant = FALSE;
  172454. cinfo->colormap = NULL;
  172455. } else if (cinfo->colormap != NULL) {
  172456. cinfo->enable_external_quant = TRUE;
  172457. } else if (cinfo->two_pass_quantize) {
  172458. cinfo->enable_2pass_quant = TRUE;
  172459. } else {
  172460. cinfo->enable_1pass_quant = TRUE;
  172461. }
  172462. if (cinfo->enable_1pass_quant) {
  172463. #ifdef QUANT_1PASS_SUPPORTED
  172464. jinit_1pass_quantizer(cinfo);
  172465. master->quantizer_1pass = cinfo->cquantize;
  172466. #else
  172467. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172468. #endif
  172469. }
  172470. /* We use the 2-pass code to map to external colormaps. */
  172471. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172472. #ifdef QUANT_2PASS_SUPPORTED
  172473. jinit_2pass_quantizer(cinfo);
  172474. master->quantizer_2pass = cinfo->cquantize;
  172475. #else
  172476. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172477. #endif
  172478. }
  172479. /* If both quantizers are initialized, the 2-pass one is left active;
  172480. * this is necessary for starting with quantization to an external map.
  172481. */
  172482. }
  172483. /* Post-processing: in particular, color conversion first */
  172484. if (! cinfo->raw_data_out) {
  172485. if (master->using_merged_upsample) {
  172486. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172487. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172488. #else
  172489. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172490. #endif
  172491. } else {
  172492. jinit_color_deconverter(cinfo);
  172493. jinit_upsampler(cinfo);
  172494. }
  172495. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172496. }
  172497. /* Inverse DCT */
  172498. jinit_inverse_dct(cinfo);
  172499. /* Entropy decoding: either Huffman or arithmetic coding. */
  172500. if (cinfo->arith_code) {
  172501. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172502. } else {
  172503. if (cinfo->progressive_mode) {
  172504. #ifdef D_PROGRESSIVE_SUPPORTED
  172505. jinit_phuff_decoder(cinfo);
  172506. #else
  172507. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172508. #endif
  172509. } else
  172510. jinit_huff_decoder(cinfo);
  172511. }
  172512. /* Initialize principal buffer controllers. */
  172513. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172514. jinit_d_coef_controller(cinfo, use_c_buffer);
  172515. if (! cinfo->raw_data_out)
  172516. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172517. /* We can now tell the memory manager to allocate virtual arrays. */
  172518. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172519. /* Initialize input side of decompressor to consume first scan. */
  172520. (*cinfo->inputctl->start_input_pass) (cinfo);
  172521. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172522. /* If jpeg_start_decompress will read the whole file, initialize
  172523. * progress monitoring appropriately. The input step is counted
  172524. * as one pass.
  172525. */
  172526. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172527. cinfo->inputctl->has_multiple_scans) {
  172528. int nscans;
  172529. /* Estimate number of scans to set pass_limit. */
  172530. if (cinfo->progressive_mode) {
  172531. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172532. nscans = 2 + 3 * cinfo->num_components;
  172533. } else {
  172534. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172535. nscans = cinfo->num_components;
  172536. }
  172537. cinfo->progress->pass_counter = 0L;
  172538. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172539. cinfo->progress->completed_passes = 0;
  172540. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172541. /* Count the input pass as done */
  172542. master->pass_number++;
  172543. }
  172544. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172545. }
  172546. /*
  172547. * Per-pass setup.
  172548. * This is called at the beginning of each output pass. We determine which
  172549. * modules will be active during this pass and give them appropriate
  172550. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172551. * is a "real" output pass or a dummy pass for color quantization.
  172552. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172553. */
  172554. METHODDEF(void)
  172555. prepare_for_output_pass (j_decompress_ptr cinfo)
  172556. {
  172557. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172558. if (master->pub.is_dummy_pass) {
  172559. #ifdef QUANT_2PASS_SUPPORTED
  172560. /* Final pass of 2-pass quantization */
  172561. master->pub.is_dummy_pass = FALSE;
  172562. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172563. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172564. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172565. #else
  172566. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172567. #endif /* QUANT_2PASS_SUPPORTED */
  172568. } else {
  172569. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172570. /* Select new quantization method */
  172571. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172572. cinfo->cquantize = master->quantizer_2pass;
  172573. master->pub.is_dummy_pass = TRUE;
  172574. } else if (cinfo->enable_1pass_quant) {
  172575. cinfo->cquantize = master->quantizer_1pass;
  172576. } else {
  172577. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172578. }
  172579. }
  172580. (*cinfo->idct->start_pass) (cinfo);
  172581. (*cinfo->coef->start_output_pass) (cinfo);
  172582. if (! cinfo->raw_data_out) {
  172583. if (! master->using_merged_upsample)
  172584. (*cinfo->cconvert->start_pass) (cinfo);
  172585. (*cinfo->upsample->start_pass) (cinfo);
  172586. if (cinfo->quantize_colors)
  172587. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172588. (*cinfo->post->start_pass) (cinfo,
  172589. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172590. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172591. }
  172592. }
  172593. /* Set up progress monitor's pass info if present */
  172594. if (cinfo->progress != NULL) {
  172595. cinfo->progress->completed_passes = master->pass_number;
  172596. cinfo->progress->total_passes = master->pass_number +
  172597. (master->pub.is_dummy_pass ? 2 : 1);
  172598. /* In buffered-image mode, we assume one more output pass if EOI not
  172599. * yet reached, but no more passes if EOI has been reached.
  172600. */
  172601. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172602. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172603. }
  172604. }
  172605. }
  172606. /*
  172607. * Finish up at end of an output pass.
  172608. */
  172609. METHODDEF(void)
  172610. finish_output_pass (j_decompress_ptr cinfo)
  172611. {
  172612. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172613. if (cinfo->quantize_colors)
  172614. (*cinfo->cquantize->finish_pass) (cinfo);
  172615. master->pass_number++;
  172616. }
  172617. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172618. /*
  172619. * Switch to a new external colormap between output passes.
  172620. */
  172621. GLOBAL(void)
  172622. jpeg_new_colormap (j_decompress_ptr cinfo)
  172623. {
  172624. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172625. /* Prevent application from calling me at wrong times */
  172626. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172627. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172628. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172629. cinfo->colormap != NULL) {
  172630. /* Select 2-pass quantizer for external colormap use */
  172631. cinfo->cquantize = master->quantizer_2pass;
  172632. /* Notify quantizer of colormap change */
  172633. (*cinfo->cquantize->new_color_map) (cinfo);
  172634. master->pub.is_dummy_pass = FALSE; /* just in case */
  172635. } else
  172636. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172637. }
  172638. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172639. /*
  172640. * Initialize master decompression control and select active modules.
  172641. * This is performed at the start of jpeg_start_decompress.
  172642. */
  172643. GLOBAL(void)
  172644. jinit_master_decompress (j_decompress_ptr cinfo)
  172645. {
  172646. my_master_ptr6 master;
  172647. master = (my_master_ptr6)
  172648. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172649. SIZEOF(my_decomp_master));
  172650. cinfo->master = (struct jpeg_decomp_master *) master;
  172651. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172652. master->pub.finish_output_pass = finish_output_pass;
  172653. master->pub.is_dummy_pass = FALSE;
  172654. master_selection(cinfo);
  172655. }
  172656. /*** End of inlined file: jdmaster.c ***/
  172657. #undef FIX
  172658. /*** Start of inlined file: jdmerge.c ***/
  172659. #define JPEG_INTERNALS
  172660. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172661. /* Private subobject */
  172662. typedef struct {
  172663. struct jpeg_upsampler pub; /* public fields */
  172664. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172665. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172666. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172667. JSAMPARRAY output_buf));
  172668. /* Private state for YCC->RGB conversion */
  172669. int * Cr_r_tab; /* => table for Cr to R conversion */
  172670. int * Cb_b_tab; /* => table for Cb to B conversion */
  172671. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172672. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172673. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172674. * We need a "spare" row buffer to hold the second output row if the
  172675. * application provides just a one-row buffer; we also use the spare
  172676. * to discard the dummy last row if the image height is odd.
  172677. */
  172678. JSAMPROW spare_row;
  172679. boolean spare_full; /* T if spare buffer is occupied */
  172680. JDIMENSION out_row_width; /* samples per output row */
  172681. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172682. } my_upsampler;
  172683. typedef my_upsampler * my_upsample_ptr;
  172684. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172685. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172686. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172687. /*
  172688. * Initialize tables for YCC->RGB colorspace conversion.
  172689. * This is taken directly from jdcolor.c; see that file for more info.
  172690. */
  172691. LOCAL(void)
  172692. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172693. {
  172694. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172695. int i;
  172696. INT32 x;
  172697. SHIFT_TEMPS
  172698. upsample->Cr_r_tab = (int *)
  172699. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172700. (MAXJSAMPLE+1) * SIZEOF(int));
  172701. upsample->Cb_b_tab = (int *)
  172702. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172703. (MAXJSAMPLE+1) * SIZEOF(int));
  172704. upsample->Cr_g_tab = (INT32 *)
  172705. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172706. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172707. upsample->Cb_g_tab = (INT32 *)
  172708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172709. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172710. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172711. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172712. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172713. /* Cr=>R value is nearest int to 1.40200 * x */
  172714. upsample->Cr_r_tab[i] = (int)
  172715. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172716. /* Cb=>B value is nearest int to 1.77200 * x */
  172717. upsample->Cb_b_tab[i] = (int)
  172718. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172719. /* Cr=>G value is scaled-up -0.71414 * x */
  172720. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172721. /* Cb=>G value is scaled-up -0.34414 * x */
  172722. /* We also add in ONE_HALF so that need not do it in inner loop */
  172723. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172724. }
  172725. }
  172726. /*
  172727. * Initialize for an upsampling pass.
  172728. */
  172729. METHODDEF(void)
  172730. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172731. {
  172732. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172733. /* Mark the spare buffer empty */
  172734. upsample->spare_full = FALSE;
  172735. /* Initialize total-height counter for detecting bottom of image */
  172736. upsample->rows_to_go = cinfo->output_height;
  172737. }
  172738. /*
  172739. * Control routine to do upsampling (and color conversion).
  172740. *
  172741. * The control routine just handles the row buffering considerations.
  172742. */
  172743. METHODDEF(void)
  172744. merged_2v_upsample (j_decompress_ptr cinfo,
  172745. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172746. JDIMENSION,
  172747. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172748. JDIMENSION out_rows_avail)
  172749. /* 2:1 vertical sampling case: may need a spare row. */
  172750. {
  172751. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172752. JSAMPROW work_ptrs[2];
  172753. JDIMENSION num_rows; /* number of rows returned to caller */
  172754. if (upsample->spare_full) {
  172755. /* If we have a spare row saved from a previous cycle, just return it. */
  172756. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172757. 1, upsample->out_row_width);
  172758. num_rows = 1;
  172759. upsample->spare_full = FALSE;
  172760. } else {
  172761. /* Figure number of rows to return to caller. */
  172762. num_rows = 2;
  172763. /* Not more than the distance to the end of the image. */
  172764. if (num_rows > upsample->rows_to_go)
  172765. num_rows = upsample->rows_to_go;
  172766. /* And not more than what the client can accept: */
  172767. out_rows_avail -= *out_row_ctr;
  172768. if (num_rows > out_rows_avail)
  172769. num_rows = out_rows_avail;
  172770. /* Create output pointer array for upsampler. */
  172771. work_ptrs[0] = output_buf[*out_row_ctr];
  172772. if (num_rows > 1) {
  172773. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172774. } else {
  172775. work_ptrs[1] = upsample->spare_row;
  172776. upsample->spare_full = TRUE;
  172777. }
  172778. /* Now do the upsampling. */
  172779. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172780. }
  172781. /* Adjust counts */
  172782. *out_row_ctr += num_rows;
  172783. upsample->rows_to_go -= num_rows;
  172784. /* When the buffer is emptied, declare this input row group consumed */
  172785. if (! upsample->spare_full)
  172786. (*in_row_group_ctr)++;
  172787. }
  172788. METHODDEF(void)
  172789. merged_1v_upsample (j_decompress_ptr cinfo,
  172790. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172791. JDIMENSION,
  172792. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172793. JDIMENSION)
  172794. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172795. {
  172796. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172797. /* Just do the upsampling. */
  172798. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172799. output_buf + *out_row_ctr);
  172800. /* Adjust counts */
  172801. (*out_row_ctr)++;
  172802. (*in_row_group_ctr)++;
  172803. }
  172804. /*
  172805. * These are the routines invoked by the control routines to do
  172806. * the actual upsampling/conversion. One row group is processed per call.
  172807. *
  172808. * Note: since we may be writing directly into application-supplied buffers,
  172809. * we have to be honest about the output width; we can't assume the buffer
  172810. * has been rounded up to an even width.
  172811. */
  172812. /*
  172813. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172814. */
  172815. METHODDEF(void)
  172816. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172817. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172818. JSAMPARRAY output_buf)
  172819. {
  172820. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172821. register int y, cred, cgreen, cblue;
  172822. int cb, cr;
  172823. register JSAMPROW outptr;
  172824. JSAMPROW inptr0, inptr1, inptr2;
  172825. JDIMENSION col;
  172826. /* copy these pointers into registers if possible */
  172827. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172828. int * Crrtab = upsample->Cr_r_tab;
  172829. int * Cbbtab = upsample->Cb_b_tab;
  172830. INT32 * Crgtab = upsample->Cr_g_tab;
  172831. INT32 * Cbgtab = upsample->Cb_g_tab;
  172832. SHIFT_TEMPS
  172833. inptr0 = input_buf[0][in_row_group_ctr];
  172834. inptr1 = input_buf[1][in_row_group_ctr];
  172835. inptr2 = input_buf[2][in_row_group_ctr];
  172836. outptr = output_buf[0];
  172837. /* Loop for each pair of output pixels */
  172838. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172839. /* Do the chroma part of the calculation */
  172840. cb = GETJSAMPLE(*inptr1++);
  172841. cr = GETJSAMPLE(*inptr2++);
  172842. cred = Crrtab[cr];
  172843. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172844. cblue = Cbbtab[cb];
  172845. /* Fetch 2 Y values and emit 2 pixels */
  172846. y = GETJSAMPLE(*inptr0++);
  172847. outptr[RGB_RED] = range_limit[y + cred];
  172848. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172849. outptr[RGB_BLUE] = range_limit[y + cblue];
  172850. outptr += RGB_PIXELSIZE;
  172851. y = GETJSAMPLE(*inptr0++);
  172852. outptr[RGB_RED] = range_limit[y + cred];
  172853. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172854. outptr[RGB_BLUE] = range_limit[y + cblue];
  172855. outptr += RGB_PIXELSIZE;
  172856. }
  172857. /* If image width is odd, do the last output column separately */
  172858. if (cinfo->output_width & 1) {
  172859. cb = GETJSAMPLE(*inptr1);
  172860. cr = GETJSAMPLE(*inptr2);
  172861. cred = Crrtab[cr];
  172862. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172863. cblue = Cbbtab[cb];
  172864. y = GETJSAMPLE(*inptr0);
  172865. outptr[RGB_RED] = range_limit[y + cred];
  172866. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172867. outptr[RGB_BLUE] = range_limit[y + cblue];
  172868. }
  172869. }
  172870. /*
  172871. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172872. */
  172873. METHODDEF(void)
  172874. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172875. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172876. JSAMPARRAY output_buf)
  172877. {
  172878. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172879. register int y, cred, cgreen, cblue;
  172880. int cb, cr;
  172881. register JSAMPROW outptr0, outptr1;
  172882. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172883. JDIMENSION col;
  172884. /* copy these pointers into registers if possible */
  172885. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172886. int * Crrtab = upsample->Cr_r_tab;
  172887. int * Cbbtab = upsample->Cb_b_tab;
  172888. INT32 * Crgtab = upsample->Cr_g_tab;
  172889. INT32 * Cbgtab = upsample->Cb_g_tab;
  172890. SHIFT_TEMPS
  172891. inptr00 = input_buf[0][in_row_group_ctr*2];
  172892. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172893. inptr1 = input_buf[1][in_row_group_ctr];
  172894. inptr2 = input_buf[2][in_row_group_ctr];
  172895. outptr0 = output_buf[0];
  172896. outptr1 = output_buf[1];
  172897. /* Loop for each group of output pixels */
  172898. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172899. /* Do the chroma part of the calculation */
  172900. cb = GETJSAMPLE(*inptr1++);
  172901. cr = GETJSAMPLE(*inptr2++);
  172902. cred = Crrtab[cr];
  172903. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172904. cblue = Cbbtab[cb];
  172905. /* Fetch 4 Y values and emit 4 pixels */
  172906. y = GETJSAMPLE(*inptr00++);
  172907. outptr0[RGB_RED] = range_limit[y + cred];
  172908. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172909. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172910. outptr0 += RGB_PIXELSIZE;
  172911. y = GETJSAMPLE(*inptr00++);
  172912. outptr0[RGB_RED] = range_limit[y + cred];
  172913. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172914. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172915. outptr0 += RGB_PIXELSIZE;
  172916. y = GETJSAMPLE(*inptr01++);
  172917. outptr1[RGB_RED] = range_limit[y + cred];
  172918. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172919. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172920. outptr1 += RGB_PIXELSIZE;
  172921. y = GETJSAMPLE(*inptr01++);
  172922. outptr1[RGB_RED] = range_limit[y + cred];
  172923. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172924. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172925. outptr1 += RGB_PIXELSIZE;
  172926. }
  172927. /* If image width is odd, do the last output column separately */
  172928. if (cinfo->output_width & 1) {
  172929. cb = GETJSAMPLE(*inptr1);
  172930. cr = GETJSAMPLE(*inptr2);
  172931. cred = Crrtab[cr];
  172932. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172933. cblue = Cbbtab[cb];
  172934. y = GETJSAMPLE(*inptr00);
  172935. outptr0[RGB_RED] = range_limit[y + cred];
  172936. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172937. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172938. 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. }
  172943. }
  172944. /*
  172945. * Module initialization routine for merged upsampling/color conversion.
  172946. *
  172947. * NB: this is called under the conditions determined by use_merged_upsample()
  172948. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172949. * of this module; no safety checks are made here.
  172950. */
  172951. GLOBAL(void)
  172952. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172953. {
  172954. my_upsample_ptr upsample;
  172955. upsample = (my_upsample_ptr)
  172956. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172957. SIZEOF(my_upsampler));
  172958. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172959. upsample->pub.start_pass = start_pass_merged_upsample;
  172960. upsample->pub.need_context_rows = FALSE;
  172961. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172962. if (cinfo->max_v_samp_factor == 2) {
  172963. upsample->pub.upsample = merged_2v_upsample;
  172964. upsample->upmethod = h2v2_merged_upsample;
  172965. /* Allocate a spare row buffer */
  172966. upsample->spare_row = (JSAMPROW)
  172967. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172968. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172969. } else {
  172970. upsample->pub.upsample = merged_1v_upsample;
  172971. upsample->upmethod = h2v1_merged_upsample;
  172972. /* No spare row needed */
  172973. upsample->spare_row = NULL;
  172974. }
  172975. build_ycc_rgb_table2(cinfo);
  172976. }
  172977. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172978. /*** End of inlined file: jdmerge.c ***/
  172979. #undef ASSIGN_STATE
  172980. /*** Start of inlined file: jdphuff.c ***/
  172981. #define JPEG_INTERNALS
  172982. #ifdef D_PROGRESSIVE_SUPPORTED
  172983. /*
  172984. * Expanded entropy decoder object for progressive Huffman decoding.
  172985. *
  172986. * The savable_state subrecord contains fields that change within an MCU,
  172987. * but must not be updated permanently until we complete the MCU.
  172988. */
  172989. typedef struct {
  172990. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172991. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172992. } savable_state3;
  172993. /* This macro is to work around compilers with missing or broken
  172994. * structure assignment. You'll need to fix this code if you have
  172995. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172996. */
  172997. #ifndef NO_STRUCT_ASSIGN
  172998. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172999. #else
  173000. #if MAX_COMPS_IN_SCAN == 4
  173001. #define ASSIGN_STATE(dest,src) \
  173002. ((dest).EOBRUN = (src).EOBRUN, \
  173003. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173004. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173005. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173006. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173007. #endif
  173008. #endif
  173009. typedef struct {
  173010. struct jpeg_entropy_decoder pub; /* public fields */
  173011. /* These fields are loaded into local variables at start of each MCU.
  173012. * In case of suspension, we exit WITHOUT updating them.
  173013. */
  173014. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173015. savable_state3 saved; /* Other state at start of MCU */
  173016. /* These fields are NOT loaded into local working state. */
  173017. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173018. /* Pointers to derived tables (these workspaces have image lifespan) */
  173019. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173020. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173021. } phuff_entropy_decoder;
  173022. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173023. /* Forward declarations */
  173024. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173025. JBLOCKROW *MCU_data));
  173026. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173027. JBLOCKROW *MCU_data));
  173028. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173029. JBLOCKROW *MCU_data));
  173030. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173031. JBLOCKROW *MCU_data));
  173032. /*
  173033. * Initialize for a Huffman-compressed scan.
  173034. */
  173035. METHODDEF(void)
  173036. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173037. {
  173038. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173039. boolean is_DC_band, bad;
  173040. int ci, coefi, tbl;
  173041. int *coef_bit_ptr;
  173042. jpeg_component_info * compptr;
  173043. is_DC_band = (cinfo->Ss == 0);
  173044. /* Validate scan parameters */
  173045. bad = FALSE;
  173046. if (is_DC_band) {
  173047. if (cinfo->Se != 0)
  173048. bad = TRUE;
  173049. } else {
  173050. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173051. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173052. bad = TRUE;
  173053. /* AC scans may have only one component */
  173054. if (cinfo->comps_in_scan != 1)
  173055. bad = TRUE;
  173056. }
  173057. if (cinfo->Ah != 0) {
  173058. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173059. if (cinfo->Al != cinfo->Ah-1)
  173060. bad = TRUE;
  173061. }
  173062. if (cinfo->Al > 13) /* need not check for < 0 */
  173063. bad = TRUE;
  173064. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173065. * but the spec doesn't say so, and we try to be liberal about what we
  173066. * accept. Note: large Al values could result in out-of-range DC
  173067. * coefficients during early scans, leading to bizarre displays due to
  173068. * overflows in the IDCT math. But we won't crash.
  173069. */
  173070. if (bad)
  173071. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173072. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173073. /* Update progression status, and verify that scan order is legal.
  173074. * Note that inter-scan inconsistencies are treated as warnings
  173075. * not fatal errors ... not clear if this is right way to behave.
  173076. */
  173077. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173078. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173079. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173080. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173081. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173082. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173083. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173084. if (cinfo->Ah != expected)
  173085. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173086. coef_bit_ptr[coefi] = cinfo->Al;
  173087. }
  173088. }
  173089. /* Select MCU decoding routine */
  173090. if (cinfo->Ah == 0) {
  173091. if (is_DC_band)
  173092. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173093. else
  173094. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173095. } else {
  173096. if (is_DC_band)
  173097. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173098. else
  173099. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173100. }
  173101. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173102. compptr = cinfo->cur_comp_info[ci];
  173103. /* Make sure requested tables are present, and compute derived tables.
  173104. * We may build same derived table more than once, but it's not expensive.
  173105. */
  173106. if (is_DC_band) {
  173107. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173108. tbl = compptr->dc_tbl_no;
  173109. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173110. & entropy->derived_tbls[tbl]);
  173111. }
  173112. } else {
  173113. tbl = compptr->ac_tbl_no;
  173114. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173115. & entropy->derived_tbls[tbl]);
  173116. /* remember the single active table */
  173117. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173118. }
  173119. /* Initialize DC predictions to 0 */
  173120. entropy->saved.last_dc_val[ci] = 0;
  173121. }
  173122. /* Initialize bitread state variables */
  173123. entropy->bitstate.bits_left = 0;
  173124. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173125. entropy->pub.insufficient_data = FALSE;
  173126. /* Initialize private state variables */
  173127. entropy->saved.EOBRUN = 0;
  173128. /* Initialize restart counter */
  173129. entropy->restarts_to_go = cinfo->restart_interval;
  173130. }
  173131. /*
  173132. * Check for a restart marker & resynchronize decoder.
  173133. * Returns FALSE if must suspend.
  173134. */
  173135. LOCAL(boolean)
  173136. process_restartp (j_decompress_ptr cinfo)
  173137. {
  173138. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173139. int ci;
  173140. /* Throw away any unused bits remaining in bit buffer; */
  173141. /* include any full bytes in next_marker's count of discarded bytes */
  173142. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173143. entropy->bitstate.bits_left = 0;
  173144. /* Advance past the RSTn marker */
  173145. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173146. return FALSE;
  173147. /* Re-initialize DC predictions to 0 */
  173148. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173149. entropy->saved.last_dc_val[ci] = 0;
  173150. /* Re-init EOB run count, too */
  173151. entropy->saved.EOBRUN = 0;
  173152. /* Reset restart counter */
  173153. entropy->restarts_to_go = cinfo->restart_interval;
  173154. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173155. * against a marker. In that case we will end up treating the next data
  173156. * segment as empty, and we can avoid producing bogus output pixels by
  173157. * leaving the flag set.
  173158. */
  173159. if (cinfo->unread_marker == 0)
  173160. entropy->pub.insufficient_data = FALSE;
  173161. return TRUE;
  173162. }
  173163. /*
  173164. * Huffman MCU decoding.
  173165. * Each of these routines decodes and returns one MCU's worth of
  173166. * Huffman-compressed coefficients.
  173167. * The coefficients are reordered from zigzag order into natural array order,
  173168. * but are not dequantized.
  173169. *
  173170. * The i'th block of the MCU is stored into the block pointed to by
  173171. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173172. *
  173173. * We return FALSE if data source requested suspension. In that case no
  173174. * changes have been made to permanent state. (Exception: some output
  173175. * coefficients may already have been assigned. This is harmless for
  173176. * spectral selection, since we'll just re-assign them on the next call.
  173177. * Successive approximation AC refinement has to be more careful, however.)
  173178. */
  173179. /*
  173180. * MCU decoding for DC initial scan (either spectral selection,
  173181. * or first pass of successive approximation).
  173182. */
  173183. METHODDEF(boolean)
  173184. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173185. {
  173186. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173187. int Al = cinfo->Al;
  173188. register int s, r;
  173189. int blkn, ci;
  173190. JBLOCKROW block;
  173191. BITREAD_STATE_VARS;
  173192. savable_state3 state;
  173193. d_derived_tbl * tbl;
  173194. jpeg_component_info * compptr;
  173195. /* Process restart marker if needed; may have to suspend */
  173196. if (cinfo->restart_interval) {
  173197. if (entropy->restarts_to_go == 0)
  173198. if (! process_restartp(cinfo))
  173199. return FALSE;
  173200. }
  173201. /* If we've run out of data, just leave the MCU set to zeroes.
  173202. * This way, we return uniform gray for the remainder of the segment.
  173203. */
  173204. if (! entropy->pub.insufficient_data) {
  173205. /* Load up working state */
  173206. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173207. ASSIGN_STATE(state, entropy->saved);
  173208. /* Outer loop handles each block in the MCU */
  173209. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173210. block = MCU_data[blkn];
  173211. ci = cinfo->MCU_membership[blkn];
  173212. compptr = cinfo->cur_comp_info[ci];
  173213. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173214. /* Decode a single block's worth of coefficients */
  173215. /* Section F.2.2.1: decode the DC coefficient difference */
  173216. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173217. if (s) {
  173218. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173219. r = GET_BITS(s);
  173220. s = HUFF_EXTEND(r, s);
  173221. }
  173222. /* Convert DC difference to actual value, update last_dc_val */
  173223. s += state.last_dc_val[ci];
  173224. state.last_dc_val[ci] = s;
  173225. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173226. (*block)[0] = (JCOEF) (s << Al);
  173227. }
  173228. /* Completed MCU, so update state */
  173229. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173230. ASSIGN_STATE(entropy->saved, state);
  173231. }
  173232. /* Account for restart interval (no-op if not using restarts) */
  173233. entropy->restarts_to_go--;
  173234. return TRUE;
  173235. }
  173236. /*
  173237. * MCU decoding for AC initial scan (either spectral selection,
  173238. * or first pass of successive approximation).
  173239. */
  173240. METHODDEF(boolean)
  173241. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173242. {
  173243. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173244. int Se = cinfo->Se;
  173245. int Al = cinfo->Al;
  173246. register int s, k, r;
  173247. unsigned int EOBRUN;
  173248. JBLOCKROW block;
  173249. BITREAD_STATE_VARS;
  173250. d_derived_tbl * tbl;
  173251. /* Process restart marker if needed; may have to suspend */
  173252. if (cinfo->restart_interval) {
  173253. if (entropy->restarts_to_go == 0)
  173254. if (! process_restartp(cinfo))
  173255. return FALSE;
  173256. }
  173257. /* If we've run out of data, just leave the MCU set to zeroes.
  173258. * This way, we return uniform gray for the remainder of the segment.
  173259. */
  173260. if (! entropy->pub.insufficient_data) {
  173261. /* Load up working state.
  173262. * We can avoid loading/saving bitread state if in an EOB run.
  173263. */
  173264. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173265. /* There is always only one block per MCU */
  173266. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173267. EOBRUN--; /* ...process it now (we do nothing) */
  173268. else {
  173269. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173270. block = MCU_data[0];
  173271. tbl = entropy->ac_derived_tbl;
  173272. for (k = cinfo->Ss; k <= Se; k++) {
  173273. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173274. r = s >> 4;
  173275. s &= 15;
  173276. if (s) {
  173277. k += r;
  173278. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173279. r = GET_BITS(s);
  173280. s = HUFF_EXTEND(r, s);
  173281. /* Scale and output coefficient in natural (dezigzagged) order */
  173282. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173283. } else {
  173284. if (r == 15) { /* ZRL */
  173285. k += 15; /* skip 15 zeroes in band */
  173286. } else { /* EOBr, run length is 2^r + appended bits */
  173287. EOBRUN = 1 << r;
  173288. if (r) { /* EOBr, r > 0 */
  173289. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173290. r = GET_BITS(r);
  173291. EOBRUN += r;
  173292. }
  173293. EOBRUN--; /* this band is processed at this moment */
  173294. break; /* force end-of-band */
  173295. }
  173296. }
  173297. }
  173298. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173299. }
  173300. /* Completed MCU, so update state */
  173301. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173302. }
  173303. /* Account for restart interval (no-op if not using restarts) */
  173304. entropy->restarts_to_go--;
  173305. return TRUE;
  173306. }
  173307. /*
  173308. * MCU decoding for DC successive approximation refinement scan.
  173309. * Note: we assume such scans can be multi-component, although the spec
  173310. * is not very clear on the point.
  173311. */
  173312. METHODDEF(boolean)
  173313. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173314. {
  173315. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173316. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173317. int blkn;
  173318. JBLOCKROW block;
  173319. BITREAD_STATE_VARS;
  173320. /* Process restart marker if needed; may have to suspend */
  173321. if (cinfo->restart_interval) {
  173322. if (entropy->restarts_to_go == 0)
  173323. if (! process_restartp(cinfo))
  173324. return FALSE;
  173325. }
  173326. /* Not worth the cycles to check insufficient_data here,
  173327. * since we will not change the data anyway if we read zeroes.
  173328. */
  173329. /* Load up working state */
  173330. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173331. /* Outer loop handles each block in the MCU */
  173332. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173333. block = MCU_data[blkn];
  173334. /* Encoded data is simply the next bit of the two's-complement DC value */
  173335. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173336. if (GET_BITS(1))
  173337. (*block)[0] |= p1;
  173338. /* Note: since we use |=, repeating the assignment later is safe */
  173339. }
  173340. /* Completed MCU, so update state */
  173341. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173342. /* Account for restart interval (no-op if not using restarts) */
  173343. entropy->restarts_to_go--;
  173344. return TRUE;
  173345. }
  173346. /*
  173347. * MCU decoding for AC successive approximation refinement scan.
  173348. */
  173349. METHODDEF(boolean)
  173350. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173351. {
  173352. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173353. int Se = cinfo->Se;
  173354. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173355. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173356. register int s, k, r;
  173357. unsigned int EOBRUN;
  173358. JBLOCKROW block;
  173359. JCOEFPTR thiscoef;
  173360. BITREAD_STATE_VARS;
  173361. d_derived_tbl * tbl;
  173362. int num_newnz;
  173363. int newnz_pos[DCTSIZE2];
  173364. /* Process restart marker if needed; may have to suspend */
  173365. if (cinfo->restart_interval) {
  173366. if (entropy->restarts_to_go == 0)
  173367. if (! process_restartp(cinfo))
  173368. return FALSE;
  173369. }
  173370. /* If we've run out of data, don't modify the MCU.
  173371. */
  173372. if (! entropy->pub.insufficient_data) {
  173373. /* Load up working state */
  173374. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173375. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173376. /* There is always only one block per MCU */
  173377. block = MCU_data[0];
  173378. tbl = entropy->ac_derived_tbl;
  173379. /* If we are forced to suspend, we must undo the assignments to any newly
  173380. * nonzero coefficients in the block, because otherwise we'd get confused
  173381. * next time about which coefficients were already nonzero.
  173382. * But we need not undo addition of bits to already-nonzero coefficients;
  173383. * instead, we can test the current bit to see if we already did it.
  173384. */
  173385. num_newnz = 0;
  173386. /* initialize coefficient loop counter to start of band */
  173387. k = cinfo->Ss;
  173388. if (EOBRUN == 0) {
  173389. for (; k <= Se; k++) {
  173390. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173391. r = s >> 4;
  173392. s &= 15;
  173393. if (s) {
  173394. if (s != 1) /* size of new coef should always be 1 */
  173395. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173396. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173397. if (GET_BITS(1))
  173398. s = p1; /* newly nonzero coef is positive */
  173399. else
  173400. s = m1; /* newly nonzero coef is negative */
  173401. } else {
  173402. if (r != 15) {
  173403. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173404. if (r) {
  173405. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173406. r = GET_BITS(r);
  173407. EOBRUN += r;
  173408. }
  173409. break; /* rest of block is handled by EOB logic */
  173410. }
  173411. /* note s = 0 for processing ZRL */
  173412. }
  173413. /* Advance over already-nonzero coefs and r still-zero coefs,
  173414. * appending correction bits to the nonzeroes. A correction bit is 1
  173415. * if the absolute value of the coefficient must be increased.
  173416. */
  173417. do {
  173418. thiscoef = *block + jpeg_natural_order[k];
  173419. if (*thiscoef != 0) {
  173420. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173421. if (GET_BITS(1)) {
  173422. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173423. if (*thiscoef >= 0)
  173424. *thiscoef += p1;
  173425. else
  173426. *thiscoef += m1;
  173427. }
  173428. }
  173429. } else {
  173430. if (--r < 0)
  173431. break; /* reached target zero coefficient */
  173432. }
  173433. k++;
  173434. } while (k <= Se);
  173435. if (s) {
  173436. int pos = jpeg_natural_order[k];
  173437. /* Output newly nonzero coefficient */
  173438. (*block)[pos] = (JCOEF) s;
  173439. /* Remember its position in case we have to suspend */
  173440. newnz_pos[num_newnz++] = pos;
  173441. }
  173442. }
  173443. }
  173444. if (EOBRUN > 0) {
  173445. /* Scan any remaining coefficient positions after the end-of-band
  173446. * (the last newly nonzero coefficient, if any). Append a correction
  173447. * bit to each already-nonzero coefficient. A correction bit is 1
  173448. * if the absolute value of the coefficient must be increased.
  173449. */
  173450. for (; k <= Se; k++) {
  173451. thiscoef = *block + jpeg_natural_order[k];
  173452. if (*thiscoef != 0) {
  173453. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173454. if (GET_BITS(1)) {
  173455. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173456. if (*thiscoef >= 0)
  173457. *thiscoef += p1;
  173458. else
  173459. *thiscoef += m1;
  173460. }
  173461. }
  173462. }
  173463. }
  173464. /* Count one block completed in EOB run */
  173465. EOBRUN--;
  173466. }
  173467. /* Completed MCU, so update state */
  173468. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173469. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173470. }
  173471. /* Account for restart interval (no-op if not using restarts) */
  173472. entropy->restarts_to_go--;
  173473. return TRUE;
  173474. undoit:
  173475. /* Re-zero any output coefficients that we made newly nonzero */
  173476. while (num_newnz > 0)
  173477. (*block)[newnz_pos[--num_newnz]] = 0;
  173478. return FALSE;
  173479. }
  173480. /*
  173481. * Module initialization routine for progressive Huffman entropy decoding.
  173482. */
  173483. GLOBAL(void)
  173484. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173485. {
  173486. phuff_entropy_ptr2 entropy;
  173487. int *coef_bit_ptr;
  173488. int ci, i;
  173489. entropy = (phuff_entropy_ptr2)
  173490. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173491. SIZEOF(phuff_entropy_decoder));
  173492. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173493. entropy->pub.start_pass = start_pass_phuff_decoder;
  173494. /* Mark derived tables unallocated */
  173495. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173496. entropy->derived_tbls[i] = NULL;
  173497. }
  173498. /* Create progression status table */
  173499. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173500. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173501. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173502. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173503. for (ci = 0; ci < cinfo->num_components; ci++)
  173504. for (i = 0; i < DCTSIZE2; i++)
  173505. *coef_bit_ptr++ = -1;
  173506. }
  173507. #endif /* D_PROGRESSIVE_SUPPORTED */
  173508. /*** End of inlined file: jdphuff.c ***/
  173509. /*** Start of inlined file: jdpostct.c ***/
  173510. #define JPEG_INTERNALS
  173511. /* Private buffer controller object */
  173512. typedef struct {
  173513. struct jpeg_d_post_controller pub; /* public fields */
  173514. /* Color quantization source buffer: this holds output data from
  173515. * the upsample/color conversion step to be passed to the quantizer.
  173516. * For two-pass color quantization, we need a full-image buffer;
  173517. * for one-pass operation, a strip buffer is sufficient.
  173518. */
  173519. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173520. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173521. JDIMENSION strip_height; /* buffer size in rows */
  173522. /* for two-pass mode only: */
  173523. JDIMENSION starting_row; /* row # of first row in current strip */
  173524. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173525. } my_post_controller;
  173526. typedef my_post_controller * my_post_ptr;
  173527. /* Forward declarations */
  173528. METHODDEF(void) post_process_1pass
  173529. JPP((j_decompress_ptr cinfo,
  173530. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173531. JDIMENSION in_row_groups_avail,
  173532. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173533. JDIMENSION out_rows_avail));
  173534. #ifdef QUANT_2PASS_SUPPORTED
  173535. METHODDEF(void) post_process_prepass
  173536. JPP((j_decompress_ptr cinfo,
  173537. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173538. JDIMENSION in_row_groups_avail,
  173539. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173540. JDIMENSION out_rows_avail));
  173541. METHODDEF(void) post_process_2pass
  173542. JPP((j_decompress_ptr cinfo,
  173543. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173544. JDIMENSION in_row_groups_avail,
  173545. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173546. JDIMENSION out_rows_avail));
  173547. #endif
  173548. /*
  173549. * Initialize for a processing pass.
  173550. */
  173551. METHODDEF(void)
  173552. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173553. {
  173554. my_post_ptr post = (my_post_ptr) cinfo->post;
  173555. switch (pass_mode) {
  173556. case JBUF_PASS_THRU:
  173557. if (cinfo->quantize_colors) {
  173558. /* Single-pass processing with color quantization. */
  173559. post->pub.post_process_data = post_process_1pass;
  173560. /* We could be doing buffered-image output before starting a 2-pass
  173561. * color quantization; in that case, jinit_d_post_controller did not
  173562. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173563. */
  173564. if (post->buffer == NULL) {
  173565. post->buffer = (*cinfo->mem->access_virt_sarray)
  173566. ((j_common_ptr) cinfo, post->whole_image,
  173567. (JDIMENSION) 0, post->strip_height, TRUE);
  173568. }
  173569. } else {
  173570. /* For single-pass processing without color quantization,
  173571. * I have no work to do; just call the upsampler directly.
  173572. */
  173573. post->pub.post_process_data = cinfo->upsample->upsample;
  173574. }
  173575. break;
  173576. #ifdef QUANT_2PASS_SUPPORTED
  173577. case JBUF_SAVE_AND_PASS:
  173578. /* First pass of 2-pass quantization */
  173579. if (post->whole_image == NULL)
  173580. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173581. post->pub.post_process_data = post_process_prepass;
  173582. break;
  173583. case JBUF_CRANK_DEST:
  173584. /* Second pass of 2-pass quantization */
  173585. if (post->whole_image == NULL)
  173586. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173587. post->pub.post_process_data = post_process_2pass;
  173588. break;
  173589. #endif /* QUANT_2PASS_SUPPORTED */
  173590. default:
  173591. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173592. break;
  173593. }
  173594. post->starting_row = post->next_row = 0;
  173595. }
  173596. /*
  173597. * Process some data in the one-pass (strip buffer) case.
  173598. * This is used for color precision reduction as well as one-pass quantization.
  173599. */
  173600. METHODDEF(void)
  173601. post_process_1pass (j_decompress_ptr cinfo,
  173602. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173603. JDIMENSION in_row_groups_avail,
  173604. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173605. JDIMENSION out_rows_avail)
  173606. {
  173607. my_post_ptr post = (my_post_ptr) cinfo->post;
  173608. JDIMENSION num_rows, max_rows;
  173609. /* Fill the buffer, but not more than what we can dump out in one go. */
  173610. /* Note we rely on the upsampler to detect bottom of image. */
  173611. max_rows = out_rows_avail - *out_row_ctr;
  173612. if (max_rows > post->strip_height)
  173613. max_rows = post->strip_height;
  173614. num_rows = 0;
  173615. (*cinfo->upsample->upsample) (cinfo,
  173616. input_buf, in_row_group_ctr, in_row_groups_avail,
  173617. post->buffer, &num_rows, max_rows);
  173618. /* Quantize and emit data. */
  173619. (*cinfo->cquantize->color_quantize) (cinfo,
  173620. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173621. *out_row_ctr += num_rows;
  173622. }
  173623. #ifdef QUANT_2PASS_SUPPORTED
  173624. /*
  173625. * Process some data in the first pass of 2-pass quantization.
  173626. */
  173627. METHODDEF(void)
  173628. post_process_prepass (j_decompress_ptr cinfo,
  173629. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173630. JDIMENSION in_row_groups_avail,
  173631. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173632. JDIMENSION)
  173633. {
  173634. my_post_ptr post = (my_post_ptr) cinfo->post;
  173635. JDIMENSION old_next_row, num_rows;
  173636. /* Reposition virtual buffer if at start of strip. */
  173637. if (post->next_row == 0) {
  173638. post->buffer = (*cinfo->mem->access_virt_sarray)
  173639. ((j_common_ptr) cinfo, post->whole_image,
  173640. post->starting_row, post->strip_height, TRUE);
  173641. }
  173642. /* Upsample some data (up to a strip height's worth). */
  173643. old_next_row = post->next_row;
  173644. (*cinfo->upsample->upsample) (cinfo,
  173645. input_buf, in_row_group_ctr, in_row_groups_avail,
  173646. post->buffer, &post->next_row, post->strip_height);
  173647. /* Allow quantizer to scan new data. No data is emitted, */
  173648. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173649. if (post->next_row > old_next_row) {
  173650. num_rows = post->next_row - old_next_row;
  173651. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173652. (JSAMPARRAY) NULL, (int) num_rows);
  173653. *out_row_ctr += num_rows;
  173654. }
  173655. /* Advance if we filled the strip. */
  173656. if (post->next_row >= post->strip_height) {
  173657. post->starting_row += post->strip_height;
  173658. post->next_row = 0;
  173659. }
  173660. }
  173661. /*
  173662. * Process some data in the second pass of 2-pass quantization.
  173663. */
  173664. METHODDEF(void)
  173665. post_process_2pass (j_decompress_ptr cinfo,
  173666. JSAMPIMAGE, JDIMENSION *,
  173667. JDIMENSION,
  173668. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173669. JDIMENSION out_rows_avail)
  173670. {
  173671. my_post_ptr post = (my_post_ptr) cinfo->post;
  173672. JDIMENSION num_rows, max_rows;
  173673. /* Reposition virtual buffer if at start of strip. */
  173674. if (post->next_row == 0) {
  173675. post->buffer = (*cinfo->mem->access_virt_sarray)
  173676. ((j_common_ptr) cinfo, post->whole_image,
  173677. post->starting_row, post->strip_height, FALSE);
  173678. }
  173679. /* Determine number of rows to emit. */
  173680. num_rows = post->strip_height - post->next_row; /* available in strip */
  173681. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173682. if (num_rows > max_rows)
  173683. num_rows = max_rows;
  173684. /* We have to check bottom of image here, can't depend on upsampler. */
  173685. max_rows = cinfo->output_height - post->starting_row;
  173686. if (num_rows > max_rows)
  173687. num_rows = max_rows;
  173688. /* Quantize and emit data. */
  173689. (*cinfo->cquantize->color_quantize) (cinfo,
  173690. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173691. (int) num_rows);
  173692. *out_row_ctr += num_rows;
  173693. /* Advance if we filled the strip. */
  173694. post->next_row += num_rows;
  173695. if (post->next_row >= post->strip_height) {
  173696. post->starting_row += post->strip_height;
  173697. post->next_row = 0;
  173698. }
  173699. }
  173700. #endif /* QUANT_2PASS_SUPPORTED */
  173701. /*
  173702. * Initialize postprocessing controller.
  173703. */
  173704. GLOBAL(void)
  173705. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173706. {
  173707. my_post_ptr post;
  173708. post = (my_post_ptr)
  173709. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173710. SIZEOF(my_post_controller));
  173711. cinfo->post = (struct jpeg_d_post_controller *) post;
  173712. post->pub.start_pass = start_pass_dpost;
  173713. post->whole_image = NULL; /* flag for no virtual arrays */
  173714. post->buffer = NULL; /* flag for no strip buffer */
  173715. /* Create the quantization buffer, if needed */
  173716. if (cinfo->quantize_colors) {
  173717. /* The buffer strip height is max_v_samp_factor, which is typically
  173718. * an efficient number of rows for upsampling to return.
  173719. * (In the presence of output rescaling, we might want to be smarter?)
  173720. */
  173721. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173722. if (need_full_buffer) {
  173723. /* Two-pass color quantization: need full-image storage. */
  173724. /* We round up the number of rows to a multiple of the strip height. */
  173725. #ifdef QUANT_2PASS_SUPPORTED
  173726. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173727. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173728. cinfo->output_width * cinfo->out_color_components,
  173729. (JDIMENSION) jround_up((long) cinfo->output_height,
  173730. (long) post->strip_height),
  173731. post->strip_height);
  173732. #else
  173733. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173734. #endif /* QUANT_2PASS_SUPPORTED */
  173735. } else {
  173736. /* One-pass color quantization: just make a strip buffer. */
  173737. post->buffer = (*cinfo->mem->alloc_sarray)
  173738. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173739. cinfo->output_width * cinfo->out_color_components,
  173740. post->strip_height);
  173741. }
  173742. }
  173743. }
  173744. /*** End of inlined file: jdpostct.c ***/
  173745. #undef FIX
  173746. /*** Start of inlined file: jdsample.c ***/
  173747. #define JPEG_INTERNALS
  173748. /* Pointer to routine to upsample a single component */
  173749. typedef JMETHOD(void, upsample1_ptr,
  173750. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173751. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173752. /* Private subobject */
  173753. typedef struct {
  173754. struct jpeg_upsampler pub; /* public fields */
  173755. /* Color conversion buffer. When using separate upsampling and color
  173756. * conversion steps, this buffer holds one upsampled row group until it
  173757. * has been color converted and output.
  173758. * Note: we do not allocate any storage for component(s) which are full-size,
  173759. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173760. * simply set to point to the input data array, thereby avoiding copying.
  173761. */
  173762. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173763. /* Per-component upsampling method pointers */
  173764. upsample1_ptr methods[MAX_COMPONENTS];
  173765. int next_row_out; /* counts rows emitted from color_buf */
  173766. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173767. /* Height of an input row group for each component. */
  173768. int rowgroup_height[MAX_COMPONENTS];
  173769. /* These arrays save pixel expansion factors so that int_expand need not
  173770. * recompute them each time. They are unused for other upsampling methods.
  173771. */
  173772. UINT8 h_expand[MAX_COMPONENTS];
  173773. UINT8 v_expand[MAX_COMPONENTS];
  173774. } my_upsampler2;
  173775. typedef my_upsampler2 * my_upsample_ptr2;
  173776. /*
  173777. * Initialize for an upsampling pass.
  173778. */
  173779. METHODDEF(void)
  173780. start_pass_upsample (j_decompress_ptr cinfo)
  173781. {
  173782. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173783. /* Mark the conversion buffer empty */
  173784. upsample->next_row_out = cinfo->max_v_samp_factor;
  173785. /* Initialize total-height counter for detecting bottom of image */
  173786. upsample->rows_to_go = cinfo->output_height;
  173787. }
  173788. /*
  173789. * Control routine to do upsampling (and color conversion).
  173790. *
  173791. * In this version we upsample each component independently.
  173792. * We upsample one row group into the conversion buffer, then apply
  173793. * color conversion a row at a time.
  173794. */
  173795. METHODDEF(void)
  173796. sep_upsample (j_decompress_ptr cinfo,
  173797. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173798. JDIMENSION,
  173799. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173800. JDIMENSION out_rows_avail)
  173801. {
  173802. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173803. int ci;
  173804. jpeg_component_info * compptr;
  173805. JDIMENSION num_rows;
  173806. /* Fill the conversion buffer, if it's empty */
  173807. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173809. ci++, compptr++) {
  173810. /* Invoke per-component upsample method. Notice we pass a POINTER
  173811. * to color_buf[ci], so that fullsize_upsample can change it.
  173812. */
  173813. (*upsample->methods[ci]) (cinfo, compptr,
  173814. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173815. upsample->color_buf + ci);
  173816. }
  173817. upsample->next_row_out = 0;
  173818. }
  173819. /* Color-convert and emit rows */
  173820. /* How many we have in the buffer: */
  173821. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173822. /* Not more than the distance to the end of the image. Need this test
  173823. * in case the image height is not a multiple of max_v_samp_factor:
  173824. */
  173825. if (num_rows > upsample->rows_to_go)
  173826. num_rows = upsample->rows_to_go;
  173827. /* And not more than what the client can accept: */
  173828. out_rows_avail -= *out_row_ctr;
  173829. if (num_rows > out_rows_avail)
  173830. num_rows = out_rows_avail;
  173831. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173832. (JDIMENSION) upsample->next_row_out,
  173833. output_buf + *out_row_ctr,
  173834. (int) num_rows);
  173835. /* Adjust counts */
  173836. *out_row_ctr += num_rows;
  173837. upsample->rows_to_go -= num_rows;
  173838. upsample->next_row_out += num_rows;
  173839. /* When the buffer is emptied, declare this input row group consumed */
  173840. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173841. (*in_row_group_ctr)++;
  173842. }
  173843. /*
  173844. * These are the routines invoked by sep_upsample to upsample pixel values
  173845. * of a single component. One row group is processed per call.
  173846. */
  173847. /*
  173848. * For full-size components, we just make color_buf[ci] point at the
  173849. * input buffer, and thus avoid copying any data. Note that this is
  173850. * safe only because sep_upsample doesn't declare the input row group
  173851. * "consumed" until we are done color converting and emitting it.
  173852. */
  173853. METHODDEF(void)
  173854. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173855. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173856. {
  173857. *output_data_ptr = input_data;
  173858. }
  173859. /*
  173860. * This is a no-op version used for "uninteresting" components.
  173861. * These components will not be referenced by color conversion.
  173862. */
  173863. METHODDEF(void)
  173864. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173865. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173866. {
  173867. *output_data_ptr = NULL; /* safety check */
  173868. }
  173869. /*
  173870. * This version handles any integral sampling ratios.
  173871. * This is not used for typical JPEG files, so it need not be fast.
  173872. * Nor, for that matter, is it particularly accurate: the algorithm is
  173873. * simple replication of the input pixel onto the corresponding output
  173874. * pixels. The hi-falutin sampling literature refers to this as a
  173875. * "box filter". A box filter tends to introduce visible artifacts,
  173876. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173877. * you would be well advised to improve this code.
  173878. */
  173879. METHODDEF(void)
  173880. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173881. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173882. {
  173883. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173884. JSAMPARRAY output_data = *output_data_ptr;
  173885. register JSAMPROW inptr, outptr;
  173886. register JSAMPLE invalue;
  173887. register int h;
  173888. JSAMPROW outend;
  173889. int h_expand, v_expand;
  173890. int inrow, outrow;
  173891. h_expand = upsample->h_expand[compptr->component_index];
  173892. v_expand = upsample->v_expand[compptr->component_index];
  173893. inrow = outrow = 0;
  173894. while (outrow < cinfo->max_v_samp_factor) {
  173895. /* Generate one output row with proper horizontal expansion */
  173896. inptr = input_data[inrow];
  173897. outptr = output_data[outrow];
  173898. outend = outptr + cinfo->output_width;
  173899. while (outptr < outend) {
  173900. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173901. for (h = h_expand; h > 0; h--) {
  173902. *outptr++ = invalue;
  173903. }
  173904. }
  173905. /* Generate any additional output rows by duplicating the first one */
  173906. if (v_expand > 1) {
  173907. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173908. v_expand-1, cinfo->output_width);
  173909. }
  173910. inrow++;
  173911. outrow += v_expand;
  173912. }
  173913. }
  173914. /*
  173915. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173916. * It's still a box filter.
  173917. */
  173918. METHODDEF(void)
  173919. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173920. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173921. {
  173922. JSAMPARRAY output_data = *output_data_ptr;
  173923. register JSAMPROW inptr, outptr;
  173924. register JSAMPLE invalue;
  173925. JSAMPROW outend;
  173926. int inrow;
  173927. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173928. inptr = input_data[inrow];
  173929. outptr = output_data[inrow];
  173930. outend = outptr + cinfo->output_width;
  173931. while (outptr < outend) {
  173932. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173933. *outptr++ = invalue;
  173934. *outptr++ = invalue;
  173935. }
  173936. }
  173937. }
  173938. /*
  173939. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173940. * It's still a box filter.
  173941. */
  173942. METHODDEF(void)
  173943. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173944. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173945. {
  173946. JSAMPARRAY output_data = *output_data_ptr;
  173947. register JSAMPROW inptr, outptr;
  173948. register JSAMPLE invalue;
  173949. JSAMPROW outend;
  173950. int inrow, outrow;
  173951. inrow = outrow = 0;
  173952. while (outrow < cinfo->max_v_samp_factor) {
  173953. inptr = input_data[inrow];
  173954. outptr = output_data[outrow];
  173955. outend = outptr + cinfo->output_width;
  173956. while (outptr < outend) {
  173957. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173958. *outptr++ = invalue;
  173959. *outptr++ = invalue;
  173960. }
  173961. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173962. 1, cinfo->output_width);
  173963. inrow++;
  173964. outrow += 2;
  173965. }
  173966. }
  173967. /*
  173968. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173969. *
  173970. * The upsampling algorithm is linear interpolation between pixel centers,
  173971. * also known as a "triangle filter". This is a good compromise between
  173972. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173973. * of the way between input pixel centers.
  173974. *
  173975. * A note about the "bias" calculations: when rounding fractional values to
  173976. * integer, we do not want to always round 0.5 up to the next integer.
  173977. * If we did that, we'd introduce a noticeable bias towards larger values.
  173978. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173979. * alternate pixel locations (a simple ordered dither pattern).
  173980. */
  173981. METHODDEF(void)
  173982. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173983. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173984. {
  173985. JSAMPARRAY output_data = *output_data_ptr;
  173986. register JSAMPROW inptr, outptr;
  173987. register int invalue;
  173988. register JDIMENSION colctr;
  173989. int inrow;
  173990. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173991. inptr = input_data[inrow];
  173992. outptr = output_data[inrow];
  173993. /* Special case for first column */
  173994. invalue = GETJSAMPLE(*inptr++);
  173995. *outptr++ = (JSAMPLE) invalue;
  173996. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173997. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173998. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173999. invalue = GETJSAMPLE(*inptr++) * 3;
  174000. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174001. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174002. }
  174003. /* Special case for last column */
  174004. invalue = GETJSAMPLE(*inptr);
  174005. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174006. *outptr++ = (JSAMPLE) invalue;
  174007. }
  174008. }
  174009. /*
  174010. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174011. * Again a triangle filter; see comments for h2v1 case, above.
  174012. *
  174013. * It is OK for us to reference the adjacent input rows because we demanded
  174014. * context from the main buffer controller (see initialization code).
  174015. */
  174016. METHODDEF(void)
  174017. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174018. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174019. {
  174020. JSAMPARRAY output_data = *output_data_ptr;
  174021. register JSAMPROW inptr0, inptr1, outptr;
  174022. #if BITS_IN_JSAMPLE == 8
  174023. register int thiscolsum, lastcolsum, nextcolsum;
  174024. #else
  174025. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174026. #endif
  174027. register JDIMENSION colctr;
  174028. int inrow, outrow, v;
  174029. inrow = outrow = 0;
  174030. while (outrow < cinfo->max_v_samp_factor) {
  174031. for (v = 0; v < 2; v++) {
  174032. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174033. inptr0 = input_data[inrow];
  174034. if (v == 0) /* next nearest is row above */
  174035. inptr1 = input_data[inrow-1];
  174036. else /* next nearest is row below */
  174037. inptr1 = input_data[inrow+1];
  174038. outptr = output_data[outrow++];
  174039. /* Special case for first column */
  174040. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174041. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174042. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174043. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174044. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174045. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174046. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174047. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174048. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174049. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174050. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174051. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174052. }
  174053. /* Special case for last column */
  174054. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174055. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174056. }
  174057. inrow++;
  174058. }
  174059. }
  174060. /*
  174061. * Module initialization routine for upsampling.
  174062. */
  174063. GLOBAL(void)
  174064. jinit_upsampler (j_decompress_ptr cinfo)
  174065. {
  174066. my_upsample_ptr2 upsample;
  174067. int ci;
  174068. jpeg_component_info * compptr;
  174069. boolean need_buffer, do_fancy;
  174070. int h_in_group, v_in_group, h_out_group, v_out_group;
  174071. upsample = (my_upsample_ptr2)
  174072. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174073. SIZEOF(my_upsampler2));
  174074. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174075. upsample->pub.start_pass = start_pass_upsample;
  174076. upsample->pub.upsample = sep_upsample;
  174077. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174078. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174079. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174080. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174081. * so don't ask for it.
  174082. */
  174083. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174084. /* Verify we can handle the sampling factors, select per-component methods,
  174085. * and create storage as needed.
  174086. */
  174087. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174088. ci++, compptr++) {
  174089. /* Compute size of an "input group" after IDCT scaling. This many samples
  174090. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174091. */
  174092. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174093. cinfo->min_DCT_scaled_size;
  174094. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174095. cinfo->min_DCT_scaled_size;
  174096. h_out_group = cinfo->max_h_samp_factor;
  174097. v_out_group = cinfo->max_v_samp_factor;
  174098. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174099. need_buffer = TRUE;
  174100. if (! compptr->component_needed) {
  174101. /* Don't bother to upsample an uninteresting component. */
  174102. upsample->methods[ci] = noop_upsample;
  174103. need_buffer = FALSE;
  174104. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174105. /* Fullsize components can be processed without any work. */
  174106. upsample->methods[ci] = fullsize_upsample;
  174107. need_buffer = FALSE;
  174108. } else if (h_in_group * 2 == h_out_group &&
  174109. v_in_group == v_out_group) {
  174110. /* Special cases for 2h1v upsampling */
  174111. if (do_fancy && compptr->downsampled_width > 2)
  174112. upsample->methods[ci] = h2v1_fancy_upsample;
  174113. else
  174114. upsample->methods[ci] = h2v1_upsample;
  174115. } else if (h_in_group * 2 == h_out_group &&
  174116. v_in_group * 2 == v_out_group) {
  174117. /* Special cases for 2h2v upsampling */
  174118. if (do_fancy && compptr->downsampled_width > 2) {
  174119. upsample->methods[ci] = h2v2_fancy_upsample;
  174120. upsample->pub.need_context_rows = TRUE;
  174121. } else
  174122. upsample->methods[ci] = h2v2_upsample;
  174123. } else if ((h_out_group % h_in_group) == 0 &&
  174124. (v_out_group % v_in_group) == 0) {
  174125. /* Generic integral-factors upsampling method */
  174126. upsample->methods[ci] = int_upsample;
  174127. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174128. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174129. } else
  174130. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174131. if (need_buffer) {
  174132. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174133. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174134. (JDIMENSION) jround_up((long) cinfo->output_width,
  174135. (long) cinfo->max_h_samp_factor),
  174136. (JDIMENSION) cinfo->max_v_samp_factor);
  174137. }
  174138. }
  174139. }
  174140. /*** End of inlined file: jdsample.c ***/
  174141. /*** Start of inlined file: jdtrans.c ***/
  174142. #define JPEG_INTERNALS
  174143. /* Forward declarations */
  174144. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174145. /*
  174146. * Read the coefficient arrays from a JPEG file.
  174147. * jpeg_read_header must be completed before calling this.
  174148. *
  174149. * The entire image is read into a set of virtual coefficient-block arrays,
  174150. * one per component. The return value is a pointer to the array of
  174151. * virtual-array descriptors. These can be manipulated directly via the
  174152. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174153. * To release the memory occupied by the virtual arrays, call
  174154. * jpeg_finish_decompress() when done with the data.
  174155. *
  174156. * An alternative usage is to simply obtain access to the coefficient arrays
  174157. * during a buffered-image-mode decompression operation. This is allowed
  174158. * after any jpeg_finish_output() call. The arrays can be accessed until
  174159. * jpeg_finish_decompress() is called. (Note that any call to the library
  174160. * may reposition the arrays, so don't rely on access_virt_barray() results
  174161. * to stay valid across library calls.)
  174162. *
  174163. * Returns NULL if suspended. This case need be checked only if
  174164. * a suspending data source is used.
  174165. */
  174166. GLOBAL(jvirt_barray_ptr *)
  174167. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174168. {
  174169. if (cinfo->global_state == DSTATE_READY) {
  174170. /* First call: initialize active modules */
  174171. transdecode_master_selection(cinfo);
  174172. cinfo->global_state = DSTATE_RDCOEFS;
  174173. }
  174174. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174175. /* Absorb whole file into the coef buffer */
  174176. for (;;) {
  174177. int retcode;
  174178. /* Call progress monitor hook if present */
  174179. if (cinfo->progress != NULL)
  174180. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174181. /* Absorb some more input */
  174182. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174183. if (retcode == JPEG_SUSPENDED)
  174184. return NULL;
  174185. if (retcode == JPEG_REACHED_EOI)
  174186. break;
  174187. /* Advance progress counter if appropriate */
  174188. if (cinfo->progress != NULL &&
  174189. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174190. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174191. /* startup underestimated number of scans; ratchet up one scan */
  174192. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174193. }
  174194. }
  174195. }
  174196. /* Set state so that jpeg_finish_decompress does the right thing */
  174197. cinfo->global_state = DSTATE_STOPPING;
  174198. }
  174199. /* At this point we should be in state DSTATE_STOPPING if being used
  174200. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174201. * to the coefficients during a full buffered-image-mode decompression.
  174202. */
  174203. if ((cinfo->global_state == DSTATE_STOPPING ||
  174204. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174205. return cinfo->coef->coef_arrays;
  174206. }
  174207. /* Oops, improper usage */
  174208. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174209. return NULL; /* keep compiler happy */
  174210. }
  174211. /*
  174212. * Master selection of decompression modules for transcoding.
  174213. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174214. */
  174215. LOCAL(void)
  174216. transdecode_master_selection (j_decompress_ptr cinfo)
  174217. {
  174218. /* This is effectively a buffered-image operation. */
  174219. cinfo->buffered_image = TRUE;
  174220. /* Entropy decoding: either Huffman or arithmetic coding. */
  174221. if (cinfo->arith_code) {
  174222. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174223. } else {
  174224. if (cinfo->progressive_mode) {
  174225. #ifdef D_PROGRESSIVE_SUPPORTED
  174226. jinit_phuff_decoder(cinfo);
  174227. #else
  174228. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174229. #endif
  174230. } else
  174231. jinit_huff_decoder(cinfo);
  174232. }
  174233. /* Always get a full-image coefficient buffer. */
  174234. jinit_d_coef_controller(cinfo, TRUE);
  174235. /* We can now tell the memory manager to allocate virtual arrays. */
  174236. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174237. /* Initialize input side of decompressor to consume first scan. */
  174238. (*cinfo->inputctl->start_input_pass) (cinfo);
  174239. /* Initialize progress monitoring. */
  174240. if (cinfo->progress != NULL) {
  174241. int nscans;
  174242. /* Estimate number of scans to set pass_limit. */
  174243. if (cinfo->progressive_mode) {
  174244. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174245. nscans = 2 + 3 * cinfo->num_components;
  174246. } else if (cinfo->inputctl->has_multiple_scans) {
  174247. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174248. nscans = cinfo->num_components;
  174249. } else {
  174250. nscans = 1;
  174251. }
  174252. cinfo->progress->pass_counter = 0L;
  174253. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174254. cinfo->progress->completed_passes = 0;
  174255. cinfo->progress->total_passes = 1;
  174256. }
  174257. }
  174258. /*** End of inlined file: jdtrans.c ***/
  174259. /*** Start of inlined file: jfdctflt.c ***/
  174260. #define JPEG_INTERNALS
  174261. #ifdef DCT_FLOAT_SUPPORTED
  174262. /*
  174263. * This module is specialized to the case DCTSIZE = 8.
  174264. */
  174265. #if DCTSIZE != 8
  174266. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174267. #endif
  174268. /*
  174269. * Perform the forward DCT on one block of samples.
  174270. */
  174271. GLOBAL(void)
  174272. jpeg_fdct_float (FAST_FLOAT * data)
  174273. {
  174274. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174275. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174276. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174277. FAST_FLOAT *dataptr;
  174278. int ctr;
  174279. /* Pass 1: process rows. */
  174280. dataptr = data;
  174281. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174282. tmp0 = dataptr[0] + dataptr[7];
  174283. tmp7 = dataptr[0] - dataptr[7];
  174284. tmp1 = dataptr[1] + dataptr[6];
  174285. tmp6 = dataptr[1] - dataptr[6];
  174286. tmp2 = dataptr[2] + dataptr[5];
  174287. tmp5 = dataptr[2] - dataptr[5];
  174288. tmp3 = dataptr[3] + dataptr[4];
  174289. tmp4 = dataptr[3] - dataptr[4];
  174290. /* Even part */
  174291. tmp10 = tmp0 + tmp3; /* phase 2 */
  174292. tmp13 = tmp0 - tmp3;
  174293. tmp11 = tmp1 + tmp2;
  174294. tmp12 = tmp1 - tmp2;
  174295. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174296. dataptr[4] = tmp10 - tmp11;
  174297. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174298. dataptr[2] = tmp13 + z1; /* phase 5 */
  174299. dataptr[6] = tmp13 - z1;
  174300. /* Odd part */
  174301. tmp10 = tmp4 + tmp5; /* phase 2 */
  174302. tmp11 = tmp5 + tmp6;
  174303. tmp12 = tmp6 + tmp7;
  174304. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174305. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174306. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174307. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174308. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174309. z11 = tmp7 + z3; /* phase 5 */
  174310. z13 = tmp7 - z3;
  174311. dataptr[5] = z13 + z2; /* phase 6 */
  174312. dataptr[3] = z13 - z2;
  174313. dataptr[1] = z11 + z4;
  174314. dataptr[7] = z11 - z4;
  174315. dataptr += DCTSIZE; /* advance pointer to next row */
  174316. }
  174317. /* Pass 2: process columns. */
  174318. dataptr = data;
  174319. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174320. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174321. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174322. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174323. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174324. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174325. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174326. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174327. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174328. /* Even part */
  174329. tmp10 = tmp0 + tmp3; /* phase 2 */
  174330. tmp13 = tmp0 - tmp3;
  174331. tmp11 = tmp1 + tmp2;
  174332. tmp12 = tmp1 - tmp2;
  174333. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174334. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174335. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174336. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174337. dataptr[DCTSIZE*6] = tmp13 - z1;
  174338. /* Odd part */
  174339. tmp10 = tmp4 + tmp5; /* phase 2 */
  174340. tmp11 = tmp5 + tmp6;
  174341. tmp12 = tmp6 + tmp7;
  174342. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174343. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174344. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174345. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174346. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174347. z11 = tmp7 + z3; /* phase 5 */
  174348. z13 = tmp7 - z3;
  174349. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174350. dataptr[DCTSIZE*3] = z13 - z2;
  174351. dataptr[DCTSIZE*1] = z11 + z4;
  174352. dataptr[DCTSIZE*7] = z11 - z4;
  174353. dataptr++; /* advance pointer to next column */
  174354. }
  174355. }
  174356. #endif /* DCT_FLOAT_SUPPORTED */
  174357. /*** End of inlined file: jfdctflt.c ***/
  174358. /*** Start of inlined file: jfdctint.c ***/
  174359. #define JPEG_INTERNALS
  174360. #ifdef DCT_ISLOW_SUPPORTED
  174361. /*
  174362. * This module is specialized to the case DCTSIZE = 8.
  174363. */
  174364. #if DCTSIZE != 8
  174365. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174366. #endif
  174367. /*
  174368. * The poop on this scaling stuff is as follows:
  174369. *
  174370. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174371. * larger than the true DCT outputs. The final outputs are therefore
  174372. * a factor of N larger than desired; since N=8 this can be cured by
  174373. * a simple right shift at the end of the algorithm. The advantage of
  174374. * this arrangement is that we save two multiplications per 1-D DCT,
  174375. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174376. * In the IJG code, this factor of 8 is removed by the quantization step
  174377. * (in jcdctmgr.c), NOT in this module.
  174378. *
  174379. * We have to do addition and subtraction of the integer inputs, which
  174380. * is no problem, and multiplication by fractional constants, which is
  174381. * a problem to do in integer arithmetic. We multiply all the constants
  174382. * by CONST_SCALE and convert them to integer constants (thus retaining
  174383. * CONST_BITS bits of precision in the constants). After doing a
  174384. * multiplication we have to divide the product by CONST_SCALE, with proper
  174385. * rounding, to produce the correct output. This division can be done
  174386. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174387. * as long as possible so that partial sums can be added together with
  174388. * full fractional precision.
  174389. *
  174390. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174391. * they are represented to better-than-integral precision. These outputs
  174392. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174393. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174394. * array is INT32 anyway.)
  174395. *
  174396. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174397. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174398. * shows that the values given below are the most effective.
  174399. */
  174400. #if BITS_IN_JSAMPLE == 8
  174401. #define CONST_BITS 13
  174402. #define PASS1_BITS 2
  174403. #else
  174404. #define CONST_BITS 13
  174405. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174406. #endif
  174407. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174408. * causing a lot of useless floating-point operations at run time.
  174409. * To get around this we use the following pre-calculated constants.
  174410. * If you change CONST_BITS you may want to add appropriate values.
  174411. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174412. */
  174413. #if CONST_BITS == 13
  174414. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174415. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174416. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174417. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174418. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174419. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174420. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174421. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174422. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174423. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174424. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174425. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174426. #else
  174427. #define FIX_0_298631336 FIX(0.298631336)
  174428. #define FIX_0_390180644 FIX(0.390180644)
  174429. #define FIX_0_541196100 FIX(0.541196100)
  174430. #define FIX_0_765366865 FIX(0.765366865)
  174431. #define FIX_0_899976223 FIX(0.899976223)
  174432. #define FIX_1_175875602 FIX(1.175875602)
  174433. #define FIX_1_501321110 FIX(1.501321110)
  174434. #define FIX_1_847759065 FIX(1.847759065)
  174435. #define FIX_1_961570560 FIX(1.961570560)
  174436. #define FIX_2_053119869 FIX(2.053119869)
  174437. #define FIX_2_562915447 FIX(2.562915447)
  174438. #define FIX_3_072711026 FIX(3.072711026)
  174439. #endif
  174440. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174441. * For 8-bit samples with the recommended scaling, all the variable
  174442. * and constant values involved are no more than 16 bits wide, so a
  174443. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174444. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174445. */
  174446. #if BITS_IN_JSAMPLE == 8
  174447. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174448. #else
  174449. #define MULTIPLY(var,const) ((var) * (const))
  174450. #endif
  174451. /*
  174452. * Perform the forward DCT on one block of samples.
  174453. */
  174454. GLOBAL(void)
  174455. jpeg_fdct_islow (DCTELEM * data)
  174456. {
  174457. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174458. INT32 tmp10, tmp11, tmp12, tmp13;
  174459. INT32 z1, z2, z3, z4, z5;
  174460. DCTELEM *dataptr;
  174461. int ctr;
  174462. SHIFT_TEMPS
  174463. /* Pass 1: process rows. */
  174464. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174465. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174466. dataptr = data;
  174467. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174468. tmp0 = dataptr[0] + dataptr[7];
  174469. tmp7 = dataptr[0] - dataptr[7];
  174470. tmp1 = dataptr[1] + dataptr[6];
  174471. tmp6 = dataptr[1] - dataptr[6];
  174472. tmp2 = dataptr[2] + dataptr[5];
  174473. tmp5 = dataptr[2] - dataptr[5];
  174474. tmp3 = dataptr[3] + dataptr[4];
  174475. tmp4 = dataptr[3] - dataptr[4];
  174476. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174477. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174478. */
  174479. tmp10 = tmp0 + tmp3;
  174480. tmp13 = tmp0 - tmp3;
  174481. tmp11 = tmp1 + tmp2;
  174482. tmp12 = tmp1 - tmp2;
  174483. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174484. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174485. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174486. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174487. CONST_BITS-PASS1_BITS);
  174488. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174489. CONST_BITS-PASS1_BITS);
  174490. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174491. * cK represents cos(K*pi/16).
  174492. * i0..i3 in the paper are tmp4..tmp7 here.
  174493. */
  174494. z1 = tmp4 + tmp7;
  174495. z2 = tmp5 + tmp6;
  174496. z3 = tmp4 + tmp6;
  174497. z4 = tmp5 + tmp7;
  174498. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174499. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174500. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174501. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174502. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174503. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174504. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174505. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174506. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174507. z3 += z5;
  174508. z4 += z5;
  174509. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174510. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174511. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174512. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174513. dataptr += DCTSIZE; /* advance pointer to next row */
  174514. }
  174515. /* Pass 2: process columns.
  174516. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174517. * by an overall factor of 8.
  174518. */
  174519. dataptr = data;
  174520. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174521. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174522. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174523. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174524. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174525. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174526. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174527. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174528. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174529. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174530. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174531. */
  174532. tmp10 = tmp0 + tmp3;
  174533. tmp13 = tmp0 - tmp3;
  174534. tmp11 = tmp1 + tmp2;
  174535. tmp12 = tmp1 - tmp2;
  174536. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174537. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174538. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174539. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174540. CONST_BITS+PASS1_BITS);
  174541. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174542. CONST_BITS+PASS1_BITS);
  174543. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174544. * cK represents cos(K*pi/16).
  174545. * i0..i3 in the paper are tmp4..tmp7 here.
  174546. */
  174547. z1 = tmp4 + tmp7;
  174548. z2 = tmp5 + tmp6;
  174549. z3 = tmp4 + tmp6;
  174550. z4 = tmp5 + tmp7;
  174551. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174552. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174553. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174554. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174555. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174556. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174557. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174558. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174559. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174560. z3 += z5;
  174561. z4 += z5;
  174562. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174563. CONST_BITS+PASS1_BITS);
  174564. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174565. CONST_BITS+PASS1_BITS);
  174566. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174567. CONST_BITS+PASS1_BITS);
  174568. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174569. CONST_BITS+PASS1_BITS);
  174570. dataptr++; /* advance pointer to next column */
  174571. }
  174572. }
  174573. #endif /* DCT_ISLOW_SUPPORTED */
  174574. /*** End of inlined file: jfdctint.c ***/
  174575. #undef CONST_BITS
  174576. #undef MULTIPLY
  174577. #undef FIX_0_541196100
  174578. /*** Start of inlined file: jfdctfst.c ***/
  174579. #define JPEG_INTERNALS
  174580. #ifdef DCT_IFAST_SUPPORTED
  174581. /*
  174582. * This module is specialized to the case DCTSIZE = 8.
  174583. */
  174584. #if DCTSIZE != 8
  174585. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174586. #endif
  174587. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174588. * see jfdctint.c for more details. However, we choose to descale
  174589. * (right shift) multiplication products as soon as they are formed,
  174590. * rather than carrying additional fractional bits into subsequent additions.
  174591. * This compromises accuracy slightly, but it lets us save a few shifts.
  174592. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174593. * everywhere except in the multiplications proper; this saves a good deal
  174594. * of work on 16-bit-int machines.
  174595. *
  174596. * Again to save a few shifts, the intermediate results between pass 1 and
  174597. * pass 2 are not upscaled, but are represented only to integral precision.
  174598. *
  174599. * A final compromise is to represent the multiplicative constants to only
  174600. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174601. * machines, and may also reduce the cost of multiplication (since there
  174602. * are fewer one-bits in the constants).
  174603. */
  174604. #define CONST_BITS 8
  174605. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174606. * causing a lot of useless floating-point operations at run time.
  174607. * To get around this we use the following pre-calculated constants.
  174608. * If you change CONST_BITS you may want to add appropriate values.
  174609. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174610. */
  174611. #if CONST_BITS == 8
  174612. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174613. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174614. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174615. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174616. #else
  174617. #define FIX_0_382683433 FIX(0.382683433)
  174618. #define FIX_0_541196100 FIX(0.541196100)
  174619. #define FIX_0_707106781 FIX(0.707106781)
  174620. #define FIX_1_306562965 FIX(1.306562965)
  174621. #endif
  174622. /* We can gain a little more speed, with a further compromise in accuracy,
  174623. * by omitting the addition in a descaling shift. This yields an incorrectly
  174624. * rounded result half the time...
  174625. */
  174626. #ifndef USE_ACCURATE_ROUNDING
  174627. #undef DESCALE
  174628. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174629. #endif
  174630. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174631. * descale to yield a DCTELEM result.
  174632. */
  174633. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174634. /*
  174635. * Perform the forward DCT on one block of samples.
  174636. */
  174637. GLOBAL(void)
  174638. jpeg_fdct_ifast (DCTELEM * data)
  174639. {
  174640. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174641. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174642. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174643. DCTELEM *dataptr;
  174644. int ctr;
  174645. SHIFT_TEMPS
  174646. /* Pass 1: process rows. */
  174647. dataptr = data;
  174648. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174649. tmp0 = dataptr[0] + dataptr[7];
  174650. tmp7 = dataptr[0] - dataptr[7];
  174651. tmp1 = dataptr[1] + dataptr[6];
  174652. tmp6 = dataptr[1] - dataptr[6];
  174653. tmp2 = dataptr[2] + dataptr[5];
  174654. tmp5 = dataptr[2] - dataptr[5];
  174655. tmp3 = dataptr[3] + dataptr[4];
  174656. tmp4 = dataptr[3] - dataptr[4];
  174657. /* Even part */
  174658. tmp10 = tmp0 + tmp3; /* phase 2 */
  174659. tmp13 = tmp0 - tmp3;
  174660. tmp11 = tmp1 + tmp2;
  174661. tmp12 = tmp1 - tmp2;
  174662. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174663. dataptr[4] = tmp10 - tmp11;
  174664. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174665. dataptr[2] = tmp13 + z1; /* phase 5 */
  174666. dataptr[6] = tmp13 - z1;
  174667. /* Odd part */
  174668. tmp10 = tmp4 + tmp5; /* phase 2 */
  174669. tmp11 = tmp5 + tmp6;
  174670. tmp12 = tmp6 + tmp7;
  174671. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174672. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174673. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174674. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174675. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174676. z11 = tmp7 + z3; /* phase 5 */
  174677. z13 = tmp7 - z3;
  174678. dataptr[5] = z13 + z2; /* phase 6 */
  174679. dataptr[3] = z13 - z2;
  174680. dataptr[1] = z11 + z4;
  174681. dataptr[7] = z11 - z4;
  174682. dataptr += DCTSIZE; /* advance pointer to next row */
  174683. }
  174684. /* Pass 2: process columns. */
  174685. dataptr = data;
  174686. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174687. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174688. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174689. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174690. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174691. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174692. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174693. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174694. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174695. /* Even part */
  174696. tmp10 = tmp0 + tmp3; /* phase 2 */
  174697. tmp13 = tmp0 - tmp3;
  174698. tmp11 = tmp1 + tmp2;
  174699. tmp12 = tmp1 - tmp2;
  174700. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174701. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174702. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174703. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174704. dataptr[DCTSIZE*6] = tmp13 - z1;
  174705. /* Odd part */
  174706. tmp10 = tmp4 + tmp5; /* phase 2 */
  174707. tmp11 = tmp5 + tmp6;
  174708. tmp12 = tmp6 + tmp7;
  174709. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174710. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174711. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174712. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174713. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174714. z11 = tmp7 + z3; /* phase 5 */
  174715. z13 = tmp7 - z3;
  174716. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174717. dataptr[DCTSIZE*3] = z13 - z2;
  174718. dataptr[DCTSIZE*1] = z11 + z4;
  174719. dataptr[DCTSIZE*7] = z11 - z4;
  174720. dataptr++; /* advance pointer to next column */
  174721. }
  174722. }
  174723. #endif /* DCT_IFAST_SUPPORTED */
  174724. /*** End of inlined file: jfdctfst.c ***/
  174725. #undef FIX_0_541196100
  174726. /*** Start of inlined file: jidctflt.c ***/
  174727. #define JPEG_INTERNALS
  174728. #ifdef DCT_FLOAT_SUPPORTED
  174729. /*
  174730. * This module is specialized to the case DCTSIZE = 8.
  174731. */
  174732. #if DCTSIZE != 8
  174733. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174734. #endif
  174735. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174736. * entry; produce a float result.
  174737. */
  174738. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174739. /*
  174740. * Perform dequantization and inverse DCT on one block of coefficients.
  174741. */
  174742. GLOBAL(void)
  174743. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174744. JCOEFPTR coef_block,
  174745. JSAMPARRAY output_buf, JDIMENSION output_col)
  174746. {
  174747. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174748. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174749. FAST_FLOAT z5, z10, z11, z12, z13;
  174750. JCOEFPTR inptr;
  174751. FLOAT_MULT_TYPE * quantptr;
  174752. FAST_FLOAT * wsptr;
  174753. JSAMPROW outptr;
  174754. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174755. int ctr;
  174756. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174757. SHIFT_TEMPS
  174758. /* Pass 1: process columns from input, store into work array. */
  174759. inptr = coef_block;
  174760. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174761. wsptr = workspace;
  174762. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174763. /* Due to quantization, we will usually find that many of the input
  174764. * coefficients are zero, especially the AC terms. We can exploit this
  174765. * by short-circuiting the IDCT calculation for any column in which all
  174766. * the AC terms are zero. In that case each output is equal to the
  174767. * DC coefficient (with scale factor as needed).
  174768. * With typical images and quantization tables, half or more of the
  174769. * column DCT calculations can be simplified this way.
  174770. */
  174771. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174772. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174773. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174774. inptr[DCTSIZE*7] == 0) {
  174775. /* AC terms all zero */
  174776. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174777. wsptr[DCTSIZE*0] = dcval;
  174778. wsptr[DCTSIZE*1] = dcval;
  174779. wsptr[DCTSIZE*2] = dcval;
  174780. wsptr[DCTSIZE*3] = dcval;
  174781. wsptr[DCTSIZE*4] = dcval;
  174782. wsptr[DCTSIZE*5] = dcval;
  174783. wsptr[DCTSIZE*6] = dcval;
  174784. wsptr[DCTSIZE*7] = dcval;
  174785. inptr++; /* advance pointers to next column */
  174786. quantptr++;
  174787. wsptr++;
  174788. continue;
  174789. }
  174790. /* Even part */
  174791. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174792. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174793. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174794. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174795. tmp10 = tmp0 + tmp2; /* phase 3 */
  174796. tmp11 = tmp0 - tmp2;
  174797. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174798. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174799. tmp0 = tmp10 + tmp13; /* phase 2 */
  174800. tmp3 = tmp10 - tmp13;
  174801. tmp1 = tmp11 + tmp12;
  174802. tmp2 = tmp11 - tmp12;
  174803. /* Odd part */
  174804. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174805. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174806. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174807. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174808. z13 = tmp6 + tmp5; /* phase 6 */
  174809. z10 = tmp6 - tmp5;
  174810. z11 = tmp4 + tmp7;
  174811. z12 = tmp4 - tmp7;
  174812. tmp7 = z11 + z13; /* phase 5 */
  174813. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174814. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174815. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174816. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174817. tmp6 = tmp12 - tmp7; /* phase 2 */
  174818. tmp5 = tmp11 - tmp6;
  174819. tmp4 = tmp10 + tmp5;
  174820. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174821. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174822. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174823. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174824. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174825. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174826. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174827. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174828. inptr++; /* advance pointers to next column */
  174829. quantptr++;
  174830. wsptr++;
  174831. }
  174832. /* Pass 2: process rows from work array, store into output array. */
  174833. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174834. wsptr = workspace;
  174835. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174836. outptr = output_buf[ctr] + output_col;
  174837. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174838. * However, the column calculation has created many nonzero AC terms, so
  174839. * the simplification applies less often (typically 5% to 10% of the time).
  174840. * And testing floats for zero is relatively expensive, so we don't bother.
  174841. */
  174842. /* Even part */
  174843. tmp10 = wsptr[0] + wsptr[4];
  174844. tmp11 = wsptr[0] - wsptr[4];
  174845. tmp13 = wsptr[2] + wsptr[6];
  174846. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174847. tmp0 = tmp10 + tmp13;
  174848. tmp3 = tmp10 - tmp13;
  174849. tmp1 = tmp11 + tmp12;
  174850. tmp2 = tmp11 - tmp12;
  174851. /* Odd part */
  174852. z13 = wsptr[5] + wsptr[3];
  174853. z10 = wsptr[5] - wsptr[3];
  174854. z11 = wsptr[1] + wsptr[7];
  174855. z12 = wsptr[1] - wsptr[7];
  174856. tmp7 = z11 + z13;
  174857. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174858. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174859. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174860. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174861. tmp6 = tmp12 - tmp7;
  174862. tmp5 = tmp11 - tmp6;
  174863. tmp4 = tmp10 + tmp5;
  174864. /* Final output stage: scale down by a factor of 8 and range-limit */
  174865. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174866. & RANGE_MASK];
  174867. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174868. & RANGE_MASK];
  174869. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174870. & RANGE_MASK];
  174871. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174872. & RANGE_MASK];
  174873. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174874. & RANGE_MASK];
  174875. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174876. & RANGE_MASK];
  174877. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174878. & RANGE_MASK];
  174879. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174880. & RANGE_MASK];
  174881. wsptr += DCTSIZE; /* advance pointer to next row */
  174882. }
  174883. }
  174884. #endif /* DCT_FLOAT_SUPPORTED */
  174885. /*** End of inlined file: jidctflt.c ***/
  174886. #undef CONST_BITS
  174887. #undef FIX_1_847759065
  174888. #undef MULTIPLY
  174889. #undef DEQUANTIZE
  174890. #undef DESCALE
  174891. /*** Start of inlined file: jidctfst.c ***/
  174892. #define JPEG_INTERNALS
  174893. #ifdef DCT_IFAST_SUPPORTED
  174894. /*
  174895. * This module is specialized to the case DCTSIZE = 8.
  174896. */
  174897. #if DCTSIZE != 8
  174898. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174899. #endif
  174900. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174901. * see jidctint.c for more details. However, we choose to descale
  174902. * (right shift) multiplication products as soon as they are formed,
  174903. * rather than carrying additional fractional bits into subsequent additions.
  174904. * This compromises accuracy slightly, but it lets us save a few shifts.
  174905. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174906. * everywhere except in the multiplications proper; this saves a good deal
  174907. * of work on 16-bit-int machines.
  174908. *
  174909. * The dequantized coefficients are not integers because the AA&N scaling
  174910. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174911. * so that the first and second IDCT rounds have the same input scaling.
  174912. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174913. * avoid a descaling shift; this compromises accuracy rather drastically
  174914. * for small quantization table entries, but it saves a lot of shifts.
  174915. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174916. * so we use a much larger scaling factor to preserve accuracy.
  174917. *
  174918. * A final compromise is to represent the multiplicative constants to only
  174919. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174920. * machines, and may also reduce the cost of multiplication (since there
  174921. * are fewer one-bits in the constants).
  174922. */
  174923. #if BITS_IN_JSAMPLE == 8
  174924. #define CONST_BITS 8
  174925. #define PASS1_BITS 2
  174926. #else
  174927. #define CONST_BITS 8
  174928. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174929. #endif
  174930. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174931. * causing a lot of useless floating-point operations at run time.
  174932. * To get around this we use the following pre-calculated constants.
  174933. * If you change CONST_BITS you may want to add appropriate values.
  174934. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174935. */
  174936. #if CONST_BITS == 8
  174937. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174938. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174939. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174940. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174941. #else
  174942. #define FIX_1_082392200 FIX(1.082392200)
  174943. #define FIX_1_414213562 FIX(1.414213562)
  174944. #define FIX_1_847759065 FIX(1.847759065)
  174945. #define FIX_2_613125930 FIX(2.613125930)
  174946. #endif
  174947. /* We can gain a little more speed, with a further compromise in accuracy,
  174948. * by omitting the addition in a descaling shift. This yields an incorrectly
  174949. * rounded result half the time...
  174950. */
  174951. #ifndef USE_ACCURATE_ROUNDING
  174952. #undef DESCALE
  174953. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174954. #endif
  174955. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174956. * descale to yield a DCTELEM result.
  174957. */
  174958. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174959. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174960. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174961. * multiplication will do. For 12-bit data, the multiplier table is
  174962. * declared INT32, so a 32-bit multiply will be used.
  174963. */
  174964. #if BITS_IN_JSAMPLE == 8
  174965. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174966. #else
  174967. #define DEQUANTIZE(coef,quantval) \
  174968. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174969. #endif
  174970. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174971. * We assume that int right shift is unsigned if INT32 right shift is.
  174972. */
  174973. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174974. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174975. #if BITS_IN_JSAMPLE == 8
  174976. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174977. #else
  174978. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174979. #endif
  174980. #define IRIGHT_SHIFT(x,shft) \
  174981. ((ishift_temp = (x)) < 0 ? \
  174982. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174983. (ishift_temp >> (shft)))
  174984. #else
  174985. #define ISHIFT_TEMPS
  174986. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174987. #endif
  174988. #ifdef USE_ACCURATE_ROUNDING
  174989. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174990. #else
  174991. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174992. #endif
  174993. /*
  174994. * Perform dequantization and inverse DCT on one block of coefficients.
  174995. */
  174996. GLOBAL(void)
  174997. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174998. JCOEFPTR coef_block,
  174999. JSAMPARRAY output_buf, JDIMENSION output_col)
  175000. {
  175001. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175002. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175003. DCTELEM z5, z10, z11, z12, z13;
  175004. JCOEFPTR inptr;
  175005. IFAST_MULT_TYPE * quantptr;
  175006. int * wsptr;
  175007. JSAMPROW outptr;
  175008. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175009. int ctr;
  175010. int workspace[DCTSIZE2]; /* buffers data between passes */
  175011. SHIFT_TEMPS /* for DESCALE */
  175012. ISHIFT_TEMPS /* for IDESCALE */
  175013. /* Pass 1: process columns from input, store into work array. */
  175014. inptr = coef_block;
  175015. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175016. wsptr = workspace;
  175017. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175018. /* Due to quantization, we will usually find that many of the input
  175019. * coefficients are zero, especially the AC terms. We can exploit this
  175020. * by short-circuiting the IDCT calculation for any column in which all
  175021. * the AC terms are zero. In that case each output is equal to the
  175022. * DC coefficient (with scale factor as needed).
  175023. * With typical images and quantization tables, half or more of the
  175024. * column DCT calculations can be simplified this way.
  175025. */
  175026. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175027. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175028. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175029. inptr[DCTSIZE*7] == 0) {
  175030. /* AC terms all zero */
  175031. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175032. wsptr[DCTSIZE*0] = dcval;
  175033. wsptr[DCTSIZE*1] = dcval;
  175034. wsptr[DCTSIZE*2] = dcval;
  175035. wsptr[DCTSIZE*3] = dcval;
  175036. wsptr[DCTSIZE*4] = dcval;
  175037. wsptr[DCTSIZE*5] = dcval;
  175038. wsptr[DCTSIZE*6] = dcval;
  175039. wsptr[DCTSIZE*7] = dcval;
  175040. inptr++; /* advance pointers to next column */
  175041. quantptr++;
  175042. wsptr++;
  175043. continue;
  175044. }
  175045. /* Even part */
  175046. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175047. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175048. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175049. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175050. tmp10 = tmp0 + tmp2; /* phase 3 */
  175051. tmp11 = tmp0 - tmp2;
  175052. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175053. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175054. tmp0 = tmp10 + tmp13; /* phase 2 */
  175055. tmp3 = tmp10 - tmp13;
  175056. tmp1 = tmp11 + tmp12;
  175057. tmp2 = tmp11 - tmp12;
  175058. /* Odd part */
  175059. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175060. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175061. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175062. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175063. z13 = tmp6 + tmp5; /* phase 6 */
  175064. z10 = tmp6 - tmp5;
  175065. z11 = tmp4 + tmp7;
  175066. z12 = tmp4 - tmp7;
  175067. tmp7 = z11 + z13; /* phase 5 */
  175068. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175069. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175070. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175071. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175072. tmp6 = tmp12 - tmp7; /* phase 2 */
  175073. tmp5 = tmp11 - tmp6;
  175074. tmp4 = tmp10 + tmp5;
  175075. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175076. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175077. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175078. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175079. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175080. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175081. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175082. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175083. inptr++; /* advance pointers to next column */
  175084. quantptr++;
  175085. wsptr++;
  175086. }
  175087. /* Pass 2: process rows from work array, store into output array. */
  175088. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175089. /* and also undo the PASS1_BITS scaling. */
  175090. wsptr = workspace;
  175091. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175092. outptr = output_buf[ctr] + output_col;
  175093. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175094. * However, the column calculation has created many nonzero AC terms, so
  175095. * the simplification applies less often (typically 5% to 10% of the time).
  175096. * On machines with very fast multiplication, it's possible that the
  175097. * test takes more time than it's worth. In that case this section
  175098. * may be commented out.
  175099. */
  175100. #ifndef NO_ZERO_ROW_TEST
  175101. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175102. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175103. /* AC terms all zero */
  175104. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175105. & RANGE_MASK];
  175106. outptr[0] = dcval;
  175107. outptr[1] = dcval;
  175108. outptr[2] = dcval;
  175109. outptr[3] = dcval;
  175110. outptr[4] = dcval;
  175111. outptr[5] = dcval;
  175112. outptr[6] = dcval;
  175113. outptr[7] = dcval;
  175114. wsptr += DCTSIZE; /* advance pointer to next row */
  175115. continue;
  175116. }
  175117. #endif
  175118. /* Even part */
  175119. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175120. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175121. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175122. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175123. - tmp13;
  175124. tmp0 = tmp10 + tmp13;
  175125. tmp3 = tmp10 - tmp13;
  175126. tmp1 = tmp11 + tmp12;
  175127. tmp2 = tmp11 - tmp12;
  175128. /* Odd part */
  175129. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175130. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175131. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175132. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175133. tmp7 = z11 + z13; /* phase 5 */
  175134. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175135. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175136. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175137. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175138. tmp6 = tmp12 - tmp7; /* phase 2 */
  175139. tmp5 = tmp11 - tmp6;
  175140. tmp4 = tmp10 + tmp5;
  175141. /* Final output stage: scale down by a factor of 8 and range-limit */
  175142. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175143. & RANGE_MASK];
  175144. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175145. & RANGE_MASK];
  175146. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175147. & RANGE_MASK];
  175148. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175149. & RANGE_MASK];
  175150. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175151. & RANGE_MASK];
  175152. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175153. & RANGE_MASK];
  175154. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175155. & RANGE_MASK];
  175156. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175157. & RANGE_MASK];
  175158. wsptr += DCTSIZE; /* advance pointer to next row */
  175159. }
  175160. }
  175161. #endif /* DCT_IFAST_SUPPORTED */
  175162. /*** End of inlined file: jidctfst.c ***/
  175163. #undef CONST_BITS
  175164. #undef FIX_1_847759065
  175165. #undef MULTIPLY
  175166. #undef DEQUANTIZE
  175167. /*** Start of inlined file: jidctint.c ***/
  175168. #define JPEG_INTERNALS
  175169. #ifdef DCT_ISLOW_SUPPORTED
  175170. /*
  175171. * This module is specialized to the case DCTSIZE = 8.
  175172. */
  175173. #if DCTSIZE != 8
  175174. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175175. #endif
  175176. /*
  175177. * The poop on this scaling stuff is as follows:
  175178. *
  175179. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175180. * larger than the true IDCT outputs. The final outputs are therefore
  175181. * a factor of N larger than desired; since N=8 this can be cured by
  175182. * a simple right shift at the end of the algorithm. The advantage of
  175183. * this arrangement is that we save two multiplications per 1-D IDCT,
  175184. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175185. *
  175186. * We have to do addition and subtraction of the integer inputs, which
  175187. * is no problem, and multiplication by fractional constants, which is
  175188. * a problem to do in integer arithmetic. We multiply all the constants
  175189. * by CONST_SCALE and convert them to integer constants (thus retaining
  175190. * CONST_BITS bits of precision in the constants). After doing a
  175191. * multiplication we have to divide the product by CONST_SCALE, with proper
  175192. * rounding, to produce the correct output. This division can be done
  175193. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175194. * as long as possible so that partial sums can be added together with
  175195. * full fractional precision.
  175196. *
  175197. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175198. * they are represented to better-than-integral precision. These outputs
  175199. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175200. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175201. * intermediate INT32 array would be needed.)
  175202. *
  175203. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175204. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175205. * shows that the values given below are the most effective.
  175206. */
  175207. #if BITS_IN_JSAMPLE == 8
  175208. #define CONST_BITS 13
  175209. #define PASS1_BITS 2
  175210. #else
  175211. #define CONST_BITS 13
  175212. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175213. #endif
  175214. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175215. * causing a lot of useless floating-point operations at run time.
  175216. * To get around this we use the following pre-calculated constants.
  175217. * If you change CONST_BITS you may want to add appropriate values.
  175218. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175219. */
  175220. #if CONST_BITS == 13
  175221. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175222. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175223. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175224. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175225. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175226. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175227. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175228. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175229. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175230. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175231. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175232. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175233. #else
  175234. #define FIX_0_298631336 FIX(0.298631336)
  175235. #define FIX_0_390180644 FIX(0.390180644)
  175236. #define FIX_0_541196100 FIX(0.541196100)
  175237. #define FIX_0_765366865 FIX(0.765366865)
  175238. #define FIX_0_899976223 FIX(0.899976223)
  175239. #define FIX_1_175875602 FIX(1.175875602)
  175240. #define FIX_1_501321110 FIX(1.501321110)
  175241. #define FIX_1_847759065 FIX(1.847759065)
  175242. #define FIX_1_961570560 FIX(1.961570560)
  175243. #define FIX_2_053119869 FIX(2.053119869)
  175244. #define FIX_2_562915447 FIX(2.562915447)
  175245. #define FIX_3_072711026 FIX(3.072711026)
  175246. #endif
  175247. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175248. * For 8-bit samples with the recommended scaling, all the variable
  175249. * and constant values involved are no more than 16 bits wide, so a
  175250. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175251. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175252. */
  175253. #if BITS_IN_JSAMPLE == 8
  175254. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175255. #else
  175256. #define MULTIPLY(var,const) ((var) * (const))
  175257. #endif
  175258. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175259. * entry; produce an int result. In this module, both inputs and result
  175260. * are 16 bits or less, so either int or short multiply will work.
  175261. */
  175262. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175263. /*
  175264. * Perform dequantization and inverse DCT on one block of coefficients.
  175265. */
  175266. GLOBAL(void)
  175267. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175268. JCOEFPTR coef_block,
  175269. JSAMPARRAY output_buf, JDIMENSION output_col)
  175270. {
  175271. INT32 tmp0, tmp1, tmp2, tmp3;
  175272. INT32 tmp10, tmp11, tmp12, tmp13;
  175273. INT32 z1, z2, z3, z4, z5;
  175274. JCOEFPTR inptr;
  175275. ISLOW_MULT_TYPE * quantptr;
  175276. int * wsptr;
  175277. JSAMPROW outptr;
  175278. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175279. int ctr;
  175280. int workspace[DCTSIZE2]; /* buffers data between passes */
  175281. SHIFT_TEMPS
  175282. /* Pass 1: process columns from input, store into work array. */
  175283. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175284. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175285. inptr = coef_block;
  175286. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175287. wsptr = workspace;
  175288. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175289. /* Due to quantization, we will usually find that many of the input
  175290. * coefficients are zero, especially the AC terms. We can exploit this
  175291. * by short-circuiting the IDCT calculation for any column in which all
  175292. * the AC terms are zero. In that case each output is equal to the
  175293. * DC coefficient (with scale factor as needed).
  175294. * With typical images and quantization tables, half or more of the
  175295. * column DCT calculations can be simplified this way.
  175296. */
  175297. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175298. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175299. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175300. inptr[DCTSIZE*7] == 0) {
  175301. /* AC terms all zero */
  175302. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175303. wsptr[DCTSIZE*0] = dcval;
  175304. wsptr[DCTSIZE*1] = dcval;
  175305. wsptr[DCTSIZE*2] = dcval;
  175306. wsptr[DCTSIZE*3] = dcval;
  175307. wsptr[DCTSIZE*4] = dcval;
  175308. wsptr[DCTSIZE*5] = dcval;
  175309. wsptr[DCTSIZE*6] = dcval;
  175310. wsptr[DCTSIZE*7] = dcval;
  175311. inptr++; /* advance pointers to next column */
  175312. quantptr++;
  175313. wsptr++;
  175314. continue;
  175315. }
  175316. /* Even part: reverse the even part of the forward DCT. */
  175317. /* The rotator is sqrt(2)*c(-6). */
  175318. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175319. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175320. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175321. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175322. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175323. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175324. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175325. tmp0 = (z2 + z3) << CONST_BITS;
  175326. tmp1 = (z2 - z3) << CONST_BITS;
  175327. tmp10 = tmp0 + tmp3;
  175328. tmp13 = tmp0 - tmp3;
  175329. tmp11 = tmp1 + tmp2;
  175330. tmp12 = tmp1 - tmp2;
  175331. /* Odd part per figure 8; the matrix is unitary and hence its
  175332. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175333. */
  175334. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175335. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175336. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175337. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175338. z1 = tmp0 + tmp3;
  175339. z2 = tmp1 + tmp2;
  175340. z3 = tmp0 + tmp2;
  175341. z4 = tmp1 + tmp3;
  175342. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175343. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175344. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175345. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175346. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175347. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175348. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175349. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175350. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175351. z3 += z5;
  175352. z4 += z5;
  175353. tmp0 += z1 + z3;
  175354. tmp1 += z2 + z4;
  175355. tmp2 += z2 + z3;
  175356. tmp3 += z1 + z4;
  175357. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175358. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175359. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175360. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175361. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175362. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175363. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175364. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175365. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175366. inptr++; /* advance pointers to next column */
  175367. quantptr++;
  175368. wsptr++;
  175369. }
  175370. /* Pass 2: process rows from work array, store into output array. */
  175371. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175372. /* and also undo the PASS1_BITS scaling. */
  175373. wsptr = workspace;
  175374. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175375. outptr = output_buf[ctr] + output_col;
  175376. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175377. * However, the column calculation has created many nonzero AC terms, so
  175378. * the simplification applies less often (typically 5% to 10% of the time).
  175379. * On machines with very fast multiplication, it's possible that the
  175380. * test takes more time than it's worth. In that case this section
  175381. * may be commented out.
  175382. */
  175383. #ifndef NO_ZERO_ROW_TEST
  175384. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175385. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175386. /* AC terms all zero */
  175387. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175388. & RANGE_MASK];
  175389. outptr[0] = dcval;
  175390. outptr[1] = dcval;
  175391. outptr[2] = dcval;
  175392. outptr[3] = dcval;
  175393. outptr[4] = dcval;
  175394. outptr[5] = dcval;
  175395. outptr[6] = dcval;
  175396. outptr[7] = dcval;
  175397. wsptr += DCTSIZE; /* advance pointer to next row */
  175398. continue;
  175399. }
  175400. #endif
  175401. /* Even part: reverse the even part of the forward DCT. */
  175402. /* The rotator is sqrt(2)*c(-6). */
  175403. z2 = (INT32) wsptr[2];
  175404. z3 = (INT32) wsptr[6];
  175405. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175406. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175407. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175408. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175409. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175410. tmp10 = tmp0 + tmp3;
  175411. tmp13 = tmp0 - tmp3;
  175412. tmp11 = tmp1 + tmp2;
  175413. tmp12 = tmp1 - tmp2;
  175414. /* Odd part per figure 8; the matrix is unitary and hence its
  175415. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175416. */
  175417. tmp0 = (INT32) wsptr[7];
  175418. tmp1 = (INT32) wsptr[5];
  175419. tmp2 = (INT32) wsptr[3];
  175420. tmp3 = (INT32) wsptr[1];
  175421. z1 = tmp0 + tmp3;
  175422. z2 = tmp1 + tmp2;
  175423. z3 = tmp0 + tmp2;
  175424. z4 = tmp1 + tmp3;
  175425. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175426. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175427. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175428. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175429. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175430. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175431. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175432. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175433. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175434. z3 += z5;
  175435. z4 += z5;
  175436. tmp0 += z1 + z3;
  175437. tmp1 += z2 + z4;
  175438. tmp2 += z2 + z3;
  175439. tmp3 += z1 + z4;
  175440. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175441. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175442. CONST_BITS+PASS1_BITS+3)
  175443. & RANGE_MASK];
  175444. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175445. CONST_BITS+PASS1_BITS+3)
  175446. & RANGE_MASK];
  175447. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175448. CONST_BITS+PASS1_BITS+3)
  175449. & RANGE_MASK];
  175450. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175451. CONST_BITS+PASS1_BITS+3)
  175452. & RANGE_MASK];
  175453. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175454. CONST_BITS+PASS1_BITS+3)
  175455. & RANGE_MASK];
  175456. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175457. CONST_BITS+PASS1_BITS+3)
  175458. & RANGE_MASK];
  175459. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175460. CONST_BITS+PASS1_BITS+3)
  175461. & RANGE_MASK];
  175462. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175463. CONST_BITS+PASS1_BITS+3)
  175464. & RANGE_MASK];
  175465. wsptr += DCTSIZE; /* advance pointer to next row */
  175466. }
  175467. }
  175468. #endif /* DCT_ISLOW_SUPPORTED */
  175469. /*** End of inlined file: jidctint.c ***/
  175470. /*** Start of inlined file: jidctred.c ***/
  175471. #define JPEG_INTERNALS
  175472. #ifdef IDCT_SCALING_SUPPORTED
  175473. /*
  175474. * This module is specialized to the case DCTSIZE = 8.
  175475. */
  175476. #if DCTSIZE != 8
  175477. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175478. #endif
  175479. /* Scaling is the same as in jidctint.c. */
  175480. #if BITS_IN_JSAMPLE == 8
  175481. #define CONST_BITS 13
  175482. #define PASS1_BITS 2
  175483. #else
  175484. #define CONST_BITS 13
  175485. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175486. #endif
  175487. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175488. * causing a lot of useless floating-point operations at run time.
  175489. * To get around this we use the following pre-calculated constants.
  175490. * If you change CONST_BITS you may want to add appropriate values.
  175491. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175492. */
  175493. #if CONST_BITS == 13
  175494. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175495. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175496. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175497. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175498. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175499. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175500. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175501. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175502. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175503. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175504. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175505. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175506. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175507. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175508. #else
  175509. #define FIX_0_211164243 FIX(0.211164243)
  175510. #define FIX_0_509795579 FIX(0.509795579)
  175511. #define FIX_0_601344887 FIX(0.601344887)
  175512. #define FIX_0_720959822 FIX(0.720959822)
  175513. #define FIX_0_765366865 FIX(0.765366865)
  175514. #define FIX_0_850430095 FIX(0.850430095)
  175515. #define FIX_0_899976223 FIX(0.899976223)
  175516. #define FIX_1_061594337 FIX(1.061594337)
  175517. #define FIX_1_272758580 FIX(1.272758580)
  175518. #define FIX_1_451774981 FIX(1.451774981)
  175519. #define FIX_1_847759065 FIX(1.847759065)
  175520. #define FIX_2_172734803 FIX(2.172734803)
  175521. #define FIX_2_562915447 FIX(2.562915447)
  175522. #define FIX_3_624509785 FIX(3.624509785)
  175523. #endif
  175524. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175525. * For 8-bit samples with the recommended scaling, all the variable
  175526. * and constant values involved are no more than 16 bits wide, so a
  175527. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175528. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175529. */
  175530. #if BITS_IN_JSAMPLE == 8
  175531. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175532. #else
  175533. #define MULTIPLY(var,const) ((var) * (const))
  175534. #endif
  175535. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175536. * entry; produce an int result. In this module, both inputs and result
  175537. * are 16 bits or less, so either int or short multiply will work.
  175538. */
  175539. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175540. /*
  175541. * Perform dequantization and inverse DCT on one block of coefficients,
  175542. * producing a reduced-size 4x4 output block.
  175543. */
  175544. GLOBAL(void)
  175545. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175546. JCOEFPTR coef_block,
  175547. JSAMPARRAY output_buf, JDIMENSION output_col)
  175548. {
  175549. INT32 tmp0, tmp2, tmp10, tmp12;
  175550. INT32 z1, z2, z3, z4;
  175551. JCOEFPTR inptr;
  175552. ISLOW_MULT_TYPE * quantptr;
  175553. int * wsptr;
  175554. JSAMPROW outptr;
  175555. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175556. int ctr;
  175557. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175558. SHIFT_TEMPS
  175559. /* Pass 1: process columns from input, store into work array. */
  175560. inptr = coef_block;
  175561. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175562. wsptr = workspace;
  175563. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175564. /* Don't bother to process column 4, because second pass won't use it */
  175565. if (ctr == DCTSIZE-4)
  175566. continue;
  175567. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175568. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175569. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175570. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175571. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175572. wsptr[DCTSIZE*0] = dcval;
  175573. wsptr[DCTSIZE*1] = dcval;
  175574. wsptr[DCTSIZE*2] = dcval;
  175575. wsptr[DCTSIZE*3] = dcval;
  175576. continue;
  175577. }
  175578. /* Even part */
  175579. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175580. tmp0 <<= (CONST_BITS+1);
  175581. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175582. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175583. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175584. tmp10 = tmp0 + tmp2;
  175585. tmp12 = tmp0 - tmp2;
  175586. /* Odd part */
  175587. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175588. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175589. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175590. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175591. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175592. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175593. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175594. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175595. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175596. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175597. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175598. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175599. /* Final output stage */
  175600. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175601. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175602. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175603. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175604. }
  175605. /* Pass 2: process 4 rows from work array, store into output array. */
  175606. wsptr = workspace;
  175607. for (ctr = 0; ctr < 4; ctr++) {
  175608. outptr = output_buf[ctr] + output_col;
  175609. /* It's not clear whether a zero row test is worthwhile here ... */
  175610. #ifndef NO_ZERO_ROW_TEST
  175611. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175612. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175613. /* AC terms all zero */
  175614. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175615. & RANGE_MASK];
  175616. outptr[0] = dcval;
  175617. outptr[1] = dcval;
  175618. outptr[2] = dcval;
  175619. outptr[3] = dcval;
  175620. wsptr += DCTSIZE; /* advance pointer to next row */
  175621. continue;
  175622. }
  175623. #endif
  175624. /* Even part */
  175625. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175626. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175627. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175628. tmp10 = tmp0 + tmp2;
  175629. tmp12 = tmp0 - tmp2;
  175630. /* Odd part */
  175631. z1 = (INT32) wsptr[7];
  175632. z2 = (INT32) wsptr[5];
  175633. z3 = (INT32) wsptr[3];
  175634. z4 = (INT32) wsptr[1];
  175635. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175636. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175637. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175638. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175639. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175640. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175641. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175642. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175643. /* Final output stage */
  175644. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175645. CONST_BITS+PASS1_BITS+3+1)
  175646. & RANGE_MASK];
  175647. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175648. CONST_BITS+PASS1_BITS+3+1)
  175649. & RANGE_MASK];
  175650. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175651. CONST_BITS+PASS1_BITS+3+1)
  175652. & RANGE_MASK];
  175653. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175654. CONST_BITS+PASS1_BITS+3+1)
  175655. & RANGE_MASK];
  175656. wsptr += DCTSIZE; /* advance pointer to next row */
  175657. }
  175658. }
  175659. /*
  175660. * Perform dequantization and inverse DCT on one block of coefficients,
  175661. * producing a reduced-size 2x2 output block.
  175662. */
  175663. GLOBAL(void)
  175664. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175665. JCOEFPTR coef_block,
  175666. JSAMPARRAY output_buf, JDIMENSION output_col)
  175667. {
  175668. INT32 tmp0, tmp10, z1;
  175669. JCOEFPTR inptr;
  175670. ISLOW_MULT_TYPE * quantptr;
  175671. int * wsptr;
  175672. JSAMPROW outptr;
  175673. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175674. int ctr;
  175675. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175676. SHIFT_TEMPS
  175677. /* Pass 1: process columns from input, store into work array. */
  175678. inptr = coef_block;
  175679. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175680. wsptr = workspace;
  175681. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175682. /* Don't bother to process columns 2,4,6 */
  175683. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175684. continue;
  175685. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175686. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175687. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175688. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175689. wsptr[DCTSIZE*0] = dcval;
  175690. wsptr[DCTSIZE*1] = dcval;
  175691. continue;
  175692. }
  175693. /* Even part */
  175694. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175695. tmp10 = z1 << (CONST_BITS+2);
  175696. /* Odd part */
  175697. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175698. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175699. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175700. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175701. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175702. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175703. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175704. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175705. /* Final output stage */
  175706. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175707. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175708. }
  175709. /* Pass 2: process 2 rows from work array, store into output array. */
  175710. wsptr = workspace;
  175711. for (ctr = 0; ctr < 2; ctr++) {
  175712. outptr = output_buf[ctr] + output_col;
  175713. /* It's not clear whether a zero row test is worthwhile here ... */
  175714. #ifndef NO_ZERO_ROW_TEST
  175715. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175716. /* AC terms all zero */
  175717. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175718. & RANGE_MASK];
  175719. outptr[0] = dcval;
  175720. outptr[1] = dcval;
  175721. wsptr += DCTSIZE; /* advance pointer to next row */
  175722. continue;
  175723. }
  175724. #endif
  175725. /* Even part */
  175726. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175727. /* Odd part */
  175728. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175729. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175730. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175731. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175732. /* Final output stage */
  175733. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175734. CONST_BITS+PASS1_BITS+3+2)
  175735. & RANGE_MASK];
  175736. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175737. CONST_BITS+PASS1_BITS+3+2)
  175738. & RANGE_MASK];
  175739. wsptr += DCTSIZE; /* advance pointer to next row */
  175740. }
  175741. }
  175742. /*
  175743. * Perform dequantization and inverse DCT on one block of coefficients,
  175744. * producing a reduced-size 1x1 output block.
  175745. */
  175746. GLOBAL(void)
  175747. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175748. JCOEFPTR coef_block,
  175749. JSAMPARRAY output_buf, JDIMENSION output_col)
  175750. {
  175751. int dcval;
  175752. ISLOW_MULT_TYPE * quantptr;
  175753. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175754. SHIFT_TEMPS
  175755. /* We hardly need an inverse DCT routine for this: just take the
  175756. * average pixel value, which is one-eighth of the DC coefficient.
  175757. */
  175758. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175759. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175760. dcval = (int) DESCALE((INT32) dcval, 3);
  175761. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175762. }
  175763. #endif /* IDCT_SCALING_SUPPORTED */
  175764. /*** End of inlined file: jidctred.c ***/
  175765. /*** Start of inlined file: jmemmgr.c ***/
  175766. #define JPEG_INTERNALS
  175767. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175768. /*** Start of inlined file: jmemsys.h ***/
  175769. #ifndef __jmemsys_h__
  175770. #define __jmemsys_h__
  175771. /* Short forms of external names for systems with brain-damaged linkers. */
  175772. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175773. #define jpeg_get_small jGetSmall
  175774. #define jpeg_free_small jFreeSmall
  175775. #define jpeg_get_large jGetLarge
  175776. #define jpeg_free_large jFreeLarge
  175777. #define jpeg_mem_available jMemAvail
  175778. #define jpeg_open_backing_store jOpenBackStore
  175779. #define jpeg_mem_init jMemInit
  175780. #define jpeg_mem_term jMemTerm
  175781. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175782. /*
  175783. * These two functions are used to allocate and release small chunks of
  175784. * memory. (Typically the total amount requested through jpeg_get_small is
  175785. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175786. * Behavior should be the same as for the standard library functions malloc
  175787. * and free; in particular, jpeg_get_small must return NULL on failure.
  175788. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175789. * size of the object being freed, just in case it's needed.
  175790. * On an 80x86 machine using small-data memory model, these manage near heap.
  175791. */
  175792. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175793. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175794. size_t sizeofobject));
  175795. /*
  175796. * These two functions are used to allocate and release large chunks of
  175797. * memory (up to the total free space designated by jpeg_mem_available).
  175798. * The interface is the same as above, except that on an 80x86 machine,
  175799. * far pointers are used. On most other machines these are identical to
  175800. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175801. * in case a different allocation strategy is desirable for large chunks.
  175802. */
  175803. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175804. size_t sizeofobject));
  175805. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175806. size_t sizeofobject));
  175807. /*
  175808. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175809. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175810. * matter, but that case should never come into play). This macro is needed
  175811. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175812. * On those machines, we expect that jconfig.h will provide a proper value.
  175813. * On machines with 32-bit flat address spaces, any large constant may be used.
  175814. *
  175815. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175816. * size_t and will be a multiple of sizeof(align_type).
  175817. */
  175818. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175819. #define MAX_ALLOC_CHUNK 1000000000L
  175820. #endif
  175821. /*
  175822. * This routine computes the total space still available for allocation by
  175823. * jpeg_get_large. If more space than this is needed, backing store will be
  175824. * used. NOTE: any memory already allocated must not be counted.
  175825. *
  175826. * There is a minimum space requirement, corresponding to the minimum
  175827. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175828. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175829. * all working storage in memory, is also passed in case it is useful.
  175830. * Finally, the total space already allocated is passed. If no better
  175831. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175832. * is often a suitable calculation.
  175833. *
  175834. * It is OK for jpeg_mem_available to underestimate the space available
  175835. * (that'll just lead to more backing-store access than is really necessary).
  175836. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175837. * a slop factor from the true available space. 5% should be enough.
  175838. *
  175839. * On machines with lots of virtual memory, any large constant may be returned.
  175840. * Conversely, zero may be returned to always use the minimum amount of memory.
  175841. */
  175842. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175843. long min_bytes_needed,
  175844. long max_bytes_needed,
  175845. long already_allocated));
  175846. /*
  175847. * This structure holds whatever state is needed to access a single
  175848. * backing-store object. The read/write/close method pointers are called
  175849. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175850. * are private to the system-dependent backing store routines.
  175851. */
  175852. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175853. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175854. typedef unsigned short XMSH; /* type of extended-memory handles */
  175855. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175856. typedef union {
  175857. short file_handle; /* DOS file handle if it's a temp file */
  175858. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175859. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175860. } handle_union;
  175861. #endif /* USE_MSDOS_MEMMGR */
  175862. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175863. #include <Files.h>
  175864. #endif /* USE_MAC_MEMMGR */
  175865. //typedef struct backing_store_struct * backing_store_ptr;
  175866. typedef struct backing_store_struct {
  175867. /* Methods for reading/writing/closing this backing-store object */
  175868. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175869. struct backing_store_struct *info,
  175870. void FAR * buffer_address,
  175871. long file_offset, long byte_count));
  175872. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175873. struct backing_store_struct *info,
  175874. void FAR * buffer_address,
  175875. long file_offset, long byte_count));
  175876. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175877. struct backing_store_struct *info));
  175878. /* Private fields for system-dependent backing-store management */
  175879. #ifdef USE_MSDOS_MEMMGR
  175880. /* For the MS-DOS manager (jmemdos.c), we need: */
  175881. handle_union handle; /* reference to backing-store storage object */
  175882. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175883. #else
  175884. #ifdef USE_MAC_MEMMGR
  175885. /* For the Mac manager (jmemmac.c), we need: */
  175886. short temp_file; /* file reference number to temp file */
  175887. FSSpec tempSpec; /* the FSSpec for the temp file */
  175888. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175889. #else
  175890. /* For a typical implementation with temp files, we need: */
  175891. FILE * temp_file; /* stdio reference to temp file */
  175892. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175893. #endif
  175894. #endif
  175895. } backing_store_info;
  175896. /*
  175897. * Initial opening of a backing-store object. This must fill in the
  175898. * read/write/close pointers in the object. The read/write routines
  175899. * may take an error exit if the specified maximum file size is exceeded.
  175900. * (If jpeg_mem_available always returns a large value, this routine can
  175901. * just take an error exit.)
  175902. */
  175903. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175904. struct backing_store_struct *info,
  175905. long total_bytes_needed));
  175906. /*
  175907. * These routines take care of any system-dependent initialization and
  175908. * cleanup required. jpeg_mem_init will be called before anything is
  175909. * allocated (and, therefore, nothing in cinfo is of use except the error
  175910. * manager pointer). It should return a suitable default value for
  175911. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175912. * application. (Note that max_memory_to_use is only important if
  175913. * jpeg_mem_available chooses to consult it ... no one else will.)
  175914. * jpeg_mem_term may assume that all requested memory has been freed and that
  175915. * all opened backing-store objects have been closed.
  175916. */
  175917. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175918. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175919. #endif
  175920. /*** End of inlined file: jmemsys.h ***/
  175921. /* import the system-dependent declarations */
  175922. #ifndef NO_GETENV
  175923. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175924. extern char * getenv JPP((const char * name));
  175925. #endif
  175926. #endif
  175927. /*
  175928. * Some important notes:
  175929. * The allocation routines provided here must never return NULL.
  175930. * They should exit to error_exit if unsuccessful.
  175931. *
  175932. * It's not a good idea to try to merge the sarray and barray routines,
  175933. * even though they are textually almost the same, because samples are
  175934. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175935. * in machines where byte pointers have a different representation from
  175936. * word pointers, the resulting machine code could not be the same.
  175937. */
  175938. /*
  175939. * Many machines require storage alignment: longs must start on 4-byte
  175940. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175941. * always returns pointers that are multiples of the worst-case alignment
  175942. * requirement, and we had better do so too.
  175943. * There isn't any really portable way to determine the worst-case alignment
  175944. * requirement. This module assumes that the alignment requirement is
  175945. * multiples of sizeof(ALIGN_TYPE).
  175946. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175947. * workstations (where doubles really do need 8-byte alignment) and will work
  175948. * fine on nearly everything. If your machine has lesser alignment needs,
  175949. * you can save a few bytes by making ALIGN_TYPE smaller.
  175950. * The only place I know of where this will NOT work is certain Macintosh
  175951. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175952. * Doing 10-byte alignment is counterproductive because longwords won't be
  175953. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175954. * such a compiler.
  175955. */
  175956. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175957. #define ALIGN_TYPE double
  175958. #endif
  175959. /*
  175960. * We allocate objects from "pools", where each pool is gotten with a single
  175961. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175962. * overhead within a pool, except for alignment padding. Each pool has a
  175963. * header with a link to the next pool of the same class.
  175964. * Small and large pool headers are identical except that the latter's
  175965. * link pointer must be FAR on 80x86 machines.
  175966. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175967. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175968. * of the alignment requirement of ALIGN_TYPE.
  175969. */
  175970. typedef union small_pool_struct * small_pool_ptr;
  175971. typedef union small_pool_struct {
  175972. struct {
  175973. small_pool_ptr next; /* next in list of pools */
  175974. size_t bytes_used; /* how many bytes already used within pool */
  175975. size_t bytes_left; /* bytes still available in this pool */
  175976. } hdr;
  175977. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175978. } small_pool_hdr;
  175979. typedef union large_pool_struct FAR * large_pool_ptr;
  175980. typedef union large_pool_struct {
  175981. struct {
  175982. large_pool_ptr next; /* next in list of pools */
  175983. size_t bytes_used; /* how many bytes already used within pool */
  175984. size_t bytes_left; /* bytes still available in this pool */
  175985. } hdr;
  175986. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175987. } large_pool_hdr;
  175988. /*
  175989. * Here is the full definition of a memory manager object.
  175990. */
  175991. typedef struct {
  175992. struct jpeg_memory_mgr pub; /* public fields */
  175993. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175994. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175995. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175996. /* Since we only have one lifetime class of virtual arrays, only one
  175997. * linked list is necessary (for each datatype). Note that the virtual
  175998. * array control blocks being linked together are actually stored somewhere
  175999. * in the small-pool list.
  176000. */
  176001. jvirt_sarray_ptr virt_sarray_list;
  176002. jvirt_barray_ptr virt_barray_list;
  176003. /* This counts total space obtained from jpeg_get_small/large */
  176004. long total_space_allocated;
  176005. /* alloc_sarray and alloc_barray set this value for use by virtual
  176006. * array routines.
  176007. */
  176008. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176009. } my_memory_mgr;
  176010. typedef my_memory_mgr * my_mem_ptr;
  176011. /*
  176012. * The control blocks for virtual arrays.
  176013. * Note that these blocks are allocated in the "small" pool area.
  176014. * System-dependent info for the associated backing store (if any) is hidden
  176015. * inside the backing_store_info struct.
  176016. */
  176017. struct jvirt_sarray_control {
  176018. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176019. JDIMENSION rows_in_array; /* total virtual array height */
  176020. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176021. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176022. JDIMENSION rows_in_mem; /* height of memory buffer */
  176023. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176024. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176025. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176026. boolean pre_zero; /* pre-zero mode requested? */
  176027. boolean dirty; /* do current buffer contents need written? */
  176028. boolean b_s_open; /* is backing-store data valid? */
  176029. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176030. backing_store_info b_s_info; /* System-dependent control info */
  176031. };
  176032. struct jvirt_barray_control {
  176033. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176034. JDIMENSION rows_in_array; /* total virtual array height */
  176035. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176036. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176037. JDIMENSION rows_in_mem; /* height of memory buffer */
  176038. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176039. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176040. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176041. boolean pre_zero; /* pre-zero mode requested? */
  176042. boolean dirty; /* do current buffer contents need written? */
  176043. boolean b_s_open; /* is backing-store data valid? */
  176044. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176045. backing_store_info b_s_info; /* System-dependent control info */
  176046. };
  176047. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176048. LOCAL(void)
  176049. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176050. {
  176051. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176052. small_pool_ptr shdr_ptr;
  176053. large_pool_ptr lhdr_ptr;
  176054. /* Since this is only a debugging stub, we can cheat a little by using
  176055. * fprintf directly rather than going through the trace message code.
  176056. * This is helpful because message parm array can't handle longs.
  176057. */
  176058. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176059. pool_id, mem->total_space_allocated);
  176060. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176061. lhdr_ptr = lhdr_ptr->hdr.next) {
  176062. fprintf(stderr, " Large chunk used %ld\n",
  176063. (long) lhdr_ptr->hdr.bytes_used);
  176064. }
  176065. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176066. shdr_ptr = shdr_ptr->hdr.next) {
  176067. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176068. (long) shdr_ptr->hdr.bytes_used,
  176069. (long) shdr_ptr->hdr.bytes_left);
  176070. }
  176071. }
  176072. #endif /* MEM_STATS */
  176073. LOCAL(void)
  176074. out_of_memory (j_common_ptr cinfo, int which)
  176075. /* Report an out-of-memory error and stop execution */
  176076. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176077. {
  176078. #ifdef MEM_STATS
  176079. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176080. #endif
  176081. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176082. }
  176083. /*
  176084. * Allocation of "small" objects.
  176085. *
  176086. * For these, we use pooled storage. When a new pool must be created,
  176087. * we try to get enough space for the current request plus a "slop" factor,
  176088. * where the slop will be the amount of leftover space in the new pool.
  176089. * The speed vs. space tradeoff is largely determined by the slop values.
  176090. * A different slop value is provided for each pool class (lifetime),
  176091. * and we also distinguish the first pool of a class from later ones.
  176092. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176093. * machines, but may be too small if longs are 64 bits or more.
  176094. */
  176095. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176096. {
  176097. 1600, /* first PERMANENT pool */
  176098. 16000 /* first IMAGE pool */
  176099. };
  176100. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176101. {
  176102. 0, /* additional PERMANENT pools */
  176103. 5000 /* additional IMAGE pools */
  176104. };
  176105. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176106. METHODDEF(void *)
  176107. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176108. /* Allocate a "small" object */
  176109. {
  176110. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176111. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176112. char * data_ptr;
  176113. size_t odd_bytes, min_request, slop;
  176114. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176115. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176116. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176117. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176118. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176119. if (odd_bytes > 0)
  176120. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176121. /* See if space is available in any existing pool */
  176122. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176123. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176124. prev_hdr_ptr = NULL;
  176125. hdr_ptr = mem->small_list[pool_id];
  176126. while (hdr_ptr != NULL) {
  176127. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176128. break; /* found pool with enough space */
  176129. prev_hdr_ptr = hdr_ptr;
  176130. hdr_ptr = hdr_ptr->hdr.next;
  176131. }
  176132. /* Time to make a new pool? */
  176133. if (hdr_ptr == NULL) {
  176134. /* min_request is what we need now, slop is what will be leftover */
  176135. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176136. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176137. slop = first_pool_slop[pool_id];
  176138. else
  176139. slop = extra_pool_slop[pool_id];
  176140. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176141. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176142. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176143. /* Try to get space, if fail reduce slop and try again */
  176144. for (;;) {
  176145. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176146. if (hdr_ptr != NULL)
  176147. break;
  176148. slop /= 2;
  176149. if (slop < MIN_SLOP) /* give up when it gets real small */
  176150. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176151. }
  176152. mem->total_space_allocated += min_request + slop;
  176153. /* Success, initialize the new pool header and add to end of list */
  176154. hdr_ptr->hdr.next = NULL;
  176155. hdr_ptr->hdr.bytes_used = 0;
  176156. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176157. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176158. mem->small_list[pool_id] = hdr_ptr;
  176159. else
  176160. prev_hdr_ptr->hdr.next = hdr_ptr;
  176161. }
  176162. /* OK, allocate the object from the current pool */
  176163. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176164. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176165. hdr_ptr->hdr.bytes_used += sizeofobject;
  176166. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176167. return (void *) data_ptr;
  176168. }
  176169. /*
  176170. * Allocation of "large" objects.
  176171. *
  176172. * The external semantics of these are the same as "small" objects,
  176173. * except that FAR pointers are used on 80x86. However the pool
  176174. * management heuristics are quite different. We assume that each
  176175. * request is large enough that it may as well be passed directly to
  176176. * jpeg_get_large; the pool management just links everything together
  176177. * so that we can free it all on demand.
  176178. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176179. * structures. The routines that create these structures (see below)
  176180. * deliberately bunch rows together to ensure a large request size.
  176181. */
  176182. METHODDEF(void FAR *)
  176183. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176184. /* Allocate a "large" object */
  176185. {
  176186. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176187. large_pool_ptr hdr_ptr;
  176188. size_t odd_bytes;
  176189. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176190. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176191. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176192. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176193. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176194. if (odd_bytes > 0)
  176195. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176196. /* Always make a new pool */
  176197. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176198. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176199. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176200. SIZEOF(large_pool_hdr));
  176201. if (hdr_ptr == NULL)
  176202. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176203. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176204. /* Success, initialize the new pool header and add to list */
  176205. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176206. /* We maintain space counts in each pool header for statistical purposes,
  176207. * even though they are not needed for allocation.
  176208. */
  176209. hdr_ptr->hdr.bytes_used = sizeofobject;
  176210. hdr_ptr->hdr.bytes_left = 0;
  176211. mem->large_list[pool_id] = hdr_ptr;
  176212. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176213. }
  176214. /*
  176215. * Creation of 2-D sample arrays.
  176216. * The pointers are in near heap, the samples themselves in FAR heap.
  176217. *
  176218. * To minimize allocation overhead and to allow I/O of large contiguous
  176219. * blocks, we allocate the sample rows in groups of as many rows as possible
  176220. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176221. * NB: the virtual array control routines, later in this file, know about
  176222. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176223. * object so that it can be saved away if this sarray is the workspace for
  176224. * a virtual array.
  176225. */
  176226. METHODDEF(JSAMPARRAY)
  176227. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176228. JDIMENSION samplesperrow, JDIMENSION numrows)
  176229. /* Allocate a 2-D sample array */
  176230. {
  176231. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176232. JSAMPARRAY result;
  176233. JSAMPROW workspace;
  176234. JDIMENSION rowsperchunk, currow, i;
  176235. long ltemp;
  176236. /* Calculate max # of rows allowed in one allocation chunk */
  176237. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176238. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176239. if (ltemp <= 0)
  176240. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176241. if (ltemp < (long) numrows)
  176242. rowsperchunk = (JDIMENSION) ltemp;
  176243. else
  176244. rowsperchunk = numrows;
  176245. mem->last_rowsperchunk = rowsperchunk;
  176246. /* Get space for row pointers (small object) */
  176247. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176248. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176249. /* Get the rows themselves (large objects) */
  176250. currow = 0;
  176251. while (currow < numrows) {
  176252. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176253. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176254. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176255. * SIZEOF(JSAMPLE)));
  176256. for (i = rowsperchunk; i > 0; i--) {
  176257. result[currow++] = workspace;
  176258. workspace += samplesperrow;
  176259. }
  176260. }
  176261. return result;
  176262. }
  176263. /*
  176264. * Creation of 2-D coefficient-block arrays.
  176265. * This is essentially the same as the code for sample arrays, above.
  176266. */
  176267. METHODDEF(JBLOCKARRAY)
  176268. alloc_barray (j_common_ptr cinfo, int pool_id,
  176269. JDIMENSION blocksperrow, JDIMENSION numrows)
  176270. /* Allocate a 2-D coefficient-block array */
  176271. {
  176272. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176273. JBLOCKARRAY result;
  176274. JBLOCKROW workspace;
  176275. JDIMENSION rowsperchunk, currow, i;
  176276. long ltemp;
  176277. /* Calculate max # of rows allowed in one allocation chunk */
  176278. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176279. ((long) blocksperrow * SIZEOF(JBLOCK));
  176280. if (ltemp <= 0)
  176281. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176282. if (ltemp < (long) numrows)
  176283. rowsperchunk = (JDIMENSION) ltemp;
  176284. else
  176285. rowsperchunk = numrows;
  176286. mem->last_rowsperchunk = rowsperchunk;
  176287. /* Get space for row pointers (small object) */
  176288. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176289. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176290. /* Get the rows themselves (large objects) */
  176291. currow = 0;
  176292. while (currow < numrows) {
  176293. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176294. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176295. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176296. * SIZEOF(JBLOCK)));
  176297. for (i = rowsperchunk; i > 0; i--) {
  176298. result[currow++] = workspace;
  176299. workspace += blocksperrow;
  176300. }
  176301. }
  176302. return result;
  176303. }
  176304. /*
  176305. * About virtual array management:
  176306. *
  176307. * The above "normal" array routines are only used to allocate strip buffers
  176308. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176309. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176310. * time, but the memory manager must save the whole array for repeated
  176311. * accesses. The intended implementation is that there is a strip buffer in
  176312. * memory (as high as is possible given the desired memory limit), plus a
  176313. * backing file that holds the rest of the array.
  176314. *
  176315. * The request_virt_array routines are told the total size of the image and
  176316. * the maximum number of rows that will be accessed at once. The in-memory
  176317. * buffer must be at least as large as the maxaccess value.
  176318. *
  176319. * The request routines create control blocks but not the in-memory buffers.
  176320. * That is postponed until realize_virt_arrays is called. At that time the
  176321. * total amount of space needed is known (approximately, anyway), so free
  176322. * memory can be divided up fairly.
  176323. *
  176324. * The access_virt_array routines are responsible for making a specific strip
  176325. * area accessible (after reading or writing the backing file, if necessary).
  176326. * Note that the access routines are told whether the caller intends to modify
  176327. * the accessed strip; during a read-only pass this saves having to rewrite
  176328. * data to disk. The access routines are also responsible for pre-zeroing
  176329. * any newly accessed rows, if pre-zeroing was requested.
  176330. *
  176331. * In current usage, the access requests are usually for nonoverlapping
  176332. * strips; that is, successive access start_row numbers differ by exactly
  176333. * num_rows = maxaccess. This means we can get good performance with simple
  176334. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176335. * of the access height; then there will never be accesses across bufferload
  176336. * boundaries. The code will still work with overlapping access requests,
  176337. * but it doesn't handle bufferload overlaps very efficiently.
  176338. */
  176339. METHODDEF(jvirt_sarray_ptr)
  176340. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176341. JDIMENSION samplesperrow, JDIMENSION numrows,
  176342. JDIMENSION maxaccess)
  176343. /* Request a virtual 2-D sample array */
  176344. {
  176345. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176346. jvirt_sarray_ptr result;
  176347. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176348. if (pool_id != JPOOL_IMAGE)
  176349. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176350. /* get control block */
  176351. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176352. SIZEOF(struct jvirt_sarray_control));
  176353. result->mem_buffer = NULL; /* marks array not yet realized */
  176354. result->rows_in_array = numrows;
  176355. result->samplesperrow = samplesperrow;
  176356. result->maxaccess = maxaccess;
  176357. result->pre_zero = pre_zero;
  176358. result->b_s_open = FALSE; /* no associated backing-store object */
  176359. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176360. mem->virt_sarray_list = result;
  176361. return result;
  176362. }
  176363. METHODDEF(jvirt_barray_ptr)
  176364. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176365. JDIMENSION blocksperrow, JDIMENSION numrows,
  176366. JDIMENSION maxaccess)
  176367. /* Request a virtual 2-D coefficient-block array */
  176368. {
  176369. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176370. jvirt_barray_ptr result;
  176371. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176372. if (pool_id != JPOOL_IMAGE)
  176373. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176374. /* get control block */
  176375. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176376. SIZEOF(struct jvirt_barray_control));
  176377. result->mem_buffer = NULL; /* marks array not yet realized */
  176378. result->rows_in_array = numrows;
  176379. result->blocksperrow = blocksperrow;
  176380. result->maxaccess = maxaccess;
  176381. result->pre_zero = pre_zero;
  176382. result->b_s_open = FALSE; /* no associated backing-store object */
  176383. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176384. mem->virt_barray_list = result;
  176385. return result;
  176386. }
  176387. METHODDEF(void)
  176388. realize_virt_arrays (j_common_ptr cinfo)
  176389. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176390. {
  176391. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176392. long space_per_minheight, maximum_space, avail_mem;
  176393. long minheights, max_minheights;
  176394. jvirt_sarray_ptr sptr;
  176395. jvirt_barray_ptr bptr;
  176396. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176397. * and the maximum space needed (full image height in each buffer).
  176398. * These may be of use to the system-dependent jpeg_mem_available routine.
  176399. */
  176400. space_per_minheight = 0;
  176401. maximum_space = 0;
  176402. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176403. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176404. space_per_minheight += (long) sptr->maxaccess *
  176405. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176406. maximum_space += (long) sptr->rows_in_array *
  176407. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176408. }
  176409. }
  176410. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176411. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176412. space_per_minheight += (long) bptr->maxaccess *
  176413. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176414. maximum_space += (long) bptr->rows_in_array *
  176415. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176416. }
  176417. }
  176418. if (space_per_minheight <= 0)
  176419. return; /* no unrealized arrays, no work */
  176420. /* Determine amount of memory to actually use; this is system-dependent. */
  176421. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176422. mem->total_space_allocated);
  176423. /* If the maximum space needed is available, make all the buffers full
  176424. * height; otherwise parcel it out with the same number of minheights
  176425. * in each buffer.
  176426. */
  176427. if (avail_mem >= maximum_space)
  176428. max_minheights = 1000000000L;
  176429. else {
  176430. max_minheights = avail_mem / space_per_minheight;
  176431. /* If there doesn't seem to be enough space, try to get the minimum
  176432. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176433. */
  176434. if (max_minheights <= 0)
  176435. max_minheights = 1;
  176436. }
  176437. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176438. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176439. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176440. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176441. if (minheights <= max_minheights) {
  176442. /* This buffer fits in memory */
  176443. sptr->rows_in_mem = sptr->rows_in_array;
  176444. } else {
  176445. /* It doesn't fit in memory, create backing store. */
  176446. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176447. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176448. (long) sptr->rows_in_array *
  176449. (long) sptr->samplesperrow *
  176450. (long) SIZEOF(JSAMPLE));
  176451. sptr->b_s_open = TRUE;
  176452. }
  176453. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176454. sptr->samplesperrow, sptr->rows_in_mem);
  176455. sptr->rowsperchunk = mem->last_rowsperchunk;
  176456. sptr->cur_start_row = 0;
  176457. sptr->first_undef_row = 0;
  176458. sptr->dirty = FALSE;
  176459. }
  176460. }
  176461. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176462. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176463. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176464. if (minheights <= max_minheights) {
  176465. /* This buffer fits in memory */
  176466. bptr->rows_in_mem = bptr->rows_in_array;
  176467. } else {
  176468. /* It doesn't fit in memory, create backing store. */
  176469. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176470. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176471. (long) bptr->rows_in_array *
  176472. (long) bptr->blocksperrow *
  176473. (long) SIZEOF(JBLOCK));
  176474. bptr->b_s_open = TRUE;
  176475. }
  176476. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176477. bptr->blocksperrow, bptr->rows_in_mem);
  176478. bptr->rowsperchunk = mem->last_rowsperchunk;
  176479. bptr->cur_start_row = 0;
  176480. bptr->first_undef_row = 0;
  176481. bptr->dirty = FALSE;
  176482. }
  176483. }
  176484. }
  176485. LOCAL(void)
  176486. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176487. /* Do backing store read or write of a virtual sample array */
  176488. {
  176489. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176490. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176491. file_offset = ptr->cur_start_row * bytesperrow;
  176492. /* Loop to read or write each allocation chunk in mem_buffer */
  176493. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176494. /* One chunk, but check for short chunk at end of buffer */
  176495. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176496. /* Transfer no more than is currently defined */
  176497. thisrow = (long) ptr->cur_start_row + i;
  176498. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176499. /* Transfer no more than fits in file */
  176500. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176501. if (rows <= 0) /* this chunk might be past end of file! */
  176502. break;
  176503. byte_count = rows * bytesperrow;
  176504. if (writing)
  176505. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176506. (void FAR *) ptr->mem_buffer[i],
  176507. file_offset, byte_count);
  176508. else
  176509. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176510. (void FAR *) ptr->mem_buffer[i],
  176511. file_offset, byte_count);
  176512. file_offset += byte_count;
  176513. }
  176514. }
  176515. LOCAL(void)
  176516. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176517. /* Do backing store read or write of a virtual coefficient-block array */
  176518. {
  176519. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176520. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176521. file_offset = ptr->cur_start_row * bytesperrow;
  176522. /* Loop to read or write each allocation chunk in mem_buffer */
  176523. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176524. /* One chunk, but check for short chunk at end of buffer */
  176525. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176526. /* Transfer no more than is currently defined */
  176527. thisrow = (long) ptr->cur_start_row + i;
  176528. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176529. /* Transfer no more than fits in file */
  176530. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176531. if (rows <= 0) /* this chunk might be past end of file! */
  176532. break;
  176533. byte_count = rows * bytesperrow;
  176534. if (writing)
  176535. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176536. (void FAR *) ptr->mem_buffer[i],
  176537. file_offset, byte_count);
  176538. else
  176539. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176540. (void FAR *) ptr->mem_buffer[i],
  176541. file_offset, byte_count);
  176542. file_offset += byte_count;
  176543. }
  176544. }
  176545. METHODDEF(JSAMPARRAY)
  176546. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176547. JDIMENSION start_row, JDIMENSION num_rows,
  176548. boolean writable)
  176549. /* Access the part of a virtual sample array starting at start_row */
  176550. /* and extending for num_rows rows. writable is true if */
  176551. /* caller intends to modify the accessed area. */
  176552. {
  176553. JDIMENSION end_row = start_row + num_rows;
  176554. JDIMENSION undef_row;
  176555. /* debugging check */
  176556. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176557. ptr->mem_buffer == NULL)
  176558. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176559. /* Make the desired part of the virtual array accessible */
  176560. if (start_row < ptr->cur_start_row ||
  176561. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176562. if (! ptr->b_s_open)
  176563. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176564. /* Flush old buffer contents if necessary */
  176565. if (ptr->dirty) {
  176566. do_sarray_io(cinfo, ptr, TRUE);
  176567. ptr->dirty = FALSE;
  176568. }
  176569. /* Decide what part of virtual array to access.
  176570. * Algorithm: if target address > current window, assume forward scan,
  176571. * load starting at target address. If target address < current window,
  176572. * assume backward scan, load so that target area is top of window.
  176573. * Note that when switching from forward write to forward read, will have
  176574. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176575. */
  176576. if (start_row > ptr->cur_start_row) {
  176577. ptr->cur_start_row = start_row;
  176578. } else {
  176579. /* use long arithmetic here to avoid overflow & unsigned problems */
  176580. long ltemp;
  176581. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176582. if (ltemp < 0)
  176583. ltemp = 0; /* don't fall off front end of file */
  176584. ptr->cur_start_row = (JDIMENSION) ltemp;
  176585. }
  176586. /* Read in the selected part of the array.
  176587. * During the initial write pass, we will do no actual read
  176588. * because the selected part is all undefined.
  176589. */
  176590. do_sarray_io(cinfo, ptr, FALSE);
  176591. }
  176592. /* Ensure the accessed part of the array is defined; prezero if needed.
  176593. * To improve locality of access, we only prezero the part of the array
  176594. * that the caller is about to access, not the entire in-memory array.
  176595. */
  176596. if (ptr->first_undef_row < end_row) {
  176597. if (ptr->first_undef_row < start_row) {
  176598. if (writable) /* writer skipped over a section of array */
  176599. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176600. undef_row = start_row; /* but reader is allowed to read ahead */
  176601. } else {
  176602. undef_row = ptr->first_undef_row;
  176603. }
  176604. if (writable)
  176605. ptr->first_undef_row = end_row;
  176606. if (ptr->pre_zero) {
  176607. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176608. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176609. end_row -= ptr->cur_start_row;
  176610. while (undef_row < end_row) {
  176611. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176612. undef_row++;
  176613. }
  176614. } else {
  176615. if (! writable) /* reader looking at undefined data */
  176616. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176617. }
  176618. }
  176619. /* Flag the buffer dirty if caller will write in it */
  176620. if (writable)
  176621. ptr->dirty = TRUE;
  176622. /* Return address of proper part of the buffer */
  176623. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176624. }
  176625. METHODDEF(JBLOCKARRAY)
  176626. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176627. JDIMENSION start_row, JDIMENSION num_rows,
  176628. boolean writable)
  176629. /* Access the part of a virtual block array starting at start_row */
  176630. /* and extending for num_rows rows. writable is true if */
  176631. /* caller intends to modify the accessed area. */
  176632. {
  176633. JDIMENSION end_row = start_row + num_rows;
  176634. JDIMENSION undef_row;
  176635. /* debugging check */
  176636. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176637. ptr->mem_buffer == NULL)
  176638. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176639. /* Make the desired part of the virtual array accessible */
  176640. if (start_row < ptr->cur_start_row ||
  176641. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176642. if (! ptr->b_s_open)
  176643. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176644. /* Flush old buffer contents if necessary */
  176645. if (ptr->dirty) {
  176646. do_barray_io(cinfo, ptr, TRUE);
  176647. ptr->dirty = FALSE;
  176648. }
  176649. /* Decide what part of virtual array to access.
  176650. * Algorithm: if target address > current window, assume forward scan,
  176651. * load starting at target address. If target address < current window,
  176652. * assume backward scan, load so that target area is top of window.
  176653. * Note that when switching from forward write to forward read, will have
  176654. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176655. */
  176656. if (start_row > ptr->cur_start_row) {
  176657. ptr->cur_start_row = start_row;
  176658. } else {
  176659. /* use long arithmetic here to avoid overflow & unsigned problems */
  176660. long ltemp;
  176661. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176662. if (ltemp < 0)
  176663. ltemp = 0; /* don't fall off front end of file */
  176664. ptr->cur_start_row = (JDIMENSION) ltemp;
  176665. }
  176666. /* Read in the selected part of the array.
  176667. * During the initial write pass, we will do no actual read
  176668. * because the selected part is all undefined.
  176669. */
  176670. do_barray_io(cinfo, ptr, FALSE);
  176671. }
  176672. /* Ensure the accessed part of the array is defined; prezero if needed.
  176673. * To improve locality of access, we only prezero the part of the array
  176674. * that the caller is about to access, not the entire in-memory array.
  176675. */
  176676. if (ptr->first_undef_row < end_row) {
  176677. if (ptr->first_undef_row < start_row) {
  176678. if (writable) /* writer skipped over a section of array */
  176679. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176680. undef_row = start_row; /* but reader is allowed to read ahead */
  176681. } else {
  176682. undef_row = ptr->first_undef_row;
  176683. }
  176684. if (writable)
  176685. ptr->first_undef_row = end_row;
  176686. if (ptr->pre_zero) {
  176687. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176688. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176689. end_row -= ptr->cur_start_row;
  176690. while (undef_row < end_row) {
  176691. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176692. undef_row++;
  176693. }
  176694. } else {
  176695. if (! writable) /* reader looking at undefined data */
  176696. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176697. }
  176698. }
  176699. /* Flag the buffer dirty if caller will write in it */
  176700. if (writable)
  176701. ptr->dirty = TRUE;
  176702. /* Return address of proper part of the buffer */
  176703. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176704. }
  176705. /*
  176706. * Release all objects belonging to a specified pool.
  176707. */
  176708. METHODDEF(void)
  176709. free_pool (j_common_ptr cinfo, int pool_id)
  176710. {
  176711. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176712. small_pool_ptr shdr_ptr;
  176713. large_pool_ptr lhdr_ptr;
  176714. size_t space_freed;
  176715. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176716. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176717. #ifdef MEM_STATS
  176718. if (cinfo->err->trace_level > 1)
  176719. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176720. #endif
  176721. /* If freeing IMAGE pool, close any virtual arrays first */
  176722. if (pool_id == JPOOL_IMAGE) {
  176723. jvirt_sarray_ptr sptr;
  176724. jvirt_barray_ptr bptr;
  176725. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176726. if (sptr->b_s_open) { /* there may be no backing store */
  176727. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176728. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176729. }
  176730. }
  176731. mem->virt_sarray_list = NULL;
  176732. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176733. if (bptr->b_s_open) { /* there may be no backing store */
  176734. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176735. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176736. }
  176737. }
  176738. mem->virt_barray_list = NULL;
  176739. }
  176740. /* Release large objects */
  176741. lhdr_ptr = mem->large_list[pool_id];
  176742. mem->large_list[pool_id] = NULL;
  176743. while (lhdr_ptr != NULL) {
  176744. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176745. space_freed = lhdr_ptr->hdr.bytes_used +
  176746. lhdr_ptr->hdr.bytes_left +
  176747. SIZEOF(large_pool_hdr);
  176748. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176749. mem->total_space_allocated -= space_freed;
  176750. lhdr_ptr = next_lhdr_ptr;
  176751. }
  176752. /* Release small objects */
  176753. shdr_ptr = mem->small_list[pool_id];
  176754. mem->small_list[pool_id] = NULL;
  176755. while (shdr_ptr != NULL) {
  176756. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176757. space_freed = shdr_ptr->hdr.bytes_used +
  176758. shdr_ptr->hdr.bytes_left +
  176759. SIZEOF(small_pool_hdr);
  176760. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176761. mem->total_space_allocated -= space_freed;
  176762. shdr_ptr = next_shdr_ptr;
  176763. }
  176764. }
  176765. /*
  176766. * Close up shop entirely.
  176767. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176768. */
  176769. METHODDEF(void)
  176770. self_destruct (j_common_ptr cinfo)
  176771. {
  176772. int pool;
  176773. /* Close all backing store, release all memory.
  176774. * Releasing pools in reverse order might help avoid fragmentation
  176775. * with some (brain-damaged) malloc libraries.
  176776. */
  176777. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176778. free_pool(cinfo, pool);
  176779. }
  176780. /* Release the memory manager control block too. */
  176781. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176782. cinfo->mem = NULL; /* ensures I will be called only once */
  176783. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176784. }
  176785. /*
  176786. * Memory manager initialization.
  176787. * When this is called, only the error manager pointer is valid in cinfo!
  176788. */
  176789. GLOBAL(void)
  176790. jinit_memory_mgr (j_common_ptr cinfo)
  176791. {
  176792. my_mem_ptr mem;
  176793. long max_to_use;
  176794. int pool;
  176795. size_t test_mac;
  176796. cinfo->mem = NULL; /* for safety if init fails */
  176797. /* Check for configuration errors.
  176798. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176799. * doesn't reflect any real hardware alignment requirement.
  176800. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176801. * in common if and only if X is a power of 2, ie has only one one-bit.
  176802. * Some compilers may give an "unreachable code" warning here; ignore it.
  176803. */
  176804. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176805. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176806. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176807. * a multiple of SIZEOF(ALIGN_TYPE).
  176808. * Again, an "unreachable code" warning may be ignored here.
  176809. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176810. */
  176811. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176812. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176813. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176814. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176815. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176816. /* Attempt to allocate memory manager's control block */
  176817. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176818. if (mem == NULL) {
  176819. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176820. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176821. }
  176822. /* OK, fill in the method pointers */
  176823. mem->pub.alloc_small = alloc_small;
  176824. mem->pub.alloc_large = alloc_large;
  176825. mem->pub.alloc_sarray = alloc_sarray;
  176826. mem->pub.alloc_barray = alloc_barray;
  176827. mem->pub.request_virt_sarray = request_virt_sarray;
  176828. mem->pub.request_virt_barray = request_virt_barray;
  176829. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176830. mem->pub.access_virt_sarray = access_virt_sarray;
  176831. mem->pub.access_virt_barray = access_virt_barray;
  176832. mem->pub.free_pool = free_pool;
  176833. mem->pub.self_destruct = self_destruct;
  176834. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176835. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176836. /* Initialize working state */
  176837. mem->pub.max_memory_to_use = max_to_use;
  176838. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176839. mem->small_list[pool] = NULL;
  176840. mem->large_list[pool] = NULL;
  176841. }
  176842. mem->virt_sarray_list = NULL;
  176843. mem->virt_barray_list = NULL;
  176844. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176845. /* Declare ourselves open for business */
  176846. cinfo->mem = & mem->pub;
  176847. /* Check for an environment variable JPEGMEM; if found, override the
  176848. * default max_memory setting from jpeg_mem_init. Note that the
  176849. * surrounding application may again override this value.
  176850. * If your system doesn't support getenv(), define NO_GETENV to disable
  176851. * this feature.
  176852. */
  176853. #ifndef NO_GETENV
  176854. { char * memenv;
  176855. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176856. char ch = 'x';
  176857. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176858. if (ch == 'm' || ch == 'M')
  176859. max_to_use *= 1000L;
  176860. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176861. }
  176862. }
  176863. }
  176864. #endif
  176865. }
  176866. /*** End of inlined file: jmemmgr.c ***/
  176867. /*** Start of inlined file: jmemnobs.c ***/
  176868. #define JPEG_INTERNALS
  176869. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176870. extern void * malloc JPP((size_t size));
  176871. extern void free JPP((void *ptr));
  176872. #endif
  176873. /*
  176874. * Memory allocation and freeing are controlled by the regular library
  176875. * routines malloc() and free().
  176876. */
  176877. GLOBAL(void *)
  176878. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176879. {
  176880. return (void *) malloc(sizeofobject);
  176881. }
  176882. GLOBAL(void)
  176883. jpeg_free_small (j_common_ptr , void * object, size_t)
  176884. {
  176885. free(object);
  176886. }
  176887. /*
  176888. * "Large" objects are treated the same as "small" ones.
  176889. * NB: although we include FAR keywords in the routine declarations,
  176890. * this file won't actually work in 80x86 small/medium model; at least,
  176891. * you probably won't be able to process useful-size images in only 64KB.
  176892. */
  176893. GLOBAL(void FAR *)
  176894. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176895. {
  176896. return (void FAR *) malloc(sizeofobject);
  176897. }
  176898. GLOBAL(void)
  176899. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176900. {
  176901. free(object);
  176902. }
  176903. /*
  176904. * This routine computes the total memory space available for allocation.
  176905. * Here we always say, "we got all you want bud!"
  176906. */
  176907. GLOBAL(long)
  176908. jpeg_mem_available (j_common_ptr, long,
  176909. long max_bytes_needed, long)
  176910. {
  176911. return max_bytes_needed;
  176912. }
  176913. /*
  176914. * Backing store (temporary file) management.
  176915. * Since jpeg_mem_available always promised the moon,
  176916. * this should never be called and we can just error out.
  176917. */
  176918. GLOBAL(void)
  176919. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176920. long )
  176921. {
  176922. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176923. }
  176924. /*
  176925. * These routines take care of any system-dependent initialization and
  176926. * cleanup required. Here, there isn't any.
  176927. */
  176928. GLOBAL(long)
  176929. jpeg_mem_init (j_common_ptr)
  176930. {
  176931. return 0; /* just set max_memory_to_use to 0 */
  176932. }
  176933. GLOBAL(void)
  176934. jpeg_mem_term (j_common_ptr)
  176935. {
  176936. /* no work */
  176937. }
  176938. /*** End of inlined file: jmemnobs.c ***/
  176939. /*** Start of inlined file: jquant1.c ***/
  176940. #define JPEG_INTERNALS
  176941. #ifdef QUANT_1PASS_SUPPORTED
  176942. /*
  176943. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176944. * high quality, colormapped output capability. A 2-pass quantizer usually
  176945. * gives better visual quality; however, for quantized grayscale output this
  176946. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176947. * quantizer, though you can turn it off if you really want to.
  176948. *
  176949. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176950. * image. We use a map consisting of all combinations of Ncolors[i] color
  176951. * values for the i'th component. The Ncolors[] values are chosen so that
  176952. * their product, the total number of colors, is no more than that requested.
  176953. * (In most cases, the product will be somewhat less.)
  176954. *
  176955. * Since the colormap is orthogonal, the representative value for each color
  176956. * component can be determined without considering the other components;
  176957. * then these indexes can be combined into a colormap index by a standard
  176958. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176959. * can be precalculated and stored in the lookup table colorindex[].
  176960. * colorindex[i][j] maps pixel value j in component i to the nearest
  176961. * representative value (grid plane) for that component; this index is
  176962. * multiplied by the array stride for component i, so that the
  176963. * index of the colormap entry closest to a given pixel value is just
  176964. * sum( colorindex[component-number][pixel-component-value] )
  176965. * Aside from being fast, this scheme allows for variable spacing between
  176966. * representative values with no additional lookup cost.
  176967. *
  176968. * If gamma correction has been applied in color conversion, it might be wise
  176969. * to adjust the color grid spacing so that the representative colors are
  176970. * equidistant in linear space. At this writing, gamma correction is not
  176971. * implemented by jdcolor, so nothing is done here.
  176972. */
  176973. /* Declarations for ordered dithering.
  176974. *
  176975. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176976. * dithering is described in many references, for instance Dale Schumacher's
  176977. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176978. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176979. * "dither" value to the input pixel and then round the result to the nearest
  176980. * output value. The dither value is equivalent to (0.5 - threshold) times
  176981. * the distance between output values. For ordered dithering, we assume that
  176982. * the output colors are equally spaced; if not, results will probably be
  176983. * worse, since the dither may be too much or too little at a given point.
  176984. *
  176985. * The normal calculation would be to form pixel value + dither, range-limit
  176986. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176987. * We can skip the separate range-limiting step by extending the colorindex
  176988. * table in both directions.
  176989. */
  176990. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176991. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176992. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176993. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176994. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176995. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176996. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176997. /* Bayer's order-4 dither array. Generated by the code given in
  176998. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176999. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177000. */
  177001. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177002. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177003. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177004. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177005. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177006. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177007. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177008. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177009. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177010. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177011. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177012. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177013. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177014. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177015. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177016. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177017. };
  177018. /* Declarations for Floyd-Steinberg dithering.
  177019. *
  177020. * Errors are accumulated into the array fserrors[], at a resolution of
  177021. * 1/16th of a pixel count. The error at a given pixel is propagated
  177022. * to its not-yet-processed neighbors using the standard F-S fractions,
  177023. * ... (here) 7/16
  177024. * 3/16 5/16 1/16
  177025. * We work left-to-right on even rows, right-to-left on odd rows.
  177026. *
  177027. * We can get away with a single array (holding one row's worth of errors)
  177028. * by using it to store the current row's errors at pixel columns not yet
  177029. * processed, but the next row's errors at columns already processed. We
  177030. * need only a few extra variables to hold the errors immediately around the
  177031. * current column. (If we are lucky, those variables are in registers, but
  177032. * even if not, they're probably cheaper to access than array elements are.)
  177033. *
  177034. * The fserrors[] array is indexed [component#][position].
  177035. * We provide (#columns + 2) entries per component; the extra entry at each
  177036. * end saves us from special-casing the first and last pixels.
  177037. *
  177038. * Note: on a wide image, we might not have enough room in a PC's near data
  177039. * segment to hold the error array; so it is allocated with alloc_large.
  177040. */
  177041. #if BITS_IN_JSAMPLE == 8
  177042. typedef INT16 FSERROR; /* 16 bits should be enough */
  177043. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177044. #else
  177045. typedef INT32 FSERROR; /* may need more than 16 bits */
  177046. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177047. #endif
  177048. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177049. /* Private subobject */
  177050. #define MAX_Q_COMPS 4 /* max components I can handle */
  177051. typedef struct {
  177052. struct jpeg_color_quantizer pub; /* public fields */
  177053. /* Initially allocated colormap is saved here */
  177054. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177055. int sv_actual; /* number of entries in use */
  177056. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177057. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177058. * premultiplied as described above. Since colormap indexes must fit into
  177059. * JSAMPLEs, the entries of this array will too.
  177060. */
  177061. boolean is_padded; /* is the colorindex padded for odither? */
  177062. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177063. /* Variables for ordered dithering */
  177064. int row_index; /* cur row's vertical index in dither matrix */
  177065. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177066. /* Variables for Floyd-Steinberg dithering */
  177067. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177068. boolean on_odd_row; /* flag to remember which row we are on */
  177069. } my_cquantizer;
  177070. typedef my_cquantizer * my_cquantize_ptr;
  177071. /*
  177072. * Policy-making subroutines for create_colormap and create_colorindex.
  177073. * These routines determine the colormap to be used. The rest of the module
  177074. * only assumes that the colormap is orthogonal.
  177075. *
  177076. * * select_ncolors decides how to divvy up the available colors
  177077. * among the components.
  177078. * * output_value defines the set of representative values for a component.
  177079. * * largest_input_value defines the mapping from input values to
  177080. * representative values for a component.
  177081. * Note that the latter two routines may impose different policies for
  177082. * different components, though this is not currently done.
  177083. */
  177084. LOCAL(int)
  177085. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177086. /* Determine allocation of desired colors to components, */
  177087. /* and fill in Ncolors[] array to indicate choice. */
  177088. /* Return value is total number of colors (product of Ncolors[] values). */
  177089. {
  177090. int nc = cinfo->out_color_components; /* number of color components */
  177091. int max_colors = cinfo->desired_number_of_colors;
  177092. int total_colors, iroot, i, j;
  177093. boolean changed;
  177094. long temp;
  177095. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177096. /* We can allocate at least the nc'th root of max_colors per component. */
  177097. /* Compute floor(nc'th root of max_colors). */
  177098. iroot = 1;
  177099. do {
  177100. iroot++;
  177101. temp = iroot; /* set temp = iroot ** nc */
  177102. for (i = 1; i < nc; i++)
  177103. temp *= iroot;
  177104. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177105. iroot--; /* now iroot = floor(root) */
  177106. /* Must have at least 2 color values per component */
  177107. if (iroot < 2)
  177108. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177109. /* Initialize to iroot color values for each component */
  177110. total_colors = 1;
  177111. for (i = 0; i < nc; i++) {
  177112. Ncolors[i] = iroot;
  177113. total_colors *= iroot;
  177114. }
  177115. /* We may be able to increment the count for one or more components without
  177116. * exceeding max_colors, though we know not all can be incremented.
  177117. * Sometimes, the first component can be incremented more than once!
  177118. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177119. * In RGB colorspace, try to increment G first, then R, then B.
  177120. */
  177121. do {
  177122. changed = FALSE;
  177123. for (i = 0; i < nc; i++) {
  177124. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177125. /* calculate new total_colors if Ncolors[j] is incremented */
  177126. temp = total_colors / Ncolors[j];
  177127. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177128. if (temp > (long) max_colors)
  177129. break; /* won't fit, done with this pass */
  177130. Ncolors[j]++; /* OK, apply the increment */
  177131. total_colors = (int) temp;
  177132. changed = TRUE;
  177133. }
  177134. } while (changed);
  177135. return total_colors;
  177136. }
  177137. LOCAL(int)
  177138. output_value (j_decompress_ptr, int, int j, int maxj)
  177139. /* Return j'th output value, where j will range from 0 to maxj */
  177140. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177141. {
  177142. /* We always provide values 0 and MAXJSAMPLE for each component;
  177143. * any additional values are equally spaced between these limits.
  177144. * (Forcing the upper and lower values to the limits ensures that
  177145. * dithering can't produce a color outside the selected gamut.)
  177146. */
  177147. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177148. }
  177149. LOCAL(int)
  177150. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177151. /* Return largest input value that should map to j'th output value */
  177152. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177153. {
  177154. /* Breakpoints are halfway between values returned by output_value */
  177155. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177156. }
  177157. /*
  177158. * Create the colormap.
  177159. */
  177160. LOCAL(void)
  177161. create_colormap (j_decompress_ptr cinfo)
  177162. {
  177163. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177164. JSAMPARRAY colormap; /* Created colormap */
  177165. int total_colors; /* Number of distinct output colors */
  177166. int i,j,k, nci, blksize, blkdist, ptr, val;
  177167. /* Select number of colors for each component */
  177168. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177169. /* Report selected color counts */
  177170. if (cinfo->out_color_components == 3)
  177171. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177172. total_colors, cquantize->Ncolors[0],
  177173. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177174. else
  177175. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177176. /* Allocate and fill in the colormap. */
  177177. /* The colors are ordered in the map in standard row-major order, */
  177178. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177179. colormap = (*cinfo->mem->alloc_sarray)
  177180. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177181. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177182. /* blksize is number of adjacent repeated entries for a component */
  177183. /* blkdist is distance between groups of identical entries for a component */
  177184. blkdist = total_colors;
  177185. for (i = 0; i < cinfo->out_color_components; i++) {
  177186. /* fill in colormap entries for i'th color component */
  177187. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177188. blksize = blkdist / nci;
  177189. for (j = 0; j < nci; j++) {
  177190. /* Compute j'th output value (out of nci) for component */
  177191. val = output_value(cinfo, i, j, nci-1);
  177192. /* Fill in all colormap entries that have this value of this component */
  177193. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177194. /* fill in blksize entries beginning at ptr */
  177195. for (k = 0; k < blksize; k++)
  177196. colormap[i][ptr+k] = (JSAMPLE) val;
  177197. }
  177198. }
  177199. blkdist = blksize; /* blksize of this color is blkdist of next */
  177200. }
  177201. /* Save the colormap in private storage,
  177202. * where it will survive color quantization mode changes.
  177203. */
  177204. cquantize->sv_colormap = colormap;
  177205. cquantize->sv_actual = total_colors;
  177206. }
  177207. /*
  177208. * Create the color index table.
  177209. */
  177210. LOCAL(void)
  177211. create_colorindex (j_decompress_ptr cinfo)
  177212. {
  177213. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177214. JSAMPROW indexptr;
  177215. int i,j,k, nci, blksize, val, pad;
  177216. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177217. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177218. * This is not necessary in the other dithering modes. However, we
  177219. * flag whether it was done in case user changes dithering mode.
  177220. */
  177221. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177222. pad = MAXJSAMPLE*2;
  177223. cquantize->is_padded = TRUE;
  177224. } else {
  177225. pad = 0;
  177226. cquantize->is_padded = FALSE;
  177227. }
  177228. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177229. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177230. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177231. (JDIMENSION) cinfo->out_color_components);
  177232. /* blksize is number of adjacent repeated entries for a component */
  177233. blksize = cquantize->sv_actual;
  177234. for (i = 0; i < cinfo->out_color_components; i++) {
  177235. /* fill in colorindex entries for i'th color component */
  177236. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177237. blksize = blksize / nci;
  177238. /* adjust colorindex pointers to provide padding at negative indexes. */
  177239. if (pad)
  177240. cquantize->colorindex[i] += MAXJSAMPLE;
  177241. /* in loop, val = index of current output value, */
  177242. /* and k = largest j that maps to current val */
  177243. indexptr = cquantize->colorindex[i];
  177244. val = 0;
  177245. k = largest_input_value(cinfo, i, 0, nci-1);
  177246. for (j = 0; j <= MAXJSAMPLE; j++) {
  177247. while (j > k) /* advance val if past boundary */
  177248. k = largest_input_value(cinfo, i, ++val, nci-1);
  177249. /* premultiply so that no multiplication needed in main processing */
  177250. indexptr[j] = (JSAMPLE) (val * blksize);
  177251. }
  177252. /* Pad at both ends if necessary */
  177253. if (pad)
  177254. for (j = 1; j <= MAXJSAMPLE; j++) {
  177255. indexptr[-j] = indexptr[0];
  177256. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177257. }
  177258. }
  177259. }
  177260. /*
  177261. * Create an ordered-dither array for a component having ncolors
  177262. * distinct output values.
  177263. */
  177264. LOCAL(ODITHER_MATRIX_PTR)
  177265. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177266. {
  177267. ODITHER_MATRIX_PTR odither;
  177268. int j,k;
  177269. INT32 num,den;
  177270. odither = (ODITHER_MATRIX_PTR)
  177271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177272. SIZEOF(ODITHER_MATRIX));
  177273. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177274. * Hence the dither value for the matrix cell with fill order f
  177275. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177276. * On 16-bit-int machine, be careful to avoid overflow.
  177277. */
  177278. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177279. for (j = 0; j < ODITHER_SIZE; j++) {
  177280. for (k = 0; k < ODITHER_SIZE; k++) {
  177281. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177282. * MAXJSAMPLE;
  177283. /* Ensure round towards zero despite C's lack of consistency
  177284. * about rounding negative values in integer division...
  177285. */
  177286. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177287. }
  177288. }
  177289. return odither;
  177290. }
  177291. /*
  177292. * Create the ordered-dither tables.
  177293. * Components having the same number of representative colors may
  177294. * share a dither table.
  177295. */
  177296. LOCAL(void)
  177297. create_odither_tables (j_decompress_ptr cinfo)
  177298. {
  177299. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177300. ODITHER_MATRIX_PTR odither;
  177301. int i, j, nci;
  177302. for (i = 0; i < cinfo->out_color_components; i++) {
  177303. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177304. odither = NULL; /* search for matching prior component */
  177305. for (j = 0; j < i; j++) {
  177306. if (nci == cquantize->Ncolors[j]) {
  177307. odither = cquantize->odither[j];
  177308. break;
  177309. }
  177310. }
  177311. if (odither == NULL) /* need a new table? */
  177312. odither = make_odither_array(cinfo, nci);
  177313. cquantize->odither[i] = odither;
  177314. }
  177315. }
  177316. /*
  177317. * Map some rows of pixels to the output colormapped representation.
  177318. */
  177319. METHODDEF(void)
  177320. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177321. JSAMPARRAY output_buf, int num_rows)
  177322. /* General case, no dithering */
  177323. {
  177324. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177325. JSAMPARRAY colorindex = cquantize->colorindex;
  177326. register int pixcode, ci;
  177327. register JSAMPROW ptrin, ptrout;
  177328. int row;
  177329. JDIMENSION col;
  177330. JDIMENSION width = cinfo->output_width;
  177331. register int nc = cinfo->out_color_components;
  177332. for (row = 0; row < num_rows; row++) {
  177333. ptrin = input_buf[row];
  177334. ptrout = output_buf[row];
  177335. for (col = width; col > 0; col--) {
  177336. pixcode = 0;
  177337. for (ci = 0; ci < nc; ci++) {
  177338. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177339. }
  177340. *ptrout++ = (JSAMPLE) pixcode;
  177341. }
  177342. }
  177343. }
  177344. METHODDEF(void)
  177345. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177346. JSAMPARRAY output_buf, int num_rows)
  177347. /* Fast path for out_color_components==3, no dithering */
  177348. {
  177349. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177350. register int pixcode;
  177351. register JSAMPROW ptrin, ptrout;
  177352. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177353. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177354. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177355. int row;
  177356. JDIMENSION col;
  177357. JDIMENSION width = cinfo->output_width;
  177358. for (row = 0; row < num_rows; row++) {
  177359. ptrin = input_buf[row];
  177360. ptrout = output_buf[row];
  177361. for (col = width; col > 0; col--) {
  177362. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177363. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177364. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177365. *ptrout++ = (JSAMPLE) pixcode;
  177366. }
  177367. }
  177368. }
  177369. METHODDEF(void)
  177370. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177371. JSAMPARRAY output_buf, int num_rows)
  177372. /* General case, with ordered dithering */
  177373. {
  177374. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177375. register JSAMPROW input_ptr;
  177376. register JSAMPROW output_ptr;
  177377. JSAMPROW colorindex_ci;
  177378. int * dither; /* points to active row of dither matrix */
  177379. int row_index, col_index; /* current indexes into dither matrix */
  177380. int nc = cinfo->out_color_components;
  177381. int ci;
  177382. int row;
  177383. JDIMENSION col;
  177384. JDIMENSION width = cinfo->output_width;
  177385. for (row = 0; row < num_rows; row++) {
  177386. /* Initialize output values to 0 so can process components separately */
  177387. jzero_far((void FAR *) output_buf[row],
  177388. (size_t) (width * SIZEOF(JSAMPLE)));
  177389. row_index = cquantize->row_index;
  177390. for (ci = 0; ci < nc; ci++) {
  177391. input_ptr = input_buf[row] + ci;
  177392. output_ptr = output_buf[row];
  177393. colorindex_ci = cquantize->colorindex[ci];
  177394. dither = cquantize->odither[ci][row_index];
  177395. col_index = 0;
  177396. for (col = width; col > 0; col--) {
  177397. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177398. * select output value, accumulate into output code for this pixel.
  177399. * Range-limiting need not be done explicitly, as we have extended
  177400. * the colorindex table to produce the right answers for out-of-range
  177401. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177402. * required amount of padding.
  177403. */
  177404. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177405. input_ptr += nc;
  177406. output_ptr++;
  177407. col_index = (col_index + 1) & ODITHER_MASK;
  177408. }
  177409. }
  177410. /* Advance row index for next row */
  177411. row_index = (row_index + 1) & ODITHER_MASK;
  177412. cquantize->row_index = row_index;
  177413. }
  177414. }
  177415. METHODDEF(void)
  177416. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177417. JSAMPARRAY output_buf, int num_rows)
  177418. /* Fast path for out_color_components==3, with ordered dithering */
  177419. {
  177420. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177421. register int pixcode;
  177422. register JSAMPROW input_ptr;
  177423. register JSAMPROW output_ptr;
  177424. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177425. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177426. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177427. int * dither0; /* points to active row of dither matrix */
  177428. int * dither1;
  177429. int * dither2;
  177430. int row_index, col_index; /* current indexes into dither matrix */
  177431. int row;
  177432. JDIMENSION col;
  177433. JDIMENSION width = cinfo->output_width;
  177434. for (row = 0; row < num_rows; row++) {
  177435. row_index = cquantize->row_index;
  177436. input_ptr = input_buf[row];
  177437. output_ptr = output_buf[row];
  177438. dither0 = cquantize->odither[0][row_index];
  177439. dither1 = cquantize->odither[1][row_index];
  177440. dither2 = cquantize->odither[2][row_index];
  177441. col_index = 0;
  177442. for (col = width; col > 0; col--) {
  177443. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177444. dither0[col_index]]);
  177445. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177446. dither1[col_index]]);
  177447. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177448. dither2[col_index]]);
  177449. *output_ptr++ = (JSAMPLE) pixcode;
  177450. col_index = (col_index + 1) & ODITHER_MASK;
  177451. }
  177452. row_index = (row_index + 1) & ODITHER_MASK;
  177453. cquantize->row_index = row_index;
  177454. }
  177455. }
  177456. METHODDEF(void)
  177457. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177458. JSAMPARRAY output_buf, int num_rows)
  177459. /* General case, with Floyd-Steinberg dithering */
  177460. {
  177461. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177462. register LOCFSERROR cur; /* current error or pixel value */
  177463. LOCFSERROR belowerr; /* error for pixel below cur */
  177464. LOCFSERROR bpreverr; /* error for below/prev col */
  177465. LOCFSERROR bnexterr; /* error for below/next col */
  177466. LOCFSERROR delta;
  177467. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177468. register JSAMPROW input_ptr;
  177469. register JSAMPROW output_ptr;
  177470. JSAMPROW colorindex_ci;
  177471. JSAMPROW colormap_ci;
  177472. int pixcode;
  177473. int nc = cinfo->out_color_components;
  177474. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177475. int dirnc; /* dir * nc */
  177476. int ci;
  177477. int row;
  177478. JDIMENSION col;
  177479. JDIMENSION width = cinfo->output_width;
  177480. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177481. SHIFT_TEMPS
  177482. for (row = 0; row < num_rows; row++) {
  177483. /* Initialize output values to 0 so can process components separately */
  177484. jzero_far((void FAR *) output_buf[row],
  177485. (size_t) (width * SIZEOF(JSAMPLE)));
  177486. for (ci = 0; ci < nc; ci++) {
  177487. input_ptr = input_buf[row] + ci;
  177488. output_ptr = output_buf[row];
  177489. if (cquantize->on_odd_row) {
  177490. /* work right to left in this row */
  177491. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177492. output_ptr += width-1;
  177493. dir = -1;
  177494. dirnc = -nc;
  177495. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177496. } else {
  177497. /* work left to right in this row */
  177498. dir = 1;
  177499. dirnc = nc;
  177500. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177501. }
  177502. colorindex_ci = cquantize->colorindex[ci];
  177503. colormap_ci = cquantize->sv_colormap[ci];
  177504. /* Preset error values: no error propagated to first pixel from left */
  177505. cur = 0;
  177506. /* and no error propagated to row below yet */
  177507. belowerr = bpreverr = 0;
  177508. for (col = width; col > 0; col--) {
  177509. /* cur holds the error propagated from the previous pixel on the
  177510. * current line. Add the error propagated from the previous line
  177511. * to form the complete error correction term for this pixel, and
  177512. * round the error term (which is expressed * 16) to an integer.
  177513. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177514. * for either sign of the error value.
  177515. * Note: errorptr points to *previous* column's array entry.
  177516. */
  177517. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177518. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177519. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177520. * of the range_limit array.
  177521. */
  177522. cur += GETJSAMPLE(*input_ptr);
  177523. cur = GETJSAMPLE(range_limit[cur]);
  177524. /* Select output value, accumulate into output code for this pixel */
  177525. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177526. *output_ptr += (JSAMPLE) pixcode;
  177527. /* Compute actual representation error at this pixel */
  177528. /* Note: we can do this even though we don't have the final */
  177529. /* pixel code, because the colormap is orthogonal. */
  177530. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177531. /* Compute error fractions to be propagated to adjacent pixels.
  177532. * Add these into the running sums, and simultaneously shift the
  177533. * next-line error sums left by 1 column.
  177534. */
  177535. bnexterr = cur;
  177536. delta = cur * 2;
  177537. cur += delta; /* form error * 3 */
  177538. errorptr[0] = (FSERROR) (bpreverr + cur);
  177539. cur += delta; /* form error * 5 */
  177540. bpreverr = belowerr + cur;
  177541. belowerr = bnexterr;
  177542. cur += delta; /* form error * 7 */
  177543. /* At this point cur contains the 7/16 error value to be propagated
  177544. * to the next pixel on the current line, and all the errors for the
  177545. * next line have been shifted over. We are therefore ready to move on.
  177546. */
  177547. input_ptr += dirnc; /* advance input ptr to next column */
  177548. output_ptr += dir; /* advance output ptr to next column */
  177549. errorptr += dir; /* advance errorptr to current column */
  177550. }
  177551. /* Post-loop cleanup: we must unload the final error value into the
  177552. * final fserrors[] entry. Note we need not unload belowerr because
  177553. * it is for the dummy column before or after the actual array.
  177554. */
  177555. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177556. }
  177557. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177558. }
  177559. }
  177560. /*
  177561. * Allocate workspace for Floyd-Steinberg errors.
  177562. */
  177563. LOCAL(void)
  177564. alloc_fs_workspace (j_decompress_ptr cinfo)
  177565. {
  177566. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177567. size_t arraysize;
  177568. int i;
  177569. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177570. for (i = 0; i < cinfo->out_color_components; i++) {
  177571. cquantize->fserrors[i] = (FSERRPTR)
  177572. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177573. }
  177574. }
  177575. /*
  177576. * Initialize for one-pass color quantization.
  177577. */
  177578. METHODDEF(void)
  177579. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177580. {
  177581. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177582. size_t arraysize;
  177583. int i;
  177584. /* Install my colormap. */
  177585. cinfo->colormap = cquantize->sv_colormap;
  177586. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177587. /* Initialize for desired dithering mode. */
  177588. switch (cinfo->dither_mode) {
  177589. case JDITHER_NONE:
  177590. if (cinfo->out_color_components == 3)
  177591. cquantize->pub.color_quantize = color_quantize3;
  177592. else
  177593. cquantize->pub.color_quantize = color_quantize;
  177594. break;
  177595. case JDITHER_ORDERED:
  177596. if (cinfo->out_color_components == 3)
  177597. cquantize->pub.color_quantize = quantize3_ord_dither;
  177598. else
  177599. cquantize->pub.color_quantize = quantize_ord_dither;
  177600. cquantize->row_index = 0; /* initialize state for ordered dither */
  177601. /* If user changed to ordered dither from another mode,
  177602. * we must recreate the color index table with padding.
  177603. * This will cost extra space, but probably isn't very likely.
  177604. */
  177605. if (! cquantize->is_padded)
  177606. create_colorindex(cinfo);
  177607. /* Create ordered-dither tables if we didn't already. */
  177608. if (cquantize->odither[0] == NULL)
  177609. create_odither_tables(cinfo);
  177610. break;
  177611. case JDITHER_FS:
  177612. cquantize->pub.color_quantize = quantize_fs_dither;
  177613. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177614. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177615. if (cquantize->fserrors[0] == NULL)
  177616. alloc_fs_workspace(cinfo);
  177617. /* Initialize the propagated errors to zero. */
  177618. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177619. for (i = 0; i < cinfo->out_color_components; i++)
  177620. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177621. break;
  177622. default:
  177623. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177624. break;
  177625. }
  177626. }
  177627. /*
  177628. * Finish up at the end of the pass.
  177629. */
  177630. METHODDEF(void)
  177631. finish_pass_1_quant (j_decompress_ptr)
  177632. {
  177633. /* no work in 1-pass case */
  177634. }
  177635. /*
  177636. * Switch to a new external colormap between output passes.
  177637. * Shouldn't get to this module!
  177638. */
  177639. METHODDEF(void)
  177640. new_color_map_1_quant (j_decompress_ptr cinfo)
  177641. {
  177642. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177643. }
  177644. /*
  177645. * Module initialization routine for 1-pass color quantization.
  177646. */
  177647. GLOBAL(void)
  177648. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177649. {
  177650. my_cquantize_ptr cquantize;
  177651. cquantize = (my_cquantize_ptr)
  177652. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177653. SIZEOF(my_cquantizer));
  177654. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177655. cquantize->pub.start_pass = start_pass_1_quant;
  177656. cquantize->pub.finish_pass = finish_pass_1_quant;
  177657. cquantize->pub.new_color_map = new_color_map_1_quant;
  177658. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177659. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177660. /* Make sure my internal arrays won't overflow */
  177661. if (cinfo->out_color_components > MAX_Q_COMPS)
  177662. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177663. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177664. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177665. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177666. /* Create the colormap and color index table. */
  177667. create_colormap(cinfo);
  177668. create_colorindex(cinfo);
  177669. /* Allocate Floyd-Steinberg workspace now if requested.
  177670. * We do this now since it is FAR storage and may affect the memory
  177671. * manager's space calculations. If the user changes to FS dither
  177672. * mode in a later pass, we will allocate the space then, and will
  177673. * possibly overrun the max_memory_to_use setting.
  177674. */
  177675. if (cinfo->dither_mode == JDITHER_FS)
  177676. alloc_fs_workspace(cinfo);
  177677. }
  177678. #endif /* QUANT_1PASS_SUPPORTED */
  177679. /*** End of inlined file: jquant1.c ***/
  177680. /*** Start of inlined file: jquant2.c ***/
  177681. #define JPEG_INTERNALS
  177682. #ifdef QUANT_2PASS_SUPPORTED
  177683. /*
  177684. * This module implements the well-known Heckbert paradigm for color
  177685. * quantization. Most of the ideas used here can be traced back to
  177686. * Heckbert's seminal paper
  177687. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177688. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177689. *
  177690. * In the first pass over the image, we accumulate a histogram showing the
  177691. * usage count of each possible color. To keep the histogram to a reasonable
  177692. * size, we reduce the precision of the input; typical practice is to retain
  177693. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177694. * in the same histogram cell.
  177695. *
  177696. * Next, the color-selection step begins with a box representing the whole
  177697. * color space, and repeatedly splits the "largest" remaining box until we
  177698. * have as many boxes as desired colors. Then the mean color in each
  177699. * remaining box becomes one of the possible output colors.
  177700. *
  177701. * The second pass over the image maps each input pixel to the closest output
  177702. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177703. * This mapping is logically trivial, but making it go fast enough requires
  177704. * considerable care.
  177705. *
  177706. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177707. * the "largest" box and deciding where to cut it. The particular policies
  177708. * used here have proved out well in experimental comparisons, but better ones
  177709. * may yet be found.
  177710. *
  177711. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177712. * space, processing the raw upsampled data without a color conversion step.
  177713. * This allowed the color conversion math to be done only once per colormap
  177714. * entry, not once per pixel. However, that optimization precluded other
  177715. * useful optimizations (such as merging color conversion with upsampling)
  177716. * and it also interfered with desired capabilities such as quantizing to an
  177717. * externally-supplied colormap. We have therefore abandoned that approach.
  177718. * The present code works in the post-conversion color space, typically RGB.
  177719. *
  177720. * To improve the visual quality of the results, we actually work in scaled
  177721. * RGB space, giving G distances more weight than R, and R in turn more than
  177722. * B. To do everything in integer math, we must use integer scale factors.
  177723. * The 2/3/1 scale factors used here correspond loosely to the relative
  177724. * weights of the colors in the NTSC grayscale equation.
  177725. * If you want to use this code to quantize a non-RGB color space, you'll
  177726. * probably need to change these scale factors.
  177727. */
  177728. #define R_SCALE 2 /* scale R distances by this much */
  177729. #define G_SCALE 3 /* scale G distances by this much */
  177730. #define B_SCALE 1 /* and B by this much */
  177731. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177732. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177733. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177734. * you'll get compile errors until you extend this logic. In that case
  177735. * you'll probably want to tweak the histogram sizes too.
  177736. */
  177737. #if RGB_RED == 0
  177738. #define C0_SCALE R_SCALE
  177739. #endif
  177740. #if RGB_BLUE == 0
  177741. #define C0_SCALE B_SCALE
  177742. #endif
  177743. #if RGB_GREEN == 1
  177744. #define C1_SCALE G_SCALE
  177745. #endif
  177746. #if RGB_RED == 2
  177747. #define C2_SCALE R_SCALE
  177748. #endif
  177749. #if RGB_BLUE == 2
  177750. #define C2_SCALE B_SCALE
  177751. #endif
  177752. /*
  177753. * First we have the histogram data structure and routines for creating it.
  177754. *
  177755. * The number of bits of precision can be adjusted by changing these symbols.
  177756. * We recommend keeping 6 bits for G and 5 each for R and B.
  177757. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177758. * better results; if you are short of memory, 5 bits all around will save
  177759. * some space but degrade the results.
  177760. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177761. * (preferably unsigned long) for each cell. In practice this is overkill;
  177762. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177763. * and clamping those that do overflow to the maximum value will give close-
  177764. * enough results. This reduces the recommended histogram size from 256Kb
  177765. * to 128Kb, which is a useful savings on PC-class machines.
  177766. * (In the second pass the histogram space is re-used for pixel mapping data;
  177767. * in that capacity, each cell must be able to store zero to the number of
  177768. * desired colors. 16 bits/cell is plenty for that too.)
  177769. * Since the JPEG code is intended to run in small memory model on 80x86
  177770. * machines, we can't just allocate the histogram in one chunk. Instead
  177771. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177772. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177773. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177774. * on 80x86 machines, the pointer row is in near memory but the actual
  177775. * arrays are in far memory (same arrangement as we use for image arrays).
  177776. */
  177777. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177778. /* These will do the right thing for either R,G,B or B,G,R color order,
  177779. * but you may not like the results for other color orders.
  177780. */
  177781. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177782. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177783. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177784. /* Number of elements along histogram axes. */
  177785. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177786. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177787. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177788. /* These are the amounts to shift an input value to get a histogram index. */
  177789. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177790. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177791. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177792. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177793. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177794. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177795. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177796. typedef hist2d * hist3d; /* type for top-level pointer */
  177797. /* Declarations for Floyd-Steinberg dithering.
  177798. *
  177799. * Errors are accumulated into the array fserrors[], at a resolution of
  177800. * 1/16th of a pixel count. The error at a given pixel is propagated
  177801. * to its not-yet-processed neighbors using the standard F-S fractions,
  177802. * ... (here) 7/16
  177803. * 3/16 5/16 1/16
  177804. * We work left-to-right on even rows, right-to-left on odd rows.
  177805. *
  177806. * We can get away with a single array (holding one row's worth of errors)
  177807. * by using it to store the current row's errors at pixel columns not yet
  177808. * processed, but the next row's errors at columns already processed. We
  177809. * need only a few extra variables to hold the errors immediately around the
  177810. * current column. (If we are lucky, those variables are in registers, but
  177811. * even if not, they're probably cheaper to access than array elements are.)
  177812. *
  177813. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177814. * each end saves us from special-casing the first and last pixels.
  177815. * Each entry is three values long, one value for each color component.
  177816. *
  177817. * Note: on a wide image, we might not have enough room in a PC's near data
  177818. * segment to hold the error array; so it is allocated with alloc_large.
  177819. */
  177820. #if BITS_IN_JSAMPLE == 8
  177821. typedef INT16 FSERROR; /* 16 bits should be enough */
  177822. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177823. #else
  177824. typedef INT32 FSERROR; /* may need more than 16 bits */
  177825. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177826. #endif
  177827. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177828. /* Private subobject */
  177829. typedef struct {
  177830. struct jpeg_color_quantizer pub; /* public fields */
  177831. /* Space for the eventually created colormap is stashed here */
  177832. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177833. int desired; /* desired # of colors = size of colormap */
  177834. /* Variables for accumulating image statistics */
  177835. hist3d histogram; /* pointer to the histogram */
  177836. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177837. /* Variables for Floyd-Steinberg dithering */
  177838. FSERRPTR fserrors; /* accumulated errors */
  177839. boolean on_odd_row; /* flag to remember which row we are on */
  177840. int * error_limiter; /* table for clamping the applied error */
  177841. } my_cquantizer2;
  177842. typedef my_cquantizer2 * my_cquantize_ptr2;
  177843. /*
  177844. * Prescan some rows of pixels.
  177845. * In this module the prescan simply updates the histogram, which has been
  177846. * initialized to zeroes by start_pass.
  177847. * An output_buf parameter is required by the method signature, but no data
  177848. * is actually output (in fact the buffer controller is probably passing a
  177849. * NULL pointer).
  177850. */
  177851. METHODDEF(void)
  177852. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177853. JSAMPARRAY, int num_rows)
  177854. {
  177855. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177856. register JSAMPROW ptr;
  177857. register histptr histp;
  177858. register hist3d histogram = cquantize->histogram;
  177859. int row;
  177860. JDIMENSION col;
  177861. JDIMENSION width = cinfo->output_width;
  177862. for (row = 0; row < num_rows; row++) {
  177863. ptr = input_buf[row];
  177864. for (col = width; col > 0; col--) {
  177865. /* get pixel value and index into the histogram */
  177866. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177867. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177868. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177869. /* increment, check for overflow and undo increment if so. */
  177870. if (++(*histp) <= 0)
  177871. (*histp)--;
  177872. ptr += 3;
  177873. }
  177874. }
  177875. }
  177876. /*
  177877. * Next we have the really interesting routines: selection of a colormap
  177878. * given the completed histogram.
  177879. * These routines work with a list of "boxes", each representing a rectangular
  177880. * subset of the input color space (to histogram precision).
  177881. */
  177882. typedef struct {
  177883. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177884. int c0min, c0max;
  177885. int c1min, c1max;
  177886. int c2min, c2max;
  177887. /* The volume (actually 2-norm) of the box */
  177888. INT32 volume;
  177889. /* The number of nonzero histogram cells within this box */
  177890. long colorcount;
  177891. } box;
  177892. typedef box * boxptr;
  177893. LOCAL(boxptr)
  177894. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177895. /* Find the splittable box with the largest color population */
  177896. /* Returns NULL if no splittable boxes remain */
  177897. {
  177898. register boxptr boxp;
  177899. register int i;
  177900. register long maxc = 0;
  177901. boxptr which = NULL;
  177902. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177903. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177904. which = boxp;
  177905. maxc = boxp->colorcount;
  177906. }
  177907. }
  177908. return which;
  177909. }
  177910. LOCAL(boxptr)
  177911. find_biggest_volume (boxptr boxlist, int numboxes)
  177912. /* Find the splittable box with the largest (scaled) volume */
  177913. /* Returns NULL if no splittable boxes remain */
  177914. {
  177915. register boxptr boxp;
  177916. register int i;
  177917. register INT32 maxv = 0;
  177918. boxptr which = NULL;
  177919. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177920. if (boxp->volume > maxv) {
  177921. which = boxp;
  177922. maxv = boxp->volume;
  177923. }
  177924. }
  177925. return which;
  177926. }
  177927. LOCAL(void)
  177928. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177929. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177930. /* and recompute its volume and population */
  177931. {
  177932. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177933. hist3d histogram = cquantize->histogram;
  177934. histptr histp;
  177935. int c0,c1,c2;
  177936. int c0min,c0max,c1min,c1max,c2min,c2max;
  177937. INT32 dist0,dist1,dist2;
  177938. long ccount;
  177939. c0min = boxp->c0min; c0max = boxp->c0max;
  177940. c1min = boxp->c1min; c1max = boxp->c1max;
  177941. c2min = boxp->c2min; c2max = boxp->c2max;
  177942. if (c0max > c0min)
  177943. for (c0 = c0min; c0 <= c0max; c0++)
  177944. for (c1 = c1min; c1 <= c1max; c1++) {
  177945. histp = & histogram[c0][c1][c2min];
  177946. for (c2 = c2min; c2 <= c2max; c2++)
  177947. if (*histp++ != 0) {
  177948. boxp->c0min = c0min = c0;
  177949. goto have_c0min;
  177950. }
  177951. }
  177952. have_c0min:
  177953. if (c0max > c0min)
  177954. for (c0 = c0max; c0 >= c0min; c0--)
  177955. for (c1 = c1min; c1 <= c1max; c1++) {
  177956. histp = & histogram[c0][c1][c2min];
  177957. for (c2 = c2min; c2 <= c2max; c2++)
  177958. if (*histp++ != 0) {
  177959. boxp->c0max = c0max = c0;
  177960. goto have_c0max;
  177961. }
  177962. }
  177963. have_c0max:
  177964. if (c1max > c1min)
  177965. for (c1 = c1min; c1 <= c1max; c1++)
  177966. for (c0 = c0min; c0 <= c0max; c0++) {
  177967. histp = & histogram[c0][c1][c2min];
  177968. for (c2 = c2min; c2 <= c2max; c2++)
  177969. if (*histp++ != 0) {
  177970. boxp->c1min = c1min = c1;
  177971. goto have_c1min;
  177972. }
  177973. }
  177974. have_c1min:
  177975. if (c1max > c1min)
  177976. for (c1 = c1max; c1 >= c1min; c1--)
  177977. for (c0 = c0min; c0 <= c0max; c0++) {
  177978. histp = & histogram[c0][c1][c2min];
  177979. for (c2 = c2min; c2 <= c2max; c2++)
  177980. if (*histp++ != 0) {
  177981. boxp->c1max = c1max = c1;
  177982. goto have_c1max;
  177983. }
  177984. }
  177985. have_c1max:
  177986. if (c2max > c2min)
  177987. for (c2 = c2min; c2 <= c2max; c2++)
  177988. for (c0 = c0min; c0 <= c0max; c0++) {
  177989. histp = & histogram[c0][c1min][c2];
  177990. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177991. if (*histp != 0) {
  177992. boxp->c2min = c2min = c2;
  177993. goto have_c2min;
  177994. }
  177995. }
  177996. have_c2min:
  177997. if (c2max > c2min)
  177998. for (c2 = c2max; c2 >= c2min; c2--)
  177999. for (c0 = c0min; c0 <= c0max; c0++) {
  178000. histp = & histogram[c0][c1min][c2];
  178001. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178002. if (*histp != 0) {
  178003. boxp->c2max = c2max = c2;
  178004. goto have_c2max;
  178005. }
  178006. }
  178007. have_c2max:
  178008. /* Update box volume.
  178009. * We use 2-norm rather than real volume here; this biases the method
  178010. * against making long narrow boxes, and it has the side benefit that
  178011. * a box is splittable iff norm > 0.
  178012. * Since the differences are expressed in histogram-cell units,
  178013. * we have to shift back to JSAMPLE units to get consistent distances;
  178014. * after which, we scale according to the selected distance scale factors.
  178015. */
  178016. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178017. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178018. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178019. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178020. /* Now scan remaining volume of box and compute population */
  178021. ccount = 0;
  178022. for (c0 = c0min; c0 <= c0max; c0++)
  178023. for (c1 = c1min; c1 <= c1max; c1++) {
  178024. histp = & histogram[c0][c1][c2min];
  178025. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178026. if (*histp != 0) {
  178027. ccount++;
  178028. }
  178029. }
  178030. boxp->colorcount = ccount;
  178031. }
  178032. LOCAL(int)
  178033. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178034. int desired_colors)
  178035. /* Repeatedly select and split the largest box until we have enough boxes */
  178036. {
  178037. int n,lb;
  178038. int c0,c1,c2,cmax;
  178039. register boxptr b1,b2;
  178040. while (numboxes < desired_colors) {
  178041. /* Select box to split.
  178042. * Current algorithm: by population for first half, then by volume.
  178043. */
  178044. if (numboxes*2 <= desired_colors) {
  178045. b1 = find_biggest_color_pop(boxlist, numboxes);
  178046. } else {
  178047. b1 = find_biggest_volume(boxlist, numboxes);
  178048. }
  178049. if (b1 == NULL) /* no splittable boxes left! */
  178050. break;
  178051. b2 = &boxlist[numboxes]; /* where new box will go */
  178052. /* Copy the color bounds to the new box. */
  178053. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178054. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178055. /* Choose which axis to split the box on.
  178056. * Current algorithm: longest scaled axis.
  178057. * See notes in update_box about scaling distances.
  178058. */
  178059. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178060. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178061. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178062. /* We want to break any ties in favor of green, then red, blue last.
  178063. * This code does the right thing for R,G,B or B,G,R color orders only.
  178064. */
  178065. #if RGB_RED == 0
  178066. cmax = c1; n = 1;
  178067. if (c0 > cmax) { cmax = c0; n = 0; }
  178068. if (c2 > cmax) { n = 2; }
  178069. #else
  178070. cmax = c1; n = 1;
  178071. if (c2 > cmax) { cmax = c2; n = 2; }
  178072. if (c0 > cmax) { n = 0; }
  178073. #endif
  178074. /* Choose split point along selected axis, and update box bounds.
  178075. * Current algorithm: split at halfway point.
  178076. * (Since the box has been shrunk to minimum volume,
  178077. * any split will produce two nonempty subboxes.)
  178078. * Note that lb value is max for lower box, so must be < old max.
  178079. */
  178080. switch (n) {
  178081. case 0:
  178082. lb = (b1->c0max + b1->c0min) / 2;
  178083. b1->c0max = lb;
  178084. b2->c0min = lb+1;
  178085. break;
  178086. case 1:
  178087. lb = (b1->c1max + b1->c1min) / 2;
  178088. b1->c1max = lb;
  178089. b2->c1min = lb+1;
  178090. break;
  178091. case 2:
  178092. lb = (b1->c2max + b1->c2min) / 2;
  178093. b1->c2max = lb;
  178094. b2->c2min = lb+1;
  178095. break;
  178096. }
  178097. /* Update stats for boxes */
  178098. update_box(cinfo, b1);
  178099. update_box(cinfo, b2);
  178100. numboxes++;
  178101. }
  178102. return numboxes;
  178103. }
  178104. LOCAL(void)
  178105. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178106. /* Compute representative color for a box, put it in colormap[icolor] */
  178107. {
  178108. /* Current algorithm: mean weighted by pixels (not colors) */
  178109. /* Note it is important to get the rounding correct! */
  178110. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178111. hist3d histogram = cquantize->histogram;
  178112. histptr histp;
  178113. int c0,c1,c2;
  178114. int c0min,c0max,c1min,c1max,c2min,c2max;
  178115. long count;
  178116. long total = 0;
  178117. long c0total = 0;
  178118. long c1total = 0;
  178119. long c2total = 0;
  178120. c0min = boxp->c0min; c0max = boxp->c0max;
  178121. c1min = boxp->c1min; c1max = boxp->c1max;
  178122. c2min = boxp->c2min; c2max = boxp->c2max;
  178123. for (c0 = c0min; c0 <= c0max; c0++)
  178124. for (c1 = c1min; c1 <= c1max; c1++) {
  178125. histp = & histogram[c0][c1][c2min];
  178126. for (c2 = c2min; c2 <= c2max; c2++) {
  178127. if ((count = *histp++) != 0) {
  178128. total += count;
  178129. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178130. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178131. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178132. }
  178133. }
  178134. }
  178135. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178136. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178137. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178138. }
  178139. LOCAL(void)
  178140. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178141. /* Master routine for color selection */
  178142. {
  178143. boxptr boxlist;
  178144. int numboxes;
  178145. int i;
  178146. /* Allocate workspace for box list */
  178147. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178148. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178149. /* Initialize one box containing whole space */
  178150. numboxes = 1;
  178151. boxlist[0].c0min = 0;
  178152. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178153. boxlist[0].c1min = 0;
  178154. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178155. boxlist[0].c2min = 0;
  178156. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178157. /* Shrink it to actually-used volume and set its statistics */
  178158. update_box(cinfo, & boxlist[0]);
  178159. /* Perform median-cut to produce final box list */
  178160. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178161. /* Compute the representative color for each box, fill colormap */
  178162. for (i = 0; i < numboxes; i++)
  178163. compute_color(cinfo, & boxlist[i], i);
  178164. cinfo->actual_number_of_colors = numboxes;
  178165. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178166. }
  178167. /*
  178168. * These routines are concerned with the time-critical task of mapping input
  178169. * colors to the nearest color in the selected colormap.
  178170. *
  178171. * We re-use the histogram space as an "inverse color map", essentially a
  178172. * cache for the results of nearest-color searches. All colors within a
  178173. * histogram cell will be mapped to the same colormap entry, namely the one
  178174. * closest to the cell's center. This may not be quite the closest entry to
  178175. * the actual input color, but it's almost as good. A zero in the cache
  178176. * indicates we haven't found the nearest color for that cell yet; the array
  178177. * is cleared to zeroes before starting the mapping pass. When we find the
  178178. * nearest color for a cell, its colormap index plus one is recorded in the
  178179. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178180. * when they need to use an unfilled entry in the cache.
  178181. *
  178182. * Our method of efficiently finding nearest colors is based on the "locally
  178183. * sorted search" idea described by Heckbert and on the incremental distance
  178184. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178185. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178186. * the distances from a given colormap entry to each cell of the histogram can
  178187. * be computed quickly using an incremental method: the differences between
  178188. * distances to adjacent cells themselves differ by a constant. This allows a
  178189. * fairly fast implementation of the "brute force" approach of computing the
  178190. * distance from every colormap entry to every histogram cell. Unfortunately,
  178191. * it needs a work array to hold the best-distance-so-far for each histogram
  178192. * cell (because the inner loop has to be over cells, not colormap entries).
  178193. * The work array elements have to be INT32s, so the work array would need
  178194. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178195. *
  178196. * To get around these problems, we apply Thomas' method to compute the
  178197. * nearest colors for only the cells within a small subbox of the histogram.
  178198. * The work array need be only as big as the subbox, so the memory usage
  178199. * problem is solved. Furthermore, we need not fill subboxes that are never
  178200. * referenced in pass2; many images use only part of the color gamut, so a
  178201. * fair amount of work is saved. An additional advantage of this
  178202. * approach is that we can apply Heckbert's locality criterion to quickly
  178203. * eliminate colormap entries that are far away from the subbox; typically
  178204. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178205. * and we need not compute their distances to individual cells in the subbox.
  178206. * The speed of this approach is heavily influenced by the subbox size: too
  178207. * small means too much overhead, too big loses because Heckbert's criterion
  178208. * can't eliminate as many colormap entries. Empirically the best subbox
  178209. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178210. *
  178211. * Thomas' article also describes a refined method which is asymptotically
  178212. * faster than the brute-force method, but it is also far more complex and
  178213. * cannot efficiently be applied to small subboxes. It is therefore not
  178214. * useful for programs intended to be portable to DOS machines. On machines
  178215. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178216. * refined method might be faster than the present code --- but then again,
  178217. * it might not be any faster, and it's certainly more complicated.
  178218. */
  178219. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178220. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178221. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178222. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178223. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178224. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178225. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178226. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178227. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178228. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178229. /*
  178230. * The next three routines implement inverse colormap filling. They could
  178231. * all be folded into one big routine, but splitting them up this way saves
  178232. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178233. * and may allow some compilers to produce better code by registerizing more
  178234. * inner-loop variables.
  178235. */
  178236. LOCAL(int)
  178237. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178238. JSAMPLE colorlist[])
  178239. /* Locate the colormap entries close enough to an update box to be candidates
  178240. * for the nearest entry to some cell(s) in the update box. The update box
  178241. * is specified by the center coordinates of its first cell. The number of
  178242. * candidate colormap entries is returned, and their colormap indexes are
  178243. * placed in colorlist[].
  178244. * This routine uses Heckbert's "locally sorted search" criterion to select
  178245. * the colors that need further consideration.
  178246. */
  178247. {
  178248. int numcolors = cinfo->actual_number_of_colors;
  178249. int maxc0, maxc1, maxc2;
  178250. int centerc0, centerc1, centerc2;
  178251. int i, x, ncolors;
  178252. INT32 minmaxdist, min_dist, max_dist, tdist;
  178253. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178254. /* Compute true coordinates of update box's upper corner and center.
  178255. * Actually we compute the coordinates of the center of the upper-corner
  178256. * histogram cell, which are the upper bounds of the volume we care about.
  178257. * Note that since ">>" rounds down, the "center" values may be closer to
  178258. * min than to max; hence comparisons to them must be "<=", not "<".
  178259. */
  178260. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178261. centerc0 = (minc0 + maxc0) >> 1;
  178262. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178263. centerc1 = (minc1 + maxc1) >> 1;
  178264. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178265. centerc2 = (minc2 + maxc2) >> 1;
  178266. /* For each color in colormap, find:
  178267. * 1. its minimum squared-distance to any point in the update box
  178268. * (zero if color is within update box);
  178269. * 2. its maximum squared-distance to any point in the update box.
  178270. * Both of these can be found by considering only the corners of the box.
  178271. * We save the minimum distance for each color in mindist[];
  178272. * only the smallest maximum distance is of interest.
  178273. */
  178274. minmaxdist = 0x7FFFFFFFL;
  178275. for (i = 0; i < numcolors; i++) {
  178276. /* We compute the squared-c0-distance term, then add in the other two. */
  178277. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178278. if (x < minc0) {
  178279. tdist = (x - minc0) * C0_SCALE;
  178280. min_dist = tdist*tdist;
  178281. tdist = (x - maxc0) * C0_SCALE;
  178282. max_dist = tdist*tdist;
  178283. } else if (x > maxc0) {
  178284. tdist = (x - maxc0) * C0_SCALE;
  178285. min_dist = tdist*tdist;
  178286. tdist = (x - minc0) * C0_SCALE;
  178287. max_dist = tdist*tdist;
  178288. } else {
  178289. /* within cell range so no contribution to min_dist */
  178290. min_dist = 0;
  178291. if (x <= centerc0) {
  178292. tdist = (x - maxc0) * C0_SCALE;
  178293. max_dist = tdist*tdist;
  178294. } else {
  178295. tdist = (x - minc0) * C0_SCALE;
  178296. max_dist = tdist*tdist;
  178297. }
  178298. }
  178299. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178300. if (x < minc1) {
  178301. tdist = (x - minc1) * C1_SCALE;
  178302. min_dist += tdist*tdist;
  178303. tdist = (x - maxc1) * C1_SCALE;
  178304. max_dist += tdist*tdist;
  178305. } else if (x > maxc1) {
  178306. tdist = (x - maxc1) * C1_SCALE;
  178307. min_dist += tdist*tdist;
  178308. tdist = (x - minc1) * C1_SCALE;
  178309. max_dist += tdist*tdist;
  178310. } else {
  178311. /* within cell range so no contribution to min_dist */
  178312. if (x <= centerc1) {
  178313. tdist = (x - maxc1) * C1_SCALE;
  178314. max_dist += tdist*tdist;
  178315. } else {
  178316. tdist = (x - minc1) * C1_SCALE;
  178317. max_dist += tdist*tdist;
  178318. }
  178319. }
  178320. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178321. if (x < minc2) {
  178322. tdist = (x - minc2) * C2_SCALE;
  178323. min_dist += tdist*tdist;
  178324. tdist = (x - maxc2) * C2_SCALE;
  178325. max_dist += tdist*tdist;
  178326. } else if (x > maxc2) {
  178327. tdist = (x - maxc2) * C2_SCALE;
  178328. min_dist += tdist*tdist;
  178329. tdist = (x - minc2) * C2_SCALE;
  178330. max_dist += tdist*tdist;
  178331. } else {
  178332. /* within cell range so no contribution to min_dist */
  178333. if (x <= centerc2) {
  178334. tdist = (x - maxc2) * C2_SCALE;
  178335. max_dist += tdist*tdist;
  178336. } else {
  178337. tdist = (x - minc2) * C2_SCALE;
  178338. max_dist += tdist*tdist;
  178339. }
  178340. }
  178341. mindist[i] = min_dist; /* save away the results */
  178342. if (max_dist < minmaxdist)
  178343. minmaxdist = max_dist;
  178344. }
  178345. /* Now we know that no cell in the update box is more than minmaxdist
  178346. * away from some colormap entry. Therefore, only colors that are
  178347. * within minmaxdist of some part of the box need be considered.
  178348. */
  178349. ncolors = 0;
  178350. for (i = 0; i < numcolors; i++) {
  178351. if (mindist[i] <= minmaxdist)
  178352. colorlist[ncolors++] = (JSAMPLE) i;
  178353. }
  178354. return ncolors;
  178355. }
  178356. LOCAL(void)
  178357. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178358. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178359. /* Find the closest colormap entry for each cell in the update box,
  178360. * given the list of candidate colors prepared by find_nearby_colors.
  178361. * Return the indexes of the closest entries in the bestcolor[] array.
  178362. * This routine uses Thomas' incremental distance calculation method to
  178363. * find the distance from a colormap entry to successive cells in the box.
  178364. */
  178365. {
  178366. int ic0, ic1, ic2;
  178367. int i, icolor;
  178368. register INT32 * bptr; /* pointer into bestdist[] array */
  178369. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178370. INT32 dist0, dist1; /* initial distance values */
  178371. register INT32 dist2; /* current distance in inner loop */
  178372. INT32 xx0, xx1; /* distance increments */
  178373. register INT32 xx2;
  178374. INT32 inc0, inc1, inc2; /* initial values for increments */
  178375. /* This array holds the distance to the nearest-so-far color for each cell */
  178376. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178377. /* Initialize best-distance for each cell of the update box */
  178378. bptr = bestdist;
  178379. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178380. *bptr++ = 0x7FFFFFFFL;
  178381. /* For each color selected by find_nearby_colors,
  178382. * compute its distance to the center of each cell in the box.
  178383. * If that's less than best-so-far, update best distance and color number.
  178384. */
  178385. /* Nominal steps between cell centers ("x" in Thomas article) */
  178386. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178387. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178388. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178389. for (i = 0; i < numcolors; i++) {
  178390. icolor = GETJSAMPLE(colorlist[i]);
  178391. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178392. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178393. dist0 = inc0*inc0;
  178394. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178395. dist0 += inc1*inc1;
  178396. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178397. dist0 += inc2*inc2;
  178398. /* Form the initial difference increments */
  178399. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178400. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178401. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178402. /* Now loop over all cells in box, updating distance per Thomas method */
  178403. bptr = bestdist;
  178404. cptr = bestcolor;
  178405. xx0 = inc0;
  178406. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178407. dist1 = dist0;
  178408. xx1 = inc1;
  178409. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178410. dist2 = dist1;
  178411. xx2 = inc2;
  178412. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178413. if (dist2 < *bptr) {
  178414. *bptr = dist2;
  178415. *cptr = (JSAMPLE) icolor;
  178416. }
  178417. dist2 += xx2;
  178418. xx2 += 2 * STEP_C2 * STEP_C2;
  178419. bptr++;
  178420. cptr++;
  178421. }
  178422. dist1 += xx1;
  178423. xx1 += 2 * STEP_C1 * STEP_C1;
  178424. }
  178425. dist0 += xx0;
  178426. xx0 += 2 * STEP_C0 * STEP_C0;
  178427. }
  178428. }
  178429. }
  178430. LOCAL(void)
  178431. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178432. /* Fill the inverse-colormap entries in the update box that contains */
  178433. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178434. /* we can fill as many others as we wish.) */
  178435. {
  178436. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178437. hist3d histogram = cquantize->histogram;
  178438. int minc0, minc1, minc2; /* lower left corner of update box */
  178439. int ic0, ic1, ic2;
  178440. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178441. register histptr cachep; /* pointer into main cache array */
  178442. /* This array lists the candidate colormap indexes. */
  178443. JSAMPLE colorlist[MAXNUMCOLORS];
  178444. int numcolors; /* number of candidate colors */
  178445. /* This array holds the actually closest colormap index for each cell. */
  178446. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178447. /* Convert cell coordinates to update box ID */
  178448. c0 >>= BOX_C0_LOG;
  178449. c1 >>= BOX_C1_LOG;
  178450. c2 >>= BOX_C2_LOG;
  178451. /* Compute true coordinates of update box's origin corner.
  178452. * Actually we compute the coordinates of the center of the corner
  178453. * histogram cell, which are the lower bounds of the volume we care about.
  178454. */
  178455. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178456. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178457. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178458. /* Determine which colormap entries are close enough to be candidates
  178459. * for the nearest entry to some cell in the update box.
  178460. */
  178461. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178462. /* Determine the actually nearest colors. */
  178463. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178464. bestcolor);
  178465. /* Save the best color numbers (plus 1) in the main cache array */
  178466. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178467. c1 <<= BOX_C1_LOG;
  178468. c2 <<= BOX_C2_LOG;
  178469. cptr = bestcolor;
  178470. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178471. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178472. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178473. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178474. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178475. }
  178476. }
  178477. }
  178478. }
  178479. /*
  178480. * Map some rows of pixels to the output colormapped representation.
  178481. */
  178482. METHODDEF(void)
  178483. pass2_no_dither (j_decompress_ptr cinfo,
  178484. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178485. /* This version performs no dithering */
  178486. {
  178487. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178488. hist3d histogram = cquantize->histogram;
  178489. register JSAMPROW inptr, outptr;
  178490. register histptr cachep;
  178491. register int c0, c1, c2;
  178492. int row;
  178493. JDIMENSION col;
  178494. JDIMENSION width = cinfo->output_width;
  178495. for (row = 0; row < num_rows; row++) {
  178496. inptr = input_buf[row];
  178497. outptr = output_buf[row];
  178498. for (col = width; col > 0; col--) {
  178499. /* get pixel value and index into the cache */
  178500. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178501. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178502. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178503. cachep = & histogram[c0][c1][c2];
  178504. /* If we have not seen this color before, find nearest colormap entry */
  178505. /* and update the cache */
  178506. if (*cachep == 0)
  178507. fill_inverse_cmap(cinfo, c0,c1,c2);
  178508. /* Now emit the colormap index for this cell */
  178509. *outptr++ = (JSAMPLE) (*cachep - 1);
  178510. }
  178511. }
  178512. }
  178513. METHODDEF(void)
  178514. pass2_fs_dither (j_decompress_ptr cinfo,
  178515. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178516. /* This version performs Floyd-Steinberg dithering */
  178517. {
  178518. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178519. hist3d histogram = cquantize->histogram;
  178520. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178521. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178522. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178523. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178524. JSAMPROW inptr; /* => current input pixel */
  178525. JSAMPROW outptr; /* => current output pixel */
  178526. histptr cachep;
  178527. int dir; /* +1 or -1 depending on direction */
  178528. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178529. int row;
  178530. JDIMENSION col;
  178531. JDIMENSION width = cinfo->output_width;
  178532. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178533. int *error_limit = cquantize->error_limiter;
  178534. JSAMPROW colormap0 = cinfo->colormap[0];
  178535. JSAMPROW colormap1 = cinfo->colormap[1];
  178536. JSAMPROW colormap2 = cinfo->colormap[2];
  178537. SHIFT_TEMPS
  178538. for (row = 0; row < num_rows; row++) {
  178539. inptr = input_buf[row];
  178540. outptr = output_buf[row];
  178541. if (cquantize->on_odd_row) {
  178542. /* work right to left in this row */
  178543. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178544. outptr += width-1;
  178545. dir = -1;
  178546. dir3 = -3;
  178547. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178548. cquantize->on_odd_row = FALSE; /* flip for next time */
  178549. } else {
  178550. /* work left to right in this row */
  178551. dir = 1;
  178552. dir3 = 3;
  178553. errorptr = cquantize->fserrors; /* => entry before first real column */
  178554. cquantize->on_odd_row = TRUE; /* flip for next time */
  178555. }
  178556. /* Preset error values: no error propagated to first pixel from left */
  178557. cur0 = cur1 = cur2 = 0;
  178558. /* and no error propagated to row below yet */
  178559. belowerr0 = belowerr1 = belowerr2 = 0;
  178560. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178561. for (col = width; col > 0; col--) {
  178562. /* curN holds the error propagated from the previous pixel on the
  178563. * current line. Add the error propagated from the previous line
  178564. * to form the complete error correction term for this pixel, and
  178565. * round the error term (which is expressed * 16) to an integer.
  178566. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178567. * for either sign of the error value.
  178568. * Note: errorptr points to *previous* column's array entry.
  178569. */
  178570. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178571. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178572. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178573. /* Limit the error using transfer function set by init_error_limit.
  178574. * See comments with init_error_limit for rationale.
  178575. */
  178576. cur0 = error_limit[cur0];
  178577. cur1 = error_limit[cur1];
  178578. cur2 = error_limit[cur2];
  178579. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178580. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178581. * this sets the required size of the range_limit array.
  178582. */
  178583. cur0 += GETJSAMPLE(inptr[0]);
  178584. cur1 += GETJSAMPLE(inptr[1]);
  178585. cur2 += GETJSAMPLE(inptr[2]);
  178586. cur0 = GETJSAMPLE(range_limit[cur0]);
  178587. cur1 = GETJSAMPLE(range_limit[cur1]);
  178588. cur2 = GETJSAMPLE(range_limit[cur2]);
  178589. /* Index into the cache with adjusted pixel value */
  178590. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178591. /* If we have not seen this color before, find nearest colormap */
  178592. /* entry and update the cache */
  178593. if (*cachep == 0)
  178594. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178595. /* Now emit the colormap index for this cell */
  178596. { register int pixcode = *cachep - 1;
  178597. *outptr = (JSAMPLE) pixcode;
  178598. /* Compute representation error for this pixel */
  178599. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178600. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178601. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178602. }
  178603. /* Compute error fractions to be propagated to adjacent pixels.
  178604. * Add these into the running sums, and simultaneously shift the
  178605. * next-line error sums left by 1 column.
  178606. */
  178607. { register LOCFSERROR bnexterr, delta;
  178608. bnexterr = cur0; /* Process component 0 */
  178609. delta = cur0 * 2;
  178610. cur0 += delta; /* form error * 3 */
  178611. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178612. cur0 += delta; /* form error * 5 */
  178613. bpreverr0 = belowerr0 + cur0;
  178614. belowerr0 = bnexterr;
  178615. cur0 += delta; /* form error * 7 */
  178616. bnexterr = cur1; /* Process component 1 */
  178617. delta = cur1 * 2;
  178618. cur1 += delta; /* form error * 3 */
  178619. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178620. cur1 += delta; /* form error * 5 */
  178621. bpreverr1 = belowerr1 + cur1;
  178622. belowerr1 = bnexterr;
  178623. cur1 += delta; /* form error * 7 */
  178624. bnexterr = cur2; /* Process component 2 */
  178625. delta = cur2 * 2;
  178626. cur2 += delta; /* form error * 3 */
  178627. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178628. cur2 += delta; /* form error * 5 */
  178629. bpreverr2 = belowerr2 + cur2;
  178630. belowerr2 = bnexterr;
  178631. cur2 += delta; /* form error * 7 */
  178632. }
  178633. /* At this point curN contains the 7/16 error value to be propagated
  178634. * to the next pixel on the current line, and all the errors for the
  178635. * next line have been shifted over. We are therefore ready to move on.
  178636. */
  178637. inptr += dir3; /* Advance pixel pointers to next column */
  178638. outptr += dir;
  178639. errorptr += dir3; /* advance errorptr to current column */
  178640. }
  178641. /* Post-loop cleanup: we must unload the final error values into the
  178642. * final fserrors[] entry. Note we need not unload belowerrN because
  178643. * it is for the dummy column before or after the actual array.
  178644. */
  178645. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178646. errorptr[1] = (FSERROR) bpreverr1;
  178647. errorptr[2] = (FSERROR) bpreverr2;
  178648. }
  178649. }
  178650. /*
  178651. * Initialize the error-limiting transfer function (lookup table).
  178652. * The raw F-S error computation can potentially compute error values of up to
  178653. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178654. * much less, otherwise obviously wrong pixels will be created. (Typical
  178655. * effects include weird fringes at color-area boundaries, isolated bright
  178656. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178657. * is to ensure that the "corners" of the color cube are allocated as output
  178658. * colors; then repeated errors in the same direction cannot cause cascading
  178659. * error buildup. However, that only prevents the error from getting
  178660. * completely out of hand; Aaron Giles reports that error limiting improves
  178661. * the results even with corner colors allocated.
  178662. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178663. * well, but the smoother transfer function used below is even better. Thanks
  178664. * to Aaron Giles for this idea.
  178665. */
  178666. LOCAL(void)
  178667. init_error_limit (j_decompress_ptr cinfo)
  178668. /* Allocate and fill in the error_limiter table */
  178669. {
  178670. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178671. int * table;
  178672. int in, out;
  178673. table = (int *) (*cinfo->mem->alloc_small)
  178674. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178675. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178676. cquantize->error_limiter = table;
  178677. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178678. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178679. out = 0;
  178680. for (in = 0; in < STEPSIZE; in++, out++) {
  178681. table[in] = out; table[-in] = -out;
  178682. }
  178683. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178684. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178685. table[in] = out; table[-in] = -out;
  178686. }
  178687. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178688. for (; in <= MAXJSAMPLE; in++) {
  178689. table[in] = out; table[-in] = -out;
  178690. }
  178691. #undef STEPSIZE
  178692. }
  178693. /*
  178694. * Finish up at the end of each pass.
  178695. */
  178696. METHODDEF(void)
  178697. finish_pass1 (j_decompress_ptr cinfo)
  178698. {
  178699. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178700. /* Select the representative colors and fill in cinfo->colormap */
  178701. cinfo->colormap = cquantize->sv_colormap;
  178702. select_colors(cinfo, cquantize->desired);
  178703. /* Force next pass to zero the color index table */
  178704. cquantize->needs_zeroed = TRUE;
  178705. }
  178706. METHODDEF(void)
  178707. finish_pass2 (j_decompress_ptr)
  178708. {
  178709. /* no work */
  178710. }
  178711. /*
  178712. * Initialize for each processing pass.
  178713. */
  178714. METHODDEF(void)
  178715. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178716. {
  178717. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178718. hist3d histogram = cquantize->histogram;
  178719. int i;
  178720. /* Only F-S dithering or no dithering is supported. */
  178721. /* If user asks for ordered dither, give him F-S. */
  178722. if (cinfo->dither_mode != JDITHER_NONE)
  178723. cinfo->dither_mode = JDITHER_FS;
  178724. if (is_pre_scan) {
  178725. /* Set up method pointers */
  178726. cquantize->pub.color_quantize = prescan_quantize;
  178727. cquantize->pub.finish_pass = finish_pass1;
  178728. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178729. } else {
  178730. /* Set up method pointers */
  178731. if (cinfo->dither_mode == JDITHER_FS)
  178732. cquantize->pub.color_quantize = pass2_fs_dither;
  178733. else
  178734. cquantize->pub.color_quantize = pass2_no_dither;
  178735. cquantize->pub.finish_pass = finish_pass2;
  178736. /* Make sure color count is acceptable */
  178737. i = cinfo->actual_number_of_colors;
  178738. if (i < 1)
  178739. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178740. if (i > MAXNUMCOLORS)
  178741. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178742. if (cinfo->dither_mode == JDITHER_FS) {
  178743. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178744. (3 * SIZEOF(FSERROR)));
  178745. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178746. if (cquantize->fserrors == NULL)
  178747. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178748. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178749. /* Initialize the propagated errors to zero. */
  178750. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178751. /* Make the error-limit table if we didn't already. */
  178752. if (cquantize->error_limiter == NULL)
  178753. init_error_limit(cinfo);
  178754. cquantize->on_odd_row = FALSE;
  178755. }
  178756. }
  178757. /* Zero the histogram or inverse color map, if necessary */
  178758. if (cquantize->needs_zeroed) {
  178759. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178760. jzero_far((void FAR *) histogram[i],
  178761. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178762. }
  178763. cquantize->needs_zeroed = FALSE;
  178764. }
  178765. }
  178766. /*
  178767. * Switch to a new external colormap between output passes.
  178768. */
  178769. METHODDEF(void)
  178770. new_color_map_2_quant (j_decompress_ptr cinfo)
  178771. {
  178772. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178773. /* Reset the inverse color map */
  178774. cquantize->needs_zeroed = TRUE;
  178775. }
  178776. /*
  178777. * Module initialization routine for 2-pass color quantization.
  178778. */
  178779. GLOBAL(void)
  178780. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178781. {
  178782. my_cquantize_ptr2 cquantize;
  178783. int i;
  178784. cquantize = (my_cquantize_ptr2)
  178785. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178786. SIZEOF(my_cquantizer2));
  178787. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178788. cquantize->pub.start_pass = start_pass_2_quant;
  178789. cquantize->pub.new_color_map = new_color_map_2_quant;
  178790. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178791. cquantize->error_limiter = NULL;
  178792. /* Make sure jdmaster didn't give me a case I can't handle */
  178793. if (cinfo->out_color_components != 3)
  178794. ERREXIT(cinfo, JERR_NOTIMPL);
  178795. /* Allocate the histogram/inverse colormap storage */
  178796. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178797. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178798. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178799. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178800. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178801. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178802. }
  178803. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178804. /* Allocate storage for the completed colormap, if required.
  178805. * We do this now since it is FAR storage and may affect
  178806. * the memory manager's space calculations.
  178807. */
  178808. if (cinfo->enable_2pass_quant) {
  178809. /* Make sure color count is acceptable */
  178810. int desired = cinfo->desired_number_of_colors;
  178811. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178812. if (desired < 8)
  178813. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178814. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178815. if (desired > MAXNUMCOLORS)
  178816. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178817. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178818. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178819. cquantize->desired = desired;
  178820. } else
  178821. cquantize->sv_colormap = NULL;
  178822. /* Only F-S dithering or no dithering is supported. */
  178823. /* If user asks for ordered dither, give him F-S. */
  178824. if (cinfo->dither_mode != JDITHER_NONE)
  178825. cinfo->dither_mode = JDITHER_FS;
  178826. /* Allocate Floyd-Steinberg workspace if necessary.
  178827. * This isn't really needed until pass 2, but again it is FAR storage.
  178828. * Although we will cope with a later change in dither_mode,
  178829. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178830. */
  178831. if (cinfo->dither_mode == JDITHER_FS) {
  178832. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178833. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178834. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178835. /* Might as well create the error-limiting table too. */
  178836. init_error_limit(cinfo);
  178837. }
  178838. }
  178839. #endif /* QUANT_2PASS_SUPPORTED */
  178840. /*** End of inlined file: jquant2.c ***/
  178841. /*** Start of inlined file: jutils.c ***/
  178842. #define JPEG_INTERNALS
  178843. /*
  178844. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178845. * of a DCT block read in natural order (left to right, top to bottom).
  178846. */
  178847. #if 0 /* This table is not actually needed in v6a */
  178848. const int jpeg_zigzag_order[DCTSIZE2] = {
  178849. 0, 1, 5, 6, 14, 15, 27, 28,
  178850. 2, 4, 7, 13, 16, 26, 29, 42,
  178851. 3, 8, 12, 17, 25, 30, 41, 43,
  178852. 9, 11, 18, 24, 31, 40, 44, 53,
  178853. 10, 19, 23, 32, 39, 45, 52, 54,
  178854. 20, 22, 33, 38, 46, 51, 55, 60,
  178855. 21, 34, 37, 47, 50, 56, 59, 61,
  178856. 35, 36, 48, 49, 57, 58, 62, 63
  178857. };
  178858. #endif
  178859. /*
  178860. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178861. * of zigzag order.
  178862. *
  178863. * When reading corrupted data, the Huffman decoders could attempt
  178864. * to reference an entry beyond the end of this array (if the decoded
  178865. * zero run length reaches past the end of the block). To prevent
  178866. * wild stores without adding an inner-loop test, we put some extra
  178867. * "63"s after the real entries. This will cause the extra coefficient
  178868. * to be stored in location 63 of the block, not somewhere random.
  178869. * The worst case would be a run-length of 15, which means we need 16
  178870. * fake entries.
  178871. */
  178872. const int jpeg_natural_order[DCTSIZE2+16] = {
  178873. 0, 1, 8, 16, 9, 2, 3, 10,
  178874. 17, 24, 32, 25, 18, 11, 4, 5,
  178875. 12, 19, 26, 33, 40, 48, 41, 34,
  178876. 27, 20, 13, 6, 7, 14, 21, 28,
  178877. 35, 42, 49, 56, 57, 50, 43, 36,
  178878. 29, 22, 15, 23, 30, 37, 44, 51,
  178879. 58, 59, 52, 45, 38, 31, 39, 46,
  178880. 53, 60, 61, 54, 47, 55, 62, 63,
  178881. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178882. 63, 63, 63, 63, 63, 63, 63, 63
  178883. };
  178884. /*
  178885. * Arithmetic utilities
  178886. */
  178887. GLOBAL(long)
  178888. jdiv_round_up (long a, long b)
  178889. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178890. /* Assumes a >= 0, b > 0 */
  178891. {
  178892. return (a + b - 1L) / b;
  178893. }
  178894. GLOBAL(long)
  178895. jround_up (long a, long b)
  178896. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178897. /* Assumes a >= 0, b > 0 */
  178898. {
  178899. a += b - 1L;
  178900. return a - (a % b);
  178901. }
  178902. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178903. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178904. * are FAR and we're assuming a small-pointer memory model. However, some
  178905. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178906. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178907. * Otherwise, the routines below do it the hard way. (The performance cost
  178908. * is not all that great, because these routines aren't very heavily used.)
  178909. */
  178910. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178911. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178912. #define FMEMZERO(target,size) MEMZERO(target,size)
  178913. #else /* 80x86 case, define if we can */
  178914. #ifdef USE_FMEM
  178915. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178916. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178917. #endif
  178918. #endif
  178919. GLOBAL(void)
  178920. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178921. JSAMPARRAY output_array, int dest_row,
  178922. int num_rows, JDIMENSION num_cols)
  178923. /* Copy some rows of samples from one place to another.
  178924. * num_rows rows are copied from input_array[source_row++]
  178925. * to output_array[dest_row++]; these areas may overlap for duplication.
  178926. * The source and destination arrays must be at least as wide as num_cols.
  178927. */
  178928. {
  178929. register JSAMPROW inptr, outptr;
  178930. #ifdef FMEMCOPY
  178931. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178932. #else
  178933. register JDIMENSION count;
  178934. #endif
  178935. register int row;
  178936. input_array += source_row;
  178937. output_array += dest_row;
  178938. for (row = num_rows; row > 0; row--) {
  178939. inptr = *input_array++;
  178940. outptr = *output_array++;
  178941. #ifdef FMEMCOPY
  178942. FMEMCOPY(outptr, inptr, count);
  178943. #else
  178944. for (count = num_cols; count > 0; count--)
  178945. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178946. #endif
  178947. }
  178948. }
  178949. GLOBAL(void)
  178950. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178951. JDIMENSION num_blocks)
  178952. /* Copy a row of coefficient blocks from one place to another. */
  178953. {
  178954. #ifdef FMEMCOPY
  178955. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178956. #else
  178957. register JCOEFPTR inptr, outptr;
  178958. register long count;
  178959. inptr = (JCOEFPTR) input_row;
  178960. outptr = (JCOEFPTR) output_row;
  178961. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178962. *outptr++ = *inptr++;
  178963. }
  178964. #endif
  178965. }
  178966. GLOBAL(void)
  178967. jzero_far (void FAR * target, size_t bytestozero)
  178968. /* Zero out a chunk of FAR memory. */
  178969. /* This might be sample-array data, block-array data, or alloc_large data. */
  178970. {
  178971. #ifdef FMEMZERO
  178972. FMEMZERO(target, bytestozero);
  178973. #else
  178974. register char FAR * ptr = (char FAR *) target;
  178975. register size_t count;
  178976. for (count = bytestozero; count > 0; count--) {
  178977. *ptr++ = 0;
  178978. }
  178979. #endif
  178980. }
  178981. /*** End of inlined file: jutils.c ***/
  178982. /*** Start of inlined file: transupp.c ***/
  178983. /* Although this file really shouldn't have access to the library internals,
  178984. * it's helpful to let it call jround_up() and jcopy_block_row().
  178985. */
  178986. #define JPEG_INTERNALS
  178987. /*** Start of inlined file: transupp.h ***/
  178988. /* If you happen not to want the image transform support, disable it here */
  178989. #ifndef TRANSFORMS_SUPPORTED
  178990. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178991. #endif
  178992. /* Short forms of external names for systems with brain-damaged linkers. */
  178993. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178994. #define jtransform_request_workspace jTrRequest
  178995. #define jtransform_adjust_parameters jTrAdjust
  178996. #define jtransform_execute_transformation jTrExec
  178997. #define jcopy_markers_setup jCMrkSetup
  178998. #define jcopy_markers_execute jCMrkExec
  178999. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179000. /*
  179001. * Codes for supported types of image transformations.
  179002. */
  179003. typedef enum {
  179004. JXFORM_NONE, /* no transformation */
  179005. JXFORM_FLIP_H, /* horizontal flip */
  179006. JXFORM_FLIP_V, /* vertical flip */
  179007. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179008. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179009. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179010. JXFORM_ROT_180, /* 180-degree rotation */
  179011. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179012. } JXFORM_CODE;
  179013. /*
  179014. * Although rotating and flipping data expressed as DCT coefficients is not
  179015. * hard, there is an asymmetry in the JPEG format specification for images
  179016. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179017. * image edges are padded out to the next iMCU boundary with junk data; but
  179018. * no padding is possible at the top and left edges. If we were to flip
  179019. * the whole image including the pad data, then pad garbage would become
  179020. * visible at the top and/or left, and real pixels would disappear into the
  179021. * pad margins --- perhaps permanently, since encoders & decoders may not
  179022. * bother to preserve DCT blocks that appear to be completely outside the
  179023. * nominal image area. So, we have to exclude any partial iMCUs from the
  179024. * basic transformation.
  179025. *
  179026. * Transpose is the only transformation that can handle partial iMCUs at the
  179027. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179028. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179029. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179030. * The other transforms are defined as combinations of these basic transforms
  179031. * and process edge blocks in a way that preserves the equivalence.
  179032. *
  179033. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179034. * this is not strictly lossless, but it usually gives the best-looking
  179035. * result for odd-size images. Note that when this option is active,
  179036. * the expected mathematical equivalences between the transforms may not hold.
  179037. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179038. * followed by -rot 180 -trim trims both edges.)
  179039. *
  179040. * We also offer a "force to grayscale" option, which simply discards the
  179041. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179042. * the luminance channel is preserved exactly. It's not the same kind of
  179043. * thing as the rotate/flip transformations, but it's convenient to handle it
  179044. * as part of this package, mainly because the transformation routines have to
  179045. * be aware of the option to know how many components to work on.
  179046. */
  179047. typedef struct {
  179048. /* Options: set by caller */
  179049. JXFORM_CODE transform; /* image transform operator */
  179050. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179051. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179052. /* Internal workspace: caller should not touch these */
  179053. int num_components; /* # of components in workspace */
  179054. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179055. } jpeg_transform_info;
  179056. #if TRANSFORMS_SUPPORTED
  179057. /* Request any required workspace */
  179058. EXTERN(void) jtransform_request_workspace
  179059. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179060. /* Adjust output image parameters */
  179061. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179062. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179063. jvirt_barray_ptr *src_coef_arrays,
  179064. jpeg_transform_info *info));
  179065. /* Execute the actual transformation, if any */
  179066. EXTERN(void) jtransform_execute_transformation
  179067. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179068. jvirt_barray_ptr *src_coef_arrays,
  179069. jpeg_transform_info *info));
  179070. #endif /* TRANSFORMS_SUPPORTED */
  179071. /*
  179072. * Support for copying optional markers from source to destination file.
  179073. */
  179074. typedef enum {
  179075. JCOPYOPT_NONE, /* copy no optional markers */
  179076. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179077. JCOPYOPT_ALL /* copy all optional markers */
  179078. } JCOPY_OPTION;
  179079. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179080. /* Setup decompression object to save desired markers in memory */
  179081. EXTERN(void) jcopy_markers_setup
  179082. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179083. /* Copy markers saved in the given source object to the destination object */
  179084. EXTERN(void) jcopy_markers_execute
  179085. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179086. JCOPY_OPTION option));
  179087. /*** End of inlined file: transupp.h ***/
  179088. /* My own external interface */
  179089. #if TRANSFORMS_SUPPORTED
  179090. /*
  179091. * Lossless image transformation routines. These routines work on DCT
  179092. * coefficient arrays and thus do not require any lossy decompression
  179093. * or recompression of the image.
  179094. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179095. *
  179096. * Horizontal flipping is done in-place, using a single top-to-bottom
  179097. * pass through the virtual source array. It will thus be much the
  179098. * fastest option for images larger than main memory.
  179099. *
  179100. * The other routines require a set of destination virtual arrays, so they
  179101. * need twice as much memory as jpegtran normally does. The destination
  179102. * arrays are always written in normal scan order (top to bottom) because
  179103. * the virtual array manager expects this. The source arrays will be scanned
  179104. * in the corresponding order, which means multiple passes through the source
  179105. * arrays for most of the transforms. That could result in much thrashing
  179106. * if the image is larger than main memory.
  179107. *
  179108. * Some notes about the operating environment of the individual transform
  179109. * routines:
  179110. * 1. Both the source and destination virtual arrays are allocated from the
  179111. * source JPEG object, and therefore should be manipulated by calling the
  179112. * source's memory manager.
  179113. * 2. The destination's component count should be used. It may be smaller
  179114. * than the source's when forcing to grayscale.
  179115. * 3. Likewise the destination's sampling factors should be used. When
  179116. * forcing to grayscale the destination's sampling factors will be all 1,
  179117. * and we may as well take that as the effective iMCU size.
  179118. * 4. When "trim" is in effect, the destination's dimensions will be the
  179119. * trimmed values but the source's will be untrimmed.
  179120. * 5. All the routines assume that the source and destination buffers are
  179121. * padded out to a full iMCU boundary. This is true, although for the
  179122. * source buffer it is an undocumented property of jdcoefct.c.
  179123. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179124. * dimensions and ignore the source's.
  179125. */
  179126. LOCAL(void)
  179127. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179128. jvirt_barray_ptr *src_coef_arrays)
  179129. /* Horizontal flip; done in-place, so no separate dest array is required */
  179130. {
  179131. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179132. int ci, k, offset_y;
  179133. JBLOCKARRAY buffer;
  179134. JCOEFPTR ptr1, ptr2;
  179135. JCOEF temp1, temp2;
  179136. jpeg_component_info *compptr;
  179137. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179138. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179139. * mirroring by changing the signs of odd-numbered columns.
  179140. * Partial iMCUs at the right edge are left untouched.
  179141. */
  179142. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179143. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179144. compptr = dstinfo->comp_info + ci;
  179145. comp_width = MCU_cols * compptr->h_samp_factor;
  179146. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179147. blk_y += compptr->v_samp_factor) {
  179148. buffer = (*srcinfo->mem->access_virt_barray)
  179149. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179150. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179151. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179152. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179153. ptr1 = buffer[offset_y][blk_x];
  179154. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179155. /* this unrolled loop doesn't need to know which row it's on... */
  179156. for (k = 0; k < DCTSIZE2; k += 2) {
  179157. temp1 = *ptr1; /* swap even column */
  179158. temp2 = *ptr2;
  179159. *ptr1++ = temp2;
  179160. *ptr2++ = temp1;
  179161. temp1 = *ptr1; /* swap odd column with sign change */
  179162. temp2 = *ptr2;
  179163. *ptr1++ = -temp2;
  179164. *ptr2++ = -temp1;
  179165. }
  179166. }
  179167. }
  179168. }
  179169. }
  179170. }
  179171. LOCAL(void)
  179172. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179173. jvirt_barray_ptr *src_coef_arrays,
  179174. jvirt_barray_ptr *dst_coef_arrays)
  179175. /* Vertical flip */
  179176. {
  179177. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179178. int ci, i, j, offset_y;
  179179. JBLOCKARRAY src_buffer, dst_buffer;
  179180. JBLOCKROW src_row_ptr, dst_row_ptr;
  179181. JCOEFPTR src_ptr, dst_ptr;
  179182. jpeg_component_info *compptr;
  179183. /* We output into a separate array because we can't touch different
  179184. * rows of the source virtual array simultaneously. Otherwise, this
  179185. * is a pretty straightforward analog of horizontal flip.
  179186. * Within a DCT block, vertical mirroring is done by changing the signs
  179187. * of odd-numbered rows.
  179188. * Partial iMCUs at the bottom edge are copied verbatim.
  179189. */
  179190. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179191. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179192. compptr = dstinfo->comp_info + ci;
  179193. comp_height = MCU_rows * compptr->v_samp_factor;
  179194. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179195. dst_blk_y += compptr->v_samp_factor) {
  179196. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179197. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179198. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179199. if (dst_blk_y < comp_height) {
  179200. /* Row is within the mirrorable area. */
  179201. src_buffer = (*srcinfo->mem->access_virt_barray)
  179202. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179203. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179204. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179205. } else {
  179206. /* Bottom-edge blocks will be copied verbatim. */
  179207. src_buffer = (*srcinfo->mem->access_virt_barray)
  179208. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179209. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179210. }
  179211. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179212. if (dst_blk_y < comp_height) {
  179213. /* Row is within the mirrorable area. */
  179214. dst_row_ptr = dst_buffer[offset_y];
  179215. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179216. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179217. dst_blk_x++) {
  179218. dst_ptr = dst_row_ptr[dst_blk_x];
  179219. src_ptr = src_row_ptr[dst_blk_x];
  179220. for (i = 0; i < DCTSIZE; i += 2) {
  179221. /* copy even row */
  179222. for (j = 0; j < DCTSIZE; j++)
  179223. *dst_ptr++ = *src_ptr++;
  179224. /* copy odd row with sign change */
  179225. for (j = 0; j < DCTSIZE; j++)
  179226. *dst_ptr++ = - *src_ptr++;
  179227. }
  179228. }
  179229. } else {
  179230. /* Just copy row verbatim. */
  179231. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179232. compptr->width_in_blocks);
  179233. }
  179234. }
  179235. }
  179236. }
  179237. }
  179238. LOCAL(void)
  179239. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179240. jvirt_barray_ptr *src_coef_arrays,
  179241. jvirt_barray_ptr *dst_coef_arrays)
  179242. /* Transpose source into destination */
  179243. {
  179244. JDIMENSION dst_blk_x, dst_blk_y;
  179245. int ci, i, j, offset_x, offset_y;
  179246. JBLOCKARRAY src_buffer, dst_buffer;
  179247. JCOEFPTR src_ptr, dst_ptr;
  179248. jpeg_component_info *compptr;
  179249. /* Transposing pixels within a block just requires transposing the
  179250. * DCT coefficients.
  179251. * Partial iMCUs at the edges require no special treatment; we simply
  179252. * process all the available DCT blocks for every component.
  179253. */
  179254. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179255. compptr = dstinfo->comp_info + ci;
  179256. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179257. dst_blk_y += compptr->v_samp_factor) {
  179258. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179259. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179260. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179261. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179262. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179263. dst_blk_x += compptr->h_samp_factor) {
  179264. src_buffer = (*srcinfo->mem->access_virt_barray)
  179265. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179266. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179267. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179268. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179269. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179270. for (i = 0; i < DCTSIZE; i++)
  179271. for (j = 0; j < DCTSIZE; j++)
  179272. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179273. }
  179274. }
  179275. }
  179276. }
  179277. }
  179278. }
  179279. LOCAL(void)
  179280. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179281. jvirt_barray_ptr *src_coef_arrays,
  179282. jvirt_barray_ptr *dst_coef_arrays)
  179283. /* 90 degree rotation is equivalent to
  179284. * 1. Transposing the image;
  179285. * 2. Horizontal mirroring.
  179286. * These two steps are merged into a single processing routine.
  179287. */
  179288. {
  179289. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179290. int ci, i, j, offset_x, offset_y;
  179291. JBLOCKARRAY src_buffer, dst_buffer;
  179292. JCOEFPTR src_ptr, dst_ptr;
  179293. jpeg_component_info *compptr;
  179294. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179295. * at the (output) right edge properly. They just get transposed and
  179296. * not mirrored.
  179297. */
  179298. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179299. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179300. compptr = dstinfo->comp_info + ci;
  179301. comp_width = MCU_cols * compptr->h_samp_factor;
  179302. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179303. dst_blk_y += compptr->v_samp_factor) {
  179304. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179305. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179306. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179307. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179308. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179309. dst_blk_x += compptr->h_samp_factor) {
  179310. src_buffer = (*srcinfo->mem->access_virt_barray)
  179311. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179312. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179313. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179314. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179315. if (dst_blk_x < comp_width) {
  179316. /* Block is within the mirrorable area. */
  179317. dst_ptr = dst_buffer[offset_y]
  179318. [comp_width - dst_blk_x - offset_x - 1];
  179319. for (i = 0; i < DCTSIZE; i++) {
  179320. for (j = 0; j < DCTSIZE; j++)
  179321. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179322. i++;
  179323. for (j = 0; j < DCTSIZE; j++)
  179324. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179325. }
  179326. } else {
  179327. /* Edge blocks are transposed but not mirrored. */
  179328. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179329. for (i = 0; i < DCTSIZE; i++)
  179330. for (j = 0; j < DCTSIZE; j++)
  179331. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179332. }
  179333. }
  179334. }
  179335. }
  179336. }
  179337. }
  179338. }
  179339. LOCAL(void)
  179340. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179341. jvirt_barray_ptr *src_coef_arrays,
  179342. jvirt_barray_ptr *dst_coef_arrays)
  179343. /* 270 degree rotation is equivalent to
  179344. * 1. Horizontal mirroring;
  179345. * 2. Transposing the image.
  179346. * These two steps are merged into a single processing routine.
  179347. */
  179348. {
  179349. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179350. int ci, i, j, offset_x, offset_y;
  179351. JBLOCKARRAY src_buffer, dst_buffer;
  179352. JCOEFPTR src_ptr, dst_ptr;
  179353. jpeg_component_info *compptr;
  179354. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179355. * at the (output) bottom edge properly. They just get transposed and
  179356. * not mirrored.
  179357. */
  179358. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179359. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179360. compptr = dstinfo->comp_info + ci;
  179361. comp_height = MCU_rows * compptr->v_samp_factor;
  179362. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179363. dst_blk_y += compptr->v_samp_factor) {
  179364. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179365. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179366. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179367. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179368. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179369. dst_blk_x += compptr->h_samp_factor) {
  179370. src_buffer = (*srcinfo->mem->access_virt_barray)
  179371. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179372. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179373. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179374. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179375. if (dst_blk_y < comp_height) {
  179376. /* Block is within the mirrorable area. */
  179377. src_ptr = src_buffer[offset_x]
  179378. [comp_height - dst_blk_y - offset_y - 1];
  179379. for (i = 0; i < DCTSIZE; i++) {
  179380. for (j = 0; j < DCTSIZE; j++) {
  179381. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179382. j++;
  179383. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179384. }
  179385. }
  179386. } else {
  179387. /* Edge blocks are transposed but not mirrored. */
  179388. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179389. for (i = 0; i < DCTSIZE; i++)
  179390. for (j = 0; j < DCTSIZE; j++)
  179391. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179392. }
  179393. }
  179394. }
  179395. }
  179396. }
  179397. }
  179398. }
  179399. LOCAL(void)
  179400. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179401. jvirt_barray_ptr *src_coef_arrays,
  179402. jvirt_barray_ptr *dst_coef_arrays)
  179403. /* 180 degree rotation is equivalent to
  179404. * 1. Vertical mirroring;
  179405. * 2. Horizontal mirroring.
  179406. * These two steps are merged into a single processing routine.
  179407. */
  179408. {
  179409. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179410. int ci, i, j, offset_y;
  179411. JBLOCKARRAY src_buffer, dst_buffer;
  179412. JBLOCKROW src_row_ptr, dst_row_ptr;
  179413. JCOEFPTR src_ptr, dst_ptr;
  179414. jpeg_component_info *compptr;
  179415. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179416. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179417. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179418. compptr = dstinfo->comp_info + ci;
  179419. comp_width = MCU_cols * compptr->h_samp_factor;
  179420. comp_height = MCU_rows * compptr->v_samp_factor;
  179421. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179422. dst_blk_y += compptr->v_samp_factor) {
  179423. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179424. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179425. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179426. if (dst_blk_y < comp_height) {
  179427. /* Row is within the vertically mirrorable area. */
  179428. src_buffer = (*srcinfo->mem->access_virt_barray)
  179429. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179430. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179431. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179432. } else {
  179433. /* Bottom-edge rows are only mirrored horizontally. */
  179434. src_buffer = (*srcinfo->mem->access_virt_barray)
  179435. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179436. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179437. }
  179438. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179439. if (dst_blk_y < comp_height) {
  179440. /* Row is within the mirrorable area. */
  179441. dst_row_ptr = dst_buffer[offset_y];
  179442. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179443. /* Process the blocks that can be mirrored both ways. */
  179444. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179445. dst_ptr = dst_row_ptr[dst_blk_x];
  179446. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179447. for (i = 0; i < DCTSIZE; i += 2) {
  179448. /* For even row, negate every odd column. */
  179449. for (j = 0; j < DCTSIZE; j += 2) {
  179450. *dst_ptr++ = *src_ptr++;
  179451. *dst_ptr++ = - *src_ptr++;
  179452. }
  179453. /* For odd row, negate every even column. */
  179454. for (j = 0; j < DCTSIZE; j += 2) {
  179455. *dst_ptr++ = - *src_ptr++;
  179456. *dst_ptr++ = *src_ptr++;
  179457. }
  179458. }
  179459. }
  179460. /* Any remaining right-edge blocks are only mirrored vertically. */
  179461. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179462. dst_ptr = dst_row_ptr[dst_blk_x];
  179463. src_ptr = src_row_ptr[dst_blk_x];
  179464. for (i = 0; i < DCTSIZE; i += 2) {
  179465. for (j = 0; j < DCTSIZE; j++)
  179466. *dst_ptr++ = *src_ptr++;
  179467. for (j = 0; j < DCTSIZE; j++)
  179468. *dst_ptr++ = - *src_ptr++;
  179469. }
  179470. }
  179471. } else {
  179472. /* Remaining rows are just mirrored horizontally. */
  179473. dst_row_ptr = dst_buffer[offset_y];
  179474. src_row_ptr = src_buffer[offset_y];
  179475. /* Process the blocks that can be mirrored. */
  179476. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179477. dst_ptr = dst_row_ptr[dst_blk_x];
  179478. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179479. for (i = 0; i < DCTSIZE2; i += 2) {
  179480. *dst_ptr++ = *src_ptr++;
  179481. *dst_ptr++ = - *src_ptr++;
  179482. }
  179483. }
  179484. /* Any remaining right-edge blocks are only copied. */
  179485. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179486. dst_ptr = dst_row_ptr[dst_blk_x];
  179487. src_ptr = src_row_ptr[dst_blk_x];
  179488. for (i = 0; i < DCTSIZE2; i++)
  179489. *dst_ptr++ = *src_ptr++;
  179490. }
  179491. }
  179492. }
  179493. }
  179494. }
  179495. }
  179496. LOCAL(void)
  179497. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179498. jvirt_barray_ptr *src_coef_arrays,
  179499. jvirt_barray_ptr *dst_coef_arrays)
  179500. /* Transverse transpose is equivalent to
  179501. * 1. 180 degree rotation;
  179502. * 2. Transposition;
  179503. * or
  179504. * 1. Horizontal mirroring;
  179505. * 2. Transposition;
  179506. * 3. Horizontal mirroring.
  179507. * These steps are merged into a single processing routine.
  179508. */
  179509. {
  179510. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179511. int ci, i, j, offset_x, offset_y;
  179512. JBLOCKARRAY src_buffer, dst_buffer;
  179513. JCOEFPTR src_ptr, dst_ptr;
  179514. jpeg_component_info *compptr;
  179515. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179516. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179517. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179518. compptr = dstinfo->comp_info + ci;
  179519. comp_width = MCU_cols * compptr->h_samp_factor;
  179520. comp_height = MCU_rows * compptr->v_samp_factor;
  179521. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179522. dst_blk_y += compptr->v_samp_factor) {
  179523. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179524. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179525. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179526. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179527. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179528. dst_blk_x += compptr->h_samp_factor) {
  179529. src_buffer = (*srcinfo->mem->access_virt_barray)
  179530. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179531. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179532. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179533. if (dst_blk_y < comp_height) {
  179534. src_ptr = src_buffer[offset_x]
  179535. [comp_height - dst_blk_y - offset_y - 1];
  179536. if (dst_blk_x < comp_width) {
  179537. /* Block is within the mirrorable area. */
  179538. dst_ptr = dst_buffer[offset_y]
  179539. [comp_width - dst_blk_x - offset_x - 1];
  179540. for (i = 0; i < DCTSIZE; i++) {
  179541. for (j = 0; j < DCTSIZE; j++) {
  179542. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179543. j++;
  179544. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179545. }
  179546. i++;
  179547. for (j = 0; j < DCTSIZE; j++) {
  179548. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179549. j++;
  179550. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179551. }
  179552. }
  179553. } else {
  179554. /* Right-edge blocks are mirrored in y only */
  179555. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179556. for (i = 0; i < DCTSIZE; i++) {
  179557. for (j = 0; j < DCTSIZE; j++) {
  179558. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179559. j++;
  179560. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179561. }
  179562. }
  179563. }
  179564. } else {
  179565. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179566. if (dst_blk_x < comp_width) {
  179567. /* Bottom-edge blocks are mirrored in x only */
  179568. dst_ptr = dst_buffer[offset_y]
  179569. [comp_width - dst_blk_x - offset_x - 1];
  179570. for (i = 0; i < DCTSIZE; i++) {
  179571. for (j = 0; j < DCTSIZE; j++)
  179572. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179573. i++;
  179574. for (j = 0; j < DCTSIZE; j++)
  179575. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179576. }
  179577. } else {
  179578. /* At lower right corner, just transpose, no mirroring */
  179579. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179580. for (i = 0; i < DCTSIZE; i++)
  179581. for (j = 0; j < DCTSIZE; j++)
  179582. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179583. }
  179584. }
  179585. }
  179586. }
  179587. }
  179588. }
  179589. }
  179590. }
  179591. /* Request any required workspace.
  179592. *
  179593. * We allocate the workspace virtual arrays from the source decompression
  179594. * object, so that all the arrays (both the original data and the workspace)
  179595. * will be taken into account while making memory management decisions.
  179596. * Hence, this routine must be called after jpeg_read_header (which reads
  179597. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179598. * the source's virtual arrays).
  179599. */
  179600. GLOBAL(void)
  179601. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179602. jpeg_transform_info *info)
  179603. {
  179604. jvirt_barray_ptr *coef_arrays = NULL;
  179605. jpeg_component_info *compptr;
  179606. int ci;
  179607. if (info->force_grayscale &&
  179608. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179609. srcinfo->num_components == 3) {
  179610. /* We'll only process the first component */
  179611. info->num_components = 1;
  179612. } else {
  179613. /* Process all the components */
  179614. info->num_components = srcinfo->num_components;
  179615. }
  179616. switch (info->transform) {
  179617. case JXFORM_NONE:
  179618. case JXFORM_FLIP_H:
  179619. /* Don't need a workspace array */
  179620. break;
  179621. case JXFORM_FLIP_V:
  179622. case JXFORM_ROT_180:
  179623. /* Need workspace arrays having same dimensions as source image.
  179624. * Note that we allocate arrays padded out to the next iMCU boundary,
  179625. * so that transform routines need not worry about missing edge blocks.
  179626. */
  179627. coef_arrays = (jvirt_barray_ptr *)
  179628. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179629. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179630. for (ci = 0; ci < info->num_components; ci++) {
  179631. compptr = srcinfo->comp_info + ci;
  179632. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179633. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179634. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179635. (long) compptr->h_samp_factor),
  179636. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179637. (long) compptr->v_samp_factor),
  179638. (JDIMENSION) compptr->v_samp_factor);
  179639. }
  179640. break;
  179641. case JXFORM_TRANSPOSE:
  179642. case JXFORM_TRANSVERSE:
  179643. case JXFORM_ROT_90:
  179644. case JXFORM_ROT_270:
  179645. /* Need workspace arrays having transposed dimensions.
  179646. * Note that we allocate arrays padded out to the next iMCU boundary,
  179647. * so that transform routines need not worry about missing edge blocks.
  179648. */
  179649. coef_arrays = (jvirt_barray_ptr *)
  179650. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179651. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179652. for (ci = 0; ci < info->num_components; ci++) {
  179653. compptr = srcinfo->comp_info + ci;
  179654. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179655. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179656. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179657. (long) compptr->v_samp_factor),
  179658. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179659. (long) compptr->h_samp_factor),
  179660. (JDIMENSION) compptr->h_samp_factor);
  179661. }
  179662. break;
  179663. }
  179664. info->workspace_coef_arrays = coef_arrays;
  179665. }
  179666. /* Transpose destination image parameters */
  179667. LOCAL(void)
  179668. transpose_critical_parameters (j_compress_ptr dstinfo)
  179669. {
  179670. int tblno, i, j, ci, itemp;
  179671. jpeg_component_info *compptr;
  179672. JQUANT_TBL *qtblptr;
  179673. JDIMENSION dtemp;
  179674. UINT16 qtemp;
  179675. /* Transpose basic image dimensions */
  179676. dtemp = dstinfo->image_width;
  179677. dstinfo->image_width = dstinfo->image_height;
  179678. dstinfo->image_height = dtemp;
  179679. /* Transpose sampling factors */
  179680. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179681. compptr = dstinfo->comp_info + ci;
  179682. itemp = compptr->h_samp_factor;
  179683. compptr->h_samp_factor = compptr->v_samp_factor;
  179684. compptr->v_samp_factor = itemp;
  179685. }
  179686. /* Transpose quantization tables */
  179687. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179688. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179689. if (qtblptr != NULL) {
  179690. for (i = 0; i < DCTSIZE; i++) {
  179691. for (j = 0; j < i; j++) {
  179692. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179693. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179694. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179695. }
  179696. }
  179697. }
  179698. }
  179699. }
  179700. /* Trim off any partial iMCUs on the indicated destination edge */
  179701. LOCAL(void)
  179702. trim_right_edge (j_compress_ptr dstinfo)
  179703. {
  179704. int ci, max_h_samp_factor;
  179705. JDIMENSION MCU_cols;
  179706. /* We have to compute max_h_samp_factor ourselves,
  179707. * because it hasn't been set yet in the destination
  179708. * (and we don't want to use the source's value).
  179709. */
  179710. max_h_samp_factor = 1;
  179711. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179712. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179713. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179714. }
  179715. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179716. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179717. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179718. }
  179719. LOCAL(void)
  179720. trim_bottom_edge (j_compress_ptr dstinfo)
  179721. {
  179722. int ci, max_v_samp_factor;
  179723. JDIMENSION MCU_rows;
  179724. /* We have to compute max_v_samp_factor ourselves,
  179725. * because it hasn't been set yet in the destination
  179726. * (and we don't want to use the source's value).
  179727. */
  179728. max_v_samp_factor = 1;
  179729. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179730. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179731. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179732. }
  179733. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179734. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179735. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179736. }
  179737. /* Adjust output image parameters as needed.
  179738. *
  179739. * This must be called after jpeg_copy_critical_parameters()
  179740. * and before jpeg_write_coefficients().
  179741. *
  179742. * The return value is the set of virtual coefficient arrays to be written
  179743. * (either the ones allocated by jtransform_request_workspace, or the
  179744. * original source data arrays). The caller will need to pass this value
  179745. * to jpeg_write_coefficients().
  179746. */
  179747. GLOBAL(jvirt_barray_ptr *)
  179748. jtransform_adjust_parameters (j_decompress_ptr,
  179749. j_compress_ptr dstinfo,
  179750. jvirt_barray_ptr *src_coef_arrays,
  179751. jpeg_transform_info *info)
  179752. {
  179753. /* If force-to-grayscale is requested, adjust destination parameters */
  179754. if (info->force_grayscale) {
  179755. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179756. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179757. * will get set to 1, which typically won't match the source.
  179758. * In fact we do this even if the source is already grayscale; that
  179759. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179760. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179761. */
  179762. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179763. dstinfo->num_components == 3) ||
  179764. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179765. dstinfo->num_components == 1)) {
  179766. /* We have to preserve the source's quantization table number. */
  179767. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179768. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179769. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179770. } else {
  179771. /* Sorry, can't do it */
  179772. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179773. }
  179774. }
  179775. /* Correct the destination's image dimensions etc if necessary */
  179776. switch (info->transform) {
  179777. case JXFORM_NONE:
  179778. /* Nothing to do */
  179779. break;
  179780. case JXFORM_FLIP_H:
  179781. if (info->trim)
  179782. trim_right_edge(dstinfo);
  179783. break;
  179784. case JXFORM_FLIP_V:
  179785. if (info->trim)
  179786. trim_bottom_edge(dstinfo);
  179787. break;
  179788. case JXFORM_TRANSPOSE:
  179789. transpose_critical_parameters(dstinfo);
  179790. /* transpose does NOT have to trim anything */
  179791. break;
  179792. case JXFORM_TRANSVERSE:
  179793. transpose_critical_parameters(dstinfo);
  179794. if (info->trim) {
  179795. trim_right_edge(dstinfo);
  179796. trim_bottom_edge(dstinfo);
  179797. }
  179798. break;
  179799. case JXFORM_ROT_90:
  179800. transpose_critical_parameters(dstinfo);
  179801. if (info->trim)
  179802. trim_right_edge(dstinfo);
  179803. break;
  179804. case JXFORM_ROT_180:
  179805. if (info->trim) {
  179806. trim_right_edge(dstinfo);
  179807. trim_bottom_edge(dstinfo);
  179808. }
  179809. break;
  179810. case JXFORM_ROT_270:
  179811. transpose_critical_parameters(dstinfo);
  179812. if (info->trim)
  179813. trim_bottom_edge(dstinfo);
  179814. break;
  179815. }
  179816. /* Return the appropriate output data set */
  179817. if (info->workspace_coef_arrays != NULL)
  179818. return info->workspace_coef_arrays;
  179819. return src_coef_arrays;
  179820. }
  179821. /* Execute the actual transformation, if any.
  179822. *
  179823. * This must be called *after* jpeg_write_coefficients, because it depends
  179824. * on jpeg_write_coefficients to have computed subsidiary values such as
  179825. * the per-component width and height fields in the destination object.
  179826. *
  179827. * Note that some transformations will modify the source data arrays!
  179828. */
  179829. GLOBAL(void)
  179830. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179831. j_compress_ptr dstinfo,
  179832. jvirt_barray_ptr *src_coef_arrays,
  179833. jpeg_transform_info *info)
  179834. {
  179835. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179836. switch (info->transform) {
  179837. case JXFORM_NONE:
  179838. break;
  179839. case JXFORM_FLIP_H:
  179840. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179841. break;
  179842. case JXFORM_FLIP_V:
  179843. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179844. break;
  179845. case JXFORM_TRANSPOSE:
  179846. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179847. break;
  179848. case JXFORM_TRANSVERSE:
  179849. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179850. break;
  179851. case JXFORM_ROT_90:
  179852. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179853. break;
  179854. case JXFORM_ROT_180:
  179855. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179856. break;
  179857. case JXFORM_ROT_270:
  179858. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179859. break;
  179860. }
  179861. }
  179862. #endif /* TRANSFORMS_SUPPORTED */
  179863. /* Setup decompression object to save desired markers in memory.
  179864. * This must be called before jpeg_read_header() to have the desired effect.
  179865. */
  179866. GLOBAL(void)
  179867. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179868. {
  179869. #ifdef SAVE_MARKERS_SUPPORTED
  179870. int m;
  179871. /* Save comments except under NONE option */
  179872. if (option != JCOPYOPT_NONE) {
  179873. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179874. }
  179875. /* Save all types of APPn markers iff ALL option */
  179876. if (option == JCOPYOPT_ALL) {
  179877. for (m = 0; m < 16; m++)
  179878. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179879. }
  179880. #endif /* SAVE_MARKERS_SUPPORTED */
  179881. }
  179882. /* Copy markers saved in the given source object to the destination object.
  179883. * This should be called just after jpeg_start_compress() or
  179884. * jpeg_write_coefficients().
  179885. * Note that those routines will have written the SOI, and also the
  179886. * JFIF APP0 or Adobe APP14 markers if selected.
  179887. */
  179888. GLOBAL(void)
  179889. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179890. JCOPY_OPTION)
  179891. {
  179892. jpeg_saved_marker_ptr marker;
  179893. /* In the current implementation, we don't actually need to examine the
  179894. * option flag here; we just copy everything that got saved.
  179895. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179896. * if the encoder library already wrote one.
  179897. */
  179898. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179899. if (dstinfo->write_JFIF_header &&
  179900. marker->marker == JPEG_APP0 &&
  179901. marker->data_length >= 5 &&
  179902. GETJOCTET(marker->data[0]) == 0x4A &&
  179903. GETJOCTET(marker->data[1]) == 0x46 &&
  179904. GETJOCTET(marker->data[2]) == 0x49 &&
  179905. GETJOCTET(marker->data[3]) == 0x46 &&
  179906. GETJOCTET(marker->data[4]) == 0)
  179907. continue; /* reject duplicate JFIF */
  179908. if (dstinfo->write_Adobe_marker &&
  179909. marker->marker == JPEG_APP0+14 &&
  179910. marker->data_length >= 5 &&
  179911. GETJOCTET(marker->data[0]) == 0x41 &&
  179912. GETJOCTET(marker->data[1]) == 0x64 &&
  179913. GETJOCTET(marker->data[2]) == 0x6F &&
  179914. GETJOCTET(marker->data[3]) == 0x62 &&
  179915. GETJOCTET(marker->data[4]) == 0x65)
  179916. continue; /* reject duplicate Adobe */
  179917. #ifdef NEED_FAR_POINTERS
  179918. /* We could use jpeg_write_marker if the data weren't FAR... */
  179919. {
  179920. unsigned int i;
  179921. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179922. for (i = 0; i < marker->data_length; i++)
  179923. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179924. }
  179925. #else
  179926. jpeg_write_marker(dstinfo, marker->marker,
  179927. marker->data, marker->data_length);
  179928. #endif
  179929. }
  179930. }
  179931. /*** End of inlined file: transupp.c ***/
  179932. #else
  179933. #define JPEG_INTERNALS
  179934. #undef FAR
  179935. #include <jpeglib.h>
  179936. #endif
  179937. }
  179938. #undef max
  179939. #undef min
  179940. #if JUCE_MSVC
  179941. #pragma warning (pop)
  179942. #endif
  179943. BEGIN_JUCE_NAMESPACE
  179944. namespace JPEGHelpers
  179945. {
  179946. using namespace jpeglibNamespace;
  179947. #if ! JUCE_MSVC
  179948. using jpeglibNamespace::boolean;
  179949. #endif
  179950. struct JPEGDecodingFailure {};
  179951. static void fatalErrorHandler (j_common_ptr)
  179952. {
  179953. throw JPEGDecodingFailure();
  179954. }
  179955. static void silentErrorCallback1 (j_common_ptr) {}
  179956. static void silentErrorCallback2 (j_common_ptr, int) {}
  179957. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179958. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179959. {
  179960. zerostruct (err);
  179961. err.error_exit = fatalErrorHandler;
  179962. err.emit_message = silentErrorCallback2;
  179963. err.output_message = silentErrorCallback1;
  179964. err.format_message = silentErrorCallback3;
  179965. err.reset_error_mgr = silentErrorCallback1;
  179966. }
  179967. static void dummyCallback1 (j_decompress_ptr)
  179968. {
  179969. }
  179970. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179971. {
  179972. decompStruct->src->next_input_byte += num;
  179973. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179974. decompStruct->src->bytes_in_buffer -= num;
  179975. }
  179976. static boolean jpegFill (j_decompress_ptr)
  179977. {
  179978. return 0;
  179979. }
  179980. static const int jpegBufferSize = 512;
  179981. struct JuceJpegDest : public jpeg_destination_mgr
  179982. {
  179983. OutputStream* output;
  179984. char* buffer;
  179985. };
  179986. static void jpegWriteInit (j_compress_ptr)
  179987. {
  179988. }
  179989. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179990. {
  179991. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179992. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179993. dest->output->write (dest->buffer, (int) numToWrite);
  179994. }
  179995. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179996. {
  179997. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179998. const int numToWrite = jpegBufferSize;
  179999. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180000. dest->free_in_buffer = jpegBufferSize;
  180001. return dest->output->write (dest->buffer, numToWrite);
  180002. }
  180003. }
  180004. JPEGImageFormat::JPEGImageFormat()
  180005. : quality (-1.0f)
  180006. {
  180007. }
  180008. JPEGImageFormat::~JPEGImageFormat() {}
  180009. void JPEGImageFormat::setQuality (const float newQuality)
  180010. {
  180011. quality = newQuality;
  180012. }
  180013. const String JPEGImageFormat::getFormatName()
  180014. {
  180015. return "JPEG";
  180016. }
  180017. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180018. {
  180019. const int bytesNeeded = 10;
  180020. uint8 header [bytesNeeded];
  180021. if (in.read (header, bytesNeeded) == bytesNeeded)
  180022. {
  180023. return header[0] == 0xff
  180024. && header[1] == 0xd8
  180025. && header[2] == 0xff
  180026. && (header[3] == 0xe0 || header[3] == 0xe1);
  180027. }
  180028. return false;
  180029. }
  180030. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180031. const Image juce_loadWithCoreImage (InputStream& input);
  180032. #endif
  180033. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180034. {
  180035. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180036. return juce_loadWithCoreImage (in);
  180037. #else
  180038. using namespace jpeglibNamespace;
  180039. using namespace JPEGHelpers;
  180040. MemoryOutputStream mb;
  180041. mb.writeFromInputStream (in, -1);
  180042. Image image;
  180043. if (mb.getDataSize() > 16)
  180044. {
  180045. struct jpeg_decompress_struct jpegDecompStruct;
  180046. struct jpeg_error_mgr jerr;
  180047. setupSilentErrorHandler (jerr);
  180048. jpegDecompStruct.err = &jerr;
  180049. jpeg_create_decompress (&jpegDecompStruct);
  180050. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180051. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180052. jpegDecompStruct.src->init_source = dummyCallback1;
  180053. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180054. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180055. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180056. jpegDecompStruct.src->term_source = dummyCallback1;
  180057. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180058. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180059. try
  180060. {
  180061. jpeg_read_header (&jpegDecompStruct, TRUE);
  180062. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180063. const int width = jpegDecompStruct.output_width;
  180064. const int height = jpegDecompStruct.output_height;
  180065. jpegDecompStruct.out_color_space = JCS_RGB;
  180066. JSAMPARRAY buffer
  180067. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180068. JPOOL_IMAGE,
  180069. width * 3, 1);
  180070. if (jpeg_start_decompress (&jpegDecompStruct))
  180071. {
  180072. image = Image (Image::RGB, width, height, false);
  180073. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180074. const Image::BitmapData destData (image, true);
  180075. for (int y = 0; y < height; ++y)
  180076. {
  180077. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180078. const uint8* src = *buffer;
  180079. uint8* dest = destData.getLinePointer (y);
  180080. if (hasAlphaChan)
  180081. {
  180082. for (int i = width; --i >= 0;)
  180083. {
  180084. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180085. ((PixelARGB*) dest)->premultiply();
  180086. dest += destData.pixelStride;
  180087. src += 3;
  180088. }
  180089. }
  180090. else
  180091. {
  180092. for (int i = width; --i >= 0;)
  180093. {
  180094. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180095. dest += destData.pixelStride;
  180096. src += 3;
  180097. }
  180098. }
  180099. }
  180100. jpeg_finish_decompress (&jpegDecompStruct);
  180101. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180102. }
  180103. jpeg_destroy_decompress (&jpegDecompStruct);
  180104. }
  180105. catch (...)
  180106. {}
  180107. }
  180108. return image;
  180109. #endif
  180110. }
  180111. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180112. {
  180113. using namespace jpeglibNamespace;
  180114. using namespace JPEGHelpers;
  180115. if (image.hasAlphaChannel())
  180116. {
  180117. // this method could fill the background in white and still save the image..
  180118. jassertfalse;
  180119. return true;
  180120. }
  180121. struct jpeg_compress_struct jpegCompStruct;
  180122. struct jpeg_error_mgr jerr;
  180123. setupSilentErrorHandler (jerr);
  180124. jpegCompStruct.err = &jerr;
  180125. jpeg_create_compress (&jpegCompStruct);
  180126. JuceJpegDest dest;
  180127. jpegCompStruct.dest = &dest;
  180128. dest.output = &out;
  180129. HeapBlock <char> tempBuffer (jpegBufferSize);
  180130. dest.buffer = tempBuffer;
  180131. dest.next_output_byte = (JOCTET*) dest.buffer;
  180132. dest.free_in_buffer = jpegBufferSize;
  180133. dest.init_destination = jpegWriteInit;
  180134. dest.empty_output_buffer = jpegWriteFlush;
  180135. dest.term_destination = jpegWriteTerminate;
  180136. jpegCompStruct.image_width = image.getWidth();
  180137. jpegCompStruct.image_height = image.getHeight();
  180138. jpegCompStruct.input_components = 3;
  180139. jpegCompStruct.in_color_space = JCS_RGB;
  180140. jpegCompStruct.write_JFIF_header = 1;
  180141. jpegCompStruct.X_density = 72;
  180142. jpegCompStruct.Y_density = 72;
  180143. jpeg_set_defaults (&jpegCompStruct);
  180144. jpegCompStruct.dct_method = JDCT_FLOAT;
  180145. jpegCompStruct.optimize_coding = 1;
  180146. //jpegCompStruct.smoothing_factor = 10;
  180147. if (quality < 0.0f)
  180148. quality = 0.85f;
  180149. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180150. jpeg_start_compress (&jpegCompStruct, TRUE);
  180151. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180152. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180153. JPOOL_IMAGE, strideBytes, 1);
  180154. const Image::BitmapData srcData (image, false);
  180155. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180156. {
  180157. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180158. uint8* dst = *buffer;
  180159. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180160. {
  180161. *dst++ = ((const PixelRGB*) src)->getRed();
  180162. *dst++ = ((const PixelRGB*) src)->getGreen();
  180163. *dst++ = ((const PixelRGB*) src)->getBlue();
  180164. src += srcData.pixelStride;
  180165. }
  180166. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180167. }
  180168. jpeg_finish_compress (&jpegCompStruct);
  180169. jpeg_destroy_compress (&jpegCompStruct);
  180170. out.flush();
  180171. return true;
  180172. }
  180173. END_JUCE_NAMESPACE
  180174. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180175. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180176. #if JUCE_MSVC
  180177. #pragma warning (push)
  180178. #pragma warning (disable: 4390 4611)
  180179. #endif
  180180. namespace zlibNamespace
  180181. {
  180182. #if JUCE_INCLUDE_ZLIB_CODE
  180183. #undef OS_CODE
  180184. #undef fdopen
  180185. #undef OS_CODE
  180186. #else
  180187. #include <zlib.h>
  180188. #endif
  180189. }
  180190. namespace pnglibNamespace
  180191. {
  180192. using namespace zlibNamespace;
  180193. #if JUCE_INCLUDE_PNGLIB_CODE
  180194. #if _MSC_VER != 1310
  180195. using ::calloc; // (causes conflict in VS.NET 2003)
  180196. using ::malloc;
  180197. using ::free;
  180198. #endif
  180199. using ::abs;
  180200. #define PNG_INTERNAL
  180201. #define NO_DUMMY_DECL
  180202. #define PNG_SETJMP_NOT_SUPPORTED
  180203. /*** Start of inlined file: png.h ***/
  180204. /* png.h - header file for PNG reference library
  180205. *
  180206. * libpng version 1.2.21 - October 4, 2007
  180207. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180208. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180209. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180210. *
  180211. * Authors and maintainers:
  180212. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180213. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180214. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180215. * See also "Contributing Authors", below.
  180216. *
  180217. * Note about libpng version numbers:
  180218. *
  180219. * Due to various miscommunications, unforeseen code incompatibilities
  180220. * and occasional factors outside the authors' control, version numbering
  180221. * on the library has not always been consistent and straightforward.
  180222. * The following table summarizes matters since version 0.89c, which was
  180223. * the first widely used release:
  180224. *
  180225. * source png.h png.h shared-lib
  180226. * version string int version
  180227. * ------- ------ ----- ----------
  180228. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180229. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180230. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180231. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180232. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180233. * 0.97c 0.97 97 2.0.97
  180234. * 0.98 0.98 98 2.0.98
  180235. * 0.99 0.99 98 2.0.99
  180236. * 0.99a-m 0.99 99 2.0.99
  180237. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180238. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180239. * 1.0.1 png.h string is 10001 2.1.0
  180240. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180241. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180242. * 1.0.2a-b 10003 version, except as noted.
  180243. * 1.0.3 10003
  180244. * 1.0.3a-d 10004
  180245. * 1.0.4 10004
  180246. * 1.0.4a-f 10005
  180247. * 1.0.5 (+ 2 patches) 10005
  180248. * 1.0.5a-d 10006
  180249. * 1.0.5e-r 10100 (not source compatible)
  180250. * 1.0.5s-v 10006 (not binary compatible)
  180251. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180252. * 1.0.6d-f 10007 (still binary incompatible)
  180253. * 1.0.6g 10007
  180254. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180255. * 1.0.6i 10007 10.6i
  180256. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180257. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180258. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180259. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180260. * 1.0.7 1 10007 (still compatible)
  180261. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180262. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180263. * 1.0.8 1 10008 2.1.0.8
  180264. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180265. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180266. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180267. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180268. * 1.0.9 1 10009 2.1.0.9
  180269. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180270. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180271. * 1.0.10 1 10010 2.1.0.10
  180272. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180273. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180274. * 1.0.11 1 10011 2.1.0.11
  180275. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180276. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180277. * 1.0.12 2 10012 2.1.0.12
  180278. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180279. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180280. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180281. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180282. * 1.2.0 3 10200 3.1.2.0
  180283. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180284. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180285. * 1.2.1 3 10201 3.1.2.1
  180286. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180287. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180288. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180289. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180290. * 1.0.13 10 10013 10.so.0.1.0.13
  180291. * 1.2.2 12 10202 12.so.0.1.2.2
  180292. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180293. * 1.2.3 12 10203 12.so.0.1.2.3
  180294. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180295. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180296. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180297. * 1.0.14 10 10014 10.so.0.1.0.14
  180298. * 1.2.4 13 10204 12.so.0.1.2.4
  180299. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180300. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180301. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180302. * 1.0.15 10 10015 10.so.0.1.0.15
  180303. * 1.2.5 13 10205 12.so.0.1.2.5
  180304. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180305. * 1.0.16 10 10016 10.so.0.1.0.16
  180306. * 1.2.6 13 10206 12.so.0.1.2.6
  180307. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180308. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180309. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180310. * 1.0.17 10 10017 10.so.0.1.0.17
  180311. * 1.2.7 13 10207 12.so.0.1.2.7
  180312. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180313. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180314. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180315. * 1.0.18 10 10018 10.so.0.1.0.18
  180316. * 1.2.8 13 10208 12.so.0.1.2.8
  180317. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180318. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180319. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180320. * 1.2.9 13 10209 12.so.0.9[.0]
  180321. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180322. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180323. * 1.2.10 13 10210 12.so.0.10[.0]
  180324. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180325. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180326. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180327. * 1.0.19 10 10019 10.so.0.19[.0]
  180328. * 1.2.11 13 10211 12.so.0.11[.0]
  180329. * 1.0.20 10 10020 10.so.0.20[.0]
  180330. * 1.2.12 13 10212 12.so.0.12[.0]
  180331. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180332. * 1.0.21 10 10021 10.so.0.21[.0]
  180333. * 1.2.13 13 10213 12.so.0.13[.0]
  180334. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180335. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180336. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180337. * 1.0.22 10 10022 10.so.0.22[.0]
  180338. * 1.2.14 13 10214 12.so.0.14[.0]
  180339. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180340. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180341. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180342. * 1.0.23 10 10023 10.so.0.23[.0]
  180343. * 1.2.15 13 10215 12.so.0.15[.0]
  180344. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180345. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180346. * 1.0.24 10 10024 10.so.0.24[.0]
  180347. * 1.2.16 13 10216 12.so.0.16[.0]
  180348. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180349. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180350. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180351. * 1.0.25 10 10025 10.so.0.25[.0]
  180352. * 1.2.17 13 10217 12.so.0.17[.0]
  180353. * 1.0.26 10 10026 10.so.0.26[.0]
  180354. * 1.2.18 13 10218 12.so.0.18[.0]
  180355. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180356. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180357. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180358. * 1.0.27 10 10027 10.so.0.27[.0]
  180359. * 1.2.19 13 10219 12.so.0.19[.0]
  180360. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180361. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180362. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180363. * 1.0.28 10 10028 10.so.0.28[.0]
  180364. * 1.2.20 13 10220 12.so.0.20[.0]
  180365. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180366. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180367. * 1.0.29 10 10029 10.so.0.29[.0]
  180368. * 1.2.21 13 10221 12.so.0.21[.0]
  180369. *
  180370. * Henceforth the source version will match the shared-library major
  180371. * and minor numbers; the shared-library major version number will be
  180372. * used for changes in backward compatibility, as it is intended. The
  180373. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180374. * for applications, is an unsigned integer of the form xyyzz corresponding
  180375. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180376. * were given the previous public release number plus a letter, until
  180377. * version 1.0.6j; from then on they were given the upcoming public
  180378. * release number plus "betaNN" or "rcN".
  180379. *
  180380. * Binary incompatibility exists only when applications make direct access
  180381. * to the info_ptr or png_ptr members through png.h, and the compiled
  180382. * application is loaded with a different version of the library.
  180383. *
  180384. * DLLNUM will change each time there are forward or backward changes
  180385. * in binary compatibility (e.g., when a new feature is added).
  180386. *
  180387. * See libpng.txt or libpng.3 for more information. The PNG specification
  180388. * is available as a W3C Recommendation and as an ISO Specification,
  180389. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180390. */
  180391. /*
  180392. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180393. *
  180394. * If you modify libpng you may insert additional notices immediately following
  180395. * this sentence.
  180396. *
  180397. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180398. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180399. * distributed according to the same disclaimer and license as libpng-1.2.5
  180400. * with the following individual added to the list of Contributing Authors:
  180401. *
  180402. * Cosmin Truta
  180403. *
  180404. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180405. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180406. * distributed according to the same disclaimer and license as libpng-1.0.6
  180407. * with the following individuals added to the list of Contributing Authors:
  180408. *
  180409. * Simon-Pierre Cadieux
  180410. * Eric S. Raymond
  180411. * Gilles Vollant
  180412. *
  180413. * and with the following additions to the disclaimer:
  180414. *
  180415. * There is no warranty against interference with your enjoyment of the
  180416. * library or against infringement. There is no warranty that our
  180417. * efforts or the library will fulfill any of your particular purposes
  180418. * or needs. This library is provided with all faults, and the entire
  180419. * risk of satisfactory quality, performance, accuracy, and effort is with
  180420. * the user.
  180421. *
  180422. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180423. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180424. * distributed according to the same disclaimer and license as libpng-0.96,
  180425. * with the following individuals added to the list of Contributing Authors:
  180426. *
  180427. * Tom Lane
  180428. * Glenn Randers-Pehrson
  180429. * Willem van Schaik
  180430. *
  180431. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180432. * Copyright (c) 1996, 1997 Andreas Dilger
  180433. * Distributed according to the same disclaimer and license as libpng-0.88,
  180434. * with the following individuals added to the list of Contributing Authors:
  180435. *
  180436. * John Bowler
  180437. * Kevin Bracey
  180438. * Sam Bushell
  180439. * Magnus Holmgren
  180440. * Greg Roelofs
  180441. * Tom Tanner
  180442. *
  180443. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180444. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180445. *
  180446. * For the purposes of this copyright and license, "Contributing Authors"
  180447. * is defined as the following set of individuals:
  180448. *
  180449. * Andreas Dilger
  180450. * Dave Martindale
  180451. * Guy Eric Schalnat
  180452. * Paul Schmidt
  180453. * Tim Wegner
  180454. *
  180455. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180456. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180457. * including, without limitation, the warranties of merchantability and of
  180458. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180459. * assume no liability for direct, indirect, incidental, special, exemplary,
  180460. * or consequential damages, which may result from the use of the PNG
  180461. * Reference Library, even if advised of the possibility of such damage.
  180462. *
  180463. * Permission is hereby granted to use, copy, modify, and distribute this
  180464. * source code, or portions hereof, for any purpose, without fee, subject
  180465. * to the following restrictions:
  180466. *
  180467. * 1. The origin of this source code must not be misrepresented.
  180468. *
  180469. * 2. Altered versions must be plainly marked as such and
  180470. * must not be misrepresented as being the original source.
  180471. *
  180472. * 3. This Copyright notice may not be removed or altered from
  180473. * any source or altered source distribution.
  180474. *
  180475. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180476. * fee, and encourage the use of this source code as a component to
  180477. * supporting the PNG file format in commercial products. If you use this
  180478. * source code in a product, acknowledgment is not required but would be
  180479. * appreciated.
  180480. */
  180481. /*
  180482. * A "png_get_copyright" function is available, for convenient use in "about"
  180483. * boxes and the like:
  180484. *
  180485. * printf("%s",png_get_copyright(NULL));
  180486. *
  180487. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180488. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180489. */
  180490. /*
  180491. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180492. * certification mark of the Open Source Initiative.
  180493. */
  180494. /*
  180495. * The contributing authors would like to thank all those who helped
  180496. * with testing, bug fixes, and patience. This wouldn't have been
  180497. * possible without all of you.
  180498. *
  180499. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180500. */
  180501. /*
  180502. * Y2K compliance in libpng:
  180503. * =========================
  180504. *
  180505. * October 4, 2007
  180506. *
  180507. * Since the PNG Development group is an ad-hoc body, we can't make
  180508. * an official declaration.
  180509. *
  180510. * This is your unofficial assurance that libpng from version 0.71 and
  180511. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180512. * versions were also Y2K compliant.
  180513. *
  180514. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180515. * that will hold years up to 65535. The other two hold the date in text
  180516. * format, and will hold years up to 9999.
  180517. *
  180518. * The integer is
  180519. * "png_uint_16 year" in png_time_struct.
  180520. *
  180521. * The strings are
  180522. * "png_charp time_buffer" in png_struct and
  180523. * "near_time_buffer", which is a local character string in png.c.
  180524. *
  180525. * There are seven time-related functions:
  180526. * png.c: png_convert_to_rfc_1123() in png.c
  180527. * (formerly png_convert_to_rfc_1152() in error)
  180528. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180529. * png_convert_from_time_t() in pngwrite.c
  180530. * png_get_tIME() in pngget.c
  180531. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180532. * png_set_tIME() in pngset.c
  180533. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180534. *
  180535. * All handle dates properly in a Y2K environment. The
  180536. * png_convert_from_time_t() function calls gmtime() to convert from system
  180537. * clock time, which returns (year - 1900), which we properly convert to
  180538. * the full 4-digit year. There is a possibility that applications using
  180539. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180540. * function, or that they are incorrectly passing only a 2-digit year
  180541. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180542. * but this is not under our control. The libpng documentation has always
  180543. * stated that it works with 4-digit years, and the APIs have been
  180544. * documented as such.
  180545. *
  180546. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180547. * integer to hold the year, and can hold years as large as 65535.
  180548. *
  180549. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180550. * no date-related code.
  180551. *
  180552. * Glenn Randers-Pehrson
  180553. * libpng maintainer
  180554. * PNG Development Group
  180555. */
  180556. #ifndef PNG_H
  180557. #define PNG_H
  180558. /* This is not the place to learn how to use libpng. The file libpng.txt
  180559. * describes how to use libpng, and the file example.c summarizes it
  180560. * with some code on which to build. This file is useful for looking
  180561. * at the actual function definitions and structure components.
  180562. */
  180563. /* Version information for png.h - this should match the version in png.c */
  180564. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180565. #define PNG_HEADER_VERSION_STRING \
  180566. " libpng version 1.2.21 - October 4, 2007\n"
  180567. #define PNG_LIBPNG_VER_SONUM 0
  180568. #define PNG_LIBPNG_VER_DLLNUM 13
  180569. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180570. #define PNG_LIBPNG_VER_MAJOR 1
  180571. #define PNG_LIBPNG_VER_MINOR 2
  180572. #define PNG_LIBPNG_VER_RELEASE 21
  180573. /* This should match the numeric part of the final component of
  180574. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180575. #define PNG_LIBPNG_VER_BUILD 0
  180576. /* Release Status */
  180577. #define PNG_LIBPNG_BUILD_ALPHA 1
  180578. #define PNG_LIBPNG_BUILD_BETA 2
  180579. #define PNG_LIBPNG_BUILD_RC 3
  180580. #define PNG_LIBPNG_BUILD_STABLE 4
  180581. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180582. /* Release-Specific Flags */
  180583. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180584. PNG_LIBPNG_BUILD_STABLE only */
  180585. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180586. PNG_LIBPNG_BUILD_SPECIAL */
  180587. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180588. PNG_LIBPNG_BUILD_PRIVATE */
  180589. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180590. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180591. * We must not include leading zeros.
  180592. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180593. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180594. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180595. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180596. #ifndef PNG_VERSION_INFO_ONLY
  180597. /* include the compression library's header */
  180598. #endif
  180599. /* include all user configurable info, including optional assembler routines */
  180600. /*** Start of inlined file: pngconf.h ***/
  180601. /* pngconf.h - machine configurable file for libpng
  180602. *
  180603. * libpng version 1.2.21 - October 4, 2007
  180604. * For conditions of distribution and use, see copyright notice in png.h
  180605. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180606. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180607. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180608. */
  180609. /* Any machine specific code is near the front of this file, so if you
  180610. * are configuring libpng for a machine, you may want to read the section
  180611. * starting here down to where it starts to typedef png_color, png_text,
  180612. * and png_info.
  180613. */
  180614. #ifndef PNGCONF_H
  180615. #define PNGCONF_H
  180616. #define PNG_1_2_X
  180617. // These are some Juce config settings that should remove any unnecessary code bloat..
  180618. #define PNG_NO_STDIO 1
  180619. #define PNG_DEBUG 0
  180620. #define PNG_NO_WARNINGS 1
  180621. #define PNG_NO_ERROR_TEXT 1
  180622. #define PNG_NO_ERROR_NUMBERS 1
  180623. #define PNG_NO_USER_MEM 1
  180624. #define PNG_NO_READ_iCCP 1
  180625. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180626. #define PNG_NO_READ_USER_CHUNKS 1
  180627. #define PNG_NO_READ_iTXt 1
  180628. #define PNG_NO_READ_sCAL 1
  180629. #define PNG_NO_READ_sPLT 1
  180630. #define png_error(a, b) png_err(a)
  180631. #define png_warning(a, b)
  180632. #define png_chunk_error(a, b) png_err(a)
  180633. #define png_chunk_warning(a, b)
  180634. /*
  180635. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180636. * includes the resource compiler for Windows DLL configurations.
  180637. */
  180638. #ifdef PNG_USER_CONFIG
  180639. # ifndef PNG_USER_PRIVATEBUILD
  180640. # define PNG_USER_PRIVATEBUILD
  180641. # endif
  180642. #include "pngusr.h"
  180643. #endif
  180644. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180645. #ifdef PNG_CONFIGURE_LIBPNG
  180646. #ifdef HAVE_CONFIG_H
  180647. #include "config.h"
  180648. #endif
  180649. #endif
  180650. /*
  180651. * Added at libpng-1.2.8
  180652. *
  180653. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180654. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180655. * the DLL was built>
  180656. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180657. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180658. * distinguish your DLL from those of the official release. These
  180659. * correspond to the trailing letters that come after the version
  180660. * number and must match your private DLL name>
  180661. * e.g. // private DLL "libpng13gx.dll"
  180662. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180663. *
  180664. * The following macros are also at your disposal if you want to complete the
  180665. * DLL VERSIONINFO structure.
  180666. * - PNG_USER_VERSIONINFO_COMMENTS
  180667. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180668. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180669. */
  180670. #ifdef __STDC__
  180671. #ifdef SPECIALBUILD
  180672. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180673. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180674. #endif
  180675. #ifdef PRIVATEBUILD
  180676. # pragma message("PRIVATEBUILD is deprecated.\
  180677. Use PNG_USER_PRIVATEBUILD instead.")
  180678. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180679. #endif
  180680. #endif /* __STDC__ */
  180681. #ifndef PNG_VERSION_INFO_ONLY
  180682. /* End of material added to libpng-1.2.8 */
  180683. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180684. Restored at libpng-1.2.21 */
  180685. # define PNG_WARN_UNINITIALIZED_ROW 1
  180686. /* End of material added at libpng-1.2.19/1.2.21 */
  180687. /* This is the size of the compression buffer, and thus the size of
  180688. * an IDAT chunk. Make this whatever size you feel is best for your
  180689. * machine. One of these will be allocated per png_struct. When this
  180690. * is full, it writes the data to the disk, and does some other
  180691. * calculations. Making this an extremely small size will slow
  180692. * the library down, but you may want to experiment to determine
  180693. * where it becomes significant, if you are concerned with memory
  180694. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180695. * this describes the size of the buffer available to read the data in.
  180696. * Unless this gets smaller than the size of a row (compressed),
  180697. * it should not make much difference how big this is.
  180698. */
  180699. #ifndef PNG_ZBUF_SIZE
  180700. # define PNG_ZBUF_SIZE 8192
  180701. #endif
  180702. /* Enable if you want a write-only libpng */
  180703. #ifndef PNG_NO_READ_SUPPORTED
  180704. # define PNG_READ_SUPPORTED
  180705. #endif
  180706. /* Enable if you want a read-only libpng */
  180707. #ifndef PNG_NO_WRITE_SUPPORTED
  180708. # define PNG_WRITE_SUPPORTED
  180709. #endif
  180710. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180711. support PNGs that are embedded in MNG datastreams */
  180712. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180713. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180714. # define PNG_MNG_FEATURES_SUPPORTED
  180715. # endif
  180716. #endif
  180717. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180718. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180719. # define PNG_FLOATING_POINT_SUPPORTED
  180720. # endif
  180721. #endif
  180722. /* If you are running on a machine where you cannot allocate more
  180723. * than 64K of memory at once, uncomment this. While libpng will not
  180724. * normally need that much memory in a chunk (unless you load up a very
  180725. * large file), zlib needs to know how big of a chunk it can use, and
  180726. * libpng thus makes sure to check any memory allocation to verify it
  180727. * will fit into memory.
  180728. #define PNG_MAX_MALLOC_64K
  180729. */
  180730. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180731. # define PNG_MAX_MALLOC_64K
  180732. #endif
  180733. /* Special munging to support doing things the 'cygwin' way:
  180734. * 'Normal' png-on-win32 defines/defaults:
  180735. * PNG_BUILD_DLL -- building dll
  180736. * PNG_USE_DLL -- building an application, linking to dll
  180737. * (no define) -- building static library, or building an
  180738. * application and linking to the static lib
  180739. * 'Cygwin' defines/defaults:
  180740. * PNG_BUILD_DLL -- (ignored) building the dll
  180741. * (no define) -- (ignored) building an application, linking to the dll
  180742. * PNG_STATIC -- (ignored) building the static lib, or building an
  180743. * application that links to the static lib.
  180744. * ALL_STATIC -- (ignored) building various static libs, or building an
  180745. * application that links to the static libs.
  180746. * Thus,
  180747. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180748. * this bit of #ifdefs will define the 'correct' config variables based on
  180749. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180750. * unnecessary.
  180751. *
  180752. * Also, the precedence order is:
  180753. * ALL_STATIC (since we can't #undef something outside our namespace)
  180754. * PNG_BUILD_DLL
  180755. * PNG_STATIC
  180756. * (nothing) == PNG_USE_DLL
  180757. *
  180758. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180759. * of auto-import in binutils, we no longer need to worry about
  180760. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180761. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180762. * to __declspec() stuff. However, we DO need to worry about
  180763. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180764. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180765. */
  180766. #if defined(__CYGWIN__)
  180767. # if defined(ALL_STATIC)
  180768. # if defined(PNG_BUILD_DLL)
  180769. # undef PNG_BUILD_DLL
  180770. # endif
  180771. # if defined(PNG_USE_DLL)
  180772. # undef PNG_USE_DLL
  180773. # endif
  180774. # if defined(PNG_DLL)
  180775. # undef PNG_DLL
  180776. # endif
  180777. # if !defined(PNG_STATIC)
  180778. # define PNG_STATIC
  180779. # endif
  180780. # else
  180781. # if defined (PNG_BUILD_DLL)
  180782. # if defined(PNG_STATIC)
  180783. # undef PNG_STATIC
  180784. # endif
  180785. # if defined(PNG_USE_DLL)
  180786. # undef PNG_USE_DLL
  180787. # endif
  180788. # if !defined(PNG_DLL)
  180789. # define PNG_DLL
  180790. # endif
  180791. # else
  180792. # if defined(PNG_STATIC)
  180793. # if defined(PNG_USE_DLL)
  180794. # undef PNG_USE_DLL
  180795. # endif
  180796. # if defined(PNG_DLL)
  180797. # undef PNG_DLL
  180798. # endif
  180799. # else
  180800. # if !defined(PNG_USE_DLL)
  180801. # define PNG_USE_DLL
  180802. # endif
  180803. # if !defined(PNG_DLL)
  180804. # define PNG_DLL
  180805. # endif
  180806. # endif
  180807. # endif
  180808. # endif
  180809. #endif
  180810. /* This protects us against compilers that run on a windowing system
  180811. * and thus don't have or would rather us not use the stdio types:
  180812. * stdin, stdout, and stderr. The only one currently used is stderr
  180813. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180814. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180815. * will also prevent these, plus will prevent the entire set of stdio
  180816. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180817. * unless (PNG_DEBUG > 0) has been #defined.
  180818. *
  180819. * #define PNG_NO_CONSOLE_IO
  180820. * #define PNG_NO_STDIO
  180821. */
  180822. #if defined(_WIN32_WCE)
  180823. # include <windows.h>
  180824. /* Console I/O functions are not supported on WindowsCE */
  180825. # define PNG_NO_CONSOLE_IO
  180826. # ifdef PNG_DEBUG
  180827. # undef PNG_DEBUG
  180828. # endif
  180829. #endif
  180830. #ifdef PNG_BUILD_DLL
  180831. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180832. # ifndef PNG_NO_CONSOLE_IO
  180833. # define PNG_NO_CONSOLE_IO
  180834. # endif
  180835. # endif
  180836. #endif
  180837. # ifdef PNG_NO_STDIO
  180838. # ifndef PNG_NO_CONSOLE_IO
  180839. # define PNG_NO_CONSOLE_IO
  180840. # endif
  180841. # ifdef PNG_DEBUG
  180842. # if (PNG_DEBUG > 0)
  180843. # include <stdio.h>
  180844. # endif
  180845. # endif
  180846. # else
  180847. # if !defined(_WIN32_WCE)
  180848. /* "stdio.h" functions are not supported on WindowsCE */
  180849. # include <stdio.h>
  180850. # endif
  180851. # endif
  180852. /* This macro protects us against machines that don't have function
  180853. * prototypes (ie K&R style headers). If your compiler does not handle
  180854. * function prototypes, define this macro and use the included ansi2knr.
  180855. * I've always been able to use _NO_PROTO as the indicator, but you may
  180856. * need to drag the empty declaration out in front of here, or change the
  180857. * ifdef to suit your own needs.
  180858. */
  180859. #ifndef PNGARG
  180860. #ifdef OF /* zlib prototype munger */
  180861. # define PNGARG(arglist) OF(arglist)
  180862. #else
  180863. #ifdef _NO_PROTO
  180864. # define PNGARG(arglist) ()
  180865. # ifndef PNG_TYPECAST_NULL
  180866. # define PNG_TYPECAST_NULL
  180867. # endif
  180868. #else
  180869. # define PNGARG(arglist) arglist
  180870. #endif /* _NO_PROTO */
  180871. #endif /* OF */
  180872. #endif /* PNGARG */
  180873. /* Try to determine if we are compiling on a Mac. Note that testing for
  180874. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180875. * on non-Mac platforms.
  180876. */
  180877. #ifndef MACOS
  180878. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180879. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180880. # define MACOS
  180881. # endif
  180882. #endif
  180883. /* enough people need this for various reasons to include it here */
  180884. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180885. # include <sys/types.h>
  180886. #endif
  180887. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180888. # define PNG_SETJMP_SUPPORTED
  180889. #endif
  180890. #ifdef PNG_SETJMP_SUPPORTED
  180891. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180892. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180893. */
  180894. # ifdef __linux__
  180895. # ifdef _BSD_SOURCE
  180896. # define PNG_SAVE_BSD_SOURCE
  180897. # undef _BSD_SOURCE
  180898. # endif
  180899. # ifdef _SETJMP_H
  180900. /* If you encounter a compiler error here, see the explanation
  180901. * near the end of INSTALL.
  180902. */
  180903. __png.h__ already includes setjmp.h;
  180904. __dont__ include it again.;
  180905. # endif
  180906. # endif /* __linux__ */
  180907. /* include setjmp.h for error handling */
  180908. # include <setjmp.h>
  180909. # ifdef __linux__
  180910. # ifdef PNG_SAVE_BSD_SOURCE
  180911. # define _BSD_SOURCE
  180912. # undef PNG_SAVE_BSD_SOURCE
  180913. # endif
  180914. # endif /* __linux__ */
  180915. #endif /* PNG_SETJMP_SUPPORTED */
  180916. #ifdef BSD
  180917. #if ! JUCE_MAC
  180918. # include <strings.h>
  180919. #endif
  180920. #else
  180921. # include <string.h>
  180922. #endif
  180923. /* Other defines for things like memory and the like can go here. */
  180924. #ifdef PNG_INTERNAL
  180925. #include <stdlib.h>
  180926. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180927. * aren't usually used outside the library (as far as I know), so it is
  180928. * debatable if they should be exported at all. In the future, when it is
  180929. * possible to have run-time registry of chunk-handling functions, some of
  180930. * these will be made available again.
  180931. #define PNG_EXTERN extern
  180932. */
  180933. #define PNG_EXTERN
  180934. /* Other defines specific to compilers can go here. Try to keep
  180935. * them inside an appropriate ifdef/endif pair for portability.
  180936. */
  180937. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180938. # if defined(MACOS)
  180939. /* We need to check that <math.h> hasn't already been included earlier
  180940. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180941. * <fp.h> if possible.
  180942. */
  180943. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180944. # include <fp.h>
  180945. # endif
  180946. # else
  180947. # include <math.h>
  180948. # endif
  180949. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180950. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180951. * MATH=68881
  180952. */
  180953. # include <m68881.h>
  180954. # endif
  180955. #endif
  180956. /* Codewarrior on NT has linking problems without this. */
  180957. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180958. # define PNG_ALWAYS_EXTERN
  180959. #endif
  180960. /* This provides the non-ANSI (far) memory allocation routines. */
  180961. #if defined(__TURBOC__) && defined(__MSDOS__)
  180962. # include <mem.h>
  180963. # include <alloc.h>
  180964. #endif
  180965. /* I have no idea why is this necessary... */
  180966. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180967. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180968. # include <malloc.h>
  180969. #endif
  180970. /* This controls how fine the dithering gets. As this allocates
  180971. * a largish chunk of memory (32K), those who are not as concerned
  180972. * with dithering quality can decrease some or all of these.
  180973. */
  180974. #ifndef PNG_DITHER_RED_BITS
  180975. # define PNG_DITHER_RED_BITS 5
  180976. #endif
  180977. #ifndef PNG_DITHER_GREEN_BITS
  180978. # define PNG_DITHER_GREEN_BITS 5
  180979. #endif
  180980. #ifndef PNG_DITHER_BLUE_BITS
  180981. # define PNG_DITHER_BLUE_BITS 5
  180982. #endif
  180983. /* This controls how fine the gamma correction becomes when you
  180984. * are only interested in 8 bits anyway. Increasing this value
  180985. * results in more memory being used, and more pow() functions
  180986. * being called to fill in the gamma tables. Don't set this value
  180987. * less then 8, and even that may not work (I haven't tested it).
  180988. */
  180989. #ifndef PNG_MAX_GAMMA_8
  180990. # define PNG_MAX_GAMMA_8 11
  180991. #endif
  180992. /* This controls how much a difference in gamma we can tolerate before
  180993. * we actually start doing gamma conversion.
  180994. */
  180995. #ifndef PNG_GAMMA_THRESHOLD
  180996. # define PNG_GAMMA_THRESHOLD 0.05
  180997. #endif
  180998. #endif /* PNG_INTERNAL */
  180999. /* The following uses const char * instead of char * for error
  181000. * and warning message functions, so some compilers won't complain.
  181001. * If you do not want to use const, define PNG_NO_CONST here.
  181002. */
  181003. #ifndef PNG_NO_CONST
  181004. # define PNG_CONST const
  181005. #else
  181006. # define PNG_CONST
  181007. #endif
  181008. /* The following defines give you the ability to remove code from the
  181009. * library that you will not be using. I wish I could figure out how to
  181010. * automate this, but I can't do that without making it seriously hard
  181011. * on the users. So if you are not using an ability, change the #define
  181012. * to and #undef, and that part of the library will not be compiled. If
  181013. * your linker can't find a function, you may want to make sure the
  181014. * ability is defined here. Some of these depend upon some others being
  181015. * defined. I haven't figured out all the interactions here, so you may
  181016. * have to experiment awhile to get everything to compile. If you are
  181017. * creating or using a shared library, you probably shouldn't touch this,
  181018. * as it will affect the size of the structures, and this will cause bad
  181019. * things to happen if the library and/or application ever change.
  181020. */
  181021. /* Any features you will not be using can be undef'ed here */
  181022. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181023. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181024. * on the compile line, then pick and choose which ones to define without
  181025. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181026. * if you only want to have a png-compliant reader/writer but don't need
  181027. * any of the extra transformations. This saves about 80 kbytes in a
  181028. * typical installation of the library. (PNG_NO_* form added in version
  181029. * 1.0.1c, for consistency)
  181030. */
  181031. /* The size of the png_text structure changed in libpng-1.0.6 when
  181032. * iTXt support was added. iTXt support was turned off by default through
  181033. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181034. * instead of calling png_set_text() and letting libpng malloc it. It
  181035. * was turned on by default in libpng-1.3.0.
  181036. */
  181037. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181038. # ifndef PNG_NO_iTXt_SUPPORTED
  181039. # define PNG_NO_iTXt_SUPPORTED
  181040. # endif
  181041. # ifndef PNG_NO_READ_iTXt
  181042. # define PNG_NO_READ_iTXt
  181043. # endif
  181044. # ifndef PNG_NO_WRITE_iTXt
  181045. # define PNG_NO_WRITE_iTXt
  181046. # endif
  181047. #endif
  181048. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181049. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181050. # define PNG_READ_iTXt
  181051. # endif
  181052. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181053. # define PNG_WRITE_iTXt
  181054. # endif
  181055. #endif
  181056. /* The following support, added after version 1.0.0, can be turned off here en
  181057. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181058. * with old applications that require the length of png_struct and png_info
  181059. * to remain unchanged.
  181060. */
  181061. #ifdef PNG_LEGACY_SUPPORTED
  181062. # define PNG_NO_FREE_ME
  181063. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181064. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181065. # define PNG_NO_READ_USER_CHUNKS
  181066. # define PNG_NO_READ_iCCP
  181067. # define PNG_NO_WRITE_iCCP
  181068. # define PNG_NO_READ_iTXt
  181069. # define PNG_NO_WRITE_iTXt
  181070. # define PNG_NO_READ_sCAL
  181071. # define PNG_NO_WRITE_sCAL
  181072. # define PNG_NO_READ_sPLT
  181073. # define PNG_NO_WRITE_sPLT
  181074. # define PNG_NO_INFO_IMAGE
  181075. # define PNG_NO_READ_RGB_TO_GRAY
  181076. # define PNG_NO_READ_USER_TRANSFORM
  181077. # define PNG_NO_WRITE_USER_TRANSFORM
  181078. # define PNG_NO_USER_MEM
  181079. # define PNG_NO_READ_EMPTY_PLTE
  181080. # define PNG_NO_MNG_FEATURES
  181081. # define PNG_NO_FIXED_POINT_SUPPORTED
  181082. #endif
  181083. /* Ignore attempt to turn off both floating and fixed point support */
  181084. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181085. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181086. # define PNG_FIXED_POINT_SUPPORTED
  181087. #endif
  181088. #ifndef PNG_NO_FREE_ME
  181089. # define PNG_FREE_ME_SUPPORTED
  181090. #endif
  181091. #if defined(PNG_READ_SUPPORTED)
  181092. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181093. !defined(PNG_NO_READ_TRANSFORMS)
  181094. # define PNG_READ_TRANSFORMS_SUPPORTED
  181095. #endif
  181096. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181097. # ifndef PNG_NO_READ_EXPAND
  181098. # define PNG_READ_EXPAND_SUPPORTED
  181099. # endif
  181100. # ifndef PNG_NO_READ_SHIFT
  181101. # define PNG_READ_SHIFT_SUPPORTED
  181102. # endif
  181103. # ifndef PNG_NO_READ_PACK
  181104. # define PNG_READ_PACK_SUPPORTED
  181105. # endif
  181106. # ifndef PNG_NO_READ_BGR
  181107. # define PNG_READ_BGR_SUPPORTED
  181108. # endif
  181109. # ifndef PNG_NO_READ_SWAP
  181110. # define PNG_READ_SWAP_SUPPORTED
  181111. # endif
  181112. # ifndef PNG_NO_READ_PACKSWAP
  181113. # define PNG_READ_PACKSWAP_SUPPORTED
  181114. # endif
  181115. # ifndef PNG_NO_READ_INVERT
  181116. # define PNG_READ_INVERT_SUPPORTED
  181117. # endif
  181118. # ifndef PNG_NO_READ_DITHER
  181119. # define PNG_READ_DITHER_SUPPORTED
  181120. # endif
  181121. # ifndef PNG_NO_READ_BACKGROUND
  181122. # define PNG_READ_BACKGROUND_SUPPORTED
  181123. # endif
  181124. # ifndef PNG_NO_READ_16_TO_8
  181125. # define PNG_READ_16_TO_8_SUPPORTED
  181126. # endif
  181127. # ifndef PNG_NO_READ_FILLER
  181128. # define PNG_READ_FILLER_SUPPORTED
  181129. # endif
  181130. # ifndef PNG_NO_READ_GAMMA
  181131. # define PNG_READ_GAMMA_SUPPORTED
  181132. # endif
  181133. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181134. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181135. # endif
  181136. # ifndef PNG_NO_READ_SWAP_ALPHA
  181137. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181138. # endif
  181139. # ifndef PNG_NO_READ_INVERT_ALPHA
  181140. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181141. # endif
  181142. # ifndef PNG_NO_READ_STRIP_ALPHA
  181143. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181144. # endif
  181145. # ifndef PNG_NO_READ_USER_TRANSFORM
  181146. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181147. # endif
  181148. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181149. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181150. # endif
  181151. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181152. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181153. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181154. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181155. #endif /* about interlacing capability! You'll */
  181156. /* still have interlacing unless you change the following line: */
  181157. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181158. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181159. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181160. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181161. # endif
  181162. #endif
  181163. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181164. /* Deprecated, will be removed from version 2.0.0.
  181165. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181166. #ifndef PNG_NO_READ_EMPTY_PLTE
  181167. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181168. #endif
  181169. #endif
  181170. #endif /* PNG_READ_SUPPORTED */
  181171. #if defined(PNG_WRITE_SUPPORTED)
  181172. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181173. !defined(PNG_NO_WRITE_TRANSFORMS)
  181174. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181175. #endif
  181176. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181177. # ifndef PNG_NO_WRITE_SHIFT
  181178. # define PNG_WRITE_SHIFT_SUPPORTED
  181179. # endif
  181180. # ifndef PNG_NO_WRITE_PACK
  181181. # define PNG_WRITE_PACK_SUPPORTED
  181182. # endif
  181183. # ifndef PNG_NO_WRITE_BGR
  181184. # define PNG_WRITE_BGR_SUPPORTED
  181185. # endif
  181186. # ifndef PNG_NO_WRITE_SWAP
  181187. # define PNG_WRITE_SWAP_SUPPORTED
  181188. # endif
  181189. # ifndef PNG_NO_WRITE_PACKSWAP
  181190. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181191. # endif
  181192. # ifndef PNG_NO_WRITE_INVERT
  181193. # define PNG_WRITE_INVERT_SUPPORTED
  181194. # endif
  181195. # ifndef PNG_NO_WRITE_FILLER
  181196. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181197. # endif
  181198. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181199. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181200. # endif
  181201. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181202. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181203. # endif
  181204. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181205. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181206. # endif
  181207. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181208. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181209. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181210. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181211. encoders, but can cause trouble
  181212. if left undefined */
  181213. #endif
  181214. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181215. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181216. defined(PNG_FLOATING_POINT_SUPPORTED)
  181217. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181218. #endif
  181219. #ifndef PNG_NO_WRITE_FLUSH
  181220. # define PNG_WRITE_FLUSH_SUPPORTED
  181221. #endif
  181222. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181223. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181224. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181225. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181226. #endif
  181227. #endif
  181228. #endif /* PNG_WRITE_SUPPORTED */
  181229. #ifndef PNG_1_0_X
  181230. # ifndef PNG_NO_ERROR_NUMBERS
  181231. # define PNG_ERROR_NUMBERS_SUPPORTED
  181232. # endif
  181233. #endif /* PNG_1_0_X */
  181234. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181235. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181236. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181237. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181238. # endif
  181239. #endif
  181240. #ifndef PNG_NO_STDIO
  181241. # define PNG_TIME_RFC1123_SUPPORTED
  181242. #endif
  181243. /* This adds extra functions in pngget.c for accessing data from the
  181244. * info pointer (added in version 0.99)
  181245. * png_get_image_width()
  181246. * png_get_image_height()
  181247. * png_get_bit_depth()
  181248. * png_get_color_type()
  181249. * png_get_compression_type()
  181250. * png_get_filter_type()
  181251. * png_get_interlace_type()
  181252. * png_get_pixel_aspect_ratio()
  181253. * png_get_pixels_per_meter()
  181254. * png_get_x_offset_pixels()
  181255. * png_get_y_offset_pixels()
  181256. * png_get_x_offset_microns()
  181257. * png_get_y_offset_microns()
  181258. */
  181259. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181260. # define PNG_EASY_ACCESS_SUPPORTED
  181261. #endif
  181262. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181263. * and removed from version 1.2.20. The following will be removed
  181264. * from libpng-1.4.0
  181265. */
  181266. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181267. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181268. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181269. # endif
  181270. #endif
  181271. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181272. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181273. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181274. # endif
  181275. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181276. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181277. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181278. # define PNG_NO_MMX_CODE
  181279. # endif
  181280. # endif
  181281. # if defined(__APPLE__)
  181282. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181283. # define PNG_NO_MMX_CODE
  181284. # endif
  181285. # endif
  181286. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181287. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181288. # define PNG_NO_MMX_CODE
  181289. # endif
  181290. # endif
  181291. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181292. # define PNG_MMX_CODE_SUPPORTED
  181293. # endif
  181294. #endif
  181295. /* end of obsolete code to be removed from libpng-1.4.0 */
  181296. #if !defined(PNG_1_0_X)
  181297. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181298. # define PNG_USER_MEM_SUPPORTED
  181299. #endif
  181300. #endif /* PNG_1_0_X */
  181301. /* Added at libpng-1.2.6 */
  181302. #if !defined(PNG_1_0_X)
  181303. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181304. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181305. # define PNG_SET_USER_LIMITS_SUPPORTED
  181306. #endif
  181307. #endif
  181308. #endif /* PNG_1_0_X */
  181309. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181310. * how large, set these limits to 0x7fffffffL
  181311. */
  181312. #ifndef PNG_USER_WIDTH_MAX
  181313. # define PNG_USER_WIDTH_MAX 1000000L
  181314. #endif
  181315. #ifndef PNG_USER_HEIGHT_MAX
  181316. # define PNG_USER_HEIGHT_MAX 1000000L
  181317. #endif
  181318. /* These are currently experimental features, define them if you want */
  181319. /* very little testing */
  181320. /*
  181321. #ifdef PNG_READ_SUPPORTED
  181322. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181323. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181324. # endif
  181325. #endif
  181326. */
  181327. /* This is only for PowerPC big-endian and 680x0 systems */
  181328. /* some testing */
  181329. /*
  181330. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181331. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181332. #endif
  181333. */
  181334. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181335. /*
  181336. #define PNG_NO_POINTER_INDEXING
  181337. */
  181338. /* These functions are turned off by default, as they will be phased out. */
  181339. /*
  181340. #define PNG_USELESS_TESTS_SUPPORTED
  181341. #define PNG_CORRECT_PALETTE_SUPPORTED
  181342. */
  181343. /* Any chunks you are not interested in, you can undef here. The
  181344. * ones that allocate memory may be expecially important (hIST,
  181345. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181346. * a bit smaller.
  181347. */
  181348. #if defined(PNG_READ_SUPPORTED) && \
  181349. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181350. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181351. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181352. #endif
  181353. #if defined(PNG_WRITE_SUPPORTED) && \
  181354. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181355. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181356. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181357. #endif
  181358. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181359. #ifdef PNG_NO_READ_TEXT
  181360. # define PNG_NO_READ_iTXt
  181361. # define PNG_NO_READ_tEXt
  181362. # define PNG_NO_READ_zTXt
  181363. #endif
  181364. #ifndef PNG_NO_READ_bKGD
  181365. # define PNG_READ_bKGD_SUPPORTED
  181366. # define PNG_bKGD_SUPPORTED
  181367. #endif
  181368. #ifndef PNG_NO_READ_cHRM
  181369. # define PNG_READ_cHRM_SUPPORTED
  181370. # define PNG_cHRM_SUPPORTED
  181371. #endif
  181372. #ifndef PNG_NO_READ_gAMA
  181373. # define PNG_READ_gAMA_SUPPORTED
  181374. # define PNG_gAMA_SUPPORTED
  181375. #endif
  181376. #ifndef PNG_NO_READ_hIST
  181377. # define PNG_READ_hIST_SUPPORTED
  181378. # define PNG_hIST_SUPPORTED
  181379. #endif
  181380. #ifndef PNG_NO_READ_iCCP
  181381. # define PNG_READ_iCCP_SUPPORTED
  181382. # define PNG_iCCP_SUPPORTED
  181383. #endif
  181384. #ifndef PNG_NO_READ_iTXt
  181385. # ifndef PNG_READ_iTXt_SUPPORTED
  181386. # define PNG_READ_iTXt_SUPPORTED
  181387. # endif
  181388. # ifndef PNG_iTXt_SUPPORTED
  181389. # define PNG_iTXt_SUPPORTED
  181390. # endif
  181391. #endif
  181392. #ifndef PNG_NO_READ_oFFs
  181393. # define PNG_READ_oFFs_SUPPORTED
  181394. # define PNG_oFFs_SUPPORTED
  181395. #endif
  181396. #ifndef PNG_NO_READ_pCAL
  181397. # define PNG_READ_pCAL_SUPPORTED
  181398. # define PNG_pCAL_SUPPORTED
  181399. #endif
  181400. #ifndef PNG_NO_READ_sCAL
  181401. # define PNG_READ_sCAL_SUPPORTED
  181402. # define PNG_sCAL_SUPPORTED
  181403. #endif
  181404. #ifndef PNG_NO_READ_pHYs
  181405. # define PNG_READ_pHYs_SUPPORTED
  181406. # define PNG_pHYs_SUPPORTED
  181407. #endif
  181408. #ifndef PNG_NO_READ_sBIT
  181409. # define PNG_READ_sBIT_SUPPORTED
  181410. # define PNG_sBIT_SUPPORTED
  181411. #endif
  181412. #ifndef PNG_NO_READ_sPLT
  181413. # define PNG_READ_sPLT_SUPPORTED
  181414. # define PNG_sPLT_SUPPORTED
  181415. #endif
  181416. #ifndef PNG_NO_READ_sRGB
  181417. # define PNG_READ_sRGB_SUPPORTED
  181418. # define PNG_sRGB_SUPPORTED
  181419. #endif
  181420. #ifndef PNG_NO_READ_tEXt
  181421. # define PNG_READ_tEXt_SUPPORTED
  181422. # define PNG_tEXt_SUPPORTED
  181423. #endif
  181424. #ifndef PNG_NO_READ_tIME
  181425. # define PNG_READ_tIME_SUPPORTED
  181426. # define PNG_tIME_SUPPORTED
  181427. #endif
  181428. #ifndef PNG_NO_READ_tRNS
  181429. # define PNG_READ_tRNS_SUPPORTED
  181430. # define PNG_tRNS_SUPPORTED
  181431. #endif
  181432. #ifndef PNG_NO_READ_zTXt
  181433. # define PNG_READ_zTXt_SUPPORTED
  181434. # define PNG_zTXt_SUPPORTED
  181435. #endif
  181436. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181437. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181438. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181439. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181440. # endif
  181441. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181442. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181443. # endif
  181444. #endif
  181445. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181446. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181447. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181448. # define PNG_USER_CHUNKS_SUPPORTED
  181449. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181450. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181451. # endif
  181452. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181453. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181454. # endif
  181455. #endif
  181456. #ifndef PNG_NO_READ_OPT_PLTE
  181457. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181458. #endif /* optional PLTE chunk in RGB and RGBA images */
  181459. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181460. defined(PNG_READ_zTXt_SUPPORTED)
  181461. # define PNG_READ_TEXT_SUPPORTED
  181462. # define PNG_TEXT_SUPPORTED
  181463. #endif
  181464. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181465. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181466. #ifdef PNG_NO_WRITE_TEXT
  181467. # define PNG_NO_WRITE_iTXt
  181468. # define PNG_NO_WRITE_tEXt
  181469. # define PNG_NO_WRITE_zTXt
  181470. #endif
  181471. #ifndef PNG_NO_WRITE_bKGD
  181472. # define PNG_WRITE_bKGD_SUPPORTED
  181473. # ifndef PNG_bKGD_SUPPORTED
  181474. # define PNG_bKGD_SUPPORTED
  181475. # endif
  181476. #endif
  181477. #ifndef PNG_NO_WRITE_cHRM
  181478. # define PNG_WRITE_cHRM_SUPPORTED
  181479. # ifndef PNG_cHRM_SUPPORTED
  181480. # define PNG_cHRM_SUPPORTED
  181481. # endif
  181482. #endif
  181483. #ifndef PNG_NO_WRITE_gAMA
  181484. # define PNG_WRITE_gAMA_SUPPORTED
  181485. # ifndef PNG_gAMA_SUPPORTED
  181486. # define PNG_gAMA_SUPPORTED
  181487. # endif
  181488. #endif
  181489. #ifndef PNG_NO_WRITE_hIST
  181490. # define PNG_WRITE_hIST_SUPPORTED
  181491. # ifndef PNG_hIST_SUPPORTED
  181492. # define PNG_hIST_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #ifndef PNG_NO_WRITE_iCCP
  181496. # define PNG_WRITE_iCCP_SUPPORTED
  181497. # ifndef PNG_iCCP_SUPPORTED
  181498. # define PNG_iCCP_SUPPORTED
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_NO_WRITE_iTXt
  181502. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181503. # define PNG_WRITE_iTXt_SUPPORTED
  181504. # endif
  181505. # ifndef PNG_iTXt_SUPPORTED
  181506. # define PNG_iTXt_SUPPORTED
  181507. # endif
  181508. #endif
  181509. #ifndef PNG_NO_WRITE_oFFs
  181510. # define PNG_WRITE_oFFs_SUPPORTED
  181511. # ifndef PNG_oFFs_SUPPORTED
  181512. # define PNG_oFFs_SUPPORTED
  181513. # endif
  181514. #endif
  181515. #ifndef PNG_NO_WRITE_pCAL
  181516. # define PNG_WRITE_pCAL_SUPPORTED
  181517. # ifndef PNG_pCAL_SUPPORTED
  181518. # define PNG_pCAL_SUPPORTED
  181519. # endif
  181520. #endif
  181521. #ifndef PNG_NO_WRITE_sCAL
  181522. # define PNG_WRITE_sCAL_SUPPORTED
  181523. # ifndef PNG_sCAL_SUPPORTED
  181524. # define PNG_sCAL_SUPPORTED
  181525. # endif
  181526. #endif
  181527. #ifndef PNG_NO_WRITE_pHYs
  181528. # define PNG_WRITE_pHYs_SUPPORTED
  181529. # ifndef PNG_pHYs_SUPPORTED
  181530. # define PNG_pHYs_SUPPORTED
  181531. # endif
  181532. #endif
  181533. #ifndef PNG_NO_WRITE_sBIT
  181534. # define PNG_WRITE_sBIT_SUPPORTED
  181535. # ifndef PNG_sBIT_SUPPORTED
  181536. # define PNG_sBIT_SUPPORTED
  181537. # endif
  181538. #endif
  181539. #ifndef PNG_NO_WRITE_sPLT
  181540. # define PNG_WRITE_sPLT_SUPPORTED
  181541. # ifndef PNG_sPLT_SUPPORTED
  181542. # define PNG_sPLT_SUPPORTED
  181543. # endif
  181544. #endif
  181545. #ifndef PNG_NO_WRITE_sRGB
  181546. # define PNG_WRITE_sRGB_SUPPORTED
  181547. # ifndef PNG_sRGB_SUPPORTED
  181548. # define PNG_sRGB_SUPPORTED
  181549. # endif
  181550. #endif
  181551. #ifndef PNG_NO_WRITE_tEXt
  181552. # define PNG_WRITE_tEXt_SUPPORTED
  181553. # ifndef PNG_tEXt_SUPPORTED
  181554. # define PNG_tEXt_SUPPORTED
  181555. # endif
  181556. #endif
  181557. #ifndef PNG_NO_WRITE_tIME
  181558. # define PNG_WRITE_tIME_SUPPORTED
  181559. # ifndef PNG_tIME_SUPPORTED
  181560. # define PNG_tIME_SUPPORTED
  181561. # endif
  181562. #endif
  181563. #ifndef PNG_NO_WRITE_tRNS
  181564. # define PNG_WRITE_tRNS_SUPPORTED
  181565. # ifndef PNG_tRNS_SUPPORTED
  181566. # define PNG_tRNS_SUPPORTED
  181567. # endif
  181568. #endif
  181569. #ifndef PNG_NO_WRITE_zTXt
  181570. # define PNG_WRITE_zTXt_SUPPORTED
  181571. # ifndef PNG_zTXt_SUPPORTED
  181572. # define PNG_zTXt_SUPPORTED
  181573. # endif
  181574. #endif
  181575. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181576. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181577. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181578. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181579. # endif
  181580. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181581. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181582. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181583. # endif
  181584. # endif
  181585. #endif
  181586. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181587. defined(PNG_WRITE_zTXt_SUPPORTED)
  181588. # define PNG_WRITE_TEXT_SUPPORTED
  181589. # ifndef PNG_TEXT_SUPPORTED
  181590. # define PNG_TEXT_SUPPORTED
  181591. # endif
  181592. #endif
  181593. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181594. /* Turn this off to disable png_read_png() and
  181595. * png_write_png() and leave the row_pointers member
  181596. * out of the info structure.
  181597. */
  181598. #ifndef PNG_NO_INFO_IMAGE
  181599. # define PNG_INFO_IMAGE_SUPPORTED
  181600. #endif
  181601. /* need the time information for reading tIME chunks */
  181602. #if defined(PNG_tIME_SUPPORTED)
  181603. # if !defined(_WIN32_WCE)
  181604. /* "time.h" functions are not supported on WindowsCE */
  181605. # include <time.h>
  181606. # endif
  181607. #endif
  181608. /* Some typedefs to get us started. These should be safe on most of the
  181609. * common platforms. The typedefs should be at least as large as the
  181610. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181611. * don't have to be exactly that size. Some compilers dislike passing
  181612. * unsigned shorts as function parameters, so you may be better off using
  181613. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181614. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181615. */
  181616. typedef unsigned long png_uint_32;
  181617. typedef long png_int_32;
  181618. typedef unsigned short png_uint_16;
  181619. typedef short png_int_16;
  181620. typedef unsigned char png_byte;
  181621. /* This is usually size_t. It is typedef'ed just in case you need it to
  181622. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181623. #ifdef PNG_SIZE_T
  181624. typedef PNG_SIZE_T png_size_t;
  181625. # define png_sizeof(x) png_convert_size(sizeof (x))
  181626. #else
  181627. typedef size_t png_size_t;
  181628. # define png_sizeof(x) sizeof (x)
  181629. #endif
  181630. /* The following is needed for medium model support. It cannot be in the
  181631. * PNG_INTERNAL section. Needs modification for other compilers besides
  181632. * MSC. Model independent support declares all arrays and pointers to be
  181633. * large using the far keyword. The zlib version used must also support
  181634. * model independent data. As of version zlib 1.0.4, the necessary changes
  181635. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181636. * changes that are needed. (Tim Wegner)
  181637. */
  181638. /* Separate compiler dependencies (problem here is that zlib.h always
  181639. defines FAR. (SJT) */
  181640. #ifdef __BORLANDC__
  181641. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181642. # define LDATA 1
  181643. # else
  181644. # define LDATA 0
  181645. # endif
  181646. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181647. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181648. # define PNG_MAX_MALLOC_64K
  181649. # if (LDATA != 1)
  181650. # ifndef FAR
  181651. # define FAR __far
  181652. # endif
  181653. # define USE_FAR_KEYWORD
  181654. # endif /* LDATA != 1 */
  181655. /* Possibly useful for moving data out of default segment.
  181656. * Uncomment it if you want. Could also define FARDATA as
  181657. * const if your compiler supports it. (SJT)
  181658. # define FARDATA FAR
  181659. */
  181660. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181661. #endif /* __BORLANDC__ */
  181662. /* Suggest testing for specific compiler first before testing for
  181663. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181664. * making reliance oncertain keywords suspect. (SJT)
  181665. */
  181666. /* MSC Medium model */
  181667. #if defined(FAR)
  181668. # if defined(M_I86MM)
  181669. # define USE_FAR_KEYWORD
  181670. # define FARDATA FAR
  181671. # include <dos.h>
  181672. # endif
  181673. #endif
  181674. /* SJT: default case */
  181675. #ifndef FAR
  181676. # define FAR
  181677. #endif
  181678. /* At this point FAR is always defined */
  181679. #ifndef FARDATA
  181680. # define FARDATA
  181681. #endif
  181682. /* Typedef for floating-point numbers that are converted
  181683. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181684. typedef png_int_32 png_fixed_point;
  181685. /* Add typedefs for pointers */
  181686. typedef void FAR * png_voidp;
  181687. typedef png_byte FAR * png_bytep;
  181688. typedef png_uint_32 FAR * png_uint_32p;
  181689. typedef png_int_32 FAR * png_int_32p;
  181690. typedef png_uint_16 FAR * png_uint_16p;
  181691. typedef png_int_16 FAR * png_int_16p;
  181692. typedef PNG_CONST char FAR * png_const_charp;
  181693. typedef char FAR * png_charp;
  181694. typedef png_fixed_point FAR * png_fixed_point_p;
  181695. #ifndef PNG_NO_STDIO
  181696. #if defined(_WIN32_WCE)
  181697. typedef HANDLE png_FILE_p;
  181698. #else
  181699. typedef FILE * png_FILE_p;
  181700. #endif
  181701. #endif
  181702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181703. typedef double FAR * png_doublep;
  181704. #endif
  181705. /* Pointers to pointers; i.e. arrays */
  181706. typedef png_byte FAR * FAR * png_bytepp;
  181707. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181708. typedef png_int_32 FAR * FAR * png_int_32pp;
  181709. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181710. typedef png_int_16 FAR * FAR * png_int_16pp;
  181711. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181712. typedef char FAR * FAR * png_charpp;
  181713. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181714. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181715. typedef double FAR * FAR * png_doublepp;
  181716. #endif
  181717. /* Pointers to pointers to pointers; i.e., pointer to array */
  181718. typedef char FAR * FAR * FAR * png_charppp;
  181719. #if 0
  181720. /* SPC - Is this stuff deprecated? */
  181721. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181722. /* libpng typedefs for types in zlib. If zlib changes
  181723. * or another compression library is used, then change these.
  181724. * Eliminates need to change all the source files.
  181725. */
  181726. typedef charf * png_zcharp;
  181727. typedef charf * FAR * png_zcharpp;
  181728. typedef z_stream FAR * png_zstreamp;
  181729. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181730. /*
  181731. * Define PNG_BUILD_DLL if the module being built is a Windows
  181732. * LIBPNG DLL.
  181733. *
  181734. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181735. * It is equivalent to Microsoft predefined macro _DLL that is
  181736. * automatically defined when you compile using the share
  181737. * version of the CRT (C Run-Time library)
  181738. *
  181739. * The cygwin mods make this behavior a little different:
  181740. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181741. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181742. * -or- if you are building an application that you want to link to the
  181743. * static library.
  181744. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181745. * the other flags is defined.
  181746. */
  181747. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181748. # define PNG_DLL
  181749. #endif
  181750. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181751. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181752. * command-line override
  181753. */
  181754. #if defined(__CYGWIN__)
  181755. # if !defined(PNG_STATIC)
  181756. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181757. # undef PNG_USE_GLOBAL_ARRAYS
  181758. # endif
  181759. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181760. # define PNG_USE_LOCAL_ARRAYS
  181761. # endif
  181762. # else
  181763. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181764. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181765. # undef PNG_USE_GLOBAL_ARRAYS
  181766. # endif
  181767. # endif
  181768. # endif
  181769. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181770. # define PNG_USE_LOCAL_ARRAYS
  181771. # endif
  181772. #endif
  181773. /* Do not use global arrays (helps with building DLL's)
  181774. * They are no longer used in libpng itself, since version 1.0.5c,
  181775. * but might be required for some pre-1.0.5c applications.
  181776. */
  181777. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181778. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181779. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181780. # define PNG_USE_LOCAL_ARRAYS
  181781. # else
  181782. # define PNG_USE_GLOBAL_ARRAYS
  181783. # endif
  181784. #endif
  181785. #if defined(__CYGWIN__)
  181786. # undef PNGAPI
  181787. # define PNGAPI __cdecl
  181788. # undef PNG_IMPEXP
  181789. # define PNG_IMPEXP
  181790. #endif
  181791. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181792. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181793. * Don't ignore those warnings; you must also reset the default calling
  181794. * convention in your compiler to match your PNGAPI, and you must build
  181795. * zlib and your applications the same way you build libpng.
  181796. */
  181797. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181798. # ifndef PNG_NO_MODULEDEF
  181799. # define PNG_NO_MODULEDEF
  181800. # endif
  181801. #endif
  181802. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181803. # define PNG_IMPEXP
  181804. #endif
  181805. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181806. (( defined(_Windows) || defined(_WINDOWS) || \
  181807. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181808. # ifndef PNGAPI
  181809. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181810. # define PNGAPI __cdecl
  181811. # else
  181812. # define PNGAPI _cdecl
  181813. # endif
  181814. # endif
  181815. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181816. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181817. # define PNG_IMPEXP
  181818. # endif
  181819. # if !defined(PNG_IMPEXP)
  181820. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181821. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181822. /* Borland/Microsoft */
  181823. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181824. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181825. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181826. # else
  181827. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181828. # if defined(PNG_BUILD_DLL)
  181829. # define PNG_IMPEXP __export
  181830. # else
  181831. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181832. VC++ */
  181833. # endif /* Exists in Borland C++ for
  181834. C++ classes (== huge) */
  181835. # endif
  181836. # endif
  181837. # if !defined(PNG_IMPEXP)
  181838. # if defined(PNG_BUILD_DLL)
  181839. # define PNG_IMPEXP __declspec(dllexport)
  181840. # else
  181841. # define PNG_IMPEXP __declspec(dllimport)
  181842. # endif
  181843. # endif
  181844. # endif /* PNG_IMPEXP */
  181845. #else /* !(DLL || non-cygwin WINDOWS) */
  181846. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181847. # ifndef PNGAPI
  181848. # define PNGAPI _System
  181849. # endif
  181850. # else
  181851. # if 0 /* ... other platforms, with other meanings */
  181852. # endif
  181853. # endif
  181854. #endif
  181855. #ifndef PNGAPI
  181856. # define PNGAPI
  181857. #endif
  181858. #ifndef PNG_IMPEXP
  181859. # define PNG_IMPEXP
  181860. #endif
  181861. #ifdef PNG_BUILDSYMS
  181862. # ifndef PNG_EXPORT
  181863. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181864. # endif
  181865. # ifdef PNG_USE_GLOBAL_ARRAYS
  181866. # ifndef PNG_EXPORT_VAR
  181867. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181868. # endif
  181869. # endif
  181870. #endif
  181871. #ifndef PNG_EXPORT
  181872. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181873. #endif
  181874. #ifdef PNG_USE_GLOBAL_ARRAYS
  181875. # ifndef PNG_EXPORT_VAR
  181876. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181877. # endif
  181878. #endif
  181879. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181880. * functions that are passed far data must be model independent.
  181881. */
  181882. #ifndef PNG_ABORT
  181883. # define PNG_ABORT() abort()
  181884. #endif
  181885. #ifdef PNG_SETJMP_SUPPORTED
  181886. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181887. #else
  181888. # define png_jmpbuf(png_ptr) \
  181889. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181890. #endif
  181891. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181892. /* use this to make far-to-near assignments */
  181893. # define CHECK 1
  181894. # define NOCHECK 0
  181895. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181896. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181897. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181898. # define png_strcpy _fstrcpy
  181899. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181900. # define png_strlen _fstrlen
  181901. # define png_memcmp _fmemcmp /* SJT: added */
  181902. # define png_memcpy _fmemcpy
  181903. # define png_memset _fmemset
  181904. #else /* use the usual functions */
  181905. # define CVT_PTR(ptr) (ptr)
  181906. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181907. # ifndef PNG_NO_SNPRINTF
  181908. # ifdef _MSC_VER
  181909. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181910. # define png_snprintf2 _snprintf
  181911. # define png_snprintf6 _snprintf
  181912. # else
  181913. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181914. # define png_snprintf2 snprintf
  181915. # define png_snprintf6 snprintf
  181916. # endif
  181917. # else
  181918. /* You don't have or don't want to use snprintf(). Caution: Using
  181919. * sprintf instead of snprintf exposes your application to accidental
  181920. * or malevolent buffer overflows. If you don't have snprintf()
  181921. * as a general rule you should provide one (you can get one from
  181922. * Portable OpenSSH). */
  181923. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181924. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181925. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181926. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181927. # endif
  181928. # define png_strcpy strcpy
  181929. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181930. # define png_strlen strlen
  181931. # define png_memcmp memcmp /* SJT: added */
  181932. # define png_memcpy memcpy
  181933. # define png_memset memset
  181934. #endif
  181935. /* End of memory model independent support */
  181936. /* Just a little check that someone hasn't tried to define something
  181937. * contradictory.
  181938. */
  181939. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181940. # undef PNG_ZBUF_SIZE
  181941. # define PNG_ZBUF_SIZE 65536L
  181942. #endif
  181943. /* Added at libpng-1.2.8 */
  181944. #endif /* PNG_VERSION_INFO_ONLY */
  181945. #endif /* PNGCONF_H */
  181946. /*** End of inlined file: pngconf.h ***/
  181947. #ifdef _MSC_VER
  181948. #pragma warning (disable: 4996 4100)
  181949. #endif
  181950. /*
  181951. * Added at libpng-1.2.8 */
  181952. /* Ref MSDN: Private as priority over Special
  181953. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181954. * procedures. If this value is given, the StringFileInfo block must
  181955. * contain a PrivateBuild string.
  181956. *
  181957. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181958. * standard release procedures but is a variation of the standard
  181959. * file of the same version number. If this value is given, the
  181960. * StringFileInfo block must contain a SpecialBuild string.
  181961. */
  181962. #if defined(PNG_USER_PRIVATEBUILD)
  181963. # define PNG_LIBPNG_BUILD_TYPE \
  181964. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181965. #else
  181966. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181967. # define PNG_LIBPNG_BUILD_TYPE \
  181968. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181969. # else
  181970. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181971. # endif
  181972. #endif
  181973. #ifndef PNG_VERSION_INFO_ONLY
  181974. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181975. #ifdef __cplusplus
  181976. //extern "C" {
  181977. #endif /* __cplusplus */
  181978. /* This file is arranged in several sections. The first section contains
  181979. * structure and type definitions. The second section contains the external
  181980. * library functions, while the third has the internal library functions,
  181981. * which applications aren't expected to use directly.
  181982. */
  181983. #ifndef PNG_NO_TYPECAST_NULL
  181984. #define int_p_NULL (int *)NULL
  181985. #define png_bytep_NULL (png_bytep)NULL
  181986. #define png_bytepp_NULL (png_bytepp)NULL
  181987. #define png_doublep_NULL (png_doublep)NULL
  181988. #define png_error_ptr_NULL (png_error_ptr)NULL
  181989. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181990. #define png_free_ptr_NULL (png_free_ptr)NULL
  181991. #define png_infopp_NULL (png_infopp)NULL
  181992. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181993. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181994. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181995. #define png_structp_NULL (png_structp)NULL
  181996. #define png_uint_16p_NULL (png_uint_16p)NULL
  181997. #define png_voidp_NULL (png_voidp)NULL
  181998. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181999. #else
  182000. #define int_p_NULL NULL
  182001. #define png_bytep_NULL NULL
  182002. #define png_bytepp_NULL NULL
  182003. #define png_doublep_NULL NULL
  182004. #define png_error_ptr_NULL NULL
  182005. #define png_flush_ptr_NULL NULL
  182006. #define png_free_ptr_NULL NULL
  182007. #define png_infopp_NULL NULL
  182008. #define png_malloc_ptr_NULL NULL
  182009. #define png_read_status_ptr_NULL NULL
  182010. #define png_rw_ptr_NULL NULL
  182011. #define png_structp_NULL NULL
  182012. #define png_uint_16p_NULL NULL
  182013. #define png_voidp_NULL NULL
  182014. #define png_write_status_ptr_NULL NULL
  182015. #endif
  182016. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182017. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182018. /* Version information for C files, stored in png.c. This had better match
  182019. * the version above.
  182020. */
  182021. #ifdef PNG_USE_GLOBAL_ARRAYS
  182022. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182023. /* need room for 99.99.99beta99z */
  182024. #else
  182025. #define png_libpng_ver png_get_header_ver(NULL)
  182026. #endif
  182027. #ifdef PNG_USE_GLOBAL_ARRAYS
  182028. /* This was removed in version 1.0.5c */
  182029. /* Structures to facilitate easy interlacing. See png.c for more details */
  182030. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182031. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182032. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182033. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182034. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182035. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182036. /* This isn't currently used. If you need it, see png.c for more details.
  182037. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182038. */
  182039. #endif
  182040. #endif /* PNG_NO_EXTERN */
  182041. /* Three color definitions. The order of the red, green, and blue, (and the
  182042. * exact size) is not important, although the size of the fields need to
  182043. * be png_byte or png_uint_16 (as defined below).
  182044. */
  182045. typedef struct png_color_struct
  182046. {
  182047. png_byte red;
  182048. png_byte green;
  182049. png_byte blue;
  182050. } png_color;
  182051. typedef png_color FAR * png_colorp;
  182052. typedef png_color FAR * FAR * png_colorpp;
  182053. typedef struct png_color_16_struct
  182054. {
  182055. png_byte index; /* used for palette files */
  182056. png_uint_16 red; /* for use in red green blue files */
  182057. png_uint_16 green;
  182058. png_uint_16 blue;
  182059. png_uint_16 gray; /* for use in grayscale files */
  182060. } png_color_16;
  182061. typedef png_color_16 FAR * png_color_16p;
  182062. typedef png_color_16 FAR * FAR * png_color_16pp;
  182063. typedef struct png_color_8_struct
  182064. {
  182065. png_byte red; /* for use in red green blue files */
  182066. png_byte green;
  182067. png_byte blue;
  182068. png_byte gray; /* for use in grayscale files */
  182069. png_byte alpha; /* for alpha channel files */
  182070. } png_color_8;
  182071. typedef png_color_8 FAR * png_color_8p;
  182072. typedef png_color_8 FAR * FAR * png_color_8pp;
  182073. /*
  182074. * The following two structures are used for the in-core representation
  182075. * of sPLT chunks.
  182076. */
  182077. typedef struct png_sPLT_entry_struct
  182078. {
  182079. png_uint_16 red;
  182080. png_uint_16 green;
  182081. png_uint_16 blue;
  182082. png_uint_16 alpha;
  182083. png_uint_16 frequency;
  182084. } png_sPLT_entry;
  182085. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182086. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182087. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182088. * occupy the LSB of their respective members, and the MSB of each member
  182089. * is zero-filled. The frequency member always occupies the full 16 bits.
  182090. */
  182091. typedef struct png_sPLT_struct
  182092. {
  182093. png_charp name; /* palette name */
  182094. png_byte depth; /* depth of palette samples */
  182095. png_sPLT_entryp entries; /* palette entries */
  182096. png_int_32 nentries; /* number of palette entries */
  182097. } png_sPLT_t;
  182098. typedef png_sPLT_t FAR * png_sPLT_tp;
  182099. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182100. #ifdef PNG_TEXT_SUPPORTED
  182101. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182102. * and whether that contents is compressed or not. The "key" field
  182103. * points to a regular zero-terminated C string. The "text", "lang", and
  182104. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182105. * However, the * structure returned by png_get_text() will always contain
  182106. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182107. * so they can be safely used in printf() and other string-handling functions.
  182108. */
  182109. typedef struct png_text_struct
  182110. {
  182111. int compression; /* compression value:
  182112. -1: tEXt, none
  182113. 0: zTXt, deflate
  182114. 1: iTXt, none
  182115. 2: iTXt, deflate */
  182116. png_charp key; /* keyword, 1-79 character description of "text" */
  182117. png_charp text; /* comment, may be an empty string (ie "")
  182118. or a NULL pointer */
  182119. png_size_t text_length; /* length of the text string */
  182120. #ifdef PNG_iTXt_SUPPORTED
  182121. png_size_t itxt_length; /* length of the itxt string */
  182122. png_charp lang; /* language code, 0-79 characters
  182123. or a NULL pointer */
  182124. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182125. chars or a NULL pointer */
  182126. #endif
  182127. } png_text;
  182128. typedef png_text FAR * png_textp;
  182129. typedef png_text FAR * FAR * png_textpp;
  182130. #endif
  182131. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182132. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182133. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182134. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182135. #define PNG_TEXT_COMPRESSION_NONE -1
  182136. #define PNG_TEXT_COMPRESSION_zTXt 0
  182137. #define PNG_ITXT_COMPRESSION_NONE 1
  182138. #define PNG_ITXT_COMPRESSION_zTXt 2
  182139. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182140. /* png_time is a way to hold the time in an machine independent way.
  182141. * Two conversions are provided, both from time_t and struct tm. There
  182142. * is no portable way to convert to either of these structures, as far
  182143. * as I know. If you know of a portable way, send it to me. As a side
  182144. * note - PNG has always been Year 2000 compliant!
  182145. */
  182146. typedef struct png_time_struct
  182147. {
  182148. png_uint_16 year; /* full year, as in, 1995 */
  182149. png_byte month; /* month of year, 1 - 12 */
  182150. png_byte day; /* day of month, 1 - 31 */
  182151. png_byte hour; /* hour of day, 0 - 23 */
  182152. png_byte minute; /* minute of hour, 0 - 59 */
  182153. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182154. } png_time;
  182155. typedef png_time FAR * png_timep;
  182156. typedef png_time FAR * FAR * png_timepp;
  182157. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182158. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182159. * no specific support. The idea is that we can use this to queue
  182160. * up private chunks for output even though the library doesn't actually
  182161. * know about their semantics.
  182162. */
  182163. typedef struct png_unknown_chunk_t
  182164. {
  182165. png_byte name[5];
  182166. png_byte *data;
  182167. png_size_t size;
  182168. /* libpng-using applications should NOT directly modify this byte. */
  182169. png_byte location; /* mode of operation at read time */
  182170. }
  182171. png_unknown_chunk;
  182172. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182173. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182174. #endif
  182175. /* png_info is a structure that holds the information in a PNG file so
  182176. * that the application can find out the characteristics of the image.
  182177. * If you are reading the file, this structure will tell you what is
  182178. * in the PNG file. If you are writing the file, fill in the information
  182179. * you want to put into the PNG file, then call png_write_info().
  182180. * The names chosen should be very close to the PNG specification, so
  182181. * consult that document for information about the meaning of each field.
  182182. *
  182183. * With libpng < 0.95, it was only possible to directly set and read the
  182184. * the values in the png_info_struct, which meant that the contents and
  182185. * order of the values had to remain fixed. With libpng 0.95 and later,
  182186. * however, there are now functions that abstract the contents of
  182187. * png_info_struct from the application, so this makes it easier to use
  182188. * libpng with dynamic libraries, and even makes it possible to use
  182189. * libraries that don't have all of the libpng ancillary chunk-handing
  182190. * functionality.
  182191. *
  182192. * In any case, the order of the parameters in png_info_struct should NOT
  182193. * be changed for as long as possible to keep compatibility with applications
  182194. * that use the old direct-access method with png_info_struct.
  182195. *
  182196. * The following members may have allocated storage attached that should be
  182197. * cleaned up before the structure is discarded: palette, trans, text,
  182198. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182199. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182200. * are automatically freed when the info structure is deallocated, if they were
  182201. * allocated internally by libpng. This behavior can be changed by means
  182202. * of the png_data_freer() function.
  182203. *
  182204. * More allocation details: all the chunk-reading functions that
  182205. * change these members go through the corresponding png_set_*
  182206. * functions. A function to clear these members is available: see
  182207. * png_free_data(). The png_set_* functions do not depend on being
  182208. * able to point info structure members to any of the storage they are
  182209. * passed (they make their own copies), EXCEPT that the png_set_text
  182210. * functions use the same storage passed to them in the text_ptr or
  182211. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182212. * functions do not make their own copies.
  182213. */
  182214. typedef struct png_info_struct
  182215. {
  182216. /* the following are necessary for every PNG file */
  182217. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182218. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182219. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182220. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182221. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182222. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182223. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182224. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182225. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182226. /* The following three should have been named *_method not *_type */
  182227. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182228. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182229. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182230. /* The following is informational only on read, and not used on writes. */
  182231. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182232. png_byte pixel_depth; /* number of bits per pixel */
  182233. png_byte spare_byte; /* to align the data, and for future use */
  182234. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182235. /* The rest of the data is optional. If you are reading, check the
  182236. * valid field to see if the information in these are valid. If you
  182237. * are writing, set the valid field to those chunks you want written,
  182238. * and initialize the appropriate fields below.
  182239. */
  182240. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182241. /* The gAMA chunk describes the gamma characteristics of the system
  182242. * on which the image was created, normally in the range [1.0, 2.5].
  182243. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182244. */
  182245. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182246. #endif
  182247. #if defined(PNG_sRGB_SUPPORTED)
  182248. /* GR-P, 0.96a */
  182249. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182250. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182251. #endif
  182252. #if defined(PNG_TEXT_SUPPORTED)
  182253. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182254. * uncompressed, compressed, and optionally compressed forms, respectively.
  182255. * The data in "text" is an array of pointers to uncompressed,
  182256. * null-terminated C strings. Each chunk has a keyword that describes the
  182257. * textual data contained in that chunk. Keywords are not required to be
  182258. * unique, and the text string may be empty. Any number of text chunks may
  182259. * be in an image.
  182260. */
  182261. int num_text; /* number of comments read/to write */
  182262. int max_text; /* current size of text array */
  182263. png_textp text; /* array of comments read/to write */
  182264. #endif /* PNG_TEXT_SUPPORTED */
  182265. #if defined(PNG_tIME_SUPPORTED)
  182266. /* The tIME chunk holds the last time the displayed image data was
  182267. * modified. See the png_time struct for the contents of this struct.
  182268. */
  182269. png_time mod_time;
  182270. #endif
  182271. #if defined(PNG_sBIT_SUPPORTED)
  182272. /* The sBIT chunk specifies the number of significant high-order bits
  182273. * in the pixel data. Values are in the range [1, bit_depth], and are
  182274. * only specified for the channels in the pixel data. The contents of
  182275. * the low-order bits is not specified. Data is valid if
  182276. * (valid & PNG_INFO_sBIT) is non-zero.
  182277. */
  182278. png_color_8 sig_bit; /* significant bits in color channels */
  182279. #endif
  182280. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182281. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182282. /* The tRNS chunk supplies transparency data for paletted images and
  182283. * other image types that don't need a full alpha channel. There are
  182284. * "num_trans" transparency values for a paletted image, stored in the
  182285. * same order as the palette colors, starting from index 0. Values
  182286. * for the data are in the range [0, 255], ranging from fully transparent
  182287. * to fully opaque, respectively. For non-paletted images, there is a
  182288. * single color specified that should be treated as fully transparent.
  182289. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182290. */
  182291. png_bytep trans; /* transparent values for paletted image */
  182292. png_color_16 trans_values; /* transparent color for non-palette image */
  182293. #endif
  182294. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182295. /* The bKGD chunk gives the suggested image background color if the
  182296. * display program does not have its own background color and the image
  182297. * is needs to composited onto a background before display. The colors
  182298. * in "background" are normally in the same color space/depth as the
  182299. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182300. */
  182301. png_color_16 background;
  182302. #endif
  182303. #if defined(PNG_oFFs_SUPPORTED)
  182304. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182305. * and downwards from the top-left corner of the display, page, or other
  182306. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182307. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182308. */
  182309. png_int_32 x_offset; /* x offset on page */
  182310. png_int_32 y_offset; /* y offset on page */
  182311. png_byte offset_unit_type; /* offset units type */
  182312. #endif
  182313. #if defined(PNG_pHYs_SUPPORTED)
  182314. /* The pHYs chunk gives the physical pixel density of the image for
  182315. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182316. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182317. */
  182318. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182319. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182320. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182321. #endif
  182322. #if defined(PNG_hIST_SUPPORTED)
  182323. /* The hIST chunk contains the relative frequency or importance of the
  182324. * various palette entries, so that a viewer can intelligently select a
  182325. * reduced-color palette, if required. Data is an array of "num_palette"
  182326. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182327. * is non-zero.
  182328. */
  182329. png_uint_16p hist;
  182330. #endif
  182331. #ifdef PNG_cHRM_SUPPORTED
  182332. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182333. * on which the PNG was created. This data allows the viewer to do gamut
  182334. * mapping of the input image to ensure that the viewer sees the same
  182335. * colors in the image as the creator. Values are in the range
  182336. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182337. */
  182338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182339. float x_white;
  182340. float y_white;
  182341. float x_red;
  182342. float y_red;
  182343. float x_green;
  182344. float y_green;
  182345. float x_blue;
  182346. float y_blue;
  182347. #endif
  182348. #endif
  182349. #if defined(PNG_pCAL_SUPPORTED)
  182350. /* The pCAL chunk describes a transformation between the stored pixel
  182351. * values and original physical data values used to create the image.
  182352. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182353. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182354. * (possibly non-linear) transformation function given by "pcal_type"
  182355. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182356. * defines below, and the PNG-Group's PNG extensions document for a
  182357. * complete description of the transformations and how they should be
  182358. * implemented, and for a description of the ASCII parameter strings.
  182359. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182360. */
  182361. png_charp pcal_purpose; /* pCAL chunk description string */
  182362. png_int_32 pcal_X0; /* minimum value */
  182363. png_int_32 pcal_X1; /* maximum value */
  182364. png_charp pcal_units; /* Latin-1 string giving physical units */
  182365. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182366. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182367. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182368. #endif
  182369. /* New members added in libpng-1.0.6 */
  182370. #ifdef PNG_FREE_ME_SUPPORTED
  182371. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182372. #endif
  182373. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182374. /* storage for unknown chunks that the library doesn't recognize. */
  182375. png_unknown_chunkp unknown_chunks;
  182376. png_size_t unknown_chunks_num;
  182377. #endif
  182378. #if defined(PNG_iCCP_SUPPORTED)
  182379. /* iCCP chunk data. */
  182380. png_charp iccp_name; /* profile name */
  182381. png_charp iccp_profile; /* International Color Consortium profile data */
  182382. /* Note to maintainer: should be png_bytep */
  182383. png_uint_32 iccp_proflen; /* ICC profile data length */
  182384. png_byte iccp_compression; /* Always zero */
  182385. #endif
  182386. #if defined(PNG_sPLT_SUPPORTED)
  182387. /* data on sPLT chunks (there may be more than one). */
  182388. png_sPLT_tp splt_palettes;
  182389. png_uint_32 splt_palettes_num;
  182390. #endif
  182391. #if defined(PNG_sCAL_SUPPORTED)
  182392. /* The sCAL chunk describes the actual physical dimensions of the
  182393. * subject matter of the graphic. The chunk contains a unit specification
  182394. * a byte value, and two ASCII strings representing floating-point
  182395. * values. The values are width and height corresponsing to one pixel
  182396. * in the image. This external representation is converted to double
  182397. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182398. */
  182399. png_byte scal_unit; /* unit of physical scale */
  182400. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182401. double scal_pixel_width; /* width of one pixel */
  182402. double scal_pixel_height; /* height of one pixel */
  182403. #endif
  182404. #ifdef PNG_FIXED_POINT_SUPPORTED
  182405. png_charp scal_s_width; /* string containing height */
  182406. png_charp scal_s_height; /* string containing width */
  182407. #endif
  182408. #endif
  182409. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182410. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182411. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182412. png_bytepp row_pointers; /* the image bits */
  182413. #endif
  182414. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182415. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182416. #endif
  182417. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182418. png_fixed_point int_x_white;
  182419. png_fixed_point int_y_white;
  182420. png_fixed_point int_x_red;
  182421. png_fixed_point int_y_red;
  182422. png_fixed_point int_x_green;
  182423. png_fixed_point int_y_green;
  182424. png_fixed_point int_x_blue;
  182425. png_fixed_point int_y_blue;
  182426. #endif
  182427. } png_info;
  182428. typedef png_info FAR * png_infop;
  182429. typedef png_info FAR * FAR * png_infopp;
  182430. /* Maximum positive integer used in PNG is (2^31)-1 */
  182431. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182432. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182433. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182434. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182435. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182436. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182437. #endif
  182438. /* These describe the color_type field in png_info. */
  182439. /* color type masks */
  182440. #define PNG_COLOR_MASK_PALETTE 1
  182441. #define PNG_COLOR_MASK_COLOR 2
  182442. #define PNG_COLOR_MASK_ALPHA 4
  182443. /* color types. Note that not all combinations are legal */
  182444. #define PNG_COLOR_TYPE_GRAY 0
  182445. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182446. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182447. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182448. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182449. /* aliases */
  182450. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182451. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182452. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182453. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182454. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182455. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182456. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182457. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182458. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182459. /* These are for the interlacing type. These values should NOT be changed. */
  182460. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182461. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182462. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182463. /* These are for the oFFs chunk. These values should NOT be changed. */
  182464. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182465. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182466. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182467. /* These are for the pCAL chunk. These values should NOT be changed. */
  182468. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182469. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182470. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182471. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182472. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182473. /* These are for the sCAL chunk. These values should NOT be changed. */
  182474. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182475. #define PNG_SCALE_METER 1 /* meters per pixel */
  182476. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182477. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182478. /* These are for the pHYs chunk. These values should NOT be changed. */
  182479. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182480. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182481. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182482. /* These are for the sRGB chunk. These values should NOT be changed. */
  182483. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182484. #define PNG_sRGB_INTENT_RELATIVE 1
  182485. #define PNG_sRGB_INTENT_SATURATION 2
  182486. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182487. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182488. /* This is for text chunks */
  182489. #define PNG_KEYWORD_MAX_LENGTH 79
  182490. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182491. #define PNG_MAX_PALETTE_LENGTH 256
  182492. /* These determine if an ancillary chunk's data has been successfully read
  182493. * from the PNG header, or if the application has filled in the corresponding
  182494. * data in the info_struct to be written into the output file. The values
  182495. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182496. */
  182497. #define PNG_INFO_gAMA 0x0001
  182498. #define PNG_INFO_sBIT 0x0002
  182499. #define PNG_INFO_cHRM 0x0004
  182500. #define PNG_INFO_PLTE 0x0008
  182501. #define PNG_INFO_tRNS 0x0010
  182502. #define PNG_INFO_bKGD 0x0020
  182503. #define PNG_INFO_hIST 0x0040
  182504. #define PNG_INFO_pHYs 0x0080
  182505. #define PNG_INFO_oFFs 0x0100
  182506. #define PNG_INFO_tIME 0x0200
  182507. #define PNG_INFO_pCAL 0x0400
  182508. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182509. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182510. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182511. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182512. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182513. /* This is used for the transformation routines, as some of them
  182514. * change these values for the row. It also should enable using
  182515. * the routines for other purposes.
  182516. */
  182517. typedef struct png_row_info_struct
  182518. {
  182519. png_uint_32 width; /* width of row */
  182520. png_uint_32 rowbytes; /* number of bytes in row */
  182521. png_byte color_type; /* color type of row */
  182522. png_byte bit_depth; /* bit depth of row */
  182523. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182524. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182525. } png_row_info;
  182526. typedef png_row_info FAR * png_row_infop;
  182527. typedef png_row_info FAR * FAR * png_row_infopp;
  182528. /* These are the function types for the I/O functions and for the functions
  182529. * that allow the user to override the default I/O functions with his or her
  182530. * own. The png_error_ptr type should match that of user-supplied warning
  182531. * and error functions, while the png_rw_ptr type should match that of the
  182532. * user read/write data functions.
  182533. */
  182534. typedef struct png_struct_def png_struct;
  182535. typedef png_struct FAR * png_structp;
  182536. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182537. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182538. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182539. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182540. int));
  182541. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182542. int));
  182543. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182544. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182545. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182546. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182547. png_uint_32, int));
  182548. #endif
  182549. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182550. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182551. defined(PNG_LEGACY_SUPPORTED)
  182552. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182553. png_row_infop, png_bytep));
  182554. #endif
  182555. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182556. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182557. #endif
  182558. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182559. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182560. #endif
  182561. /* Transform masks for the high-level interface */
  182562. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182563. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182564. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182565. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182566. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182567. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182568. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182569. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182570. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182571. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182572. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182573. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182574. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182575. /* Flags for MNG supported features */
  182576. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182577. #define PNG_FLAG_MNG_FILTER_64 0x04
  182578. #define PNG_ALL_MNG_FEATURES 0x05
  182579. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182580. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182581. /* The structure that holds the information to read and write PNG files.
  182582. * The only people who need to care about what is inside of this are the
  182583. * people who will be modifying the library for their own special needs.
  182584. * It should NOT be accessed directly by an application, except to store
  182585. * the jmp_buf.
  182586. */
  182587. struct png_struct_def
  182588. {
  182589. #ifdef PNG_SETJMP_SUPPORTED
  182590. jmp_buf jmpbuf; /* used in png_error */
  182591. #endif
  182592. png_error_ptr error_fn; /* function for printing errors and aborting */
  182593. png_error_ptr warning_fn; /* function for printing warnings */
  182594. png_voidp error_ptr; /* user supplied struct for error functions */
  182595. png_rw_ptr write_data_fn; /* function for writing output data */
  182596. png_rw_ptr read_data_fn; /* function for reading input data */
  182597. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182598. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182599. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182600. #endif
  182601. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182602. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182603. #endif
  182604. /* These were added in libpng-1.0.2 */
  182605. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182606. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182607. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182608. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182609. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182610. png_byte user_transform_channels; /* channels in user transformed pixels */
  182611. #endif
  182612. #endif
  182613. png_uint_32 mode; /* tells us where we are in the PNG file */
  182614. png_uint_32 flags; /* flags indicating various things to libpng */
  182615. png_uint_32 transformations; /* which transformations to perform */
  182616. z_stream zstream; /* pointer to decompression structure (below) */
  182617. png_bytep zbuf; /* buffer for zlib */
  182618. png_size_t zbuf_size; /* size of zbuf */
  182619. int zlib_level; /* holds zlib compression level */
  182620. int zlib_method; /* holds zlib compression method */
  182621. int zlib_window_bits; /* holds zlib compression window bits */
  182622. int zlib_mem_level; /* holds zlib compression memory level */
  182623. int zlib_strategy; /* holds zlib compression strategy */
  182624. png_uint_32 width; /* width of image in pixels */
  182625. png_uint_32 height; /* height of image in pixels */
  182626. png_uint_32 num_rows; /* number of rows in current pass */
  182627. png_uint_32 usr_width; /* width of row at start of write */
  182628. png_uint_32 rowbytes; /* size of row in bytes */
  182629. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182630. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182631. png_uint_32 row_number; /* current row in interlace pass */
  182632. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182633. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182634. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182635. png_bytep up_row; /* buffer to save "up" row when filtering */
  182636. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182637. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182638. png_row_info row_info; /* used for transformation routines */
  182639. png_uint_32 idat_size; /* current IDAT size for read */
  182640. png_uint_32 crc; /* current chunk CRC value */
  182641. png_colorp palette; /* palette from the input file */
  182642. png_uint_16 num_palette; /* number of color entries in palette */
  182643. png_uint_16 num_trans; /* number of transparency values */
  182644. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182645. png_byte compression; /* file compression type (always 0) */
  182646. png_byte filter; /* file filter type (always 0) */
  182647. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182648. png_byte pass; /* current interlace pass (0 - 6) */
  182649. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182650. png_byte color_type; /* color type of file */
  182651. png_byte bit_depth; /* bit depth of file */
  182652. png_byte usr_bit_depth; /* bit depth of users row */
  182653. png_byte pixel_depth; /* number of bits per pixel */
  182654. png_byte channels; /* number of channels in file */
  182655. png_byte usr_channels; /* channels at start of write */
  182656. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182657. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182658. #ifdef PNG_LEGACY_SUPPORTED
  182659. png_byte filler; /* filler byte for pixel expansion */
  182660. #else
  182661. png_uint_16 filler; /* filler bytes for pixel expansion */
  182662. #endif
  182663. #endif
  182664. #if defined(PNG_bKGD_SUPPORTED)
  182665. png_byte background_gamma_type;
  182666. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182667. float background_gamma;
  182668. # endif
  182669. png_color_16 background; /* background color in screen gamma space */
  182670. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182671. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182672. #endif
  182673. #endif /* PNG_bKGD_SUPPORTED */
  182674. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182675. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182676. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182677. png_uint_32 flush_rows; /* number of rows written since last flush */
  182678. #endif
  182679. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182680. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182681. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182682. float gamma; /* file gamma value */
  182683. float screen_gamma; /* screen gamma value (display_exponent) */
  182684. #endif
  182685. #endif
  182686. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182687. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182688. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182689. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182690. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182691. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182692. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182693. #endif
  182694. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182695. png_color_8 sig_bit; /* significant bits in each available channel */
  182696. #endif
  182697. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182698. png_color_8 shift; /* shift for significant bit tranformation */
  182699. #endif
  182700. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182701. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182702. png_bytep trans; /* transparency values for paletted files */
  182703. png_color_16 trans_values; /* transparency values for non-paletted files */
  182704. #endif
  182705. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182706. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182707. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182708. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182709. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182710. png_progressive_end_ptr end_fn; /* called after image is complete */
  182711. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182712. png_bytep save_buffer; /* buffer for previously read data */
  182713. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182714. png_bytep current_buffer; /* buffer for recently used data */
  182715. png_uint_32 push_length; /* size of current input chunk */
  182716. png_uint_32 skip_length; /* bytes to skip in input data */
  182717. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182718. png_size_t save_buffer_max; /* total size of save_buffer */
  182719. png_size_t buffer_size; /* total amount of available input data */
  182720. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182721. int process_mode; /* what push library is currently doing */
  182722. int cur_palette; /* current push library palette index */
  182723. # if defined(PNG_TEXT_SUPPORTED)
  182724. png_size_t current_text_size; /* current size of text input data */
  182725. png_size_t current_text_left; /* how much text left to read in input */
  182726. png_charp current_text; /* current text chunk buffer */
  182727. png_charp current_text_ptr; /* current location in current_text */
  182728. # endif /* PNG_TEXT_SUPPORTED */
  182729. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182730. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182731. /* for the Borland special 64K segment handler */
  182732. png_bytepp offset_table_ptr;
  182733. png_bytep offset_table;
  182734. png_uint_16 offset_table_number;
  182735. png_uint_16 offset_table_count;
  182736. png_uint_16 offset_table_count_free;
  182737. #endif
  182738. #if defined(PNG_READ_DITHER_SUPPORTED)
  182739. png_bytep palette_lookup; /* lookup table for dithering */
  182740. png_bytep dither_index; /* index translation for palette files */
  182741. #endif
  182742. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182743. png_uint_16p hist; /* histogram */
  182744. #endif
  182745. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182746. png_byte heuristic_method; /* heuristic for row filter selection */
  182747. png_byte num_prev_filters; /* number of weights for previous rows */
  182748. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182749. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182750. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182751. png_uint_16p filter_costs; /* relative filter calculation cost */
  182752. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182753. #endif
  182754. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182755. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182756. #endif
  182757. /* New members added in libpng-1.0.6 */
  182758. #ifdef PNG_FREE_ME_SUPPORTED
  182759. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182760. #endif
  182761. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182762. png_voidp user_chunk_ptr;
  182763. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182764. #endif
  182765. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182766. int num_chunk_list;
  182767. png_bytep chunk_list;
  182768. #endif
  182769. /* New members added in libpng-1.0.3 */
  182770. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182771. png_byte rgb_to_gray_status;
  182772. /* These were changed from png_byte in libpng-1.0.6 */
  182773. png_uint_16 rgb_to_gray_red_coeff;
  182774. png_uint_16 rgb_to_gray_green_coeff;
  182775. png_uint_16 rgb_to_gray_blue_coeff;
  182776. #endif
  182777. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182778. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182779. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182780. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182781. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182782. #ifdef PNG_1_0_X
  182783. png_byte mng_features_permitted;
  182784. #else
  182785. png_uint_32 mng_features_permitted;
  182786. #endif /* PNG_1_0_X */
  182787. #endif
  182788. /* New member added in libpng-1.0.7 */
  182789. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182790. png_fixed_point int_gamma;
  182791. #endif
  182792. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182793. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182794. png_byte filter_type;
  182795. #endif
  182796. #if defined(PNG_1_0_X)
  182797. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182798. png_uint_32 row_buf_size;
  182799. #endif
  182800. /* New members added in libpng-1.2.0 */
  182801. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182802. # if !defined(PNG_1_0_X)
  182803. # if defined(PNG_MMX_CODE_SUPPORTED)
  182804. png_byte mmx_bitdepth_threshold;
  182805. png_uint_32 mmx_rowbytes_threshold;
  182806. # endif
  182807. png_uint_32 asm_flags;
  182808. # endif
  182809. #endif
  182810. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182811. #ifdef PNG_USER_MEM_SUPPORTED
  182812. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182813. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182814. png_free_ptr free_fn; /* function for freeing memory */
  182815. #endif
  182816. /* New member added in libpng-1.0.13 and 1.2.0 */
  182817. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182818. #if defined(PNG_READ_DITHER_SUPPORTED)
  182819. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182820. png_bytep dither_sort; /* working sort array */
  182821. png_bytep index_to_palette; /* where the original index currently is */
  182822. /* in the palette */
  182823. png_bytep palette_to_index; /* which original index points to this */
  182824. /* palette color */
  182825. #endif
  182826. /* New members added in libpng-1.0.16 and 1.2.6 */
  182827. png_byte compression_type;
  182828. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182829. png_uint_32 user_width_max;
  182830. png_uint_32 user_height_max;
  182831. #endif
  182832. /* New member added in libpng-1.0.25 and 1.2.17 */
  182833. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182834. /* storage for unknown chunk that the library doesn't recognize. */
  182835. png_unknown_chunk unknown_chunk;
  182836. #endif
  182837. };
  182838. /* This triggers a compiler error in png.c, if png.c and png.h
  182839. * do not agree upon the version number.
  182840. */
  182841. typedef png_structp version_1_2_21;
  182842. typedef png_struct FAR * FAR * png_structpp;
  182843. /* Here are the function definitions most commonly used. This is not
  182844. * the place to find out how to use libpng. See libpng.txt for the
  182845. * full explanation, see example.c for the summary. This just provides
  182846. * a simple one line description of the use of each function.
  182847. */
  182848. /* Returns the version number of the library */
  182849. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182850. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182851. * Handling more than 8 bytes from the beginning of the file is an error.
  182852. */
  182853. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182854. int num_bytes));
  182855. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182856. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182857. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182858. * start > 7 will always fail (ie return non-zero).
  182859. */
  182860. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182861. png_size_t num_to_check));
  182862. /* Simple signature checking function. This is the same as calling
  182863. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182864. */
  182865. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182866. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182867. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182868. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182869. png_error_ptr error_fn, png_error_ptr warn_fn));
  182870. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182871. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182872. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182873. png_error_ptr error_fn, png_error_ptr warn_fn));
  182874. #ifdef PNG_WRITE_SUPPORTED
  182875. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182876. PNGARG((png_structp png_ptr));
  182877. #endif
  182878. #ifdef PNG_WRITE_SUPPORTED
  182879. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182880. PNGARG((png_structp png_ptr, png_uint_32 size));
  182881. #endif
  182882. /* Reset the compression stream */
  182883. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182884. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182885. #ifdef PNG_USER_MEM_SUPPORTED
  182886. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182887. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182888. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182889. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182890. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182891. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182892. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182893. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182894. #endif
  182895. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182896. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182897. png_bytep chunk_name, png_bytep data, png_size_t length));
  182898. /* Write the start of a PNG chunk - length and chunk name. */
  182899. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182900. png_bytep chunk_name, png_uint_32 length));
  182901. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182902. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182903. png_bytep data, png_size_t length));
  182904. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182905. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182906. /* Allocate and initialize the info structure */
  182907. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182908. PNGARG((png_structp png_ptr));
  182909. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182910. /* Initialize the info structure (old interface - DEPRECATED) */
  182911. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182912. #undef png_info_init
  182913. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182914. png_sizeof(png_info));
  182915. #endif
  182916. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182917. png_size_t png_info_struct_size));
  182918. /* Writes all the PNG information before the image. */
  182919. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182920. png_infop info_ptr));
  182921. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182922. png_infop info_ptr));
  182923. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182924. /* read the information before the actual image data. */
  182925. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182926. png_infop info_ptr));
  182927. #endif
  182928. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182929. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182930. PNGARG((png_structp png_ptr, png_timep ptime));
  182931. #endif
  182932. #if !defined(_WIN32_WCE)
  182933. /* "time.h" functions are not supported on WindowsCE */
  182934. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182935. /* convert from a struct tm to png_time */
  182936. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182937. struct tm FAR * ttime));
  182938. /* convert from time_t to png_time. Uses gmtime() */
  182939. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182940. time_t ttime));
  182941. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182942. #endif /* _WIN32_WCE */
  182943. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182944. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182945. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182946. #if !defined(PNG_1_0_X)
  182947. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182948. png_ptr));
  182949. #endif
  182950. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182951. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182952. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182953. /* Deprecated */
  182954. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182955. #endif
  182956. #endif
  182957. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182958. /* Use blue, green, red order for pixels. */
  182959. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182960. #endif
  182961. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182962. /* Expand the grayscale to 24-bit RGB if necessary. */
  182963. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182964. #endif
  182965. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182966. /* Reduce RGB to grayscale. */
  182967. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182968. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182969. int error_action, double red, double green ));
  182970. #endif
  182971. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182972. int error_action, png_fixed_point red, png_fixed_point green ));
  182973. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182974. png_ptr));
  182975. #endif
  182976. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182977. png_colorp palette));
  182978. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182979. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182980. #endif
  182981. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182982. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182983. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182984. #endif
  182985. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182986. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182987. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182988. #endif
  182989. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182990. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182991. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182992. png_uint_32 filler, int flags));
  182993. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182994. #define PNG_FILLER_BEFORE 0
  182995. #define PNG_FILLER_AFTER 1
  182996. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182997. #if !defined(PNG_1_0_X)
  182998. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182999. png_uint_32 filler, int flags));
  183000. #endif
  183001. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183002. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183003. /* Swap bytes in 16-bit depth files. */
  183004. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183005. #endif
  183006. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183007. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183008. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183009. #endif
  183010. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183011. /* Swap packing order of pixels in bytes. */
  183012. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183013. #endif
  183014. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183015. /* Converts files to legal bit depths. */
  183016. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183017. png_color_8p true_bits));
  183018. #endif
  183019. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183020. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183021. /* Have the code handle the interlacing. Returns the number of passes. */
  183022. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183023. #endif
  183024. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183025. /* Invert monochrome files */
  183026. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183027. #endif
  183028. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183029. /* Handle alpha and tRNS by replacing with a background color. */
  183030. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183031. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183032. png_color_16p background_color, int background_gamma_code,
  183033. int need_expand, double background_gamma));
  183034. #endif
  183035. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183036. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183037. #define PNG_BACKGROUND_GAMMA_FILE 2
  183038. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183039. #endif
  183040. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183041. /* strip the second byte of information from a 16-bit depth file. */
  183042. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183043. #endif
  183044. #if defined(PNG_READ_DITHER_SUPPORTED)
  183045. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183046. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183047. png_colorp palette, int num_palette, int maximum_colors,
  183048. png_uint_16p histogram, int full_dither));
  183049. #endif
  183050. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183051. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183052. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183053. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183054. double screen_gamma, double default_file_gamma));
  183055. #endif
  183056. #endif
  183057. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183058. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183059. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183060. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183061. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183062. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183063. int empty_plte_permitted));
  183064. #endif
  183065. #endif
  183066. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183067. /* Set how many lines between output flushes - 0 for no flushing */
  183068. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183069. /* Flush the current PNG output buffer */
  183070. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183071. #endif
  183072. /* optional update palette with requested transformations */
  183073. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183074. /* optional call to update the users info structure */
  183075. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183076. png_infop info_ptr));
  183077. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183078. /* read one or more rows of image data. */
  183079. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183080. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183081. #endif
  183082. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183083. /* read a row of data. */
  183084. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183085. png_bytep row,
  183086. png_bytep display_row));
  183087. #endif
  183088. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183089. /* read the whole image into memory at once. */
  183090. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183091. png_bytepp image));
  183092. #endif
  183093. /* write a row of image data */
  183094. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183095. png_bytep row));
  183096. /* write a few rows of image data */
  183097. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183098. png_bytepp row, png_uint_32 num_rows));
  183099. /* write the image data */
  183100. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183101. png_bytepp image));
  183102. /* writes the end of the PNG file. */
  183103. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183104. png_infop info_ptr));
  183105. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183106. /* read the end of the PNG file. */
  183107. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183108. png_infop info_ptr));
  183109. #endif
  183110. /* free any memory associated with the png_info_struct */
  183111. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183112. png_infopp info_ptr_ptr));
  183113. /* free any memory associated with the png_struct and the png_info_structs */
  183114. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183115. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183116. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183117. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183118. png_infop end_info_ptr));
  183119. /* free any memory associated with the png_struct and the png_info_structs */
  183120. extern PNG_EXPORT(void,png_destroy_write_struct)
  183121. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183122. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183123. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183124. /* set the libpng method of handling chunk CRC errors */
  183125. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183126. int crit_action, int ancil_action));
  183127. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183128. * ancillary and critical chunks, and whether to use the data contained
  183129. * therein. Note that it is impossible to "discard" data in a critical
  183130. * chunk. For versions prior to 0.90, the action was always error/quit,
  183131. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183132. * chunks is warn/discard. These values should NOT be changed.
  183133. *
  183134. * value action:critical action:ancillary
  183135. */
  183136. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183137. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183138. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183139. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183140. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183141. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183142. /* These functions give the user control over the scan-line filtering in
  183143. * libpng and the compression methods used by zlib. These functions are
  183144. * mainly useful for testing, as the defaults should work with most users.
  183145. * Those users who are tight on memory or want faster performance at the
  183146. * expense of compression can modify them. See the compression library
  183147. * header file (zlib.h) for an explination of the compression functions.
  183148. */
  183149. /* set the filtering method(s) used by libpng. Currently, the only valid
  183150. * value for "method" is 0.
  183151. */
  183152. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183153. int filters));
  183154. /* Flags for png_set_filter() to say which filters to use. The flags
  183155. * are chosen so that they don't conflict with real filter types
  183156. * below, in case they are supplied instead of the #defined constants.
  183157. * These values should NOT be changed.
  183158. */
  183159. #define PNG_NO_FILTERS 0x00
  183160. #define PNG_FILTER_NONE 0x08
  183161. #define PNG_FILTER_SUB 0x10
  183162. #define PNG_FILTER_UP 0x20
  183163. #define PNG_FILTER_AVG 0x40
  183164. #define PNG_FILTER_PAETH 0x80
  183165. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183166. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183167. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183168. * These defines should NOT be changed.
  183169. */
  183170. #define PNG_FILTER_VALUE_NONE 0
  183171. #define PNG_FILTER_VALUE_SUB 1
  183172. #define PNG_FILTER_VALUE_UP 2
  183173. #define PNG_FILTER_VALUE_AVG 3
  183174. #define PNG_FILTER_VALUE_PAETH 4
  183175. #define PNG_FILTER_VALUE_LAST 5
  183176. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183177. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183178. * defines, either the default (minimum-sum-of-absolute-differences), or
  183179. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183180. *
  183181. * Weights are factors >= 1.0, indicating how important it is to keep the
  183182. * filter type consistent between rows. Larger numbers mean the current
  183183. * filter is that many times as likely to be the same as the "num_weights"
  183184. * previous filters. This is cumulative for each previous row with a weight.
  183185. * There needs to be "num_weights" values in "filter_weights", or it can be
  183186. * NULL if the weights aren't being specified. Weights have no influence on
  183187. * the selection of the first row filter. Well chosen weights can (in theory)
  183188. * improve the compression for a given image.
  183189. *
  183190. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183191. * filter type. Higher costs indicate more decoding expense, and are
  183192. * therefore less likely to be selected over a filter with lower computational
  183193. * costs. There needs to be a value in "filter_costs" for each valid filter
  183194. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183195. * setting the costs. Costs try to improve the speed of decompression without
  183196. * unduly increasing the compressed image size.
  183197. *
  183198. * A negative weight or cost indicates the default value is to be used, and
  183199. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183200. * The default values for both weights and costs are currently 1.0, but may
  183201. * change if good general weighting/cost heuristics can be found. If both
  183202. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183203. * to the UNWEIGHTED method, but with added encoding time/computation.
  183204. */
  183205. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183206. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183207. int heuristic_method, int num_weights, png_doublep filter_weights,
  183208. png_doublep filter_costs));
  183209. #endif
  183210. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183211. /* Heuristic used for row filter selection. These defines should NOT be
  183212. * changed.
  183213. */
  183214. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183215. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183216. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183217. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183218. /* Set the library compression level. Currently, valid values range from
  183219. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183220. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183221. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183222. * for PNG images, and do considerably fewer caclulations. In the future,
  183223. * these values may not correspond directly to the zlib compression levels.
  183224. */
  183225. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183226. int level));
  183227. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183228. PNGARG((png_structp png_ptr, int mem_level));
  183229. extern PNG_EXPORT(void,png_set_compression_strategy)
  183230. PNGARG((png_structp png_ptr, int strategy));
  183231. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183232. PNGARG((png_structp png_ptr, int window_bits));
  183233. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183234. int method));
  183235. /* These next functions are called for input/output, memory, and error
  183236. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183237. * and call standard C I/O routines such as fread(), fwrite(), and
  183238. * fprintf(). These functions can be made to use other I/O routines
  183239. * at run time for those applications that need to handle I/O in a
  183240. * different manner by calling png_set_???_fn(). See libpng.txt for
  183241. * more information.
  183242. */
  183243. #if !defined(PNG_NO_STDIO)
  183244. /* Initialize the input/output for the PNG file to the default functions. */
  183245. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183246. #endif
  183247. /* Replace the (error and abort), and warning functions with user
  183248. * supplied functions. If no messages are to be printed you must still
  183249. * write and use replacement functions. The replacement error_fn should
  183250. * still do a longjmp to the last setjmp location if you are using this
  183251. * method of error handling. If error_fn or warning_fn is NULL, the
  183252. * default function will be used.
  183253. */
  183254. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183255. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183256. /* Return the user pointer associated with the error functions */
  183257. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183258. /* Replace the default data output functions with a user supplied one(s).
  183259. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183260. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183261. * output_flush_fn will be ignored (and thus can be NULL).
  183262. */
  183263. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183264. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183265. /* Replace the default data input function with a user supplied one. */
  183266. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183267. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183268. /* Return the user pointer associated with the I/O functions */
  183269. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183270. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183271. png_read_status_ptr read_row_fn));
  183272. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183273. png_write_status_ptr write_row_fn));
  183274. #ifdef PNG_USER_MEM_SUPPORTED
  183275. /* Replace the default memory allocation functions with user supplied one(s). */
  183276. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183277. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183278. /* Return the user pointer associated with the memory functions */
  183279. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183280. #endif
  183281. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183282. defined(PNG_LEGACY_SUPPORTED)
  183283. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183284. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183285. #endif
  183286. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183287. defined(PNG_LEGACY_SUPPORTED)
  183288. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183289. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183290. #endif
  183291. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183292. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183293. defined(PNG_LEGACY_SUPPORTED)
  183294. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183295. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183296. int user_transform_channels));
  183297. /* Return the user pointer associated with the user transform functions */
  183298. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183299. PNGARG((png_structp png_ptr));
  183300. #endif
  183301. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183302. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183303. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183304. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183305. png_ptr));
  183306. #endif
  183307. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183308. /* Sets the function callbacks for the push reader, and a pointer to a
  183309. * user-defined structure available to the callback functions.
  183310. */
  183311. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183312. png_voidp progressive_ptr,
  183313. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183314. png_progressive_end_ptr end_fn));
  183315. /* returns the user pointer associated with the push read functions */
  183316. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183317. PNGARG((png_structp png_ptr));
  183318. /* function to be called when data becomes available */
  183319. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183320. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183321. /* function that combines rows. Not very much different than the
  183322. * png_combine_row() call. Is this even used?????
  183323. */
  183324. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183325. png_bytep old_row, png_bytep new_row));
  183326. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183327. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183328. png_uint_32 size));
  183329. #if defined(PNG_1_0_X)
  183330. # define png_malloc_warn png_malloc
  183331. #else
  183332. /* Added at libpng version 1.2.4 */
  183333. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183334. png_uint_32 size));
  183335. #endif
  183336. /* frees a pointer allocated by png_malloc() */
  183337. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183338. #if defined(PNG_1_0_X)
  183339. /* Function to allocate memory for zlib. */
  183340. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183341. uInt size));
  183342. /* Function to free memory for zlib */
  183343. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183344. #endif
  183345. /* Free data that was allocated internally */
  183346. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183347. png_infop info_ptr, png_uint_32 free_me, int num));
  183348. #ifdef PNG_FREE_ME_SUPPORTED
  183349. /* Reassign responsibility for freeing existing data, whether allocated
  183350. * by libpng or by the application */
  183351. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183352. png_infop info_ptr, int freer, png_uint_32 mask));
  183353. #endif
  183354. /* assignments for png_data_freer */
  183355. #define PNG_DESTROY_WILL_FREE_DATA 1
  183356. #define PNG_SET_WILL_FREE_DATA 1
  183357. #define PNG_USER_WILL_FREE_DATA 2
  183358. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183359. #define PNG_FREE_HIST 0x0008
  183360. #define PNG_FREE_ICCP 0x0010
  183361. #define PNG_FREE_SPLT 0x0020
  183362. #define PNG_FREE_ROWS 0x0040
  183363. #define PNG_FREE_PCAL 0x0080
  183364. #define PNG_FREE_SCAL 0x0100
  183365. #define PNG_FREE_UNKN 0x0200
  183366. #define PNG_FREE_LIST 0x0400
  183367. #define PNG_FREE_PLTE 0x1000
  183368. #define PNG_FREE_TRNS 0x2000
  183369. #define PNG_FREE_TEXT 0x4000
  183370. #define PNG_FREE_ALL 0x7fff
  183371. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183372. #ifdef PNG_USER_MEM_SUPPORTED
  183373. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183374. png_uint_32 size));
  183375. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183376. png_voidp ptr));
  183377. #endif
  183378. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183379. png_voidp s1, png_voidp s2, png_uint_32 size));
  183380. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183381. png_voidp s1, int value, png_uint_32 size));
  183382. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183383. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183384. int check));
  183385. #endif /* USE_FAR_KEYWORD */
  183386. #ifndef PNG_NO_ERROR_TEXT
  183387. /* Fatal error in PNG image of libpng - can't continue */
  183388. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183389. png_const_charp error_message));
  183390. /* The same, but the chunk name is prepended to the error string. */
  183391. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183392. png_const_charp error_message));
  183393. #else
  183394. /* Fatal error in PNG image of libpng - can't continue */
  183395. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183396. #endif
  183397. #ifndef PNG_NO_WARNINGS
  183398. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183399. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183400. png_const_charp warning_message));
  183401. #ifdef PNG_READ_SUPPORTED
  183402. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183403. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183404. png_const_charp warning_message));
  183405. #endif /* PNG_READ_SUPPORTED */
  183406. #endif /* PNG_NO_WARNINGS */
  183407. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183408. * Similarly, the png_get_<chunk> calls are used to read values from the
  183409. * png_info_struct, either storing the parameters in the passed variables, or
  183410. * setting pointers into the png_info_struct where the data is stored. The
  183411. * png_get_<chunk> functions return a non-zero value if the data was available
  183412. * in info_ptr, or return zero and do not change any of the parameters if the
  183413. * data was not available.
  183414. *
  183415. * These functions should be used instead of directly accessing png_info
  183416. * to avoid problems with future changes in the size and internal layout of
  183417. * png_info_struct.
  183418. */
  183419. /* Returns "flag" if chunk data is valid in info_ptr. */
  183420. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183421. png_infop info_ptr, png_uint_32 flag));
  183422. /* Returns number of bytes needed to hold a transformed row. */
  183423. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183424. png_infop info_ptr));
  183425. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183426. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183427. returned from png_read_png(). */
  183428. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183429. png_infop info_ptr));
  183430. /* Set row_pointers, which is an array of pointers to scanlines for use
  183431. by png_write_png(). */
  183432. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183433. png_infop info_ptr, png_bytepp row_pointers));
  183434. #endif
  183435. /* Returns number of color channels in image. */
  183436. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183437. png_infop info_ptr));
  183438. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183439. /* Returns image width in pixels. */
  183440. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183441. png_ptr, png_infop info_ptr));
  183442. /* Returns image height in pixels. */
  183443. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183444. png_ptr, png_infop info_ptr));
  183445. /* Returns image bit_depth. */
  183446. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183447. png_ptr, png_infop info_ptr));
  183448. /* Returns image color_type. */
  183449. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183450. png_ptr, png_infop info_ptr));
  183451. /* Returns image filter_type. */
  183452. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183453. png_ptr, png_infop info_ptr));
  183454. /* Returns image interlace_type. */
  183455. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183456. png_ptr, png_infop info_ptr));
  183457. /* Returns image compression_type. */
  183458. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183459. png_ptr, png_infop info_ptr));
  183460. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183461. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183462. png_ptr, png_infop info_ptr));
  183463. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183464. png_ptr, png_infop info_ptr));
  183465. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183466. png_ptr, png_infop info_ptr));
  183467. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183468. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183469. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183470. png_ptr, png_infop info_ptr));
  183471. #endif
  183472. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183473. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183474. png_ptr, png_infop info_ptr));
  183475. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183476. png_ptr, png_infop info_ptr));
  183477. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183478. png_ptr, png_infop info_ptr));
  183479. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183480. png_ptr, png_infop info_ptr));
  183481. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183482. /* Returns pointer to signature string read from PNG header */
  183483. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183484. png_infop info_ptr));
  183485. #if defined(PNG_bKGD_SUPPORTED)
  183486. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183487. png_infop info_ptr, png_color_16p *background));
  183488. #endif
  183489. #if defined(PNG_bKGD_SUPPORTED)
  183490. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183491. png_infop info_ptr, png_color_16p background));
  183492. #endif
  183493. #if defined(PNG_cHRM_SUPPORTED)
  183494. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183495. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183496. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183497. double *red_y, double *green_x, double *green_y, double *blue_x,
  183498. double *blue_y));
  183499. #endif
  183500. #ifdef PNG_FIXED_POINT_SUPPORTED
  183501. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183502. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183503. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183504. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183505. *int_blue_x, png_fixed_point *int_blue_y));
  183506. #endif
  183507. #endif
  183508. #if defined(PNG_cHRM_SUPPORTED)
  183509. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183510. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183511. png_infop info_ptr, double white_x, double white_y, double red_x,
  183512. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183513. #endif
  183514. #ifdef PNG_FIXED_POINT_SUPPORTED
  183515. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183516. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183517. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183518. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183519. png_fixed_point int_blue_y));
  183520. #endif
  183521. #endif
  183522. #if defined(PNG_gAMA_SUPPORTED)
  183523. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183524. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183525. png_infop info_ptr, double *file_gamma));
  183526. #endif
  183527. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183528. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183529. #endif
  183530. #if defined(PNG_gAMA_SUPPORTED)
  183531. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183532. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183533. png_infop info_ptr, double file_gamma));
  183534. #endif
  183535. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183536. png_infop info_ptr, png_fixed_point int_file_gamma));
  183537. #endif
  183538. #if defined(PNG_hIST_SUPPORTED)
  183539. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183540. png_infop info_ptr, png_uint_16p *hist));
  183541. #endif
  183542. #if defined(PNG_hIST_SUPPORTED)
  183543. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183544. png_infop info_ptr, png_uint_16p hist));
  183545. #endif
  183546. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183547. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183548. int *bit_depth, int *color_type, int *interlace_method,
  183549. int *compression_method, int *filter_method));
  183550. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183551. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183552. int color_type, int interlace_method, int compression_method,
  183553. int filter_method));
  183554. #if defined(PNG_oFFs_SUPPORTED)
  183555. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183556. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183557. int *unit_type));
  183558. #endif
  183559. #if defined(PNG_oFFs_SUPPORTED)
  183560. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183561. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183562. int unit_type));
  183563. #endif
  183564. #if defined(PNG_pCAL_SUPPORTED)
  183565. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183566. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183567. int *type, int *nparams, png_charp *units, png_charpp *params));
  183568. #endif
  183569. #if defined(PNG_pCAL_SUPPORTED)
  183570. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183571. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183572. int type, int nparams, png_charp units, png_charpp params));
  183573. #endif
  183574. #if defined(PNG_pHYs_SUPPORTED)
  183575. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183577. #endif
  183578. #if defined(PNG_pHYs_SUPPORTED)
  183579. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183580. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183581. #endif
  183582. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183583. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183584. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183585. png_infop info_ptr, png_colorp palette, int num_palette));
  183586. #if defined(PNG_sBIT_SUPPORTED)
  183587. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183588. png_infop info_ptr, png_color_8p *sig_bit));
  183589. #endif
  183590. #if defined(PNG_sBIT_SUPPORTED)
  183591. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183592. png_infop info_ptr, png_color_8p sig_bit));
  183593. #endif
  183594. #if defined(PNG_sRGB_SUPPORTED)
  183595. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183596. png_infop info_ptr, int *intent));
  183597. #endif
  183598. #if defined(PNG_sRGB_SUPPORTED)
  183599. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, int intent));
  183601. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183602. png_infop info_ptr, int intent));
  183603. #endif
  183604. #if defined(PNG_iCCP_SUPPORTED)
  183605. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183606. png_infop info_ptr, png_charpp name, int *compression_type,
  183607. png_charpp profile, png_uint_32 *proflen));
  183608. /* Note to maintainer: profile should be png_bytepp */
  183609. #endif
  183610. #if defined(PNG_iCCP_SUPPORTED)
  183611. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183612. png_infop info_ptr, png_charp name, int compression_type,
  183613. png_charp profile, png_uint_32 proflen));
  183614. /* Note to maintainer: profile should be png_bytep */
  183615. #endif
  183616. #if defined(PNG_sPLT_SUPPORTED)
  183617. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183618. png_infop info_ptr, png_sPLT_tpp entries));
  183619. #endif
  183620. #if defined(PNG_sPLT_SUPPORTED)
  183621. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183622. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183623. #endif
  183624. #if defined(PNG_TEXT_SUPPORTED)
  183625. /* png_get_text also returns the number of text chunks in *num_text */
  183626. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183627. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183628. #endif
  183629. /*
  183630. * Note while png_set_text() will accept a structure whose text,
  183631. * language, and translated keywords are NULL pointers, the structure
  183632. * returned by png_get_text will always contain regular
  183633. * zero-terminated C strings. They might be empty strings but
  183634. * they will never be NULL pointers.
  183635. */
  183636. #if defined(PNG_TEXT_SUPPORTED)
  183637. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183638. png_infop info_ptr, png_textp text_ptr, int num_text));
  183639. #endif
  183640. #if defined(PNG_tIME_SUPPORTED)
  183641. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183642. png_infop info_ptr, png_timep *mod_time));
  183643. #endif
  183644. #if defined(PNG_tIME_SUPPORTED)
  183645. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183646. png_infop info_ptr, png_timep mod_time));
  183647. #endif
  183648. #if defined(PNG_tRNS_SUPPORTED)
  183649. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183651. png_color_16p *trans_values));
  183652. #endif
  183653. #if defined(PNG_tRNS_SUPPORTED)
  183654. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183655. png_infop info_ptr, png_bytep trans, int num_trans,
  183656. png_color_16p trans_values));
  183657. #endif
  183658. #if defined(PNG_tRNS_SUPPORTED)
  183659. #endif
  183660. #if defined(PNG_sCAL_SUPPORTED)
  183661. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183662. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183663. png_infop info_ptr, int *unit, double *width, double *height));
  183664. #else
  183665. #ifdef PNG_FIXED_POINT_SUPPORTED
  183666. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183667. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183668. #endif
  183669. #endif
  183670. #endif /* PNG_sCAL_SUPPORTED */
  183671. #if defined(PNG_sCAL_SUPPORTED)
  183672. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183673. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183674. png_infop info_ptr, int unit, double width, double height));
  183675. #else
  183676. #ifdef PNG_FIXED_POINT_SUPPORTED
  183677. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183678. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183679. #endif
  183680. #endif
  183681. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183682. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183683. /* provide a list of chunks and how they are to be handled, if the built-in
  183684. handling or default unknown chunk handling is not desired. Any chunks not
  183685. listed will be handled in the default manner. The IHDR and IEND chunks
  183686. must not be listed.
  183687. keep = 0: follow default behaviour
  183688. = 1: do not keep
  183689. = 2: keep only if safe-to-copy
  183690. = 3: keep even if unsafe-to-copy
  183691. */
  183692. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183693. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183694. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183695. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183696. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183697. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183698. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183699. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183700. #endif
  183701. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183702. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183703. chunk_name));
  183704. #endif
  183705. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183706. If you need to turn it off for a chunk that your application has freed,
  183707. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183708. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183709. png_infop info_ptr, int mask));
  183710. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183711. /* The "params" pointer is currently not used and is for future expansion. */
  183712. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183713. png_infop info_ptr,
  183714. int transforms,
  183715. png_voidp params));
  183716. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183717. png_infop info_ptr,
  183718. int transforms,
  183719. png_voidp params));
  183720. #endif
  183721. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183722. * numbers for PNG_DEBUG mean more debugging information. This has
  183723. * only been added since version 0.95 so it is not implemented throughout
  183724. * libpng yet, but more support will be added as needed.
  183725. */
  183726. #ifdef PNG_DEBUG
  183727. #if (PNG_DEBUG > 0)
  183728. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183729. #include <crtdbg.h>
  183730. #if (PNG_DEBUG > 1)
  183731. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183732. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183733. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183734. #endif
  183735. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183736. #ifndef PNG_DEBUG_FILE
  183737. #define PNG_DEBUG_FILE stderr
  183738. #endif /* PNG_DEBUG_FILE */
  183739. #if (PNG_DEBUG > 1)
  183740. #define png_debug(l,m) \
  183741. { \
  183742. int num_tabs=l; \
  183743. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183744. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183745. }
  183746. #define png_debug1(l,m,p1) \
  183747. { \
  183748. int num_tabs=l; \
  183749. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183750. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183751. }
  183752. #define png_debug2(l,m,p1,p2) \
  183753. { \
  183754. int num_tabs=l; \
  183755. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183756. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183757. }
  183758. #endif /* (PNG_DEBUG > 1) */
  183759. #endif /* _MSC_VER */
  183760. #endif /* (PNG_DEBUG > 0) */
  183761. #endif /* PNG_DEBUG */
  183762. #ifndef png_debug
  183763. #define png_debug(l, m)
  183764. #endif
  183765. #ifndef png_debug1
  183766. #define png_debug1(l, m, p1)
  183767. #endif
  183768. #ifndef png_debug2
  183769. #define png_debug2(l, m, p1, p2)
  183770. #endif
  183771. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183772. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183773. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183774. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183775. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183776. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183777. png_ptr, png_uint_32 mng_features_permitted));
  183778. #endif
  183779. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183780. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183781. #define PNG_HANDLE_CHUNK_NEVER 1
  183782. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183783. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183784. /* Added to version 1.2.0 */
  183785. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183786. #if defined(PNG_MMX_CODE_SUPPORTED)
  183787. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183788. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183789. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183790. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183791. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183792. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183793. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183794. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183795. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183796. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183797. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183798. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183799. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183800. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183801. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183802. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183803. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183804. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183805. | PNG_MMX_READ_FLAGS \
  183806. | PNG_MMX_WRITE_FLAGS )
  183807. #define PNG_SELECT_READ 1
  183808. #define PNG_SELECT_WRITE 2
  183809. #endif /* PNG_MMX_CODE_SUPPORTED */
  183810. #if !defined(PNG_1_0_X)
  183811. /* pngget.c */
  183812. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183813. PNGARG((int flag_select, int *compilerID));
  183814. /* pngget.c */
  183815. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183816. PNGARG((int flag_select));
  183817. /* pngget.c */
  183818. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183819. PNGARG((png_structp png_ptr));
  183820. /* pngget.c */
  183821. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183822. PNGARG((png_structp png_ptr));
  183823. /* pngget.c */
  183824. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183825. PNGARG((png_structp png_ptr));
  183826. /* pngset.c */
  183827. extern PNG_EXPORT(void,png_set_asm_flags)
  183828. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183829. /* pngset.c */
  183830. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183831. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183832. png_uint_32 mmx_rowbytes_threshold));
  183833. #endif /* PNG_1_0_X */
  183834. #if !defined(PNG_1_0_X)
  183835. /* png.c, pnggccrd.c, or pngvcrd.c */
  183836. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183837. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183838. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183839. * messages before passing them to the error or warning handler. */
  183840. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183841. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183842. png_ptr, png_uint_32 strip_mode));
  183843. #endif
  183844. #endif /* PNG_1_0_X */
  183845. /* Added at libpng-1.2.6 */
  183846. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183847. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183848. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183849. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183850. png_ptr));
  183851. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183852. png_ptr));
  183853. #endif
  183854. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183855. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183856. /* With these routines we avoid an integer divide, which will be slower on
  183857. * most machines. However, it does take more operations than the corresponding
  183858. * divide method, so it may be slower on a few RISC systems. There are two
  183859. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183860. *
  183861. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183862. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183863. * standard method.
  183864. *
  183865. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183866. */
  183867. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183868. # define png_composite(composite, fg, alpha, bg) \
  183869. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183870. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183871. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183872. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183873. # define png_composite_16(composite, fg, alpha, bg) \
  183874. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183875. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183876. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183877. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183878. #else /* standard method using integer division */
  183879. # define png_composite(composite, fg, alpha, bg) \
  183880. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183881. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183882. (png_uint_16)127) / 255)
  183883. # define png_composite_16(composite, fg, alpha, bg) \
  183884. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183885. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183886. (png_uint_32)32767) / (png_uint_32)65535L)
  183887. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183888. /* Inline macros to do direct reads of bytes from the input buffer. These
  183889. * require that you are using an architecture that uses PNG byte ordering
  183890. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183891. * in big-endian mode and 680x0 are the only ones that will support this.
  183892. * The x86 line of processors definitely do not. The png_get_int_32()
  183893. * routine also assumes we are using two's complement format for negative
  183894. * values, which is almost certainly true.
  183895. */
  183896. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183897. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183898. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183899. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183900. #else
  183901. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183902. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183903. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183904. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183905. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183906. PNGARG((png_structp png_ptr, png_bytep buf));
  183907. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183908. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183909. */
  183910. extern PNG_EXPORT(void,png_save_uint_32)
  183911. PNGARG((png_bytep buf, png_uint_32 i));
  183912. extern PNG_EXPORT(void,png_save_int_32)
  183913. PNGARG((png_bytep buf, png_int_32 i));
  183914. /* Place a 16-bit number into a buffer in PNG byte order.
  183915. * The parameter is declared unsigned int, not png_uint_16,
  183916. * just to avoid potential problems on pre-ANSI C compilers.
  183917. */
  183918. extern PNG_EXPORT(void,png_save_uint_16)
  183919. PNGARG((png_bytep buf, unsigned int i));
  183920. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183921. /* ************************************************************************* */
  183922. /* These next functions are used internally in the code. They generally
  183923. * shouldn't be used unless you are writing code to add or replace some
  183924. * functionality in libpng. More information about most functions can
  183925. * be found in the files where the functions are located.
  183926. */
  183927. /* Various modes of operation, that are visible to applications because
  183928. * they are used for unknown chunk location.
  183929. */
  183930. #define PNG_HAVE_IHDR 0x01
  183931. #define PNG_HAVE_PLTE 0x02
  183932. #define PNG_HAVE_IDAT 0x04
  183933. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183934. #define PNG_HAVE_IEND 0x10
  183935. #if defined(PNG_INTERNAL)
  183936. /* More modes of operation. Note that after an init, mode is set to
  183937. * zero automatically when the structure is created.
  183938. */
  183939. #define PNG_HAVE_gAMA 0x20
  183940. #define PNG_HAVE_cHRM 0x40
  183941. #define PNG_HAVE_sRGB 0x80
  183942. #define PNG_HAVE_CHUNK_HEADER 0x100
  183943. #define PNG_WROTE_tIME 0x200
  183944. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183945. #define PNG_BACKGROUND_IS_GRAY 0x800
  183946. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183947. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183948. /* flags for the transformations the PNG library does on the image data */
  183949. #define PNG_BGR 0x0001
  183950. #define PNG_INTERLACE 0x0002
  183951. #define PNG_PACK 0x0004
  183952. #define PNG_SHIFT 0x0008
  183953. #define PNG_SWAP_BYTES 0x0010
  183954. #define PNG_INVERT_MONO 0x0020
  183955. #define PNG_DITHER 0x0040
  183956. #define PNG_BACKGROUND 0x0080
  183957. #define PNG_BACKGROUND_EXPAND 0x0100
  183958. /* 0x0200 unused */
  183959. #define PNG_16_TO_8 0x0400
  183960. #define PNG_RGBA 0x0800
  183961. #define PNG_EXPAND 0x1000
  183962. #define PNG_GAMMA 0x2000
  183963. #define PNG_GRAY_TO_RGB 0x4000
  183964. #define PNG_FILLER 0x8000L
  183965. #define PNG_PACKSWAP 0x10000L
  183966. #define PNG_SWAP_ALPHA 0x20000L
  183967. #define PNG_STRIP_ALPHA 0x40000L
  183968. #define PNG_INVERT_ALPHA 0x80000L
  183969. #define PNG_USER_TRANSFORM 0x100000L
  183970. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183971. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183972. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183973. /* 0x800000L Unused */
  183974. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183975. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183976. /* 0x4000000L unused */
  183977. /* 0x8000000L unused */
  183978. /* 0x10000000L unused */
  183979. /* 0x20000000L unused */
  183980. /* 0x40000000L unused */
  183981. /* flags for png_create_struct */
  183982. #define PNG_STRUCT_PNG 0x0001
  183983. #define PNG_STRUCT_INFO 0x0002
  183984. /* Scaling factor for filter heuristic weighting calculations */
  183985. #define PNG_WEIGHT_SHIFT 8
  183986. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183987. #define PNG_COST_SHIFT 3
  183988. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183989. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183990. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183991. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183992. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183993. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183994. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183995. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183996. #define PNG_FLAG_ROW_INIT 0x0040
  183997. #define PNG_FLAG_FILLER_AFTER 0x0080
  183998. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183999. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184000. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184001. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184002. #define PNG_FLAG_FREE_PLTE 0x1000
  184003. #define PNG_FLAG_FREE_TRNS 0x2000
  184004. #define PNG_FLAG_FREE_HIST 0x4000
  184005. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184006. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184007. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184008. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184009. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184010. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184011. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184012. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184013. /* 0x800000L unused */
  184014. /* 0x1000000L unused */
  184015. /* 0x2000000L unused */
  184016. /* 0x4000000L unused */
  184017. /* 0x8000000L unused */
  184018. /* 0x10000000L unused */
  184019. /* 0x20000000L unused */
  184020. /* 0x40000000L unused */
  184021. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184022. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184023. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184024. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184025. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184026. PNG_FLAG_CRC_CRITICAL_MASK)
  184027. /* save typing and make code easier to understand */
  184028. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184029. abs((int)((c1).green) - (int)((c2).green)) + \
  184030. abs((int)((c1).blue) - (int)((c2).blue)))
  184031. /* Added to libpng-1.2.6 JB */
  184032. #define PNG_ROWBYTES(pixel_bits, width) \
  184033. ((pixel_bits) >= 8 ? \
  184034. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184035. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184036. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184037. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184038. "ideal" and "delta" should be constants, normally simple
  184039. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184040. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184041. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184042. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184043. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184044. /* place to hold the signature string for a PNG file. */
  184045. #ifdef PNG_USE_GLOBAL_ARRAYS
  184046. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184047. #else
  184048. #endif
  184049. #endif /* PNG_NO_EXTERN */
  184050. /* Constant strings for known chunk types. If you need to add a chunk,
  184051. * define the name here, and add an invocation of the macro in png.c and
  184052. * wherever it's needed.
  184053. */
  184054. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184055. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184056. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184057. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184058. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184059. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184060. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184061. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184062. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184063. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184064. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184065. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184066. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184067. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184068. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184069. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184070. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184071. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184072. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184073. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184074. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184075. #ifdef PNG_USE_GLOBAL_ARRAYS
  184076. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184077. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184078. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184079. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184080. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184081. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184082. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184083. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184084. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184085. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184086. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184087. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184088. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184089. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184090. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184091. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184092. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184093. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184094. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184095. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184096. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184097. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184098. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184099. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184100. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184101. */
  184102. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184103. #undef png_read_init
  184104. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184105. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184106. #endif
  184107. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184108. png_const_charp user_png_ver, png_size_t png_struct_size));
  184109. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184110. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184111. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184112. png_info_size));
  184113. #endif
  184114. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184115. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184116. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184117. */
  184118. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184119. #undef png_write_init
  184120. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184121. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184122. #endif
  184123. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184124. png_const_charp user_png_ver, png_size_t png_struct_size));
  184125. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184126. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184127. png_info_size));
  184128. /* Allocate memory for an internal libpng struct */
  184129. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184130. /* Free memory from internal libpng struct */
  184131. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184132. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184133. malloc_fn, png_voidp mem_ptr));
  184134. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184135. png_free_ptr free_fn, png_voidp mem_ptr));
  184136. /* Free any memory that info_ptr points to and reset struct. */
  184137. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184138. png_infop info_ptr));
  184139. #ifndef PNG_1_0_X
  184140. /* Function to allocate memory for zlib. */
  184141. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184142. /* Function to free memory for zlib */
  184143. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184144. #ifdef PNG_SIZE_T
  184145. /* Function to convert a sizeof an item to png_sizeof item */
  184146. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184147. #endif
  184148. /* Next four functions are used internally as callbacks. PNGAPI is required
  184149. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184150. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184151. png_bytep data, png_size_t length));
  184152. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184153. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184154. png_bytep buffer, png_size_t length));
  184155. #endif
  184156. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184157. png_bytep data, png_size_t length));
  184158. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184159. #if !defined(PNG_NO_STDIO)
  184160. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184161. #endif
  184162. #endif
  184163. #else /* PNG_1_0_X */
  184164. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184165. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184166. png_bytep buffer, png_size_t length));
  184167. #endif
  184168. #endif /* PNG_1_0_X */
  184169. /* Reset the CRC variable */
  184170. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184171. /* Write the "data" buffer to whatever output you are using. */
  184172. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184173. png_size_t length));
  184174. /* Read data from whatever input you are using into the "data" buffer */
  184175. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184176. png_size_t length));
  184177. /* Read bytes into buf, and update png_ptr->crc */
  184178. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184179. png_size_t length));
  184180. /* Decompress data in a chunk that uses compression */
  184181. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184182. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184183. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184184. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184185. png_size_t prefix_length, png_size_t *data_length));
  184186. #endif
  184187. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184188. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184189. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184190. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184191. /* Calculate the CRC over a section of data. Note that we are only
  184192. * passing a maximum of 64K on systems that have this as a memory limit,
  184193. * since this is the maximum buffer size we can specify.
  184194. */
  184195. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184196. png_size_t length));
  184197. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184198. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184199. #endif
  184200. /* simple function to write the signature */
  184201. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184202. /* write various chunks */
  184203. /* Write the IHDR chunk, and update the png_struct with the necessary
  184204. * information.
  184205. */
  184206. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184207. png_uint_32 height,
  184208. int bit_depth, int color_type, int compression_method, int filter_method,
  184209. int interlace_method));
  184210. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184211. png_uint_32 num_pal));
  184212. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184213. png_size_t length));
  184214. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184215. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184216. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184217. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184218. #endif
  184219. #ifdef PNG_FIXED_POINT_SUPPORTED
  184220. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184221. file_gamma));
  184222. #endif
  184223. #endif
  184224. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184225. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184226. int color_type));
  184227. #endif
  184228. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184229. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184230. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184231. double white_x, double white_y,
  184232. double red_x, double red_y, double green_x, double green_y,
  184233. double blue_x, double blue_y));
  184234. #endif
  184235. #ifdef PNG_FIXED_POINT_SUPPORTED
  184236. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184237. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184238. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184239. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184240. png_fixed_point int_blue_y));
  184241. #endif
  184242. #endif
  184243. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184244. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184245. int intent));
  184246. #endif
  184247. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184248. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184249. png_charp name, int compression_type,
  184250. png_charp profile, int proflen));
  184251. /* Note to maintainer: profile should be png_bytep */
  184252. #endif
  184253. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184254. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184255. png_sPLT_tp palette));
  184256. #endif
  184257. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184258. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184259. png_color_16p values, int number, int color_type));
  184260. #endif
  184261. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184262. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184263. png_color_16p values, int color_type));
  184264. #endif
  184265. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184266. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184267. int num_hist));
  184268. #endif
  184269. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184270. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184271. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184272. png_charp key, png_charpp new_key));
  184273. #endif
  184274. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184275. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184276. png_charp text, png_size_t text_len));
  184277. #endif
  184278. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184279. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184280. png_charp text, png_size_t text_len, int compression));
  184281. #endif
  184282. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184283. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184284. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184285. png_charp text));
  184286. #endif
  184287. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184288. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184289. png_infop info_ptr, png_textp text_ptr, int num_text));
  184290. #endif
  184291. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184292. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184293. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184294. #endif
  184295. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184296. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184297. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184298. png_charp units, png_charpp params));
  184299. #endif
  184300. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184301. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184302. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184303. int unit_type));
  184304. #endif
  184305. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184306. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184307. png_timep mod_time));
  184308. #endif
  184309. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184310. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184311. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184312. int unit, double width, double height));
  184313. #else
  184314. #ifdef PNG_FIXED_POINT_SUPPORTED
  184315. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184316. int unit, png_charp width, png_charp height));
  184317. #endif
  184318. #endif
  184319. #endif
  184320. /* Called when finished processing a row of data */
  184321. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184322. /* Internal use only. Called before first row of data */
  184323. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184324. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184325. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184326. #endif
  184327. /* combine a row of data, dealing with alpha, etc. if requested */
  184328. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184329. int mask));
  184330. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184331. /* expand an interlaced row */
  184332. /* OLD pre-1.0.9 interface:
  184333. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184334. png_bytep row, int pass, png_uint_32 transformations));
  184335. */
  184336. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184337. #endif
  184338. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184339. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184340. /* grab pixels out of a row for an interlaced pass */
  184341. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184342. png_bytep row, int pass));
  184343. #endif
  184344. /* unfilter a row */
  184345. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184346. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184347. /* Choose the best filter to use and filter the row data */
  184348. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184349. png_row_infop row_info));
  184350. /* Write out the filtered row. */
  184351. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184352. png_bytep filtered_row));
  184353. /* finish a row while reading, dealing with interlacing passes, etc. */
  184354. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184355. /* initialize the row buffers, etc. */
  184356. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184357. /* optional call to update the users info structure */
  184358. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184359. png_infop info_ptr));
  184360. /* these are the functions that do the transformations */
  184361. #if defined(PNG_READ_FILLER_SUPPORTED)
  184362. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184363. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184364. #endif
  184365. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184366. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184367. png_bytep row));
  184368. #endif
  184369. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184370. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184371. png_bytep row));
  184372. #endif
  184373. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184374. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184375. png_bytep row));
  184376. #endif
  184377. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184378. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184379. png_bytep row));
  184380. #endif
  184381. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184382. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184383. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184384. png_bytep row, png_uint_32 flags));
  184385. #endif
  184386. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184387. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184388. #endif
  184389. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184390. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184391. #endif
  184392. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184393. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184394. row_info, png_bytep row));
  184395. #endif
  184396. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184397. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184398. png_bytep row));
  184399. #endif
  184400. #if defined(PNG_READ_PACK_SUPPORTED)
  184401. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184402. #endif
  184403. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184404. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184405. png_color_8p sig_bits));
  184406. #endif
  184407. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184408. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184409. #endif
  184410. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184411. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184412. #endif
  184413. #if defined(PNG_READ_DITHER_SUPPORTED)
  184414. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184415. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184416. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184417. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184418. png_colorp palette, int num_palette));
  184419. # endif
  184420. #endif
  184421. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184422. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184423. #endif
  184424. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184425. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184426. png_bytep row, png_uint_32 bit_depth));
  184427. #endif
  184428. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184429. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184430. png_color_8p bit_depth));
  184431. #endif
  184432. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184433. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184434. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184435. png_color_16p trans_values, png_color_16p background,
  184436. png_color_16p background_1,
  184437. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184438. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184439. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184440. #else
  184441. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184442. png_color_16p trans_values, png_color_16p background));
  184443. #endif
  184444. #endif
  184445. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184446. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184447. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184448. int gamma_shift));
  184449. #endif
  184450. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184451. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184452. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184453. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184454. png_bytep row, png_color_16p trans_value));
  184455. #endif
  184456. /* The following decodes the appropriate chunks, and does error correction,
  184457. * then calls the appropriate callback for the chunk if it is valid.
  184458. */
  184459. /* decode the IHDR chunk */
  184460. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184461. png_uint_32 length));
  184462. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184463. png_uint_32 length));
  184464. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184465. png_uint_32 length));
  184466. #if defined(PNG_READ_bKGD_SUPPORTED)
  184467. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184468. png_uint_32 length));
  184469. #endif
  184470. #if defined(PNG_READ_cHRM_SUPPORTED)
  184471. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184472. png_uint_32 length));
  184473. #endif
  184474. #if defined(PNG_READ_gAMA_SUPPORTED)
  184475. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184476. png_uint_32 length));
  184477. #endif
  184478. #if defined(PNG_READ_hIST_SUPPORTED)
  184479. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184480. png_uint_32 length));
  184481. #endif
  184482. #if defined(PNG_READ_iCCP_SUPPORTED)
  184483. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184484. png_uint_32 length));
  184485. #endif /* PNG_READ_iCCP_SUPPORTED */
  184486. #if defined(PNG_READ_iTXt_SUPPORTED)
  184487. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184488. png_uint_32 length));
  184489. #endif
  184490. #if defined(PNG_READ_oFFs_SUPPORTED)
  184491. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184492. png_uint_32 length));
  184493. #endif
  184494. #if defined(PNG_READ_pCAL_SUPPORTED)
  184495. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184496. png_uint_32 length));
  184497. #endif
  184498. #if defined(PNG_READ_pHYs_SUPPORTED)
  184499. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184500. png_uint_32 length));
  184501. #endif
  184502. #if defined(PNG_READ_sBIT_SUPPORTED)
  184503. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184504. png_uint_32 length));
  184505. #endif
  184506. #if defined(PNG_READ_sCAL_SUPPORTED)
  184507. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184508. png_uint_32 length));
  184509. #endif
  184510. #if defined(PNG_READ_sPLT_SUPPORTED)
  184511. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184512. png_uint_32 length));
  184513. #endif /* PNG_READ_sPLT_SUPPORTED */
  184514. #if defined(PNG_READ_sRGB_SUPPORTED)
  184515. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184516. png_uint_32 length));
  184517. #endif
  184518. #if defined(PNG_READ_tEXt_SUPPORTED)
  184519. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184520. png_uint_32 length));
  184521. #endif
  184522. #if defined(PNG_READ_tIME_SUPPORTED)
  184523. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184524. png_uint_32 length));
  184525. #endif
  184526. #if defined(PNG_READ_tRNS_SUPPORTED)
  184527. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184528. png_uint_32 length));
  184529. #endif
  184530. #if defined(PNG_READ_zTXt_SUPPORTED)
  184531. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184532. png_uint_32 length));
  184533. #endif
  184534. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184535. png_infop info_ptr, png_uint_32 length));
  184536. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184537. png_bytep chunk_name));
  184538. /* handle the transformations for reading and writing */
  184539. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184540. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184541. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184542. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184543. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184544. png_infop info_ptr));
  184545. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184546. png_infop info_ptr));
  184547. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184548. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184549. png_uint_32 length));
  184550. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184551. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184552. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184553. png_bytep buffer, png_size_t buffer_length));
  184554. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184555. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184556. png_bytep buffer, png_size_t buffer_length));
  184557. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184558. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184559. png_infop info_ptr, png_uint_32 length));
  184560. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184561. png_infop info_ptr));
  184562. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184563. png_infop info_ptr));
  184564. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184565. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184566. png_infop info_ptr));
  184567. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184568. png_infop info_ptr));
  184569. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184570. #if defined(PNG_READ_tEXt_SUPPORTED)
  184571. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184572. png_infop info_ptr, png_uint_32 length));
  184573. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184574. png_infop info_ptr));
  184575. #endif
  184576. #if defined(PNG_READ_zTXt_SUPPORTED)
  184577. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184578. png_infop info_ptr, png_uint_32 length));
  184579. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184580. png_infop info_ptr));
  184581. #endif
  184582. #if defined(PNG_READ_iTXt_SUPPORTED)
  184583. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184584. png_infop info_ptr, png_uint_32 length));
  184585. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184586. png_infop info_ptr));
  184587. #endif
  184588. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184589. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184590. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184591. png_bytep row));
  184592. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184593. png_bytep row));
  184594. #endif
  184595. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184596. #if defined(PNG_MMX_CODE_SUPPORTED)
  184597. /* png.c */ /* PRIVATE */
  184598. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184599. #endif
  184600. #endif
  184601. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184602. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184603. png_infop info_ptr));
  184604. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184605. png_infop info_ptr));
  184606. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184607. png_infop info_ptr));
  184608. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184609. png_infop info_ptr));
  184610. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184611. png_infop info_ptr));
  184612. #if defined(PNG_pHYs_SUPPORTED)
  184613. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184614. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184615. #endif /* PNG_pHYs_SUPPORTED */
  184616. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184617. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184618. #endif /* PNG_INTERNAL */
  184619. #ifdef __cplusplus
  184620. //}
  184621. #endif
  184622. #endif /* PNG_VERSION_INFO_ONLY */
  184623. /* do not put anything past this line */
  184624. #endif /* PNG_H */
  184625. /*** End of inlined file: png.h ***/
  184626. #define PNG_NO_EXTERN
  184627. /*** Start of inlined file: png.c ***/
  184628. /* png.c - location for general purpose libpng functions
  184629. *
  184630. * Last changed in libpng 1.2.21 [October 4, 2007]
  184631. * For conditions of distribution and use, see copyright notice in png.h
  184632. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184633. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184634. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184635. */
  184636. #define PNG_INTERNAL
  184637. #define PNG_NO_EXTERN
  184638. /* Generate a compiler error if there is an old png.h in the search path. */
  184639. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184640. /* Version information for C files. This had better match the version
  184641. * string defined in png.h. */
  184642. #ifdef PNG_USE_GLOBAL_ARRAYS
  184643. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184644. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184645. #ifdef PNG_READ_SUPPORTED
  184646. /* png_sig was changed to a function in version 1.0.5c */
  184647. /* Place to hold the signature string for a PNG file. */
  184648. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184649. #endif /* PNG_READ_SUPPORTED */
  184650. /* Invoke global declarations for constant strings for known chunk types */
  184651. PNG_IHDR;
  184652. PNG_IDAT;
  184653. PNG_IEND;
  184654. PNG_PLTE;
  184655. PNG_bKGD;
  184656. PNG_cHRM;
  184657. PNG_gAMA;
  184658. PNG_hIST;
  184659. PNG_iCCP;
  184660. PNG_iTXt;
  184661. PNG_oFFs;
  184662. PNG_pCAL;
  184663. PNG_sCAL;
  184664. PNG_pHYs;
  184665. PNG_sBIT;
  184666. PNG_sPLT;
  184667. PNG_sRGB;
  184668. PNG_tEXt;
  184669. PNG_tIME;
  184670. PNG_tRNS;
  184671. PNG_zTXt;
  184672. #ifdef PNG_READ_SUPPORTED
  184673. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184674. /* start of interlace block */
  184675. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184676. /* offset to next interlace block */
  184677. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184678. /* start of interlace block in the y direction */
  184679. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184680. /* offset to next interlace block in the y direction */
  184681. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184682. /* Height of interlace block. This is not currently used - if you need
  184683. * it, uncomment it here and in png.h
  184684. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184685. */
  184686. /* Mask to determine which pixels are valid in a pass */
  184687. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184688. /* Mask to determine which pixels to overwrite while displaying */
  184689. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184690. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184691. #endif /* PNG_READ_SUPPORTED */
  184692. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184693. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184694. * of the PNG file signature. If the PNG data is embedded into another
  184695. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184696. * or write any of the magic bytes before it starts on the IHDR.
  184697. */
  184698. #ifdef PNG_READ_SUPPORTED
  184699. void PNGAPI
  184700. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184701. {
  184702. if(png_ptr == NULL) return;
  184703. png_debug(1, "in png_set_sig_bytes\n");
  184704. if (num_bytes > 8)
  184705. png_error(png_ptr, "Too many bytes for PNG signature.");
  184706. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184707. }
  184708. /* Checks whether the supplied bytes match the PNG signature. We allow
  184709. * checking less than the full 8-byte signature so that those apps that
  184710. * already read the first few bytes of a file to determine the file type
  184711. * can simply check the remaining bytes for extra assurance. Returns
  184712. * an integer less than, equal to, or greater than zero if sig is found,
  184713. * respectively, to be less than, to match, or be greater than the correct
  184714. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184715. */
  184716. int PNGAPI
  184717. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184718. {
  184719. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184720. if (num_to_check > 8)
  184721. num_to_check = 8;
  184722. else if (num_to_check < 1)
  184723. return (-1);
  184724. if (start > 7)
  184725. return (-1);
  184726. if (start + num_to_check > 8)
  184727. num_to_check = 8 - start;
  184728. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184729. }
  184730. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184731. /* (Obsolete) function to check signature bytes. It does not allow one
  184732. * to check a partial signature. This function might be removed in the
  184733. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184734. */
  184735. int PNGAPI
  184736. png_check_sig(png_bytep sig, int num)
  184737. {
  184738. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184739. }
  184740. #endif
  184741. #endif /* PNG_READ_SUPPORTED */
  184742. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184743. /* Function to allocate memory for zlib and clear it to 0. */
  184744. #ifdef PNG_1_0_X
  184745. voidpf PNGAPI
  184746. #else
  184747. voidpf /* private */
  184748. #endif
  184749. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184750. {
  184751. png_voidp ptr;
  184752. png_structp p=(png_structp)png_ptr;
  184753. png_uint_32 save_flags=p->flags;
  184754. png_uint_32 num_bytes;
  184755. if(png_ptr == NULL) return (NULL);
  184756. if (items > PNG_UINT_32_MAX/size)
  184757. {
  184758. png_warning (p, "Potential overflow in png_zalloc()");
  184759. return (NULL);
  184760. }
  184761. num_bytes = (png_uint_32)items * size;
  184762. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184763. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184764. p->flags=save_flags;
  184765. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184766. if (ptr == NULL)
  184767. return ((voidpf)ptr);
  184768. if (num_bytes > (png_uint_32)0x8000L)
  184769. {
  184770. png_memset(ptr, 0, (png_size_t)0x8000L);
  184771. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184772. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184773. }
  184774. else
  184775. {
  184776. png_memset(ptr, 0, (png_size_t)num_bytes);
  184777. }
  184778. #endif
  184779. return ((voidpf)ptr);
  184780. }
  184781. /* function to free memory for zlib */
  184782. #ifdef PNG_1_0_X
  184783. void PNGAPI
  184784. #else
  184785. void /* private */
  184786. #endif
  184787. png_zfree(voidpf png_ptr, voidpf ptr)
  184788. {
  184789. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184790. }
  184791. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184792. * in case CRC is > 32 bits to leave the top bits 0.
  184793. */
  184794. void /* PRIVATE */
  184795. png_reset_crc(png_structp png_ptr)
  184796. {
  184797. png_ptr->crc = crc32(0, Z_NULL, 0);
  184798. }
  184799. /* Calculate the CRC over a section of data. We can only pass as
  184800. * much data to this routine as the largest single buffer size. We
  184801. * also check that this data will actually be used before going to the
  184802. * trouble of calculating it.
  184803. */
  184804. void /* PRIVATE */
  184805. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184806. {
  184807. int need_crc = 1;
  184808. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184809. {
  184810. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184811. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184812. need_crc = 0;
  184813. }
  184814. else /* critical */
  184815. {
  184816. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184817. need_crc = 0;
  184818. }
  184819. if (need_crc)
  184820. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184821. }
  184822. /* Allocate the memory for an info_struct for the application. We don't
  184823. * really need the png_ptr, but it could potentially be useful in the
  184824. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184825. * and png_info_init() so that applications that want to use a shared
  184826. * libpng don't have to be recompiled if png_info changes size.
  184827. */
  184828. png_infop PNGAPI
  184829. png_create_info_struct(png_structp png_ptr)
  184830. {
  184831. png_infop info_ptr;
  184832. png_debug(1, "in png_create_info_struct\n");
  184833. if(png_ptr == NULL) return (NULL);
  184834. #ifdef PNG_USER_MEM_SUPPORTED
  184835. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184836. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184837. #else
  184838. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184839. #endif
  184840. if (info_ptr != NULL)
  184841. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184842. return (info_ptr);
  184843. }
  184844. /* This function frees the memory associated with a single info struct.
  184845. * Normally, one would use either png_destroy_read_struct() or
  184846. * png_destroy_write_struct() to free an info struct, but this may be
  184847. * useful for some applications.
  184848. */
  184849. void PNGAPI
  184850. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184851. {
  184852. png_infop info_ptr = NULL;
  184853. if(png_ptr == NULL) return;
  184854. png_debug(1, "in png_destroy_info_struct\n");
  184855. if (info_ptr_ptr != NULL)
  184856. info_ptr = *info_ptr_ptr;
  184857. if (info_ptr != NULL)
  184858. {
  184859. png_info_destroy(png_ptr, info_ptr);
  184860. #ifdef PNG_USER_MEM_SUPPORTED
  184861. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184862. png_ptr->mem_ptr);
  184863. #else
  184864. png_destroy_struct((png_voidp)info_ptr);
  184865. #endif
  184866. *info_ptr_ptr = NULL;
  184867. }
  184868. }
  184869. /* Initialize the info structure. This is now an internal function (0.89)
  184870. * and applications using it are urged to use png_create_info_struct()
  184871. * instead.
  184872. */
  184873. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184874. #undef png_info_init
  184875. void PNGAPI
  184876. png_info_init(png_infop info_ptr)
  184877. {
  184878. /* We only come here via pre-1.0.12-compiled applications */
  184879. png_info_init_3(&info_ptr, 0);
  184880. }
  184881. #endif
  184882. void PNGAPI
  184883. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184884. {
  184885. png_infop info_ptr = *ptr_ptr;
  184886. if(info_ptr == NULL) return;
  184887. png_debug(1, "in png_info_init_3\n");
  184888. if(png_sizeof(png_info) > png_info_struct_size)
  184889. {
  184890. png_destroy_struct(info_ptr);
  184891. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184892. *ptr_ptr = info_ptr;
  184893. }
  184894. /* set everything to 0 */
  184895. png_memset(info_ptr, 0, png_sizeof (png_info));
  184896. }
  184897. #ifdef PNG_FREE_ME_SUPPORTED
  184898. void PNGAPI
  184899. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184900. int freer, png_uint_32 mask)
  184901. {
  184902. png_debug(1, "in png_data_freer\n");
  184903. if (png_ptr == NULL || info_ptr == NULL)
  184904. return;
  184905. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184906. info_ptr->free_me |= mask;
  184907. else if(freer == PNG_USER_WILL_FREE_DATA)
  184908. info_ptr->free_me &= ~mask;
  184909. else
  184910. png_warning(png_ptr,
  184911. "Unknown freer parameter in png_data_freer.");
  184912. }
  184913. #endif
  184914. void PNGAPI
  184915. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184916. int num)
  184917. {
  184918. png_debug(1, "in png_free_data\n");
  184919. if (png_ptr == NULL || info_ptr == NULL)
  184920. return;
  184921. #if defined(PNG_TEXT_SUPPORTED)
  184922. /* free text item num or (if num == -1) all text items */
  184923. #ifdef PNG_FREE_ME_SUPPORTED
  184924. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184925. #else
  184926. if (mask & PNG_FREE_TEXT)
  184927. #endif
  184928. {
  184929. if (num != -1)
  184930. {
  184931. if (info_ptr->text && info_ptr->text[num].key)
  184932. {
  184933. png_free(png_ptr, info_ptr->text[num].key);
  184934. info_ptr->text[num].key = NULL;
  184935. }
  184936. }
  184937. else
  184938. {
  184939. int i;
  184940. for (i = 0; i < info_ptr->num_text; i++)
  184941. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184942. png_free(png_ptr, info_ptr->text);
  184943. info_ptr->text = NULL;
  184944. info_ptr->num_text=0;
  184945. }
  184946. }
  184947. #endif
  184948. #if defined(PNG_tRNS_SUPPORTED)
  184949. /* free any tRNS entry */
  184950. #ifdef PNG_FREE_ME_SUPPORTED
  184951. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184952. #else
  184953. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184954. #endif
  184955. {
  184956. png_free(png_ptr, info_ptr->trans);
  184957. info_ptr->valid &= ~PNG_INFO_tRNS;
  184958. #ifndef PNG_FREE_ME_SUPPORTED
  184959. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184960. #endif
  184961. info_ptr->trans = NULL;
  184962. }
  184963. #endif
  184964. #if defined(PNG_sCAL_SUPPORTED)
  184965. /* free any sCAL entry */
  184966. #ifdef PNG_FREE_ME_SUPPORTED
  184967. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184968. #else
  184969. if (mask & PNG_FREE_SCAL)
  184970. #endif
  184971. {
  184972. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184973. png_free(png_ptr, info_ptr->scal_s_width);
  184974. png_free(png_ptr, info_ptr->scal_s_height);
  184975. info_ptr->scal_s_width = NULL;
  184976. info_ptr->scal_s_height = NULL;
  184977. #endif
  184978. info_ptr->valid &= ~PNG_INFO_sCAL;
  184979. }
  184980. #endif
  184981. #if defined(PNG_pCAL_SUPPORTED)
  184982. /* free any pCAL entry */
  184983. #ifdef PNG_FREE_ME_SUPPORTED
  184984. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184985. #else
  184986. if (mask & PNG_FREE_PCAL)
  184987. #endif
  184988. {
  184989. png_free(png_ptr, info_ptr->pcal_purpose);
  184990. png_free(png_ptr, info_ptr->pcal_units);
  184991. info_ptr->pcal_purpose = NULL;
  184992. info_ptr->pcal_units = NULL;
  184993. if (info_ptr->pcal_params != NULL)
  184994. {
  184995. int i;
  184996. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184997. {
  184998. png_free(png_ptr, info_ptr->pcal_params[i]);
  184999. info_ptr->pcal_params[i]=NULL;
  185000. }
  185001. png_free(png_ptr, info_ptr->pcal_params);
  185002. info_ptr->pcal_params = NULL;
  185003. }
  185004. info_ptr->valid &= ~PNG_INFO_pCAL;
  185005. }
  185006. #endif
  185007. #if defined(PNG_iCCP_SUPPORTED)
  185008. /* free any iCCP entry */
  185009. #ifdef PNG_FREE_ME_SUPPORTED
  185010. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185011. #else
  185012. if (mask & PNG_FREE_ICCP)
  185013. #endif
  185014. {
  185015. png_free(png_ptr, info_ptr->iccp_name);
  185016. png_free(png_ptr, info_ptr->iccp_profile);
  185017. info_ptr->iccp_name = NULL;
  185018. info_ptr->iccp_profile = NULL;
  185019. info_ptr->valid &= ~PNG_INFO_iCCP;
  185020. }
  185021. #endif
  185022. #if defined(PNG_sPLT_SUPPORTED)
  185023. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185024. #ifdef PNG_FREE_ME_SUPPORTED
  185025. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185026. #else
  185027. if (mask & PNG_FREE_SPLT)
  185028. #endif
  185029. {
  185030. if (num != -1)
  185031. {
  185032. if(info_ptr->splt_palettes)
  185033. {
  185034. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185035. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185036. info_ptr->splt_palettes[num].name = NULL;
  185037. info_ptr->splt_palettes[num].entries = NULL;
  185038. }
  185039. }
  185040. else
  185041. {
  185042. if(info_ptr->splt_palettes_num)
  185043. {
  185044. int i;
  185045. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185046. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185047. png_free(png_ptr, info_ptr->splt_palettes);
  185048. info_ptr->splt_palettes = NULL;
  185049. info_ptr->splt_palettes_num = 0;
  185050. }
  185051. info_ptr->valid &= ~PNG_INFO_sPLT;
  185052. }
  185053. }
  185054. #endif
  185055. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185056. if(png_ptr->unknown_chunk.data)
  185057. {
  185058. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185059. png_ptr->unknown_chunk.data = NULL;
  185060. }
  185061. #ifdef PNG_FREE_ME_SUPPORTED
  185062. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185063. #else
  185064. if (mask & PNG_FREE_UNKN)
  185065. #endif
  185066. {
  185067. if (num != -1)
  185068. {
  185069. if(info_ptr->unknown_chunks)
  185070. {
  185071. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185072. info_ptr->unknown_chunks[num].data = NULL;
  185073. }
  185074. }
  185075. else
  185076. {
  185077. int i;
  185078. if(info_ptr->unknown_chunks_num)
  185079. {
  185080. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185081. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185082. png_free(png_ptr, info_ptr->unknown_chunks);
  185083. info_ptr->unknown_chunks = NULL;
  185084. info_ptr->unknown_chunks_num = 0;
  185085. }
  185086. }
  185087. }
  185088. #endif
  185089. #if defined(PNG_hIST_SUPPORTED)
  185090. /* free any hIST entry */
  185091. #ifdef PNG_FREE_ME_SUPPORTED
  185092. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185093. #else
  185094. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185095. #endif
  185096. {
  185097. png_free(png_ptr, info_ptr->hist);
  185098. info_ptr->hist = NULL;
  185099. info_ptr->valid &= ~PNG_INFO_hIST;
  185100. #ifndef PNG_FREE_ME_SUPPORTED
  185101. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185102. #endif
  185103. }
  185104. #endif
  185105. /* free any PLTE entry that was internally allocated */
  185106. #ifdef PNG_FREE_ME_SUPPORTED
  185107. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185108. #else
  185109. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185110. #endif
  185111. {
  185112. png_zfree(png_ptr, info_ptr->palette);
  185113. info_ptr->palette = NULL;
  185114. info_ptr->valid &= ~PNG_INFO_PLTE;
  185115. #ifndef PNG_FREE_ME_SUPPORTED
  185116. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185117. #endif
  185118. info_ptr->num_palette = 0;
  185119. }
  185120. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185121. /* free any image bits attached to the info structure */
  185122. #ifdef PNG_FREE_ME_SUPPORTED
  185123. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185124. #else
  185125. if (mask & PNG_FREE_ROWS)
  185126. #endif
  185127. {
  185128. if(info_ptr->row_pointers)
  185129. {
  185130. int row;
  185131. for (row = 0; row < (int)info_ptr->height; row++)
  185132. {
  185133. png_free(png_ptr, info_ptr->row_pointers[row]);
  185134. info_ptr->row_pointers[row]=NULL;
  185135. }
  185136. png_free(png_ptr, info_ptr->row_pointers);
  185137. info_ptr->row_pointers=NULL;
  185138. }
  185139. info_ptr->valid &= ~PNG_INFO_IDAT;
  185140. }
  185141. #endif
  185142. #ifdef PNG_FREE_ME_SUPPORTED
  185143. if(num == -1)
  185144. info_ptr->free_me &= ~mask;
  185145. else
  185146. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185147. #endif
  185148. }
  185149. /* This is an internal routine to free any memory that the info struct is
  185150. * pointing to before re-using it or freeing the struct itself. Recall
  185151. * that png_free() checks for NULL pointers for us.
  185152. */
  185153. void /* PRIVATE */
  185154. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185155. {
  185156. png_debug(1, "in png_info_destroy\n");
  185157. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185158. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185159. if (png_ptr->num_chunk_list)
  185160. {
  185161. png_free(png_ptr, png_ptr->chunk_list);
  185162. png_ptr->chunk_list=NULL;
  185163. png_ptr->num_chunk_list=0;
  185164. }
  185165. #endif
  185166. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185167. }
  185168. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185169. /* This function returns a pointer to the io_ptr associated with the user
  185170. * functions. The application should free any memory associated with this
  185171. * pointer before png_write_destroy() or png_read_destroy() are called.
  185172. */
  185173. png_voidp PNGAPI
  185174. png_get_io_ptr(png_structp png_ptr)
  185175. {
  185176. if(png_ptr == NULL) return (NULL);
  185177. return (png_ptr->io_ptr);
  185178. }
  185179. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185180. #if !defined(PNG_NO_STDIO)
  185181. /* Initialize the default input/output functions for the PNG file. If you
  185182. * use your own read or write routines, you can call either png_set_read_fn()
  185183. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185184. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185185. * necessarily available.
  185186. */
  185187. void PNGAPI
  185188. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185189. {
  185190. png_debug(1, "in png_init_io\n");
  185191. if(png_ptr == NULL) return;
  185192. png_ptr->io_ptr = (png_voidp)fp;
  185193. }
  185194. #endif
  185195. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185196. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185197. * a "Creation Time" or other text-based time string.
  185198. */
  185199. png_charp PNGAPI
  185200. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185201. {
  185202. static PNG_CONST char short_months[12][4] =
  185203. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185204. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185205. if(png_ptr == NULL) return (NULL);
  185206. if (png_ptr->time_buffer == NULL)
  185207. {
  185208. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185209. png_sizeof(char)));
  185210. }
  185211. #if defined(_WIN32_WCE)
  185212. {
  185213. wchar_t time_buf[29];
  185214. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185215. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185216. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185217. ptime->second % 61);
  185218. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185219. NULL, NULL);
  185220. }
  185221. #else
  185222. #ifdef USE_FAR_KEYWORD
  185223. {
  185224. char near_time_buf[29];
  185225. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185226. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185227. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185228. ptime->second % 61);
  185229. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185230. 29*png_sizeof(char));
  185231. }
  185232. #else
  185233. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185234. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185235. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185236. ptime->second % 61);
  185237. #endif
  185238. #endif /* _WIN32_WCE */
  185239. return ((png_charp)png_ptr->time_buffer);
  185240. }
  185241. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185242. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185243. png_charp PNGAPI
  185244. png_get_copyright(png_structp png_ptr)
  185245. {
  185246. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185247. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185248. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185249. Copyright (c) 1996-1997 Andreas Dilger\n\
  185250. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185251. }
  185252. /* The following return the library version as a short string in the
  185253. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185254. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185255. * is defined in png.h.
  185256. * Note: now there is no difference between png_get_libpng_ver() and
  185257. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185258. * it is guaranteed that png.c uses the correct version of png.h.
  185259. */
  185260. png_charp PNGAPI
  185261. png_get_libpng_ver(png_structp png_ptr)
  185262. {
  185263. /* Version of *.c files used when building libpng */
  185264. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185265. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185266. }
  185267. png_charp PNGAPI
  185268. png_get_header_ver(png_structp png_ptr)
  185269. {
  185270. /* Version of *.h files used when building libpng */
  185271. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185272. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185273. }
  185274. png_charp PNGAPI
  185275. png_get_header_version(png_structp png_ptr)
  185276. {
  185277. /* Returns longer string containing both version and date */
  185278. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185279. return ((png_charp) PNG_HEADER_VERSION_STRING
  185280. #ifndef PNG_READ_SUPPORTED
  185281. " (NO READ SUPPORT)"
  185282. #endif
  185283. "\n");
  185284. }
  185285. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185286. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185287. int PNGAPI
  185288. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185289. {
  185290. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185291. int i;
  185292. png_bytep p;
  185293. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185294. return 0;
  185295. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185296. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185297. if (!png_memcmp(chunk_name, p, 4))
  185298. return ((int)*(p+4));
  185299. return 0;
  185300. }
  185301. #endif
  185302. /* This function, added to libpng-1.0.6g, is untested. */
  185303. int PNGAPI
  185304. png_reset_zstream(png_structp png_ptr)
  185305. {
  185306. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185307. return (inflateReset(&png_ptr->zstream));
  185308. }
  185309. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185310. /* This function was added to libpng-1.0.7 */
  185311. png_uint_32 PNGAPI
  185312. png_access_version_number(void)
  185313. {
  185314. /* Version of *.c files used when building libpng */
  185315. return((png_uint_32) PNG_LIBPNG_VER);
  185316. }
  185317. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185318. #if !defined(PNG_1_0_X)
  185319. /* this function was added to libpng 1.2.0 */
  185320. int PNGAPI
  185321. png_mmx_support(void)
  185322. {
  185323. /* obsolete, to be removed from libpng-1.4.0 */
  185324. return -1;
  185325. }
  185326. #endif /* PNG_1_0_X */
  185327. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185328. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185329. #ifdef PNG_SIZE_T
  185330. /* Added at libpng version 1.2.6 */
  185331. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185332. png_size_t PNGAPI
  185333. png_convert_size(size_t size)
  185334. {
  185335. if (size > (png_size_t)-1)
  185336. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185337. return ((png_size_t)size);
  185338. }
  185339. #endif /* PNG_SIZE_T */
  185340. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185341. /*** End of inlined file: png.c ***/
  185342. /*** Start of inlined file: pngerror.c ***/
  185343. /* pngerror.c - stub functions for i/o and memory allocation
  185344. *
  185345. * Last changed in libpng 1.2.20 October 4, 2007
  185346. * For conditions of distribution and use, see copyright notice in png.h
  185347. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185348. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185349. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185350. *
  185351. * This file provides a location for all error handling. Users who
  185352. * need special error handling are expected to write replacement functions
  185353. * and use png_set_error_fn() to use those functions. See the instructions
  185354. * at each function.
  185355. */
  185356. #define PNG_INTERNAL
  185357. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185358. static void /* PRIVATE */
  185359. png_default_error PNGARG((png_structp png_ptr,
  185360. png_const_charp error_message));
  185361. #ifndef PNG_NO_WARNINGS
  185362. static void /* PRIVATE */
  185363. png_default_warning PNGARG((png_structp png_ptr,
  185364. png_const_charp warning_message));
  185365. #endif /* PNG_NO_WARNINGS */
  185366. /* This function is called whenever there is a fatal error. This function
  185367. * should not be changed. If there is a need to handle errors differently,
  185368. * you should supply a replacement error function and use png_set_error_fn()
  185369. * to replace the error function at run-time.
  185370. */
  185371. #ifndef PNG_NO_ERROR_TEXT
  185372. void PNGAPI
  185373. png_error(png_structp png_ptr, png_const_charp error_message)
  185374. {
  185375. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185376. char msg[16];
  185377. if (png_ptr != NULL)
  185378. {
  185379. if (png_ptr->flags&
  185380. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185381. {
  185382. if (*error_message == '#')
  185383. {
  185384. int offset;
  185385. for (offset=1; offset<15; offset++)
  185386. if (*(error_message+offset) == ' ')
  185387. break;
  185388. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185389. {
  185390. int i;
  185391. for (i=0; i<offset-1; i++)
  185392. msg[i]=error_message[i+1];
  185393. msg[i]='\0';
  185394. error_message=msg;
  185395. }
  185396. else
  185397. error_message+=offset;
  185398. }
  185399. else
  185400. {
  185401. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185402. {
  185403. msg[0]='0';
  185404. msg[1]='\0';
  185405. error_message=msg;
  185406. }
  185407. }
  185408. }
  185409. }
  185410. #endif
  185411. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185412. (*(png_ptr->error_fn))(png_ptr, error_message);
  185413. /* If the custom handler doesn't exist, or if it returns,
  185414. use the default handler, which will not return. */
  185415. png_default_error(png_ptr, error_message);
  185416. }
  185417. #else
  185418. void PNGAPI
  185419. png_err(png_structp png_ptr)
  185420. {
  185421. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185422. (*(png_ptr->error_fn))(png_ptr, '\0');
  185423. /* If the custom handler doesn't exist, or if it returns,
  185424. use the default handler, which will not return. */
  185425. png_default_error(png_ptr, '\0');
  185426. }
  185427. #endif /* PNG_NO_ERROR_TEXT */
  185428. #ifndef PNG_NO_WARNINGS
  185429. /* This function is called whenever there is a non-fatal error. This function
  185430. * should not be changed. If there is a need to handle warnings differently,
  185431. * you should supply a replacement warning function and use
  185432. * png_set_error_fn() to replace the warning function at run-time.
  185433. */
  185434. void PNGAPI
  185435. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185436. {
  185437. int offset = 0;
  185438. if (png_ptr != NULL)
  185439. {
  185440. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185441. if (png_ptr->flags&
  185442. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185443. #endif
  185444. {
  185445. if (*warning_message == '#')
  185446. {
  185447. for (offset=1; offset<15; offset++)
  185448. if (*(warning_message+offset) == ' ')
  185449. break;
  185450. }
  185451. }
  185452. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185453. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185454. }
  185455. else
  185456. png_default_warning(png_ptr, warning_message+offset);
  185457. }
  185458. #endif /* PNG_NO_WARNINGS */
  185459. /* These utilities are used internally to build an error message that relates
  185460. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185461. * this is used to prefix the message. The message is limited in length
  185462. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185463. * if the character is invalid.
  185464. */
  185465. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185466. /*static PNG_CONST char png_digit[16] = {
  185467. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185468. 'A', 'B', 'C', 'D', 'E', 'F'
  185469. };*/
  185470. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185471. static void /* PRIVATE */
  185472. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185473. error_message)
  185474. {
  185475. int iout = 0, iin = 0;
  185476. while (iin < 4)
  185477. {
  185478. int c = png_ptr->chunk_name[iin++];
  185479. if (isnonalpha(c))
  185480. {
  185481. buffer[iout++] = '[';
  185482. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185483. buffer[iout++] = png_digit[c & 0x0f];
  185484. buffer[iout++] = ']';
  185485. }
  185486. else
  185487. {
  185488. buffer[iout++] = (png_byte)c;
  185489. }
  185490. }
  185491. if (error_message == NULL)
  185492. buffer[iout] = 0;
  185493. else
  185494. {
  185495. buffer[iout++] = ':';
  185496. buffer[iout++] = ' ';
  185497. png_strncpy(buffer+iout, error_message, 63);
  185498. buffer[iout+63] = 0;
  185499. }
  185500. }
  185501. #ifdef PNG_READ_SUPPORTED
  185502. void PNGAPI
  185503. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185504. {
  185505. char msg[18+64];
  185506. if (png_ptr == NULL)
  185507. png_error(png_ptr, error_message);
  185508. else
  185509. {
  185510. png_format_buffer(png_ptr, msg, error_message);
  185511. png_error(png_ptr, msg);
  185512. }
  185513. }
  185514. #endif /* PNG_READ_SUPPORTED */
  185515. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185516. #ifndef PNG_NO_WARNINGS
  185517. void PNGAPI
  185518. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185519. {
  185520. char msg[18+64];
  185521. if (png_ptr == NULL)
  185522. png_warning(png_ptr, warning_message);
  185523. else
  185524. {
  185525. png_format_buffer(png_ptr, msg, warning_message);
  185526. png_warning(png_ptr, msg);
  185527. }
  185528. }
  185529. #endif /* PNG_NO_WARNINGS */
  185530. /* This is the default error handling function. Note that replacements for
  185531. * this function MUST NOT RETURN, or the program will likely crash. This
  185532. * function is used by default, or if the program supplies NULL for the
  185533. * error function pointer in png_set_error_fn().
  185534. */
  185535. static void /* PRIVATE */
  185536. png_default_error(png_structp, png_const_charp error_message)
  185537. {
  185538. #ifndef PNG_NO_CONSOLE_IO
  185539. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185540. if (*error_message == '#')
  185541. {
  185542. int offset;
  185543. char error_number[16];
  185544. for (offset=0; offset<15; offset++)
  185545. {
  185546. error_number[offset] = *(error_message+offset+1);
  185547. if (*(error_message+offset) == ' ')
  185548. break;
  185549. }
  185550. if((offset > 1) && (offset < 15))
  185551. {
  185552. error_number[offset-1]='\0';
  185553. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185554. error_message+offset);
  185555. }
  185556. else
  185557. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185558. }
  185559. else
  185560. #endif
  185561. fprintf(stderr, "libpng error: %s\n", error_message);
  185562. #endif
  185563. #ifdef PNG_SETJMP_SUPPORTED
  185564. if (png_ptr)
  185565. {
  185566. # ifdef USE_FAR_KEYWORD
  185567. {
  185568. jmp_buf jmpbuf;
  185569. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185570. longjmp(jmpbuf, 1);
  185571. }
  185572. # else
  185573. longjmp(png_ptr->jmpbuf, 1);
  185574. # endif
  185575. }
  185576. #else
  185577. PNG_ABORT();
  185578. #endif
  185579. #ifdef PNG_NO_CONSOLE_IO
  185580. error_message = error_message; /* make compiler happy */
  185581. #endif
  185582. }
  185583. #ifndef PNG_NO_WARNINGS
  185584. /* This function is called when there is a warning, but the library thinks
  185585. * it can continue anyway. Replacement functions don't have to do anything
  185586. * here if you don't want them to. In the default configuration, png_ptr is
  185587. * not used, but it is passed in case it may be useful.
  185588. */
  185589. static void /* PRIVATE */
  185590. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185591. {
  185592. #ifndef PNG_NO_CONSOLE_IO
  185593. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185594. if (*warning_message == '#')
  185595. {
  185596. int offset;
  185597. char warning_number[16];
  185598. for (offset=0; offset<15; offset++)
  185599. {
  185600. warning_number[offset]=*(warning_message+offset+1);
  185601. if (*(warning_message+offset) == ' ')
  185602. break;
  185603. }
  185604. if((offset > 1) && (offset < 15))
  185605. {
  185606. warning_number[offset-1]='\0';
  185607. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185608. warning_message+offset);
  185609. }
  185610. else
  185611. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185612. }
  185613. else
  185614. # endif
  185615. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185616. #else
  185617. warning_message = warning_message; /* make compiler happy */
  185618. #endif
  185619. png_ptr = png_ptr; /* make compiler happy */
  185620. }
  185621. #endif /* PNG_NO_WARNINGS */
  185622. /* This function is called when the application wants to use another method
  185623. * of handling errors and warnings. Note that the error function MUST NOT
  185624. * return to the calling routine or serious problems will occur. The return
  185625. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185626. */
  185627. void PNGAPI
  185628. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185629. png_error_ptr error_fn, png_error_ptr warning_fn)
  185630. {
  185631. if (png_ptr == NULL)
  185632. return;
  185633. png_ptr->error_ptr = error_ptr;
  185634. png_ptr->error_fn = error_fn;
  185635. png_ptr->warning_fn = warning_fn;
  185636. }
  185637. /* This function returns a pointer to the error_ptr associated with the user
  185638. * functions. The application should free any memory associated with this
  185639. * pointer before png_write_destroy and png_read_destroy are called.
  185640. */
  185641. png_voidp PNGAPI
  185642. png_get_error_ptr(png_structp png_ptr)
  185643. {
  185644. if (png_ptr == NULL)
  185645. return NULL;
  185646. return ((png_voidp)png_ptr->error_ptr);
  185647. }
  185648. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185649. void PNGAPI
  185650. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185651. {
  185652. if(png_ptr != NULL)
  185653. {
  185654. png_ptr->flags &=
  185655. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185656. }
  185657. }
  185658. #endif
  185659. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185660. /*** End of inlined file: pngerror.c ***/
  185661. /*** Start of inlined file: pngget.c ***/
  185662. /* pngget.c - retrieval of values from info struct
  185663. *
  185664. * Last changed in libpng 1.2.15 January 5, 2007
  185665. * For conditions of distribution and use, see copyright notice in png.h
  185666. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185667. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185668. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185669. */
  185670. #define PNG_INTERNAL
  185671. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185672. png_uint_32 PNGAPI
  185673. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185674. {
  185675. if (png_ptr != NULL && info_ptr != NULL)
  185676. return(info_ptr->valid & flag);
  185677. else
  185678. return(0);
  185679. }
  185680. png_uint_32 PNGAPI
  185681. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185682. {
  185683. if (png_ptr != NULL && info_ptr != NULL)
  185684. return(info_ptr->rowbytes);
  185685. else
  185686. return(0);
  185687. }
  185688. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185689. png_bytepp PNGAPI
  185690. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185691. {
  185692. if (png_ptr != NULL && info_ptr != NULL)
  185693. return(info_ptr->row_pointers);
  185694. else
  185695. return(0);
  185696. }
  185697. #endif
  185698. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185699. /* easy access to info, added in libpng-0.99 */
  185700. png_uint_32 PNGAPI
  185701. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185702. {
  185703. if (png_ptr != NULL && info_ptr != NULL)
  185704. {
  185705. return info_ptr->width;
  185706. }
  185707. return (0);
  185708. }
  185709. png_uint_32 PNGAPI
  185710. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185711. {
  185712. if (png_ptr != NULL && info_ptr != NULL)
  185713. {
  185714. return info_ptr->height;
  185715. }
  185716. return (0);
  185717. }
  185718. png_byte PNGAPI
  185719. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185720. {
  185721. if (png_ptr != NULL && info_ptr != NULL)
  185722. {
  185723. return info_ptr->bit_depth;
  185724. }
  185725. return (0);
  185726. }
  185727. png_byte PNGAPI
  185728. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185729. {
  185730. if (png_ptr != NULL && info_ptr != NULL)
  185731. {
  185732. return info_ptr->color_type;
  185733. }
  185734. return (0);
  185735. }
  185736. png_byte PNGAPI
  185737. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185738. {
  185739. if (png_ptr != NULL && info_ptr != NULL)
  185740. {
  185741. return info_ptr->filter_type;
  185742. }
  185743. return (0);
  185744. }
  185745. png_byte PNGAPI
  185746. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185747. {
  185748. if (png_ptr != NULL && info_ptr != NULL)
  185749. {
  185750. return info_ptr->interlace_type;
  185751. }
  185752. return (0);
  185753. }
  185754. png_byte PNGAPI
  185755. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185756. {
  185757. if (png_ptr != NULL && info_ptr != NULL)
  185758. {
  185759. return info_ptr->compression_type;
  185760. }
  185761. return (0);
  185762. }
  185763. png_uint_32 PNGAPI
  185764. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185765. {
  185766. if (png_ptr != NULL && info_ptr != NULL)
  185767. #if defined(PNG_pHYs_SUPPORTED)
  185768. if (info_ptr->valid & PNG_INFO_pHYs)
  185769. {
  185770. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185771. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185772. return (0);
  185773. else return (info_ptr->x_pixels_per_unit);
  185774. }
  185775. #else
  185776. return (0);
  185777. #endif
  185778. return (0);
  185779. }
  185780. png_uint_32 PNGAPI
  185781. png_get_y_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_y_pixels_per_meter");
  185788. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185789. return (0);
  185790. else return (info_ptr->y_pixels_per_unit);
  185791. }
  185792. #else
  185793. return (0);
  185794. #endif
  185795. return (0);
  185796. }
  185797. png_uint_32 PNGAPI
  185798. png_get_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_pixels_per_meter");
  185805. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185806. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185807. return (0);
  185808. else return (info_ptr->x_pixels_per_unit);
  185809. }
  185810. #else
  185811. return (0);
  185812. #endif
  185813. return (0);
  185814. }
  185815. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185816. float PNGAPI
  185817. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185818. {
  185819. if (png_ptr != NULL && info_ptr != NULL)
  185820. #if defined(PNG_pHYs_SUPPORTED)
  185821. if (info_ptr->valid & PNG_INFO_pHYs)
  185822. {
  185823. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185824. if (info_ptr->x_pixels_per_unit == 0)
  185825. return ((float)0.0);
  185826. else
  185827. return ((float)((float)info_ptr->y_pixels_per_unit
  185828. /(float)info_ptr->x_pixels_per_unit));
  185829. }
  185830. #else
  185831. return (0.0);
  185832. #endif
  185833. return ((float)0.0);
  185834. }
  185835. #endif
  185836. png_int_32 PNGAPI
  185837. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185838. {
  185839. if (png_ptr != NULL && info_ptr != NULL)
  185840. #if defined(PNG_oFFs_SUPPORTED)
  185841. if (info_ptr->valid & PNG_INFO_oFFs)
  185842. {
  185843. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185844. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185845. return (0);
  185846. else return (info_ptr->x_offset);
  185847. }
  185848. #else
  185849. return (0);
  185850. #endif
  185851. return (0);
  185852. }
  185853. png_int_32 PNGAPI
  185854. png_get_y_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_y_offset_microns");
  185861. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185862. return (0);
  185863. else return (info_ptr->y_offset);
  185864. }
  185865. #else
  185866. return (0);
  185867. #endif
  185868. return (0);
  185869. }
  185870. png_int_32 PNGAPI
  185871. png_get_x_offset_pixels(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_x_offset_microns");
  185878. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185879. return (0);
  185880. else return (info_ptr->x_offset);
  185881. }
  185882. #else
  185883. return (0);
  185884. #endif
  185885. return (0);
  185886. }
  185887. png_int_32 PNGAPI
  185888. png_get_y_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_y_offset_microns");
  185895. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185896. return (0);
  185897. else return (info_ptr->y_offset);
  185898. }
  185899. #else
  185900. return (0);
  185901. #endif
  185902. return (0);
  185903. }
  185904. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185905. png_uint_32 PNGAPI
  185906. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185907. {
  185908. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185909. *.0254 +.5));
  185910. }
  185911. png_uint_32 PNGAPI
  185912. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185913. {
  185914. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185915. *.0254 +.5));
  185916. }
  185917. png_uint_32 PNGAPI
  185918. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185919. {
  185920. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185921. *.0254 +.5));
  185922. }
  185923. float PNGAPI
  185924. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185925. {
  185926. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185927. *.00003937);
  185928. }
  185929. float PNGAPI
  185930. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185931. {
  185932. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185933. *.00003937);
  185934. }
  185935. #if defined(PNG_pHYs_SUPPORTED)
  185936. png_uint_32 PNGAPI
  185937. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185938. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185939. {
  185940. png_uint_32 retval = 0;
  185941. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185942. {
  185943. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185944. if (res_x != NULL)
  185945. {
  185946. *res_x = info_ptr->x_pixels_per_unit;
  185947. retval |= PNG_INFO_pHYs;
  185948. }
  185949. if (res_y != NULL)
  185950. {
  185951. *res_y = info_ptr->y_pixels_per_unit;
  185952. retval |= PNG_INFO_pHYs;
  185953. }
  185954. if (unit_type != NULL)
  185955. {
  185956. *unit_type = (int)info_ptr->phys_unit_type;
  185957. retval |= PNG_INFO_pHYs;
  185958. if(*unit_type == 1)
  185959. {
  185960. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185961. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185962. }
  185963. }
  185964. }
  185965. return (retval);
  185966. }
  185967. #endif /* PNG_pHYs_SUPPORTED */
  185968. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185969. /* png_get_channels really belongs in here, too, but it's been around longer */
  185970. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185971. png_byte PNGAPI
  185972. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185973. {
  185974. if (png_ptr != NULL && info_ptr != NULL)
  185975. return(info_ptr->channels);
  185976. else
  185977. return (0);
  185978. }
  185979. png_bytep PNGAPI
  185980. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185981. {
  185982. if (png_ptr != NULL && info_ptr != NULL)
  185983. return(info_ptr->signature);
  185984. else
  185985. return (NULL);
  185986. }
  185987. #if defined(PNG_bKGD_SUPPORTED)
  185988. png_uint_32 PNGAPI
  185989. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185990. png_color_16p *background)
  185991. {
  185992. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185993. && background != NULL)
  185994. {
  185995. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185996. *background = &(info_ptr->background);
  185997. return (PNG_INFO_bKGD);
  185998. }
  185999. return (0);
  186000. }
  186001. #endif
  186002. #if defined(PNG_cHRM_SUPPORTED)
  186003. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186004. png_uint_32 PNGAPI
  186005. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186006. double *white_x, double *white_y, double *red_x, double *red_y,
  186007. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186008. {
  186009. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186010. {
  186011. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186012. if (white_x != NULL)
  186013. *white_x = (double)info_ptr->x_white;
  186014. if (white_y != NULL)
  186015. *white_y = (double)info_ptr->y_white;
  186016. if (red_x != NULL)
  186017. *red_x = (double)info_ptr->x_red;
  186018. if (red_y != NULL)
  186019. *red_y = (double)info_ptr->y_red;
  186020. if (green_x != NULL)
  186021. *green_x = (double)info_ptr->x_green;
  186022. if (green_y != NULL)
  186023. *green_y = (double)info_ptr->y_green;
  186024. if (blue_x != NULL)
  186025. *blue_x = (double)info_ptr->x_blue;
  186026. if (blue_y != NULL)
  186027. *blue_y = (double)info_ptr->y_blue;
  186028. return (PNG_INFO_cHRM);
  186029. }
  186030. return (0);
  186031. }
  186032. #endif
  186033. #ifdef PNG_FIXED_POINT_SUPPORTED
  186034. png_uint_32 PNGAPI
  186035. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186036. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186037. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186038. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186039. {
  186040. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186041. {
  186042. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186043. if (white_x != NULL)
  186044. *white_x = info_ptr->int_x_white;
  186045. if (white_y != NULL)
  186046. *white_y = info_ptr->int_y_white;
  186047. if (red_x != NULL)
  186048. *red_x = info_ptr->int_x_red;
  186049. if (red_y != NULL)
  186050. *red_y = info_ptr->int_y_red;
  186051. if (green_x != NULL)
  186052. *green_x = info_ptr->int_x_green;
  186053. if (green_y != NULL)
  186054. *green_y = info_ptr->int_y_green;
  186055. if (blue_x != NULL)
  186056. *blue_x = info_ptr->int_x_blue;
  186057. if (blue_y != NULL)
  186058. *blue_y = info_ptr->int_y_blue;
  186059. return (PNG_INFO_cHRM);
  186060. }
  186061. return (0);
  186062. }
  186063. #endif
  186064. #endif
  186065. #if defined(PNG_gAMA_SUPPORTED)
  186066. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186067. png_uint_32 PNGAPI
  186068. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186069. {
  186070. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186071. && file_gamma != NULL)
  186072. {
  186073. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186074. *file_gamma = (double)info_ptr->gamma;
  186075. return (PNG_INFO_gAMA);
  186076. }
  186077. return (0);
  186078. }
  186079. #endif
  186080. #ifdef PNG_FIXED_POINT_SUPPORTED
  186081. png_uint_32 PNGAPI
  186082. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186083. png_fixed_point *int_file_gamma)
  186084. {
  186085. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186086. && int_file_gamma != NULL)
  186087. {
  186088. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186089. *int_file_gamma = info_ptr->int_gamma;
  186090. return (PNG_INFO_gAMA);
  186091. }
  186092. return (0);
  186093. }
  186094. #endif
  186095. #endif
  186096. #if defined(PNG_sRGB_SUPPORTED)
  186097. png_uint_32 PNGAPI
  186098. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186099. {
  186100. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186101. && file_srgb_intent != NULL)
  186102. {
  186103. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186104. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186105. return (PNG_INFO_sRGB);
  186106. }
  186107. return (0);
  186108. }
  186109. #endif
  186110. #if defined(PNG_iCCP_SUPPORTED)
  186111. png_uint_32 PNGAPI
  186112. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186113. png_charpp name, int *compression_type,
  186114. png_charpp profile, png_uint_32 *proflen)
  186115. {
  186116. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186117. && name != NULL && profile != NULL && proflen != NULL)
  186118. {
  186119. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186120. *name = info_ptr->iccp_name;
  186121. *profile = info_ptr->iccp_profile;
  186122. /* compression_type is a dummy so the API won't have to change
  186123. if we introduce multiple compression types later. */
  186124. *proflen = (int)info_ptr->iccp_proflen;
  186125. *compression_type = (int)info_ptr->iccp_compression;
  186126. return (PNG_INFO_iCCP);
  186127. }
  186128. return (0);
  186129. }
  186130. #endif
  186131. #if defined(PNG_sPLT_SUPPORTED)
  186132. png_uint_32 PNGAPI
  186133. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186134. png_sPLT_tpp spalettes)
  186135. {
  186136. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186137. {
  186138. *spalettes = info_ptr->splt_palettes;
  186139. return ((png_uint_32)info_ptr->splt_palettes_num);
  186140. }
  186141. return (0);
  186142. }
  186143. #endif
  186144. #if defined(PNG_hIST_SUPPORTED)
  186145. png_uint_32 PNGAPI
  186146. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186147. {
  186148. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186149. && hist != NULL)
  186150. {
  186151. png_debug1(1, "in %s retrieval function\n", "hIST");
  186152. *hist = info_ptr->hist;
  186153. return (PNG_INFO_hIST);
  186154. }
  186155. return (0);
  186156. }
  186157. #endif
  186158. png_uint_32 PNGAPI
  186159. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186160. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186161. int *color_type, int *interlace_type, int *compression_type,
  186162. int *filter_type)
  186163. {
  186164. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186165. bit_depth != NULL && color_type != NULL)
  186166. {
  186167. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186168. *width = info_ptr->width;
  186169. *height = info_ptr->height;
  186170. *bit_depth = info_ptr->bit_depth;
  186171. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186172. png_error(png_ptr, "Invalid bit depth");
  186173. *color_type = info_ptr->color_type;
  186174. if (info_ptr->color_type > 6)
  186175. png_error(png_ptr, "Invalid color type");
  186176. if (compression_type != NULL)
  186177. *compression_type = info_ptr->compression_type;
  186178. if (filter_type != NULL)
  186179. *filter_type = info_ptr->filter_type;
  186180. if (interlace_type != NULL)
  186181. *interlace_type = info_ptr->interlace_type;
  186182. /* check for potential overflow of rowbytes */
  186183. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186184. png_error(png_ptr, "Invalid image width");
  186185. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186186. png_error(png_ptr, "Invalid image height");
  186187. if (info_ptr->width > (PNG_UINT_32_MAX
  186188. >> 3) /* 8-byte RGBA pixels */
  186189. - 64 /* bigrowbuf hack */
  186190. - 1 /* filter byte */
  186191. - 7*8 /* rounding of width to multiple of 8 pixels */
  186192. - 8) /* extra max_pixel_depth pad */
  186193. {
  186194. png_warning(png_ptr,
  186195. "Width too large for libpng to process image data.");
  186196. }
  186197. return (1);
  186198. }
  186199. return (0);
  186200. }
  186201. #if defined(PNG_oFFs_SUPPORTED)
  186202. png_uint_32 PNGAPI
  186203. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186204. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186205. {
  186206. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186207. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186208. {
  186209. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186210. *offset_x = info_ptr->x_offset;
  186211. *offset_y = info_ptr->y_offset;
  186212. *unit_type = (int)info_ptr->offset_unit_type;
  186213. return (PNG_INFO_oFFs);
  186214. }
  186215. return (0);
  186216. }
  186217. #endif
  186218. #if defined(PNG_pCAL_SUPPORTED)
  186219. png_uint_32 PNGAPI
  186220. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186221. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186222. png_charp *units, png_charpp *params)
  186223. {
  186224. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186225. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186226. nparams != NULL && units != NULL && params != NULL)
  186227. {
  186228. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186229. *purpose = info_ptr->pcal_purpose;
  186230. *X0 = info_ptr->pcal_X0;
  186231. *X1 = info_ptr->pcal_X1;
  186232. *type = (int)info_ptr->pcal_type;
  186233. *nparams = (int)info_ptr->pcal_nparams;
  186234. *units = info_ptr->pcal_units;
  186235. *params = info_ptr->pcal_params;
  186236. return (PNG_INFO_pCAL);
  186237. }
  186238. return (0);
  186239. }
  186240. #endif
  186241. #if defined(PNG_sCAL_SUPPORTED)
  186242. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186243. png_uint_32 PNGAPI
  186244. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186245. int *unit, double *width, double *height)
  186246. {
  186247. if (png_ptr != NULL && info_ptr != NULL &&
  186248. (info_ptr->valid & PNG_INFO_sCAL))
  186249. {
  186250. *unit = info_ptr->scal_unit;
  186251. *width = info_ptr->scal_pixel_width;
  186252. *height = info_ptr->scal_pixel_height;
  186253. return (PNG_INFO_sCAL);
  186254. }
  186255. return(0);
  186256. }
  186257. #else
  186258. #ifdef PNG_FIXED_POINT_SUPPORTED
  186259. png_uint_32 PNGAPI
  186260. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186261. int *unit, png_charpp width, png_charpp height)
  186262. {
  186263. if (png_ptr != NULL && info_ptr != NULL &&
  186264. (info_ptr->valid & PNG_INFO_sCAL))
  186265. {
  186266. *unit = info_ptr->scal_unit;
  186267. *width = info_ptr->scal_s_width;
  186268. *height = info_ptr->scal_s_height;
  186269. return (PNG_INFO_sCAL);
  186270. }
  186271. return(0);
  186272. }
  186273. #endif
  186274. #endif
  186275. #endif
  186276. #if defined(PNG_pHYs_SUPPORTED)
  186277. png_uint_32 PNGAPI
  186278. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186279. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186280. {
  186281. png_uint_32 retval = 0;
  186282. if (png_ptr != NULL && info_ptr != NULL &&
  186283. (info_ptr->valid & PNG_INFO_pHYs))
  186284. {
  186285. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186286. if (res_x != NULL)
  186287. {
  186288. *res_x = info_ptr->x_pixels_per_unit;
  186289. retval |= PNG_INFO_pHYs;
  186290. }
  186291. if (res_y != NULL)
  186292. {
  186293. *res_y = info_ptr->y_pixels_per_unit;
  186294. retval |= PNG_INFO_pHYs;
  186295. }
  186296. if (unit_type != NULL)
  186297. {
  186298. *unit_type = (int)info_ptr->phys_unit_type;
  186299. retval |= PNG_INFO_pHYs;
  186300. }
  186301. }
  186302. return (retval);
  186303. }
  186304. #endif
  186305. png_uint_32 PNGAPI
  186306. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186307. int *num_palette)
  186308. {
  186309. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186310. && palette != NULL)
  186311. {
  186312. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186313. *palette = info_ptr->palette;
  186314. *num_palette = info_ptr->num_palette;
  186315. png_debug1(3, "num_palette = %d\n", *num_palette);
  186316. return (PNG_INFO_PLTE);
  186317. }
  186318. return (0);
  186319. }
  186320. #if defined(PNG_sBIT_SUPPORTED)
  186321. png_uint_32 PNGAPI
  186322. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186323. {
  186324. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186325. && sig_bit != NULL)
  186326. {
  186327. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186328. *sig_bit = &(info_ptr->sig_bit);
  186329. return (PNG_INFO_sBIT);
  186330. }
  186331. return (0);
  186332. }
  186333. #endif
  186334. #if defined(PNG_TEXT_SUPPORTED)
  186335. png_uint_32 PNGAPI
  186336. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186337. int *num_text)
  186338. {
  186339. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186340. {
  186341. png_debug1(1, "in %s retrieval function\n",
  186342. (png_ptr->chunk_name[0] == '\0' ? "text"
  186343. : (png_const_charp)png_ptr->chunk_name));
  186344. if (text_ptr != NULL)
  186345. *text_ptr = info_ptr->text;
  186346. if (num_text != NULL)
  186347. *num_text = info_ptr->num_text;
  186348. return ((png_uint_32)info_ptr->num_text);
  186349. }
  186350. if (num_text != NULL)
  186351. *num_text = 0;
  186352. return(0);
  186353. }
  186354. #endif
  186355. #if defined(PNG_tIME_SUPPORTED)
  186356. png_uint_32 PNGAPI
  186357. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186358. {
  186359. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186360. && mod_time != NULL)
  186361. {
  186362. png_debug1(1, "in %s retrieval function\n", "tIME");
  186363. *mod_time = &(info_ptr->mod_time);
  186364. return (PNG_INFO_tIME);
  186365. }
  186366. return (0);
  186367. }
  186368. #endif
  186369. #if defined(PNG_tRNS_SUPPORTED)
  186370. png_uint_32 PNGAPI
  186371. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186372. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186373. {
  186374. png_uint_32 retval = 0;
  186375. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186376. {
  186377. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186378. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186379. {
  186380. if (trans != NULL)
  186381. {
  186382. *trans = info_ptr->trans;
  186383. retval |= PNG_INFO_tRNS;
  186384. }
  186385. if (trans_values != NULL)
  186386. *trans_values = &(info_ptr->trans_values);
  186387. }
  186388. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186389. {
  186390. if (trans_values != NULL)
  186391. {
  186392. *trans_values = &(info_ptr->trans_values);
  186393. retval |= PNG_INFO_tRNS;
  186394. }
  186395. if(trans != NULL)
  186396. *trans = NULL;
  186397. }
  186398. if(num_trans != NULL)
  186399. {
  186400. *num_trans = info_ptr->num_trans;
  186401. retval |= PNG_INFO_tRNS;
  186402. }
  186403. }
  186404. return (retval);
  186405. }
  186406. #endif
  186407. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186408. png_uint_32 PNGAPI
  186409. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186410. png_unknown_chunkpp unknowns)
  186411. {
  186412. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186413. {
  186414. *unknowns = info_ptr->unknown_chunks;
  186415. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186416. }
  186417. return (0);
  186418. }
  186419. #endif
  186420. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186421. png_byte PNGAPI
  186422. png_get_rgb_to_gray_status (png_structp png_ptr)
  186423. {
  186424. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186425. }
  186426. #endif
  186427. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186428. png_voidp PNGAPI
  186429. png_get_user_chunk_ptr(png_structp png_ptr)
  186430. {
  186431. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186432. }
  186433. #endif
  186434. #ifdef PNG_WRITE_SUPPORTED
  186435. png_uint_32 PNGAPI
  186436. png_get_compression_buffer_size(png_structp png_ptr)
  186437. {
  186438. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186439. }
  186440. #endif
  186441. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186442. #ifndef PNG_1_0_X
  186443. /* this function was added to libpng 1.2.0 and should exist by default */
  186444. png_uint_32 PNGAPI
  186445. png_get_asm_flags (png_structp png_ptr)
  186446. {
  186447. /* obsolete, to be removed from libpng-1.4.0 */
  186448. return (png_ptr? 0L: 0L);
  186449. }
  186450. /* this function was added to libpng 1.2.0 and should exist by default */
  186451. png_uint_32 PNGAPI
  186452. png_get_asm_flagmask (int flag_select)
  186453. {
  186454. /* obsolete, to be removed from libpng-1.4.0 */
  186455. flag_select=flag_select;
  186456. return 0L;
  186457. }
  186458. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186459. /* this function was added to libpng 1.2.0 */
  186460. png_uint_32 PNGAPI
  186461. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186462. {
  186463. /* obsolete, to be removed from libpng-1.4.0 */
  186464. flag_select=flag_select;
  186465. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186466. return 0L;
  186467. }
  186468. /* this function was added to libpng 1.2.0 */
  186469. png_byte PNGAPI
  186470. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186471. {
  186472. /* obsolete, to be removed from libpng-1.4.0 */
  186473. return (png_ptr? 0: 0);
  186474. }
  186475. /* this function was added to libpng 1.2.0 */
  186476. png_uint_32 PNGAPI
  186477. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186478. {
  186479. /* obsolete, to be removed from libpng-1.4.0 */
  186480. return (png_ptr? 0L: 0L);
  186481. }
  186482. #endif /* ?PNG_1_0_X */
  186483. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186484. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186485. /* these functions were added to libpng 1.2.6 */
  186486. png_uint_32 PNGAPI
  186487. png_get_user_width_max (png_structp png_ptr)
  186488. {
  186489. return (png_ptr? png_ptr->user_width_max : 0);
  186490. }
  186491. png_uint_32 PNGAPI
  186492. png_get_user_height_max (png_structp png_ptr)
  186493. {
  186494. return (png_ptr? png_ptr->user_height_max : 0);
  186495. }
  186496. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186497. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186498. /*** End of inlined file: pngget.c ***/
  186499. /*** Start of inlined file: pngmem.c ***/
  186500. /* pngmem.c - stub functions for memory allocation
  186501. *
  186502. * Last changed in libpng 1.2.13 November 13, 2006
  186503. * For conditions of distribution and use, see copyright notice in png.h
  186504. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186505. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186506. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186507. *
  186508. * This file provides a location for all memory allocation. Users who
  186509. * need special memory handling are expected to supply replacement
  186510. * functions for png_malloc() and png_free(), and to use
  186511. * png_create_read_struct_2() and png_create_write_struct_2() to
  186512. * identify the replacement functions.
  186513. */
  186514. #define PNG_INTERNAL
  186515. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186516. /* Borland DOS special memory handler */
  186517. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186518. /* if you change this, be sure to change the one in png.h also */
  186519. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186520. by a single call to calloc() if this is thought to improve performance. */
  186521. png_voidp /* PRIVATE */
  186522. png_create_struct(int type)
  186523. {
  186524. #ifdef PNG_USER_MEM_SUPPORTED
  186525. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186526. }
  186527. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186528. png_voidp /* PRIVATE */
  186529. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186530. {
  186531. #endif /* PNG_USER_MEM_SUPPORTED */
  186532. png_size_t size;
  186533. png_voidp struct_ptr;
  186534. if (type == PNG_STRUCT_INFO)
  186535. size = png_sizeof(png_info);
  186536. else if (type == PNG_STRUCT_PNG)
  186537. size = png_sizeof(png_struct);
  186538. else
  186539. return (png_get_copyright(NULL));
  186540. #ifdef PNG_USER_MEM_SUPPORTED
  186541. if(malloc_fn != NULL)
  186542. {
  186543. png_struct dummy_struct;
  186544. png_structp png_ptr = &dummy_struct;
  186545. png_ptr->mem_ptr=mem_ptr;
  186546. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186547. }
  186548. else
  186549. #endif /* PNG_USER_MEM_SUPPORTED */
  186550. struct_ptr = (png_voidp)farmalloc(size);
  186551. if (struct_ptr != NULL)
  186552. png_memset(struct_ptr, 0, size);
  186553. return (struct_ptr);
  186554. }
  186555. /* Free memory allocated by a png_create_struct() call */
  186556. void /* PRIVATE */
  186557. png_destroy_struct(png_voidp struct_ptr)
  186558. {
  186559. #ifdef PNG_USER_MEM_SUPPORTED
  186560. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186561. }
  186562. /* Free memory allocated by a png_create_struct() call */
  186563. void /* PRIVATE */
  186564. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186565. png_voidp mem_ptr)
  186566. {
  186567. #endif
  186568. if (struct_ptr != NULL)
  186569. {
  186570. #ifdef PNG_USER_MEM_SUPPORTED
  186571. if(free_fn != NULL)
  186572. {
  186573. png_struct dummy_struct;
  186574. png_structp png_ptr = &dummy_struct;
  186575. png_ptr->mem_ptr=mem_ptr;
  186576. (*(free_fn))(png_ptr, struct_ptr);
  186577. return;
  186578. }
  186579. #endif /* PNG_USER_MEM_SUPPORTED */
  186580. farfree (struct_ptr);
  186581. }
  186582. }
  186583. /* Allocate memory. For reasonable files, size should never exceed
  186584. * 64K. However, zlib may allocate more then 64K if you don't tell
  186585. * it not to. See zconf.h and png.h for more information. zlib does
  186586. * need to allocate exactly 64K, so whatever you call here must
  186587. * have the ability to do that.
  186588. *
  186589. * Borland seems to have a problem in DOS mode for exactly 64K.
  186590. * It gives you a segment with an offset of 8 (perhaps to store its
  186591. * memory stuff). zlib doesn't like this at all, so we have to
  186592. * detect and deal with it. This code should not be needed in
  186593. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186594. * been updated by Alexander Lehmann for version 0.89 to waste less
  186595. * memory.
  186596. *
  186597. * Note that we can't use png_size_t for the "size" declaration,
  186598. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186599. * result, we would be truncating potentially larger memory requests
  186600. * (which should cause a fatal error) and introducing major problems.
  186601. */
  186602. png_voidp PNGAPI
  186603. png_malloc(png_structp png_ptr, png_uint_32 size)
  186604. {
  186605. png_voidp ret;
  186606. if (png_ptr == NULL || size == 0)
  186607. return (NULL);
  186608. #ifdef PNG_USER_MEM_SUPPORTED
  186609. if(png_ptr->malloc_fn != NULL)
  186610. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186611. else
  186612. ret = (png_malloc_default(png_ptr, size));
  186613. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186614. png_error(png_ptr, "Out of memory!");
  186615. return (ret);
  186616. }
  186617. png_voidp PNGAPI
  186618. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186619. {
  186620. png_voidp ret;
  186621. #endif /* PNG_USER_MEM_SUPPORTED */
  186622. if (png_ptr == NULL || size == 0)
  186623. return (NULL);
  186624. #ifdef PNG_MAX_MALLOC_64K
  186625. if (size > (png_uint_32)65536L)
  186626. {
  186627. png_warning(png_ptr, "Cannot Allocate > 64K");
  186628. ret = NULL;
  186629. }
  186630. else
  186631. #endif
  186632. if (size != (size_t)size)
  186633. ret = NULL;
  186634. else if (size == (png_uint_32)65536L)
  186635. {
  186636. if (png_ptr->offset_table == NULL)
  186637. {
  186638. /* try to see if we need to do any of this fancy stuff */
  186639. ret = farmalloc(size);
  186640. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186641. {
  186642. int num_blocks;
  186643. png_uint_32 total_size;
  186644. png_bytep table;
  186645. int i;
  186646. png_byte huge * hptr;
  186647. if (ret != NULL)
  186648. {
  186649. farfree(ret);
  186650. ret = NULL;
  186651. }
  186652. if(png_ptr->zlib_window_bits > 14)
  186653. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186654. else
  186655. num_blocks = 1;
  186656. if (png_ptr->zlib_mem_level >= 7)
  186657. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186658. else
  186659. num_blocks++;
  186660. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186661. table = farmalloc(total_size);
  186662. if (table == NULL)
  186663. {
  186664. #ifndef PNG_USER_MEM_SUPPORTED
  186665. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186666. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186667. else
  186668. png_warning(png_ptr, "Out Of Memory.");
  186669. #endif
  186670. return (NULL);
  186671. }
  186672. if ((png_size_t)table & 0xfff0)
  186673. {
  186674. #ifndef PNG_USER_MEM_SUPPORTED
  186675. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186676. png_error(png_ptr,
  186677. "Farmalloc didn't return normalized pointer");
  186678. else
  186679. png_warning(png_ptr,
  186680. "Farmalloc didn't return normalized pointer");
  186681. #endif
  186682. return (NULL);
  186683. }
  186684. png_ptr->offset_table = table;
  186685. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186686. png_sizeof (png_bytep));
  186687. if (png_ptr->offset_table_ptr == NULL)
  186688. {
  186689. #ifndef PNG_USER_MEM_SUPPORTED
  186690. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186691. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186692. else
  186693. png_warning(png_ptr, "Out Of memory.");
  186694. #endif
  186695. return (NULL);
  186696. }
  186697. hptr = (png_byte huge *)table;
  186698. if ((png_size_t)hptr & 0xf)
  186699. {
  186700. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186701. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186702. }
  186703. for (i = 0; i < num_blocks; i++)
  186704. {
  186705. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186706. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186707. }
  186708. png_ptr->offset_table_number = num_blocks;
  186709. png_ptr->offset_table_count = 0;
  186710. png_ptr->offset_table_count_free = 0;
  186711. }
  186712. }
  186713. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186714. {
  186715. #ifndef PNG_USER_MEM_SUPPORTED
  186716. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186717. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186718. else
  186719. png_warning(png_ptr, "Out of Memory.");
  186720. #endif
  186721. return (NULL);
  186722. }
  186723. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186724. }
  186725. else
  186726. ret = farmalloc(size);
  186727. #ifndef PNG_USER_MEM_SUPPORTED
  186728. if (ret == NULL)
  186729. {
  186730. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186731. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186732. else
  186733. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186734. }
  186735. #endif
  186736. return (ret);
  186737. }
  186738. /* free a pointer allocated by png_malloc(). In the default
  186739. configuration, png_ptr is not used, but is passed in case it
  186740. is needed. If ptr is NULL, return without taking any action. */
  186741. void PNGAPI
  186742. png_free(png_structp png_ptr, png_voidp ptr)
  186743. {
  186744. if (png_ptr == NULL || ptr == NULL)
  186745. return;
  186746. #ifdef PNG_USER_MEM_SUPPORTED
  186747. if (png_ptr->free_fn != NULL)
  186748. {
  186749. (*(png_ptr->free_fn))(png_ptr, ptr);
  186750. return;
  186751. }
  186752. else png_free_default(png_ptr, ptr);
  186753. }
  186754. void PNGAPI
  186755. png_free_default(png_structp png_ptr, png_voidp ptr)
  186756. {
  186757. #endif /* PNG_USER_MEM_SUPPORTED */
  186758. if(png_ptr == NULL) return;
  186759. if (png_ptr->offset_table != NULL)
  186760. {
  186761. int i;
  186762. for (i = 0; i < png_ptr->offset_table_count; i++)
  186763. {
  186764. if (ptr == png_ptr->offset_table_ptr[i])
  186765. {
  186766. ptr = NULL;
  186767. png_ptr->offset_table_count_free++;
  186768. break;
  186769. }
  186770. }
  186771. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186772. {
  186773. farfree(png_ptr->offset_table);
  186774. farfree(png_ptr->offset_table_ptr);
  186775. png_ptr->offset_table = NULL;
  186776. png_ptr->offset_table_ptr = NULL;
  186777. }
  186778. }
  186779. if (ptr != NULL)
  186780. {
  186781. farfree(ptr);
  186782. }
  186783. }
  186784. #else /* Not the Borland DOS special memory handler */
  186785. /* Allocate memory for a png_struct or a png_info. The malloc and
  186786. memset can be replaced by a single call to calloc() if this is thought
  186787. to improve performance noticably. */
  186788. png_voidp /* PRIVATE */
  186789. png_create_struct(int type)
  186790. {
  186791. #ifdef PNG_USER_MEM_SUPPORTED
  186792. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186793. }
  186794. /* Allocate memory for a png_struct or a png_info. The malloc and
  186795. memset can be replaced by a single call to calloc() if this is thought
  186796. to improve performance noticably. */
  186797. png_voidp /* PRIVATE */
  186798. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186799. {
  186800. #endif /* PNG_USER_MEM_SUPPORTED */
  186801. png_size_t size;
  186802. png_voidp struct_ptr;
  186803. if (type == PNG_STRUCT_INFO)
  186804. size = png_sizeof(png_info);
  186805. else if (type == PNG_STRUCT_PNG)
  186806. size = png_sizeof(png_struct);
  186807. else
  186808. return (NULL);
  186809. #ifdef PNG_USER_MEM_SUPPORTED
  186810. if(malloc_fn != NULL)
  186811. {
  186812. png_struct dummy_struct;
  186813. png_structp png_ptr = &dummy_struct;
  186814. png_ptr->mem_ptr=mem_ptr;
  186815. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186816. if (struct_ptr != NULL)
  186817. png_memset(struct_ptr, 0, size);
  186818. return (struct_ptr);
  186819. }
  186820. #endif /* PNG_USER_MEM_SUPPORTED */
  186821. #if defined(__TURBOC__) && !defined(__FLAT__)
  186822. struct_ptr = (png_voidp)farmalloc(size);
  186823. #else
  186824. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186825. struct_ptr = (png_voidp)halloc(size,1);
  186826. # else
  186827. struct_ptr = (png_voidp)malloc(size);
  186828. # endif
  186829. #endif
  186830. if (struct_ptr != NULL)
  186831. png_memset(struct_ptr, 0, size);
  186832. return (struct_ptr);
  186833. }
  186834. /* Free memory allocated by a png_create_struct() call */
  186835. void /* PRIVATE */
  186836. png_destroy_struct(png_voidp struct_ptr)
  186837. {
  186838. #ifdef PNG_USER_MEM_SUPPORTED
  186839. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186840. }
  186841. /* Free memory allocated by a png_create_struct() call */
  186842. void /* PRIVATE */
  186843. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186844. png_voidp mem_ptr)
  186845. {
  186846. #endif /* PNG_USER_MEM_SUPPORTED */
  186847. if (struct_ptr != NULL)
  186848. {
  186849. #ifdef PNG_USER_MEM_SUPPORTED
  186850. if(free_fn != NULL)
  186851. {
  186852. png_struct dummy_struct;
  186853. png_structp png_ptr = &dummy_struct;
  186854. png_ptr->mem_ptr=mem_ptr;
  186855. (*(free_fn))(png_ptr, struct_ptr);
  186856. return;
  186857. }
  186858. #endif /* PNG_USER_MEM_SUPPORTED */
  186859. #if defined(__TURBOC__) && !defined(__FLAT__)
  186860. farfree(struct_ptr);
  186861. #else
  186862. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186863. hfree(struct_ptr);
  186864. # else
  186865. free(struct_ptr);
  186866. # endif
  186867. #endif
  186868. }
  186869. }
  186870. /* Allocate memory. For reasonable files, size should never exceed
  186871. 64K. However, zlib may allocate more then 64K if you don't tell
  186872. it not to. See zconf.h and png.h for more information. zlib does
  186873. need to allocate exactly 64K, so whatever you call here must
  186874. have the ability to do that. */
  186875. png_voidp PNGAPI
  186876. png_malloc(png_structp png_ptr, png_uint_32 size)
  186877. {
  186878. png_voidp ret;
  186879. #ifdef PNG_USER_MEM_SUPPORTED
  186880. if (png_ptr == NULL || size == 0)
  186881. return (NULL);
  186882. if(png_ptr->malloc_fn != NULL)
  186883. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186884. else
  186885. ret = (png_malloc_default(png_ptr, size));
  186886. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186887. png_error(png_ptr, "Out of Memory!");
  186888. return (ret);
  186889. }
  186890. png_voidp PNGAPI
  186891. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186892. {
  186893. png_voidp ret;
  186894. #endif /* PNG_USER_MEM_SUPPORTED */
  186895. if (png_ptr == NULL || size == 0)
  186896. return (NULL);
  186897. #ifdef PNG_MAX_MALLOC_64K
  186898. if (size > (png_uint_32)65536L)
  186899. {
  186900. #ifndef PNG_USER_MEM_SUPPORTED
  186901. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186902. png_error(png_ptr, "Cannot Allocate > 64K");
  186903. else
  186904. #endif
  186905. return NULL;
  186906. }
  186907. #endif
  186908. /* Check for overflow */
  186909. #if defined(__TURBOC__) && !defined(__FLAT__)
  186910. if (size != (unsigned long)size)
  186911. ret = NULL;
  186912. else
  186913. ret = farmalloc(size);
  186914. #else
  186915. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186916. if (size != (unsigned long)size)
  186917. ret = NULL;
  186918. else
  186919. ret = halloc(size, 1);
  186920. # else
  186921. if (size != (size_t)size)
  186922. ret = NULL;
  186923. else
  186924. ret = malloc((size_t)size);
  186925. # endif
  186926. #endif
  186927. #ifndef PNG_USER_MEM_SUPPORTED
  186928. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186929. png_error(png_ptr, "Out of Memory");
  186930. #endif
  186931. return (ret);
  186932. }
  186933. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186934. without taking any action. */
  186935. void PNGAPI
  186936. png_free(png_structp png_ptr, png_voidp ptr)
  186937. {
  186938. if (png_ptr == NULL || ptr == NULL)
  186939. return;
  186940. #ifdef PNG_USER_MEM_SUPPORTED
  186941. if (png_ptr->free_fn != NULL)
  186942. {
  186943. (*(png_ptr->free_fn))(png_ptr, ptr);
  186944. return;
  186945. }
  186946. else png_free_default(png_ptr, ptr);
  186947. }
  186948. void PNGAPI
  186949. png_free_default(png_structp png_ptr, png_voidp ptr)
  186950. {
  186951. if (png_ptr == NULL || ptr == NULL)
  186952. return;
  186953. #endif /* PNG_USER_MEM_SUPPORTED */
  186954. #if defined(__TURBOC__) && !defined(__FLAT__)
  186955. farfree(ptr);
  186956. #else
  186957. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186958. hfree(ptr);
  186959. # else
  186960. free(ptr);
  186961. # endif
  186962. #endif
  186963. }
  186964. #endif /* Not Borland DOS special memory handler */
  186965. #if defined(PNG_1_0_X)
  186966. # define png_malloc_warn png_malloc
  186967. #else
  186968. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186969. * function will set up png_malloc() to issue a png_warning and return NULL
  186970. * instead of issuing a png_error, if it fails to allocate the requested
  186971. * memory.
  186972. */
  186973. png_voidp PNGAPI
  186974. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186975. {
  186976. png_voidp ptr;
  186977. png_uint_32 save_flags;
  186978. if(png_ptr == NULL) return (NULL);
  186979. save_flags=png_ptr->flags;
  186980. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186981. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186982. png_ptr->flags=save_flags;
  186983. return(ptr);
  186984. }
  186985. #endif
  186986. png_voidp PNGAPI
  186987. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186988. png_uint_32 length)
  186989. {
  186990. png_size_t size;
  186991. size = (png_size_t)length;
  186992. if ((png_uint_32)size != length)
  186993. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186994. return(png_memcpy (s1, s2, size));
  186995. }
  186996. png_voidp PNGAPI
  186997. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186998. png_uint_32 length)
  186999. {
  187000. png_size_t size;
  187001. size = (png_size_t)length;
  187002. if ((png_uint_32)size != length)
  187003. png_error(png_ptr,"Overflow in png_memset_check.");
  187004. return (png_memset (s1, value, size));
  187005. }
  187006. #ifdef PNG_USER_MEM_SUPPORTED
  187007. /* This function is called when the application wants to use another method
  187008. * of allocating and freeing memory.
  187009. */
  187010. void PNGAPI
  187011. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187012. malloc_fn, png_free_ptr free_fn)
  187013. {
  187014. if(png_ptr != NULL) {
  187015. png_ptr->mem_ptr = mem_ptr;
  187016. png_ptr->malloc_fn = malloc_fn;
  187017. png_ptr->free_fn = free_fn;
  187018. }
  187019. }
  187020. /* This function returns a pointer to the mem_ptr associated with the user
  187021. * functions. The application should free any memory associated with this
  187022. * pointer before png_write_destroy and png_read_destroy are called.
  187023. */
  187024. png_voidp PNGAPI
  187025. png_get_mem_ptr(png_structp png_ptr)
  187026. {
  187027. if(png_ptr == NULL) return (NULL);
  187028. return ((png_voidp)png_ptr->mem_ptr);
  187029. }
  187030. #endif /* PNG_USER_MEM_SUPPORTED */
  187031. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187032. /*** End of inlined file: pngmem.c ***/
  187033. /*** Start of inlined file: pngread.c ***/
  187034. /* pngread.c - read a PNG file
  187035. *
  187036. * Last changed in libpng 1.2.20 September 7, 2007
  187037. * For conditions of distribution and use, see copyright notice in png.h
  187038. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187039. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187040. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187041. *
  187042. * This file contains routines that an application calls directly to
  187043. * read a PNG file or stream.
  187044. */
  187045. #define PNG_INTERNAL
  187046. #if defined(PNG_READ_SUPPORTED)
  187047. /* Create a PNG structure for reading, and allocate any memory needed. */
  187048. png_structp PNGAPI
  187049. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187050. png_error_ptr error_fn, png_error_ptr warn_fn)
  187051. {
  187052. #ifdef PNG_USER_MEM_SUPPORTED
  187053. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187054. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187055. }
  187056. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187057. png_structp PNGAPI
  187058. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187059. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187060. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187061. {
  187062. #endif /* PNG_USER_MEM_SUPPORTED */
  187063. png_structp png_ptr;
  187064. #ifdef PNG_SETJMP_SUPPORTED
  187065. #ifdef USE_FAR_KEYWORD
  187066. jmp_buf jmpbuf;
  187067. #endif
  187068. #endif
  187069. int i;
  187070. png_debug(1, "in png_create_read_struct\n");
  187071. #ifdef PNG_USER_MEM_SUPPORTED
  187072. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187073. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187074. #else
  187075. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187076. #endif
  187077. if (png_ptr == NULL)
  187078. return (NULL);
  187079. /* added at libpng-1.2.6 */
  187080. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187081. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187082. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187083. #endif
  187084. #ifdef PNG_SETJMP_SUPPORTED
  187085. #ifdef USE_FAR_KEYWORD
  187086. if (setjmp(jmpbuf))
  187087. #else
  187088. if (setjmp(png_ptr->jmpbuf))
  187089. #endif
  187090. {
  187091. png_free(png_ptr, png_ptr->zbuf);
  187092. png_ptr->zbuf=NULL;
  187093. #ifdef PNG_USER_MEM_SUPPORTED
  187094. png_destroy_struct_2((png_voidp)png_ptr,
  187095. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187096. #else
  187097. png_destroy_struct((png_voidp)png_ptr);
  187098. #endif
  187099. return (NULL);
  187100. }
  187101. #ifdef USE_FAR_KEYWORD
  187102. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187103. #endif
  187104. #endif
  187105. #ifdef PNG_USER_MEM_SUPPORTED
  187106. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187107. #endif
  187108. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187109. i=0;
  187110. do
  187111. {
  187112. if(user_png_ver[i] != png_libpng_ver[i])
  187113. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187114. } while (png_libpng_ver[i++]);
  187115. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187116. {
  187117. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187118. * we must recompile any applications that use any older library version.
  187119. * For versions after libpng 1.0, we will be compatible, so we need
  187120. * only check the first digit.
  187121. */
  187122. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187123. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187124. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187125. {
  187126. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187127. char msg[80];
  187128. if (user_png_ver)
  187129. {
  187130. png_snprintf(msg, 80,
  187131. "Application was compiled with png.h from libpng-%.20s",
  187132. user_png_ver);
  187133. png_warning(png_ptr, msg);
  187134. }
  187135. png_snprintf(msg, 80,
  187136. "Application is running with png.c from libpng-%.20s",
  187137. png_libpng_ver);
  187138. png_warning(png_ptr, msg);
  187139. #endif
  187140. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187141. png_ptr->flags=0;
  187142. #endif
  187143. png_error(png_ptr,
  187144. "Incompatible libpng version in application and library");
  187145. }
  187146. }
  187147. /* initialize zbuf - compression buffer */
  187148. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187149. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187150. (png_uint_32)png_ptr->zbuf_size);
  187151. png_ptr->zstream.zalloc = png_zalloc;
  187152. png_ptr->zstream.zfree = png_zfree;
  187153. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187154. switch (inflateInit(&png_ptr->zstream))
  187155. {
  187156. case Z_OK: /* Do nothing */ break;
  187157. case Z_MEM_ERROR:
  187158. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187159. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187160. default: png_error(png_ptr, "Unknown zlib error");
  187161. }
  187162. png_ptr->zstream.next_out = png_ptr->zbuf;
  187163. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187164. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187165. #ifdef PNG_SETJMP_SUPPORTED
  187166. /* Applications that neglect to set up their own setjmp() and then encounter
  187167. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187168. abort instead of returning. */
  187169. #ifdef USE_FAR_KEYWORD
  187170. if (setjmp(jmpbuf))
  187171. PNG_ABORT();
  187172. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187173. #else
  187174. if (setjmp(png_ptr->jmpbuf))
  187175. PNG_ABORT();
  187176. #endif
  187177. #endif
  187178. return (png_ptr);
  187179. }
  187180. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187181. /* Initialize PNG structure for reading, and allocate any memory needed.
  187182. This interface is deprecated in favour of the png_create_read_struct(),
  187183. and it will disappear as of libpng-1.3.0. */
  187184. #undef png_read_init
  187185. void PNGAPI
  187186. png_read_init(png_structp png_ptr)
  187187. {
  187188. /* We only come here via pre-1.0.7-compiled applications */
  187189. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187190. }
  187191. void PNGAPI
  187192. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187193. png_size_t png_struct_size, png_size_t png_info_size)
  187194. {
  187195. /* We only come here via pre-1.0.12-compiled applications */
  187196. if(png_ptr == NULL) return;
  187197. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187198. if(png_sizeof(png_struct) > png_struct_size ||
  187199. png_sizeof(png_info) > png_info_size)
  187200. {
  187201. char msg[80];
  187202. png_ptr->warning_fn=NULL;
  187203. if (user_png_ver)
  187204. {
  187205. png_snprintf(msg, 80,
  187206. "Application was compiled with png.h from libpng-%.20s",
  187207. user_png_ver);
  187208. png_warning(png_ptr, msg);
  187209. }
  187210. png_snprintf(msg, 80,
  187211. "Application is running with png.c from libpng-%.20s",
  187212. png_libpng_ver);
  187213. png_warning(png_ptr, msg);
  187214. }
  187215. #endif
  187216. if(png_sizeof(png_struct) > png_struct_size)
  187217. {
  187218. png_ptr->error_fn=NULL;
  187219. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187220. png_ptr->flags=0;
  187221. #endif
  187222. png_error(png_ptr,
  187223. "The png struct allocated by the application for reading is too small.");
  187224. }
  187225. if(png_sizeof(png_info) > png_info_size)
  187226. {
  187227. png_ptr->error_fn=NULL;
  187228. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187229. png_ptr->flags=0;
  187230. #endif
  187231. png_error(png_ptr,
  187232. "The info struct allocated by application for reading is too small.");
  187233. }
  187234. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187235. }
  187236. #endif /* PNG_1_0_X || PNG_1_2_X */
  187237. void PNGAPI
  187238. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187239. png_size_t png_struct_size)
  187240. {
  187241. #ifdef PNG_SETJMP_SUPPORTED
  187242. jmp_buf tmp_jmp; /* to save current jump buffer */
  187243. #endif
  187244. int i=0;
  187245. png_structp png_ptr=*ptr_ptr;
  187246. if(png_ptr == NULL) return;
  187247. do
  187248. {
  187249. if(user_png_ver[i] != png_libpng_ver[i])
  187250. {
  187251. #ifdef PNG_LEGACY_SUPPORTED
  187252. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187253. #else
  187254. png_ptr->warning_fn=NULL;
  187255. png_warning(png_ptr,
  187256. "Application uses deprecated png_read_init() and should be recompiled.");
  187257. break;
  187258. #endif
  187259. }
  187260. } while (png_libpng_ver[i++]);
  187261. png_debug(1, "in png_read_init_3\n");
  187262. #ifdef PNG_SETJMP_SUPPORTED
  187263. /* save jump buffer and error functions */
  187264. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187265. #endif
  187266. if(png_sizeof(png_struct) > png_struct_size)
  187267. {
  187268. png_destroy_struct(png_ptr);
  187269. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187270. png_ptr = *ptr_ptr;
  187271. }
  187272. /* reset all variables to 0 */
  187273. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187274. #ifdef PNG_SETJMP_SUPPORTED
  187275. /* restore jump buffer */
  187276. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187277. #endif
  187278. /* added at libpng-1.2.6 */
  187279. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187280. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187281. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187282. #endif
  187283. /* initialize zbuf - compression buffer */
  187284. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187285. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187286. (png_uint_32)png_ptr->zbuf_size);
  187287. png_ptr->zstream.zalloc = png_zalloc;
  187288. png_ptr->zstream.zfree = png_zfree;
  187289. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187290. switch (inflateInit(&png_ptr->zstream))
  187291. {
  187292. case Z_OK: /* Do nothing */ break;
  187293. case Z_MEM_ERROR:
  187294. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187295. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187296. default: png_error(png_ptr, "Unknown zlib error");
  187297. }
  187298. png_ptr->zstream.next_out = png_ptr->zbuf;
  187299. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187300. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187301. }
  187302. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187303. /* Read the information before the actual image data. This has been
  187304. * changed in v0.90 to allow reading a file that already has the magic
  187305. * bytes read from the stream. You can tell libpng how many bytes have
  187306. * been read from the beginning of the stream (up to the maximum of 8)
  187307. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187308. * here. The application can then have access to the signature bytes we
  187309. * read if it is determined that this isn't a valid PNG file.
  187310. */
  187311. void PNGAPI
  187312. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187313. {
  187314. if(png_ptr == NULL) return;
  187315. png_debug(1, "in png_read_info\n");
  187316. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187317. if (png_ptr->sig_bytes < 8)
  187318. {
  187319. png_size_t num_checked = png_ptr->sig_bytes,
  187320. num_to_check = 8 - num_checked;
  187321. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187322. png_ptr->sig_bytes = 8;
  187323. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187324. {
  187325. if (num_checked < 4 &&
  187326. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187327. png_error(png_ptr, "Not a PNG file");
  187328. else
  187329. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187330. }
  187331. if (num_checked < 3)
  187332. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187333. }
  187334. for(;;)
  187335. {
  187336. #ifdef PNG_USE_LOCAL_ARRAYS
  187337. PNG_CONST PNG_IHDR;
  187338. PNG_CONST PNG_IDAT;
  187339. PNG_CONST PNG_IEND;
  187340. PNG_CONST PNG_PLTE;
  187341. #if defined(PNG_READ_bKGD_SUPPORTED)
  187342. PNG_CONST PNG_bKGD;
  187343. #endif
  187344. #if defined(PNG_READ_cHRM_SUPPORTED)
  187345. PNG_CONST PNG_cHRM;
  187346. #endif
  187347. #if defined(PNG_READ_gAMA_SUPPORTED)
  187348. PNG_CONST PNG_gAMA;
  187349. #endif
  187350. #if defined(PNG_READ_hIST_SUPPORTED)
  187351. PNG_CONST PNG_hIST;
  187352. #endif
  187353. #if defined(PNG_READ_iCCP_SUPPORTED)
  187354. PNG_CONST PNG_iCCP;
  187355. #endif
  187356. #if defined(PNG_READ_iTXt_SUPPORTED)
  187357. PNG_CONST PNG_iTXt;
  187358. #endif
  187359. #if defined(PNG_READ_oFFs_SUPPORTED)
  187360. PNG_CONST PNG_oFFs;
  187361. #endif
  187362. #if defined(PNG_READ_pCAL_SUPPORTED)
  187363. PNG_CONST PNG_pCAL;
  187364. #endif
  187365. #if defined(PNG_READ_pHYs_SUPPORTED)
  187366. PNG_CONST PNG_pHYs;
  187367. #endif
  187368. #if defined(PNG_READ_sBIT_SUPPORTED)
  187369. PNG_CONST PNG_sBIT;
  187370. #endif
  187371. #if defined(PNG_READ_sCAL_SUPPORTED)
  187372. PNG_CONST PNG_sCAL;
  187373. #endif
  187374. #if defined(PNG_READ_sPLT_SUPPORTED)
  187375. PNG_CONST PNG_sPLT;
  187376. #endif
  187377. #if defined(PNG_READ_sRGB_SUPPORTED)
  187378. PNG_CONST PNG_sRGB;
  187379. #endif
  187380. #if defined(PNG_READ_tEXt_SUPPORTED)
  187381. PNG_CONST PNG_tEXt;
  187382. #endif
  187383. #if defined(PNG_READ_tIME_SUPPORTED)
  187384. PNG_CONST PNG_tIME;
  187385. #endif
  187386. #if defined(PNG_READ_tRNS_SUPPORTED)
  187387. PNG_CONST PNG_tRNS;
  187388. #endif
  187389. #if defined(PNG_READ_zTXt_SUPPORTED)
  187390. PNG_CONST PNG_zTXt;
  187391. #endif
  187392. #endif /* PNG_USE_LOCAL_ARRAYS */
  187393. png_byte chunk_length[4];
  187394. png_uint_32 length;
  187395. png_read_data(png_ptr, chunk_length, 4);
  187396. length = png_get_uint_31(png_ptr,chunk_length);
  187397. png_reset_crc(png_ptr);
  187398. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187399. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187400. length);
  187401. /* This should be a binary subdivision search or a hash for
  187402. * matching the chunk name rather than a linear search.
  187403. */
  187404. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187405. if(png_ptr->mode & PNG_AFTER_IDAT)
  187406. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187407. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187408. png_handle_IHDR(png_ptr, info_ptr, length);
  187409. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187410. png_handle_IEND(png_ptr, info_ptr, length);
  187411. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187412. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187413. {
  187414. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187415. png_ptr->mode |= PNG_HAVE_IDAT;
  187416. png_handle_unknown(png_ptr, info_ptr, length);
  187417. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187418. png_ptr->mode |= PNG_HAVE_PLTE;
  187419. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187420. {
  187421. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187422. png_error(png_ptr, "Missing IHDR before IDAT");
  187423. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187424. !(png_ptr->mode & PNG_HAVE_PLTE))
  187425. png_error(png_ptr, "Missing PLTE before IDAT");
  187426. break;
  187427. }
  187428. }
  187429. #endif
  187430. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187431. png_handle_PLTE(png_ptr, info_ptr, length);
  187432. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187433. {
  187434. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187435. png_error(png_ptr, "Missing IHDR before IDAT");
  187436. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187437. !(png_ptr->mode & PNG_HAVE_PLTE))
  187438. png_error(png_ptr, "Missing PLTE before IDAT");
  187439. png_ptr->idat_size = length;
  187440. png_ptr->mode |= PNG_HAVE_IDAT;
  187441. break;
  187442. }
  187443. #if defined(PNG_READ_bKGD_SUPPORTED)
  187444. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187445. png_handle_bKGD(png_ptr, info_ptr, length);
  187446. #endif
  187447. #if defined(PNG_READ_cHRM_SUPPORTED)
  187448. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187449. png_handle_cHRM(png_ptr, info_ptr, length);
  187450. #endif
  187451. #if defined(PNG_READ_gAMA_SUPPORTED)
  187452. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187453. png_handle_gAMA(png_ptr, info_ptr, length);
  187454. #endif
  187455. #if defined(PNG_READ_hIST_SUPPORTED)
  187456. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187457. png_handle_hIST(png_ptr, info_ptr, length);
  187458. #endif
  187459. #if defined(PNG_READ_oFFs_SUPPORTED)
  187460. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187461. png_handle_oFFs(png_ptr, info_ptr, length);
  187462. #endif
  187463. #if defined(PNG_READ_pCAL_SUPPORTED)
  187464. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187465. png_handle_pCAL(png_ptr, info_ptr, length);
  187466. #endif
  187467. #if defined(PNG_READ_sCAL_SUPPORTED)
  187468. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187469. png_handle_sCAL(png_ptr, info_ptr, length);
  187470. #endif
  187471. #if defined(PNG_READ_pHYs_SUPPORTED)
  187472. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187473. png_handle_pHYs(png_ptr, info_ptr, length);
  187474. #endif
  187475. #if defined(PNG_READ_sBIT_SUPPORTED)
  187476. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187477. png_handle_sBIT(png_ptr, info_ptr, length);
  187478. #endif
  187479. #if defined(PNG_READ_sRGB_SUPPORTED)
  187480. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187481. png_handle_sRGB(png_ptr, info_ptr, length);
  187482. #endif
  187483. #if defined(PNG_READ_iCCP_SUPPORTED)
  187484. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187485. png_handle_iCCP(png_ptr, info_ptr, length);
  187486. #endif
  187487. #if defined(PNG_READ_sPLT_SUPPORTED)
  187488. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187489. png_handle_sPLT(png_ptr, info_ptr, length);
  187490. #endif
  187491. #if defined(PNG_READ_tEXt_SUPPORTED)
  187492. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187493. png_handle_tEXt(png_ptr, info_ptr, length);
  187494. #endif
  187495. #if defined(PNG_READ_tIME_SUPPORTED)
  187496. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187497. png_handle_tIME(png_ptr, info_ptr, length);
  187498. #endif
  187499. #if defined(PNG_READ_tRNS_SUPPORTED)
  187500. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187501. png_handle_tRNS(png_ptr, info_ptr, length);
  187502. #endif
  187503. #if defined(PNG_READ_zTXt_SUPPORTED)
  187504. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187505. png_handle_zTXt(png_ptr, info_ptr, length);
  187506. #endif
  187507. #if defined(PNG_READ_iTXt_SUPPORTED)
  187508. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187509. png_handle_iTXt(png_ptr, info_ptr, length);
  187510. #endif
  187511. else
  187512. png_handle_unknown(png_ptr, info_ptr, length);
  187513. }
  187514. }
  187515. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187516. /* optional call to update the users info_ptr structure */
  187517. void PNGAPI
  187518. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187519. {
  187520. png_debug(1, "in png_read_update_info\n");
  187521. if(png_ptr == NULL) return;
  187522. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187523. png_read_start_row(png_ptr);
  187524. else
  187525. png_warning(png_ptr,
  187526. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187527. png_read_transform_info(png_ptr, info_ptr);
  187528. }
  187529. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187530. /* Initialize palette, background, etc, after transformations
  187531. * are set, but before any reading takes place. This allows
  187532. * the user to obtain a gamma-corrected palette, for example.
  187533. * If the user doesn't call this, we will do it ourselves.
  187534. */
  187535. void PNGAPI
  187536. png_start_read_image(png_structp png_ptr)
  187537. {
  187538. png_debug(1, "in png_start_read_image\n");
  187539. if(png_ptr == NULL) return;
  187540. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187541. png_read_start_row(png_ptr);
  187542. }
  187543. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187544. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187545. void PNGAPI
  187546. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187547. {
  187548. #ifdef PNG_USE_LOCAL_ARRAYS
  187549. PNG_CONST PNG_IDAT;
  187550. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187551. 0xff};
  187552. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187553. #endif
  187554. int ret;
  187555. if(png_ptr == NULL) return;
  187556. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187557. png_ptr->row_number, png_ptr->pass);
  187558. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187559. png_read_start_row(png_ptr);
  187560. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187561. {
  187562. /* check for transforms that have been set but were defined out */
  187563. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187564. if (png_ptr->transformations & PNG_INVERT_MONO)
  187565. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187566. #endif
  187567. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187568. if (png_ptr->transformations & PNG_FILLER)
  187569. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187570. #endif
  187571. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187572. if (png_ptr->transformations & PNG_PACKSWAP)
  187573. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187574. #endif
  187575. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187576. if (png_ptr->transformations & PNG_PACK)
  187577. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187578. #endif
  187579. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187580. if (png_ptr->transformations & PNG_SHIFT)
  187581. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187582. #endif
  187583. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187584. if (png_ptr->transformations & PNG_BGR)
  187585. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187586. #endif
  187587. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187588. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187589. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187590. #endif
  187591. }
  187592. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187593. /* if interlaced and we do not need a new row, combine row and return */
  187594. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187595. {
  187596. switch (png_ptr->pass)
  187597. {
  187598. case 0:
  187599. if (png_ptr->row_number & 0x07)
  187600. {
  187601. if (dsp_row != NULL)
  187602. png_combine_row(png_ptr, dsp_row,
  187603. png_pass_dsp_mask[png_ptr->pass]);
  187604. png_read_finish_row(png_ptr);
  187605. return;
  187606. }
  187607. break;
  187608. case 1:
  187609. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187610. {
  187611. if (dsp_row != NULL)
  187612. png_combine_row(png_ptr, dsp_row,
  187613. png_pass_dsp_mask[png_ptr->pass]);
  187614. png_read_finish_row(png_ptr);
  187615. return;
  187616. }
  187617. break;
  187618. case 2:
  187619. if ((png_ptr->row_number & 0x07) != 4)
  187620. {
  187621. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187622. png_combine_row(png_ptr, dsp_row,
  187623. png_pass_dsp_mask[png_ptr->pass]);
  187624. png_read_finish_row(png_ptr);
  187625. return;
  187626. }
  187627. break;
  187628. case 3:
  187629. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187630. {
  187631. if (dsp_row != NULL)
  187632. png_combine_row(png_ptr, dsp_row,
  187633. png_pass_dsp_mask[png_ptr->pass]);
  187634. png_read_finish_row(png_ptr);
  187635. return;
  187636. }
  187637. break;
  187638. case 4:
  187639. if ((png_ptr->row_number & 3) != 2)
  187640. {
  187641. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187642. png_combine_row(png_ptr, dsp_row,
  187643. png_pass_dsp_mask[png_ptr->pass]);
  187644. png_read_finish_row(png_ptr);
  187645. return;
  187646. }
  187647. break;
  187648. case 5:
  187649. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187650. {
  187651. if (dsp_row != NULL)
  187652. png_combine_row(png_ptr, dsp_row,
  187653. png_pass_dsp_mask[png_ptr->pass]);
  187654. png_read_finish_row(png_ptr);
  187655. return;
  187656. }
  187657. break;
  187658. case 6:
  187659. if (!(png_ptr->row_number & 1))
  187660. {
  187661. png_read_finish_row(png_ptr);
  187662. return;
  187663. }
  187664. break;
  187665. }
  187666. }
  187667. #endif
  187668. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187669. png_error(png_ptr, "Invalid attempt to read row data");
  187670. png_ptr->zstream.next_out = png_ptr->row_buf;
  187671. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187672. do
  187673. {
  187674. if (!(png_ptr->zstream.avail_in))
  187675. {
  187676. while (!png_ptr->idat_size)
  187677. {
  187678. png_byte chunk_length[4];
  187679. png_crc_finish(png_ptr, 0);
  187680. png_read_data(png_ptr, chunk_length, 4);
  187681. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187682. png_reset_crc(png_ptr);
  187683. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187684. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187685. png_error(png_ptr, "Not enough image data");
  187686. }
  187687. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187688. png_ptr->zstream.next_in = png_ptr->zbuf;
  187689. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187690. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187691. png_crc_read(png_ptr, png_ptr->zbuf,
  187692. (png_size_t)png_ptr->zstream.avail_in);
  187693. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187694. }
  187695. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187696. if (ret == Z_STREAM_END)
  187697. {
  187698. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187699. png_ptr->idat_size)
  187700. png_error(png_ptr, "Extra compressed data");
  187701. png_ptr->mode |= PNG_AFTER_IDAT;
  187702. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187703. break;
  187704. }
  187705. if (ret != Z_OK)
  187706. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187707. "Decompression error");
  187708. } while (png_ptr->zstream.avail_out);
  187709. png_ptr->row_info.color_type = png_ptr->color_type;
  187710. png_ptr->row_info.width = png_ptr->iwidth;
  187711. png_ptr->row_info.channels = png_ptr->channels;
  187712. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187713. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187714. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187715. png_ptr->row_info.width);
  187716. if(png_ptr->row_buf[0])
  187717. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187718. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187719. (int)(png_ptr->row_buf[0]));
  187720. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187721. png_ptr->rowbytes + 1);
  187722. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187723. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187724. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187725. {
  187726. /* Intrapixel differencing */
  187727. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187728. }
  187729. #endif
  187730. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187731. png_do_read_transformations(png_ptr);
  187732. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187733. /* blow up interlaced rows to full size */
  187734. if (png_ptr->interlaced &&
  187735. (png_ptr->transformations & PNG_INTERLACE))
  187736. {
  187737. if (png_ptr->pass < 6)
  187738. /* old interface (pre-1.0.9):
  187739. png_do_read_interlace(&(png_ptr->row_info),
  187740. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187741. */
  187742. png_do_read_interlace(png_ptr);
  187743. if (dsp_row != NULL)
  187744. png_combine_row(png_ptr, dsp_row,
  187745. png_pass_dsp_mask[png_ptr->pass]);
  187746. if (row != NULL)
  187747. png_combine_row(png_ptr, row,
  187748. png_pass_mask[png_ptr->pass]);
  187749. }
  187750. else
  187751. #endif
  187752. {
  187753. if (row != NULL)
  187754. png_combine_row(png_ptr, row, 0xff);
  187755. if (dsp_row != NULL)
  187756. png_combine_row(png_ptr, dsp_row, 0xff);
  187757. }
  187758. png_read_finish_row(png_ptr);
  187759. if (png_ptr->read_row_fn != NULL)
  187760. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187761. }
  187762. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187763. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187764. /* Read one or more rows of image data. If the image is interlaced,
  187765. * and png_set_interlace_handling() has been called, the rows need to
  187766. * contain the contents of the rows from the previous pass. If the
  187767. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187768. * called, the rows contents must be initialized to the contents of the
  187769. * screen.
  187770. *
  187771. * "row" holds the actual image, and pixels are placed in it
  187772. * as they arrive. If the image is displayed after each pass, it will
  187773. * appear to "sparkle" in. "display_row" can be used to display a
  187774. * "chunky" progressive image, with finer detail added as it becomes
  187775. * available. If you do not want this "chunky" display, you may pass
  187776. * NULL for display_row. If you do not want the sparkle display, and
  187777. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187778. * If you have called png_handle_alpha(), and the image has either an
  187779. * alpha channel or a transparency chunk, you must provide a buffer for
  187780. * rows. In this case, you do not have to provide a display_row buffer
  187781. * also, but you may. If the image is not interlaced, or if you have
  187782. * not called png_set_interlace_handling(), the display_row buffer will
  187783. * be ignored, so pass NULL to it.
  187784. *
  187785. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187786. */
  187787. void PNGAPI
  187788. png_read_rows(png_structp png_ptr, png_bytepp row,
  187789. png_bytepp display_row, png_uint_32 num_rows)
  187790. {
  187791. png_uint_32 i;
  187792. png_bytepp rp;
  187793. png_bytepp dp;
  187794. png_debug(1, "in png_read_rows\n");
  187795. if(png_ptr == NULL) return;
  187796. rp = row;
  187797. dp = display_row;
  187798. if (rp != NULL && dp != NULL)
  187799. for (i = 0; i < num_rows; i++)
  187800. {
  187801. png_bytep rptr = *rp++;
  187802. png_bytep dptr = *dp++;
  187803. png_read_row(png_ptr, rptr, dptr);
  187804. }
  187805. else if(rp != NULL)
  187806. for (i = 0; i < num_rows; i++)
  187807. {
  187808. png_bytep rptr = *rp;
  187809. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187810. rp++;
  187811. }
  187812. else if(dp != NULL)
  187813. for (i = 0; i < num_rows; i++)
  187814. {
  187815. png_bytep dptr = *dp;
  187816. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187817. dp++;
  187818. }
  187819. }
  187820. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187821. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187822. /* Read the entire image. If the image has an alpha channel or a tRNS
  187823. * chunk, and you have called png_handle_alpha()[*], you will need to
  187824. * initialize the image to the current image that PNG will be overlaying.
  187825. * We set the num_rows again here, in case it was incorrectly set in
  187826. * png_read_start_row() by a call to png_read_update_info() or
  187827. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187828. * prior to either of these functions like it should have been. You can
  187829. * only call this function once. If you desire to have an image for
  187830. * each pass of a interlaced image, use png_read_rows() instead.
  187831. *
  187832. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187833. */
  187834. void PNGAPI
  187835. png_read_image(png_structp png_ptr, png_bytepp image)
  187836. {
  187837. png_uint_32 i,image_height;
  187838. int pass, j;
  187839. png_bytepp rp;
  187840. png_debug(1, "in png_read_image\n");
  187841. if(png_ptr == NULL) return;
  187842. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187843. pass = png_set_interlace_handling(png_ptr);
  187844. #else
  187845. if (png_ptr->interlaced)
  187846. png_error(png_ptr,
  187847. "Cannot read interlaced image -- interlace handler disabled.");
  187848. pass = 1;
  187849. #endif
  187850. image_height=png_ptr->height;
  187851. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187852. for (j = 0; j < pass; j++)
  187853. {
  187854. rp = image;
  187855. for (i = 0; i < image_height; i++)
  187856. {
  187857. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187858. rp++;
  187859. }
  187860. }
  187861. }
  187862. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187863. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187864. /* Read the end of the PNG file. Will not read past the end of the
  187865. * file, will verify the end is accurate, and will read any comments
  187866. * or time information at the end of the file, if info is not NULL.
  187867. */
  187868. void PNGAPI
  187869. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187870. {
  187871. png_byte chunk_length[4];
  187872. png_uint_32 length;
  187873. png_debug(1, "in png_read_end\n");
  187874. if(png_ptr == NULL) return;
  187875. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187876. do
  187877. {
  187878. #ifdef PNG_USE_LOCAL_ARRAYS
  187879. PNG_CONST PNG_IHDR;
  187880. PNG_CONST PNG_IDAT;
  187881. PNG_CONST PNG_IEND;
  187882. PNG_CONST PNG_PLTE;
  187883. #if defined(PNG_READ_bKGD_SUPPORTED)
  187884. PNG_CONST PNG_bKGD;
  187885. #endif
  187886. #if defined(PNG_READ_cHRM_SUPPORTED)
  187887. PNG_CONST PNG_cHRM;
  187888. #endif
  187889. #if defined(PNG_READ_gAMA_SUPPORTED)
  187890. PNG_CONST PNG_gAMA;
  187891. #endif
  187892. #if defined(PNG_READ_hIST_SUPPORTED)
  187893. PNG_CONST PNG_hIST;
  187894. #endif
  187895. #if defined(PNG_READ_iCCP_SUPPORTED)
  187896. PNG_CONST PNG_iCCP;
  187897. #endif
  187898. #if defined(PNG_READ_iTXt_SUPPORTED)
  187899. PNG_CONST PNG_iTXt;
  187900. #endif
  187901. #if defined(PNG_READ_oFFs_SUPPORTED)
  187902. PNG_CONST PNG_oFFs;
  187903. #endif
  187904. #if defined(PNG_READ_pCAL_SUPPORTED)
  187905. PNG_CONST PNG_pCAL;
  187906. #endif
  187907. #if defined(PNG_READ_pHYs_SUPPORTED)
  187908. PNG_CONST PNG_pHYs;
  187909. #endif
  187910. #if defined(PNG_READ_sBIT_SUPPORTED)
  187911. PNG_CONST PNG_sBIT;
  187912. #endif
  187913. #if defined(PNG_READ_sCAL_SUPPORTED)
  187914. PNG_CONST PNG_sCAL;
  187915. #endif
  187916. #if defined(PNG_READ_sPLT_SUPPORTED)
  187917. PNG_CONST PNG_sPLT;
  187918. #endif
  187919. #if defined(PNG_READ_sRGB_SUPPORTED)
  187920. PNG_CONST PNG_sRGB;
  187921. #endif
  187922. #if defined(PNG_READ_tEXt_SUPPORTED)
  187923. PNG_CONST PNG_tEXt;
  187924. #endif
  187925. #if defined(PNG_READ_tIME_SUPPORTED)
  187926. PNG_CONST PNG_tIME;
  187927. #endif
  187928. #if defined(PNG_READ_tRNS_SUPPORTED)
  187929. PNG_CONST PNG_tRNS;
  187930. #endif
  187931. #if defined(PNG_READ_zTXt_SUPPORTED)
  187932. PNG_CONST PNG_zTXt;
  187933. #endif
  187934. #endif /* PNG_USE_LOCAL_ARRAYS */
  187935. png_read_data(png_ptr, chunk_length, 4);
  187936. length = png_get_uint_31(png_ptr,chunk_length);
  187937. png_reset_crc(png_ptr);
  187938. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187939. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187940. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187941. png_handle_IHDR(png_ptr, info_ptr, length);
  187942. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187943. png_handle_IEND(png_ptr, info_ptr, length);
  187944. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187945. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187946. {
  187947. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187948. {
  187949. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187950. png_error(png_ptr, "Too many IDAT's found");
  187951. }
  187952. png_handle_unknown(png_ptr, info_ptr, length);
  187953. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187954. png_ptr->mode |= PNG_HAVE_PLTE;
  187955. }
  187956. #endif
  187957. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187958. {
  187959. /* Zero length IDATs are legal after the last IDAT has been
  187960. * read, but not after other chunks have been read.
  187961. */
  187962. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187963. png_error(png_ptr, "Too many IDAT's found");
  187964. png_crc_finish(png_ptr, length);
  187965. }
  187966. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187967. png_handle_PLTE(png_ptr, info_ptr, length);
  187968. #if defined(PNG_READ_bKGD_SUPPORTED)
  187969. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187970. png_handle_bKGD(png_ptr, info_ptr, length);
  187971. #endif
  187972. #if defined(PNG_READ_cHRM_SUPPORTED)
  187973. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187974. png_handle_cHRM(png_ptr, info_ptr, length);
  187975. #endif
  187976. #if defined(PNG_READ_gAMA_SUPPORTED)
  187977. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187978. png_handle_gAMA(png_ptr, info_ptr, length);
  187979. #endif
  187980. #if defined(PNG_READ_hIST_SUPPORTED)
  187981. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187982. png_handle_hIST(png_ptr, info_ptr, length);
  187983. #endif
  187984. #if defined(PNG_READ_oFFs_SUPPORTED)
  187985. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187986. png_handle_oFFs(png_ptr, info_ptr, length);
  187987. #endif
  187988. #if defined(PNG_READ_pCAL_SUPPORTED)
  187989. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187990. png_handle_pCAL(png_ptr, info_ptr, length);
  187991. #endif
  187992. #if defined(PNG_READ_sCAL_SUPPORTED)
  187993. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187994. png_handle_sCAL(png_ptr, info_ptr, length);
  187995. #endif
  187996. #if defined(PNG_READ_pHYs_SUPPORTED)
  187997. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187998. png_handle_pHYs(png_ptr, info_ptr, length);
  187999. #endif
  188000. #if defined(PNG_READ_sBIT_SUPPORTED)
  188001. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188002. png_handle_sBIT(png_ptr, info_ptr, length);
  188003. #endif
  188004. #if defined(PNG_READ_sRGB_SUPPORTED)
  188005. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188006. png_handle_sRGB(png_ptr, info_ptr, length);
  188007. #endif
  188008. #if defined(PNG_READ_iCCP_SUPPORTED)
  188009. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188010. png_handle_iCCP(png_ptr, info_ptr, length);
  188011. #endif
  188012. #if defined(PNG_READ_sPLT_SUPPORTED)
  188013. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188014. png_handle_sPLT(png_ptr, info_ptr, length);
  188015. #endif
  188016. #if defined(PNG_READ_tEXt_SUPPORTED)
  188017. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188018. png_handle_tEXt(png_ptr, info_ptr, length);
  188019. #endif
  188020. #if defined(PNG_READ_tIME_SUPPORTED)
  188021. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188022. png_handle_tIME(png_ptr, info_ptr, length);
  188023. #endif
  188024. #if defined(PNG_READ_tRNS_SUPPORTED)
  188025. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188026. png_handle_tRNS(png_ptr, info_ptr, length);
  188027. #endif
  188028. #if defined(PNG_READ_zTXt_SUPPORTED)
  188029. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188030. png_handle_zTXt(png_ptr, info_ptr, length);
  188031. #endif
  188032. #if defined(PNG_READ_iTXt_SUPPORTED)
  188033. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188034. png_handle_iTXt(png_ptr, info_ptr, length);
  188035. #endif
  188036. else
  188037. png_handle_unknown(png_ptr, info_ptr, length);
  188038. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188039. }
  188040. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188041. /* free all memory used by the read */
  188042. void PNGAPI
  188043. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188044. png_infopp end_info_ptr_ptr)
  188045. {
  188046. png_structp png_ptr = NULL;
  188047. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188048. #ifdef PNG_USER_MEM_SUPPORTED
  188049. png_free_ptr free_fn;
  188050. png_voidp mem_ptr;
  188051. #endif
  188052. png_debug(1, "in png_destroy_read_struct\n");
  188053. if (png_ptr_ptr != NULL)
  188054. png_ptr = *png_ptr_ptr;
  188055. if (info_ptr_ptr != NULL)
  188056. info_ptr = *info_ptr_ptr;
  188057. if (end_info_ptr_ptr != NULL)
  188058. end_info_ptr = *end_info_ptr_ptr;
  188059. #ifdef PNG_USER_MEM_SUPPORTED
  188060. free_fn = png_ptr->free_fn;
  188061. mem_ptr = png_ptr->mem_ptr;
  188062. #endif
  188063. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188064. if (info_ptr != NULL)
  188065. {
  188066. #if defined(PNG_TEXT_SUPPORTED)
  188067. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188068. #endif
  188069. #ifdef PNG_USER_MEM_SUPPORTED
  188070. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188071. (png_voidp)mem_ptr);
  188072. #else
  188073. png_destroy_struct((png_voidp)info_ptr);
  188074. #endif
  188075. *info_ptr_ptr = NULL;
  188076. }
  188077. if (end_info_ptr != NULL)
  188078. {
  188079. #if defined(PNG_READ_TEXT_SUPPORTED)
  188080. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188081. #endif
  188082. #ifdef PNG_USER_MEM_SUPPORTED
  188083. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188084. (png_voidp)mem_ptr);
  188085. #else
  188086. png_destroy_struct((png_voidp)end_info_ptr);
  188087. #endif
  188088. *end_info_ptr_ptr = NULL;
  188089. }
  188090. if (png_ptr != NULL)
  188091. {
  188092. #ifdef PNG_USER_MEM_SUPPORTED
  188093. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188094. (png_voidp)mem_ptr);
  188095. #else
  188096. png_destroy_struct((png_voidp)png_ptr);
  188097. #endif
  188098. *png_ptr_ptr = NULL;
  188099. }
  188100. }
  188101. /* free all memory used by the read (old method) */
  188102. void /* PRIVATE */
  188103. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188104. {
  188105. #ifdef PNG_SETJMP_SUPPORTED
  188106. jmp_buf tmp_jmp;
  188107. #endif
  188108. png_error_ptr error_fn;
  188109. png_error_ptr warning_fn;
  188110. png_voidp error_ptr;
  188111. #ifdef PNG_USER_MEM_SUPPORTED
  188112. png_free_ptr free_fn;
  188113. #endif
  188114. png_debug(1, "in png_read_destroy\n");
  188115. if (info_ptr != NULL)
  188116. png_info_destroy(png_ptr, info_ptr);
  188117. if (end_info_ptr != NULL)
  188118. png_info_destroy(png_ptr, end_info_ptr);
  188119. png_free(png_ptr, png_ptr->zbuf);
  188120. png_free(png_ptr, png_ptr->big_row_buf);
  188121. png_free(png_ptr, png_ptr->prev_row);
  188122. #if defined(PNG_READ_DITHER_SUPPORTED)
  188123. png_free(png_ptr, png_ptr->palette_lookup);
  188124. png_free(png_ptr, png_ptr->dither_index);
  188125. #endif
  188126. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188127. png_free(png_ptr, png_ptr->gamma_table);
  188128. #endif
  188129. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188130. png_free(png_ptr, png_ptr->gamma_from_1);
  188131. png_free(png_ptr, png_ptr->gamma_to_1);
  188132. #endif
  188133. #ifdef PNG_FREE_ME_SUPPORTED
  188134. if (png_ptr->free_me & PNG_FREE_PLTE)
  188135. png_zfree(png_ptr, png_ptr->palette);
  188136. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188137. #else
  188138. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188139. png_zfree(png_ptr, png_ptr->palette);
  188140. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188141. #endif
  188142. #if defined(PNG_tRNS_SUPPORTED) || \
  188143. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188144. #ifdef PNG_FREE_ME_SUPPORTED
  188145. if (png_ptr->free_me & PNG_FREE_TRNS)
  188146. png_free(png_ptr, png_ptr->trans);
  188147. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188148. #else
  188149. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188150. png_free(png_ptr, png_ptr->trans);
  188151. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188152. #endif
  188153. #endif
  188154. #if defined(PNG_READ_hIST_SUPPORTED)
  188155. #ifdef PNG_FREE_ME_SUPPORTED
  188156. if (png_ptr->free_me & PNG_FREE_HIST)
  188157. png_free(png_ptr, png_ptr->hist);
  188158. png_ptr->free_me &= ~PNG_FREE_HIST;
  188159. #else
  188160. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188161. png_free(png_ptr, png_ptr->hist);
  188162. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188163. #endif
  188164. #endif
  188165. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188166. if (png_ptr->gamma_16_table != NULL)
  188167. {
  188168. int i;
  188169. int istop = (1 << (8 - png_ptr->gamma_shift));
  188170. for (i = 0; i < istop; i++)
  188171. {
  188172. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188173. }
  188174. png_free(png_ptr, png_ptr->gamma_16_table);
  188175. }
  188176. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188177. if (png_ptr->gamma_16_from_1 != NULL)
  188178. {
  188179. int i;
  188180. int istop = (1 << (8 - png_ptr->gamma_shift));
  188181. for (i = 0; i < istop; i++)
  188182. {
  188183. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188184. }
  188185. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188186. }
  188187. if (png_ptr->gamma_16_to_1 != NULL)
  188188. {
  188189. int i;
  188190. int istop = (1 << (8 - png_ptr->gamma_shift));
  188191. for (i = 0; i < istop; i++)
  188192. {
  188193. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188194. }
  188195. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188196. }
  188197. #endif
  188198. #endif
  188199. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188200. png_free(png_ptr, png_ptr->time_buffer);
  188201. #endif
  188202. inflateEnd(&png_ptr->zstream);
  188203. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188204. png_free(png_ptr, png_ptr->save_buffer);
  188205. #endif
  188206. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188207. #ifdef PNG_TEXT_SUPPORTED
  188208. png_free(png_ptr, png_ptr->current_text);
  188209. #endif /* PNG_TEXT_SUPPORTED */
  188210. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188211. /* Save the important info out of the png_struct, in case it is
  188212. * being used again.
  188213. */
  188214. #ifdef PNG_SETJMP_SUPPORTED
  188215. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188216. #endif
  188217. error_fn = png_ptr->error_fn;
  188218. warning_fn = png_ptr->warning_fn;
  188219. error_ptr = png_ptr->error_ptr;
  188220. #ifdef PNG_USER_MEM_SUPPORTED
  188221. free_fn = png_ptr->free_fn;
  188222. #endif
  188223. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188224. png_ptr->error_fn = error_fn;
  188225. png_ptr->warning_fn = warning_fn;
  188226. png_ptr->error_ptr = error_ptr;
  188227. #ifdef PNG_USER_MEM_SUPPORTED
  188228. png_ptr->free_fn = free_fn;
  188229. #endif
  188230. #ifdef PNG_SETJMP_SUPPORTED
  188231. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188232. #endif
  188233. }
  188234. void PNGAPI
  188235. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188236. {
  188237. if(png_ptr == NULL) return;
  188238. png_ptr->read_row_fn = read_row_fn;
  188239. }
  188240. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188241. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188242. void PNGAPI
  188243. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188244. int transforms,
  188245. voidp params)
  188246. {
  188247. int row;
  188248. if(png_ptr == NULL) return;
  188249. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188250. /* invert the alpha channel from opacity to transparency
  188251. */
  188252. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188253. png_set_invert_alpha(png_ptr);
  188254. #endif
  188255. /* png_read_info() gives us all of the information from the
  188256. * PNG file before the first IDAT (image data chunk).
  188257. */
  188258. png_read_info(png_ptr, info_ptr);
  188259. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188260. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188261. /* -------------- image transformations start here ------------------- */
  188262. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188263. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188264. */
  188265. if (transforms & PNG_TRANSFORM_STRIP_16)
  188266. png_set_strip_16(png_ptr);
  188267. #endif
  188268. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188269. /* Strip alpha bytes from the input data without combining with
  188270. * the background (not recommended).
  188271. */
  188272. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188273. png_set_strip_alpha(png_ptr);
  188274. #endif
  188275. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188276. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188277. * byte into separate bytes (useful for paletted and grayscale images).
  188278. */
  188279. if (transforms & PNG_TRANSFORM_PACKING)
  188280. png_set_packing(png_ptr);
  188281. #endif
  188282. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188283. /* Change the order of packed pixels to least significant bit first
  188284. * (not useful if you are using png_set_packing).
  188285. */
  188286. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188287. png_set_packswap(png_ptr);
  188288. #endif
  188289. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188290. /* Expand paletted colors into true RGB triplets
  188291. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188292. * Expand paletted or RGB images with transparency to full alpha
  188293. * channels so the data will be available as RGBA quartets.
  188294. */
  188295. if (transforms & PNG_TRANSFORM_EXPAND)
  188296. if ((png_ptr->bit_depth < 8) ||
  188297. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188298. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188299. png_set_expand(png_ptr);
  188300. #endif
  188301. /* We don't handle background color or gamma transformation or dithering.
  188302. */
  188303. #if defined(PNG_READ_INVERT_SUPPORTED)
  188304. /* invert monochrome files to have 0 as white and 1 as black
  188305. */
  188306. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188307. png_set_invert_mono(png_ptr);
  188308. #endif
  188309. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188310. /* If you want to shift the pixel values from the range [0,255] or
  188311. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188312. * colors were originally in:
  188313. */
  188314. if ((transforms & PNG_TRANSFORM_SHIFT)
  188315. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188316. {
  188317. png_color_8p sig_bit;
  188318. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188319. png_set_shift(png_ptr, sig_bit);
  188320. }
  188321. #endif
  188322. #if defined(PNG_READ_BGR_SUPPORTED)
  188323. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188324. */
  188325. if (transforms & PNG_TRANSFORM_BGR)
  188326. png_set_bgr(png_ptr);
  188327. #endif
  188328. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188329. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188330. */
  188331. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188332. png_set_swap_alpha(png_ptr);
  188333. #endif
  188334. #if defined(PNG_READ_SWAP_SUPPORTED)
  188335. /* swap bytes of 16 bit files to least significant byte first
  188336. */
  188337. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188338. png_set_swap(png_ptr);
  188339. #endif
  188340. /* We don't handle adding filler bytes */
  188341. /* Optional call to gamma correct and add the background to the palette
  188342. * and update info structure. REQUIRED if you are expecting libpng to
  188343. * update the palette for you (i.e., you selected such a transform above).
  188344. */
  188345. png_read_update_info(png_ptr, info_ptr);
  188346. /* -------------- image transformations end here ------------------- */
  188347. #ifdef PNG_FREE_ME_SUPPORTED
  188348. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188349. #endif
  188350. if(info_ptr->row_pointers == NULL)
  188351. {
  188352. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188353. info_ptr->height * png_sizeof(png_bytep));
  188354. #ifdef PNG_FREE_ME_SUPPORTED
  188355. info_ptr->free_me |= PNG_FREE_ROWS;
  188356. #endif
  188357. for (row = 0; row < (int)info_ptr->height; row++)
  188358. {
  188359. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188360. png_get_rowbytes(png_ptr, info_ptr));
  188361. }
  188362. }
  188363. png_read_image(png_ptr, info_ptr->row_pointers);
  188364. info_ptr->valid |= PNG_INFO_IDAT;
  188365. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188366. png_read_end(png_ptr, info_ptr);
  188367. transforms = transforms; /* quiet compiler warnings */
  188368. params = params;
  188369. }
  188370. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188371. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188372. #endif /* PNG_READ_SUPPORTED */
  188373. /*** End of inlined file: pngread.c ***/
  188374. /*** Start of inlined file: pngpread.c ***/
  188375. /* pngpread.c - read a png file in push mode
  188376. *
  188377. * Last changed in libpng 1.2.21 October 4, 2007
  188378. * For conditions of distribution and use, see copyright notice in png.h
  188379. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188380. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188381. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188382. */
  188383. #define PNG_INTERNAL
  188384. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188385. /* push model modes */
  188386. #define PNG_READ_SIG_MODE 0
  188387. #define PNG_READ_CHUNK_MODE 1
  188388. #define PNG_READ_IDAT_MODE 2
  188389. #define PNG_SKIP_MODE 3
  188390. #define PNG_READ_tEXt_MODE 4
  188391. #define PNG_READ_zTXt_MODE 5
  188392. #define PNG_READ_DONE_MODE 6
  188393. #define PNG_READ_iTXt_MODE 7
  188394. #define PNG_ERROR_MODE 8
  188395. void PNGAPI
  188396. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188397. png_bytep buffer, png_size_t buffer_size)
  188398. {
  188399. if(png_ptr == NULL) return;
  188400. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188401. while (png_ptr->buffer_size)
  188402. {
  188403. png_process_some_data(png_ptr, info_ptr);
  188404. }
  188405. }
  188406. /* What we do with the incoming data depends on what we were previously
  188407. * doing before we ran out of data...
  188408. */
  188409. void /* PRIVATE */
  188410. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188411. {
  188412. if(png_ptr == NULL) return;
  188413. switch (png_ptr->process_mode)
  188414. {
  188415. case PNG_READ_SIG_MODE:
  188416. {
  188417. png_push_read_sig(png_ptr, info_ptr);
  188418. break;
  188419. }
  188420. case PNG_READ_CHUNK_MODE:
  188421. {
  188422. png_push_read_chunk(png_ptr, info_ptr);
  188423. break;
  188424. }
  188425. case PNG_READ_IDAT_MODE:
  188426. {
  188427. png_push_read_IDAT(png_ptr);
  188428. break;
  188429. }
  188430. #if defined(PNG_READ_tEXt_SUPPORTED)
  188431. case PNG_READ_tEXt_MODE:
  188432. {
  188433. png_push_read_tEXt(png_ptr, info_ptr);
  188434. break;
  188435. }
  188436. #endif
  188437. #if defined(PNG_READ_zTXt_SUPPORTED)
  188438. case PNG_READ_zTXt_MODE:
  188439. {
  188440. png_push_read_zTXt(png_ptr, info_ptr);
  188441. break;
  188442. }
  188443. #endif
  188444. #if defined(PNG_READ_iTXt_SUPPORTED)
  188445. case PNG_READ_iTXt_MODE:
  188446. {
  188447. png_push_read_iTXt(png_ptr, info_ptr);
  188448. break;
  188449. }
  188450. #endif
  188451. case PNG_SKIP_MODE:
  188452. {
  188453. png_push_crc_finish(png_ptr);
  188454. break;
  188455. }
  188456. default:
  188457. {
  188458. png_ptr->buffer_size = 0;
  188459. break;
  188460. }
  188461. }
  188462. }
  188463. /* Read any remaining signature bytes from the stream and compare them with
  188464. * the correct PNG signature. It is possible that this routine is called
  188465. * with bytes already read from the signature, either because they have been
  188466. * checked by the calling application, or because of multiple calls to this
  188467. * routine.
  188468. */
  188469. void /* PRIVATE */
  188470. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188471. {
  188472. png_size_t num_checked = png_ptr->sig_bytes,
  188473. num_to_check = 8 - num_checked;
  188474. if (png_ptr->buffer_size < num_to_check)
  188475. {
  188476. num_to_check = png_ptr->buffer_size;
  188477. }
  188478. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188479. num_to_check);
  188480. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188481. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188482. {
  188483. if (num_checked < 4 &&
  188484. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188485. png_error(png_ptr, "Not a PNG file");
  188486. else
  188487. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188488. }
  188489. else
  188490. {
  188491. if (png_ptr->sig_bytes >= 8)
  188492. {
  188493. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188494. }
  188495. }
  188496. }
  188497. void /* PRIVATE */
  188498. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188499. {
  188500. #ifdef PNG_USE_LOCAL_ARRAYS
  188501. PNG_CONST PNG_IHDR;
  188502. PNG_CONST PNG_IDAT;
  188503. PNG_CONST PNG_IEND;
  188504. PNG_CONST PNG_PLTE;
  188505. #if defined(PNG_READ_bKGD_SUPPORTED)
  188506. PNG_CONST PNG_bKGD;
  188507. #endif
  188508. #if defined(PNG_READ_cHRM_SUPPORTED)
  188509. PNG_CONST PNG_cHRM;
  188510. #endif
  188511. #if defined(PNG_READ_gAMA_SUPPORTED)
  188512. PNG_CONST PNG_gAMA;
  188513. #endif
  188514. #if defined(PNG_READ_hIST_SUPPORTED)
  188515. PNG_CONST PNG_hIST;
  188516. #endif
  188517. #if defined(PNG_READ_iCCP_SUPPORTED)
  188518. PNG_CONST PNG_iCCP;
  188519. #endif
  188520. #if defined(PNG_READ_iTXt_SUPPORTED)
  188521. PNG_CONST PNG_iTXt;
  188522. #endif
  188523. #if defined(PNG_READ_oFFs_SUPPORTED)
  188524. PNG_CONST PNG_oFFs;
  188525. #endif
  188526. #if defined(PNG_READ_pCAL_SUPPORTED)
  188527. PNG_CONST PNG_pCAL;
  188528. #endif
  188529. #if defined(PNG_READ_pHYs_SUPPORTED)
  188530. PNG_CONST PNG_pHYs;
  188531. #endif
  188532. #if defined(PNG_READ_sBIT_SUPPORTED)
  188533. PNG_CONST PNG_sBIT;
  188534. #endif
  188535. #if defined(PNG_READ_sCAL_SUPPORTED)
  188536. PNG_CONST PNG_sCAL;
  188537. #endif
  188538. #if defined(PNG_READ_sRGB_SUPPORTED)
  188539. PNG_CONST PNG_sRGB;
  188540. #endif
  188541. #if defined(PNG_READ_sPLT_SUPPORTED)
  188542. PNG_CONST PNG_sPLT;
  188543. #endif
  188544. #if defined(PNG_READ_tEXt_SUPPORTED)
  188545. PNG_CONST PNG_tEXt;
  188546. #endif
  188547. #if defined(PNG_READ_tIME_SUPPORTED)
  188548. PNG_CONST PNG_tIME;
  188549. #endif
  188550. #if defined(PNG_READ_tRNS_SUPPORTED)
  188551. PNG_CONST PNG_tRNS;
  188552. #endif
  188553. #if defined(PNG_READ_zTXt_SUPPORTED)
  188554. PNG_CONST PNG_zTXt;
  188555. #endif
  188556. #endif /* PNG_USE_LOCAL_ARRAYS */
  188557. /* First we make sure we have enough data for the 4 byte chunk name
  188558. * and the 4 byte chunk length before proceeding with decoding the
  188559. * chunk data. To fully decode each of these chunks, we also make
  188560. * sure we have enough data in the buffer for the 4 byte CRC at the
  188561. * end of every chunk (except IDAT, which is handled separately).
  188562. */
  188563. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188564. {
  188565. png_byte chunk_length[4];
  188566. if (png_ptr->buffer_size < 8)
  188567. {
  188568. png_push_save_buffer(png_ptr);
  188569. return;
  188570. }
  188571. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188572. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188573. png_reset_crc(png_ptr);
  188574. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188575. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188576. }
  188577. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188578. if(png_ptr->mode & PNG_AFTER_IDAT)
  188579. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188580. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188581. {
  188582. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188583. {
  188584. png_push_save_buffer(png_ptr);
  188585. return;
  188586. }
  188587. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188588. }
  188589. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188590. {
  188591. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188592. {
  188593. png_push_save_buffer(png_ptr);
  188594. return;
  188595. }
  188596. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188597. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188598. png_push_have_end(png_ptr, info_ptr);
  188599. }
  188600. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188601. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188602. {
  188603. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188604. {
  188605. png_push_save_buffer(png_ptr);
  188606. return;
  188607. }
  188608. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188609. png_ptr->mode |= PNG_HAVE_IDAT;
  188610. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188611. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188612. png_ptr->mode |= PNG_HAVE_PLTE;
  188613. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188614. {
  188615. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188616. png_error(png_ptr, "Missing IHDR before IDAT");
  188617. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188618. !(png_ptr->mode & PNG_HAVE_PLTE))
  188619. png_error(png_ptr, "Missing PLTE before IDAT");
  188620. }
  188621. }
  188622. #endif
  188623. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188624. {
  188625. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188626. {
  188627. png_push_save_buffer(png_ptr);
  188628. return;
  188629. }
  188630. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188631. }
  188632. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188633. {
  188634. /* If we reach an IDAT chunk, this means we have read all of the
  188635. * header chunks, and we can start reading the image (or if this
  188636. * is called after the image has been read - we have an error).
  188637. */
  188638. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188639. png_error(png_ptr, "Missing IHDR before IDAT");
  188640. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188641. !(png_ptr->mode & PNG_HAVE_PLTE))
  188642. png_error(png_ptr, "Missing PLTE before IDAT");
  188643. if (png_ptr->mode & PNG_HAVE_IDAT)
  188644. {
  188645. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188646. if (png_ptr->push_length == 0)
  188647. return;
  188648. if (png_ptr->mode & PNG_AFTER_IDAT)
  188649. png_error(png_ptr, "Too many IDAT's found");
  188650. }
  188651. png_ptr->idat_size = png_ptr->push_length;
  188652. png_ptr->mode |= PNG_HAVE_IDAT;
  188653. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188654. png_push_have_info(png_ptr, info_ptr);
  188655. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188656. png_ptr->zstream.next_out = png_ptr->row_buf;
  188657. return;
  188658. }
  188659. #if defined(PNG_READ_gAMA_SUPPORTED)
  188660. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188661. {
  188662. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188663. {
  188664. png_push_save_buffer(png_ptr);
  188665. return;
  188666. }
  188667. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188668. }
  188669. #endif
  188670. #if defined(PNG_READ_sBIT_SUPPORTED)
  188671. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188672. {
  188673. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188674. {
  188675. png_push_save_buffer(png_ptr);
  188676. return;
  188677. }
  188678. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188679. }
  188680. #endif
  188681. #if defined(PNG_READ_cHRM_SUPPORTED)
  188682. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188683. {
  188684. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188685. {
  188686. png_push_save_buffer(png_ptr);
  188687. return;
  188688. }
  188689. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188690. }
  188691. #endif
  188692. #if defined(PNG_READ_sRGB_SUPPORTED)
  188693. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188694. {
  188695. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188696. {
  188697. png_push_save_buffer(png_ptr);
  188698. return;
  188699. }
  188700. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188701. }
  188702. #endif
  188703. #if defined(PNG_READ_iCCP_SUPPORTED)
  188704. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188705. {
  188706. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188707. {
  188708. png_push_save_buffer(png_ptr);
  188709. return;
  188710. }
  188711. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188712. }
  188713. #endif
  188714. #if defined(PNG_READ_sPLT_SUPPORTED)
  188715. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188716. {
  188717. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188718. {
  188719. png_push_save_buffer(png_ptr);
  188720. return;
  188721. }
  188722. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188723. }
  188724. #endif
  188725. #if defined(PNG_READ_tRNS_SUPPORTED)
  188726. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188727. {
  188728. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188729. {
  188730. png_push_save_buffer(png_ptr);
  188731. return;
  188732. }
  188733. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188734. }
  188735. #endif
  188736. #if defined(PNG_READ_bKGD_SUPPORTED)
  188737. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188738. {
  188739. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188740. {
  188741. png_push_save_buffer(png_ptr);
  188742. return;
  188743. }
  188744. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188745. }
  188746. #endif
  188747. #if defined(PNG_READ_hIST_SUPPORTED)
  188748. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188749. {
  188750. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188751. {
  188752. png_push_save_buffer(png_ptr);
  188753. return;
  188754. }
  188755. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188756. }
  188757. #endif
  188758. #if defined(PNG_READ_pHYs_SUPPORTED)
  188759. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188760. {
  188761. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188762. {
  188763. png_push_save_buffer(png_ptr);
  188764. return;
  188765. }
  188766. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188767. }
  188768. #endif
  188769. #if defined(PNG_READ_oFFs_SUPPORTED)
  188770. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188771. {
  188772. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188773. {
  188774. png_push_save_buffer(png_ptr);
  188775. return;
  188776. }
  188777. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188778. }
  188779. #endif
  188780. #if defined(PNG_READ_pCAL_SUPPORTED)
  188781. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188782. {
  188783. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188784. {
  188785. png_push_save_buffer(png_ptr);
  188786. return;
  188787. }
  188788. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188789. }
  188790. #endif
  188791. #if defined(PNG_READ_sCAL_SUPPORTED)
  188792. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188793. {
  188794. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188795. {
  188796. png_push_save_buffer(png_ptr);
  188797. return;
  188798. }
  188799. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188800. }
  188801. #endif
  188802. #if defined(PNG_READ_tIME_SUPPORTED)
  188803. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188804. {
  188805. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188806. {
  188807. png_push_save_buffer(png_ptr);
  188808. return;
  188809. }
  188810. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188811. }
  188812. #endif
  188813. #if defined(PNG_READ_tEXt_SUPPORTED)
  188814. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188815. {
  188816. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188817. {
  188818. png_push_save_buffer(png_ptr);
  188819. return;
  188820. }
  188821. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188822. }
  188823. #endif
  188824. #if defined(PNG_READ_zTXt_SUPPORTED)
  188825. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188826. {
  188827. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188828. {
  188829. png_push_save_buffer(png_ptr);
  188830. return;
  188831. }
  188832. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188833. }
  188834. #endif
  188835. #if defined(PNG_READ_iTXt_SUPPORTED)
  188836. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188837. {
  188838. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188839. {
  188840. png_push_save_buffer(png_ptr);
  188841. return;
  188842. }
  188843. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188844. }
  188845. #endif
  188846. else
  188847. {
  188848. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188849. {
  188850. png_push_save_buffer(png_ptr);
  188851. return;
  188852. }
  188853. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188854. }
  188855. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188856. }
  188857. void /* PRIVATE */
  188858. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188859. {
  188860. png_ptr->process_mode = PNG_SKIP_MODE;
  188861. png_ptr->skip_length = skip;
  188862. }
  188863. void /* PRIVATE */
  188864. png_push_crc_finish(png_structp png_ptr)
  188865. {
  188866. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188867. {
  188868. png_size_t save_size;
  188869. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188870. save_size = (png_size_t)png_ptr->skip_length;
  188871. else
  188872. save_size = png_ptr->save_buffer_size;
  188873. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188874. png_ptr->skip_length -= save_size;
  188875. png_ptr->buffer_size -= save_size;
  188876. png_ptr->save_buffer_size -= save_size;
  188877. png_ptr->save_buffer_ptr += save_size;
  188878. }
  188879. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188880. {
  188881. png_size_t save_size;
  188882. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188883. save_size = (png_size_t)png_ptr->skip_length;
  188884. else
  188885. save_size = png_ptr->current_buffer_size;
  188886. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188887. png_ptr->skip_length -= save_size;
  188888. png_ptr->buffer_size -= save_size;
  188889. png_ptr->current_buffer_size -= save_size;
  188890. png_ptr->current_buffer_ptr += save_size;
  188891. }
  188892. if (!png_ptr->skip_length)
  188893. {
  188894. if (png_ptr->buffer_size < 4)
  188895. {
  188896. png_push_save_buffer(png_ptr);
  188897. return;
  188898. }
  188899. png_crc_finish(png_ptr, 0);
  188900. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188901. }
  188902. }
  188903. void PNGAPI
  188904. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188905. {
  188906. png_bytep ptr;
  188907. if(png_ptr == NULL) return;
  188908. ptr = buffer;
  188909. if (png_ptr->save_buffer_size)
  188910. {
  188911. png_size_t save_size;
  188912. if (length < png_ptr->save_buffer_size)
  188913. save_size = length;
  188914. else
  188915. save_size = png_ptr->save_buffer_size;
  188916. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188917. length -= save_size;
  188918. ptr += save_size;
  188919. png_ptr->buffer_size -= save_size;
  188920. png_ptr->save_buffer_size -= save_size;
  188921. png_ptr->save_buffer_ptr += save_size;
  188922. }
  188923. if (length && png_ptr->current_buffer_size)
  188924. {
  188925. png_size_t save_size;
  188926. if (length < png_ptr->current_buffer_size)
  188927. save_size = length;
  188928. else
  188929. save_size = png_ptr->current_buffer_size;
  188930. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188931. png_ptr->buffer_size -= save_size;
  188932. png_ptr->current_buffer_size -= save_size;
  188933. png_ptr->current_buffer_ptr += save_size;
  188934. }
  188935. }
  188936. void /* PRIVATE */
  188937. png_push_save_buffer(png_structp png_ptr)
  188938. {
  188939. if (png_ptr->save_buffer_size)
  188940. {
  188941. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188942. {
  188943. png_size_t i,istop;
  188944. png_bytep sp;
  188945. png_bytep dp;
  188946. istop = png_ptr->save_buffer_size;
  188947. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188948. i < istop; i++, sp++, dp++)
  188949. {
  188950. *dp = *sp;
  188951. }
  188952. }
  188953. }
  188954. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188955. png_ptr->save_buffer_max)
  188956. {
  188957. png_size_t new_max;
  188958. png_bytep old_buffer;
  188959. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188960. (png_ptr->current_buffer_size + 256))
  188961. {
  188962. png_error(png_ptr, "Potential overflow of save_buffer");
  188963. }
  188964. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188965. old_buffer = png_ptr->save_buffer;
  188966. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188967. (png_uint_32)new_max);
  188968. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188969. png_free(png_ptr, old_buffer);
  188970. png_ptr->save_buffer_max = new_max;
  188971. }
  188972. if (png_ptr->current_buffer_size)
  188973. {
  188974. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188975. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188976. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188977. png_ptr->current_buffer_size = 0;
  188978. }
  188979. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188980. png_ptr->buffer_size = 0;
  188981. }
  188982. void /* PRIVATE */
  188983. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188984. png_size_t buffer_length)
  188985. {
  188986. png_ptr->current_buffer = buffer;
  188987. png_ptr->current_buffer_size = buffer_length;
  188988. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188989. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188990. }
  188991. void /* PRIVATE */
  188992. png_push_read_IDAT(png_structp png_ptr)
  188993. {
  188994. #ifdef PNG_USE_LOCAL_ARRAYS
  188995. PNG_CONST PNG_IDAT;
  188996. #endif
  188997. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188998. {
  188999. png_byte chunk_length[4];
  189000. if (png_ptr->buffer_size < 8)
  189001. {
  189002. png_push_save_buffer(png_ptr);
  189003. return;
  189004. }
  189005. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189006. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189007. png_reset_crc(png_ptr);
  189008. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189009. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189010. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189011. {
  189012. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189013. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189014. png_error(png_ptr, "Not enough compressed data");
  189015. return;
  189016. }
  189017. png_ptr->idat_size = png_ptr->push_length;
  189018. }
  189019. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189020. {
  189021. png_size_t save_size;
  189022. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189023. {
  189024. save_size = (png_size_t)png_ptr->idat_size;
  189025. /* check for overflow */
  189026. if((png_uint_32)save_size != png_ptr->idat_size)
  189027. png_error(png_ptr, "save_size overflowed in pngpread");
  189028. }
  189029. else
  189030. save_size = png_ptr->save_buffer_size;
  189031. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189032. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189033. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189034. png_ptr->idat_size -= save_size;
  189035. png_ptr->buffer_size -= save_size;
  189036. png_ptr->save_buffer_size -= save_size;
  189037. png_ptr->save_buffer_ptr += save_size;
  189038. }
  189039. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189040. {
  189041. png_size_t save_size;
  189042. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189043. {
  189044. save_size = (png_size_t)png_ptr->idat_size;
  189045. /* check for overflow */
  189046. if((png_uint_32)save_size != png_ptr->idat_size)
  189047. png_error(png_ptr, "save_size overflowed in pngpread");
  189048. }
  189049. else
  189050. save_size = png_ptr->current_buffer_size;
  189051. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189052. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189053. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189054. png_ptr->idat_size -= save_size;
  189055. png_ptr->buffer_size -= save_size;
  189056. png_ptr->current_buffer_size -= save_size;
  189057. png_ptr->current_buffer_ptr += save_size;
  189058. }
  189059. if (!png_ptr->idat_size)
  189060. {
  189061. if (png_ptr->buffer_size < 4)
  189062. {
  189063. png_push_save_buffer(png_ptr);
  189064. return;
  189065. }
  189066. png_crc_finish(png_ptr, 0);
  189067. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189068. png_ptr->mode |= PNG_AFTER_IDAT;
  189069. }
  189070. }
  189071. void /* PRIVATE */
  189072. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189073. png_size_t buffer_length)
  189074. {
  189075. int ret;
  189076. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189077. png_error(png_ptr, "Extra compression data");
  189078. png_ptr->zstream.next_in = buffer;
  189079. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189080. for(;;)
  189081. {
  189082. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189083. if (ret != Z_OK)
  189084. {
  189085. if (ret == Z_STREAM_END)
  189086. {
  189087. if (png_ptr->zstream.avail_in)
  189088. png_error(png_ptr, "Extra compressed data");
  189089. if (!(png_ptr->zstream.avail_out))
  189090. {
  189091. png_push_process_row(png_ptr);
  189092. }
  189093. png_ptr->mode |= PNG_AFTER_IDAT;
  189094. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189095. break;
  189096. }
  189097. else if (ret == Z_BUF_ERROR)
  189098. break;
  189099. else
  189100. png_error(png_ptr, "Decompression Error");
  189101. }
  189102. if (!(png_ptr->zstream.avail_out))
  189103. {
  189104. if ((
  189105. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189106. png_ptr->interlaced && png_ptr->pass > 6) ||
  189107. (!png_ptr->interlaced &&
  189108. #endif
  189109. png_ptr->row_number == png_ptr->num_rows))
  189110. {
  189111. if (png_ptr->zstream.avail_in)
  189112. {
  189113. png_warning(png_ptr, "Too much data in IDAT chunks");
  189114. }
  189115. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189116. break;
  189117. }
  189118. png_push_process_row(png_ptr);
  189119. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189120. png_ptr->zstream.next_out = png_ptr->row_buf;
  189121. }
  189122. else
  189123. break;
  189124. }
  189125. }
  189126. void /* PRIVATE */
  189127. png_push_process_row(png_structp png_ptr)
  189128. {
  189129. png_ptr->row_info.color_type = png_ptr->color_type;
  189130. png_ptr->row_info.width = png_ptr->iwidth;
  189131. png_ptr->row_info.channels = png_ptr->channels;
  189132. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189133. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189134. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189135. png_ptr->row_info.width);
  189136. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189137. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189138. (int)(png_ptr->row_buf[0]));
  189139. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189140. png_ptr->rowbytes + 1);
  189141. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189142. png_do_read_transformations(png_ptr);
  189143. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189144. /* blow up interlaced rows to full size */
  189145. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189146. {
  189147. if (png_ptr->pass < 6)
  189148. /* old interface (pre-1.0.9):
  189149. png_do_read_interlace(&(png_ptr->row_info),
  189150. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189151. */
  189152. png_do_read_interlace(png_ptr);
  189153. switch (png_ptr->pass)
  189154. {
  189155. case 0:
  189156. {
  189157. int i;
  189158. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189159. {
  189160. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189161. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189162. }
  189163. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189164. {
  189165. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189166. {
  189167. png_push_have_row(png_ptr, png_bytep_NULL);
  189168. png_read_push_finish_row(png_ptr);
  189169. }
  189170. }
  189171. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189172. {
  189173. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189174. {
  189175. png_push_have_row(png_ptr, png_bytep_NULL);
  189176. png_read_push_finish_row(png_ptr);
  189177. }
  189178. }
  189179. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189180. {
  189181. png_push_have_row(png_ptr, png_bytep_NULL);
  189182. png_read_push_finish_row(png_ptr);
  189183. }
  189184. break;
  189185. }
  189186. case 1:
  189187. {
  189188. int i;
  189189. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189190. {
  189191. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189192. png_read_push_finish_row(png_ptr);
  189193. }
  189194. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189195. {
  189196. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189197. {
  189198. png_push_have_row(png_ptr, png_bytep_NULL);
  189199. png_read_push_finish_row(png_ptr);
  189200. }
  189201. }
  189202. break;
  189203. }
  189204. case 2:
  189205. {
  189206. int i;
  189207. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189208. {
  189209. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189210. png_read_push_finish_row(png_ptr);
  189211. }
  189212. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189213. {
  189214. png_push_have_row(png_ptr, png_bytep_NULL);
  189215. png_read_push_finish_row(png_ptr);
  189216. }
  189217. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189218. {
  189219. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189220. {
  189221. png_push_have_row(png_ptr, png_bytep_NULL);
  189222. png_read_push_finish_row(png_ptr);
  189223. }
  189224. }
  189225. break;
  189226. }
  189227. case 3:
  189228. {
  189229. int i;
  189230. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189231. {
  189232. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189233. png_read_push_finish_row(png_ptr);
  189234. }
  189235. if (png_ptr->pass == 4) /* skip top two generated rows */
  189236. {
  189237. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189238. {
  189239. png_push_have_row(png_ptr, png_bytep_NULL);
  189240. png_read_push_finish_row(png_ptr);
  189241. }
  189242. }
  189243. break;
  189244. }
  189245. case 4:
  189246. {
  189247. int i;
  189248. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189249. {
  189250. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189251. png_read_push_finish_row(png_ptr);
  189252. }
  189253. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189254. {
  189255. png_push_have_row(png_ptr, png_bytep_NULL);
  189256. png_read_push_finish_row(png_ptr);
  189257. }
  189258. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189259. {
  189260. png_push_have_row(png_ptr, png_bytep_NULL);
  189261. png_read_push_finish_row(png_ptr);
  189262. }
  189263. break;
  189264. }
  189265. case 5:
  189266. {
  189267. int i;
  189268. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189269. {
  189270. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189271. png_read_push_finish_row(png_ptr);
  189272. }
  189273. if (png_ptr->pass == 6) /* skip top generated row */
  189274. {
  189275. png_push_have_row(png_ptr, png_bytep_NULL);
  189276. png_read_push_finish_row(png_ptr);
  189277. }
  189278. break;
  189279. }
  189280. case 6:
  189281. {
  189282. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189283. png_read_push_finish_row(png_ptr);
  189284. if (png_ptr->pass != 6)
  189285. break;
  189286. png_push_have_row(png_ptr, png_bytep_NULL);
  189287. png_read_push_finish_row(png_ptr);
  189288. }
  189289. }
  189290. }
  189291. else
  189292. #endif
  189293. {
  189294. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189295. png_read_push_finish_row(png_ptr);
  189296. }
  189297. }
  189298. void /* PRIVATE */
  189299. png_read_push_finish_row(png_structp png_ptr)
  189300. {
  189301. #ifdef PNG_USE_LOCAL_ARRAYS
  189302. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189303. /* start of interlace block */
  189304. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189305. /* offset to next interlace block */
  189306. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189307. /* start of interlace block in the y direction */
  189308. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189309. /* offset to next interlace block in the y direction */
  189310. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189311. /* Height of interlace block. This is not currently used - if you need
  189312. * it, uncomment it here and in png.h
  189313. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189314. */
  189315. #endif
  189316. png_ptr->row_number++;
  189317. if (png_ptr->row_number < png_ptr->num_rows)
  189318. return;
  189319. if (png_ptr->interlaced)
  189320. {
  189321. png_ptr->row_number = 0;
  189322. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189323. png_ptr->rowbytes + 1);
  189324. do
  189325. {
  189326. png_ptr->pass++;
  189327. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189328. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189329. (png_ptr->pass == 5 && png_ptr->width < 2))
  189330. png_ptr->pass++;
  189331. if (png_ptr->pass > 7)
  189332. png_ptr->pass--;
  189333. if (png_ptr->pass >= 7)
  189334. break;
  189335. png_ptr->iwidth = (png_ptr->width +
  189336. png_pass_inc[png_ptr->pass] - 1 -
  189337. png_pass_start[png_ptr->pass]) /
  189338. png_pass_inc[png_ptr->pass];
  189339. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189340. png_ptr->iwidth) + 1;
  189341. if (png_ptr->transformations & PNG_INTERLACE)
  189342. break;
  189343. png_ptr->num_rows = (png_ptr->height +
  189344. png_pass_yinc[png_ptr->pass] - 1 -
  189345. png_pass_ystart[png_ptr->pass]) /
  189346. png_pass_yinc[png_ptr->pass];
  189347. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189348. }
  189349. }
  189350. #if defined(PNG_READ_tEXt_SUPPORTED)
  189351. void /* PRIVATE */
  189352. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189353. length)
  189354. {
  189355. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189356. {
  189357. png_error(png_ptr, "Out of place tEXt");
  189358. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189359. }
  189360. #ifdef PNG_MAX_MALLOC_64K
  189361. png_ptr->skip_length = 0; /* This may not be necessary */
  189362. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189363. {
  189364. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189365. png_ptr->skip_length = length - (png_uint_32)65535L;
  189366. length = (png_uint_32)65535L;
  189367. }
  189368. #endif
  189369. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189370. (png_uint_32)(length+1));
  189371. png_ptr->current_text[length] = '\0';
  189372. png_ptr->current_text_ptr = png_ptr->current_text;
  189373. png_ptr->current_text_size = (png_size_t)length;
  189374. png_ptr->current_text_left = (png_size_t)length;
  189375. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189376. }
  189377. void /* PRIVATE */
  189378. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189379. {
  189380. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189381. {
  189382. png_size_t text_size;
  189383. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189384. text_size = png_ptr->buffer_size;
  189385. else
  189386. text_size = png_ptr->current_text_left;
  189387. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189388. png_ptr->current_text_left -= text_size;
  189389. png_ptr->current_text_ptr += text_size;
  189390. }
  189391. if (!(png_ptr->current_text_left))
  189392. {
  189393. png_textp text_ptr;
  189394. png_charp text;
  189395. png_charp key;
  189396. int ret;
  189397. if (png_ptr->buffer_size < 4)
  189398. {
  189399. png_push_save_buffer(png_ptr);
  189400. return;
  189401. }
  189402. png_push_crc_finish(png_ptr);
  189403. #if defined(PNG_MAX_MALLOC_64K)
  189404. if (png_ptr->skip_length)
  189405. return;
  189406. #endif
  189407. key = png_ptr->current_text;
  189408. for (text = key; *text; text++)
  189409. /* empty loop */ ;
  189410. if (text < key + png_ptr->current_text_size)
  189411. text++;
  189412. text_ptr = (png_textp)png_malloc(png_ptr,
  189413. (png_uint_32)png_sizeof(png_text));
  189414. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189415. text_ptr->key = key;
  189416. #ifdef PNG_iTXt_SUPPORTED
  189417. text_ptr->lang = NULL;
  189418. text_ptr->lang_key = NULL;
  189419. #endif
  189420. text_ptr->text = text;
  189421. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189422. png_free(png_ptr, key);
  189423. png_free(png_ptr, text_ptr);
  189424. png_ptr->current_text = NULL;
  189425. if (ret)
  189426. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189427. }
  189428. }
  189429. #endif
  189430. #if defined(PNG_READ_zTXt_SUPPORTED)
  189431. void /* PRIVATE */
  189432. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189433. length)
  189434. {
  189435. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189436. {
  189437. png_error(png_ptr, "Out of place zTXt");
  189438. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189439. }
  189440. #ifdef PNG_MAX_MALLOC_64K
  189441. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189442. * to be able to store the uncompressed data. Actually, the threshold
  189443. * is probably around 32K, but it isn't as definite as 64K is.
  189444. */
  189445. if (length > (png_uint_32)65535L)
  189446. {
  189447. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189448. png_push_crc_skip(png_ptr, length);
  189449. return;
  189450. }
  189451. #endif
  189452. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189453. (png_uint_32)(length+1));
  189454. png_ptr->current_text[length] = '\0';
  189455. png_ptr->current_text_ptr = png_ptr->current_text;
  189456. png_ptr->current_text_size = (png_size_t)length;
  189457. png_ptr->current_text_left = (png_size_t)length;
  189458. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189459. }
  189460. void /* PRIVATE */
  189461. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189462. {
  189463. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189464. {
  189465. png_size_t text_size;
  189466. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189467. text_size = png_ptr->buffer_size;
  189468. else
  189469. text_size = png_ptr->current_text_left;
  189470. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189471. png_ptr->current_text_left -= text_size;
  189472. png_ptr->current_text_ptr += text_size;
  189473. }
  189474. if (!(png_ptr->current_text_left))
  189475. {
  189476. png_textp text_ptr;
  189477. png_charp text;
  189478. png_charp key;
  189479. int ret;
  189480. png_size_t text_size, key_size;
  189481. if (png_ptr->buffer_size < 4)
  189482. {
  189483. png_push_save_buffer(png_ptr);
  189484. return;
  189485. }
  189486. png_push_crc_finish(png_ptr);
  189487. key = png_ptr->current_text;
  189488. for (text = key; *text; text++)
  189489. /* empty loop */ ;
  189490. /* zTXt can't have zero text */
  189491. if (text >= key + png_ptr->current_text_size)
  189492. {
  189493. png_ptr->current_text = NULL;
  189494. png_free(png_ptr, key);
  189495. return;
  189496. }
  189497. text++;
  189498. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189499. {
  189500. png_ptr->current_text = NULL;
  189501. png_free(png_ptr, key);
  189502. return;
  189503. }
  189504. text++;
  189505. png_ptr->zstream.next_in = (png_bytep )text;
  189506. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189507. (text - key));
  189508. png_ptr->zstream.next_out = png_ptr->zbuf;
  189509. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189510. key_size = text - key;
  189511. text_size = 0;
  189512. text = NULL;
  189513. ret = Z_STREAM_END;
  189514. while (png_ptr->zstream.avail_in)
  189515. {
  189516. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189517. if (ret != Z_OK && ret != Z_STREAM_END)
  189518. {
  189519. inflateReset(&png_ptr->zstream);
  189520. png_ptr->zstream.avail_in = 0;
  189521. png_ptr->current_text = NULL;
  189522. png_free(png_ptr, key);
  189523. png_free(png_ptr, text);
  189524. return;
  189525. }
  189526. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189527. {
  189528. if (text == NULL)
  189529. {
  189530. text = (png_charp)png_malloc(png_ptr,
  189531. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189532. + key_size + 1));
  189533. png_memcpy(text + key_size, png_ptr->zbuf,
  189534. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189535. png_memcpy(text, key, key_size);
  189536. text_size = key_size + png_ptr->zbuf_size -
  189537. png_ptr->zstream.avail_out;
  189538. *(text + text_size) = '\0';
  189539. }
  189540. else
  189541. {
  189542. png_charp tmp;
  189543. tmp = text;
  189544. text = (png_charp)png_malloc(png_ptr, text_size +
  189545. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189546. + 1));
  189547. png_memcpy(text, tmp, text_size);
  189548. png_free(png_ptr, tmp);
  189549. png_memcpy(text + text_size, png_ptr->zbuf,
  189550. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189551. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189552. *(text + text_size) = '\0';
  189553. }
  189554. if (ret != Z_STREAM_END)
  189555. {
  189556. png_ptr->zstream.next_out = png_ptr->zbuf;
  189557. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189558. }
  189559. }
  189560. else
  189561. {
  189562. break;
  189563. }
  189564. if (ret == Z_STREAM_END)
  189565. break;
  189566. }
  189567. inflateReset(&png_ptr->zstream);
  189568. png_ptr->zstream.avail_in = 0;
  189569. if (ret != Z_STREAM_END)
  189570. {
  189571. png_ptr->current_text = NULL;
  189572. png_free(png_ptr, key);
  189573. png_free(png_ptr, text);
  189574. return;
  189575. }
  189576. png_ptr->current_text = NULL;
  189577. png_free(png_ptr, key);
  189578. key = text;
  189579. text += key_size;
  189580. text_ptr = (png_textp)png_malloc(png_ptr,
  189581. (png_uint_32)png_sizeof(png_text));
  189582. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189583. text_ptr->key = key;
  189584. #ifdef PNG_iTXt_SUPPORTED
  189585. text_ptr->lang = NULL;
  189586. text_ptr->lang_key = NULL;
  189587. #endif
  189588. text_ptr->text = text;
  189589. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189590. png_free(png_ptr, key);
  189591. png_free(png_ptr, text_ptr);
  189592. if (ret)
  189593. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189594. }
  189595. }
  189596. #endif
  189597. #if defined(PNG_READ_iTXt_SUPPORTED)
  189598. void /* PRIVATE */
  189599. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189600. length)
  189601. {
  189602. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189603. {
  189604. png_error(png_ptr, "Out of place iTXt");
  189605. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189606. }
  189607. #ifdef PNG_MAX_MALLOC_64K
  189608. png_ptr->skip_length = 0; /* This may not be necessary */
  189609. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189610. {
  189611. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189612. png_ptr->skip_length = length - (png_uint_32)65535L;
  189613. length = (png_uint_32)65535L;
  189614. }
  189615. #endif
  189616. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189617. (png_uint_32)(length+1));
  189618. png_ptr->current_text[length] = '\0';
  189619. png_ptr->current_text_ptr = png_ptr->current_text;
  189620. png_ptr->current_text_size = (png_size_t)length;
  189621. png_ptr->current_text_left = (png_size_t)length;
  189622. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189623. }
  189624. void /* PRIVATE */
  189625. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189626. {
  189627. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189628. {
  189629. png_size_t text_size;
  189630. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189631. text_size = png_ptr->buffer_size;
  189632. else
  189633. text_size = png_ptr->current_text_left;
  189634. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189635. png_ptr->current_text_left -= text_size;
  189636. png_ptr->current_text_ptr += text_size;
  189637. }
  189638. if (!(png_ptr->current_text_left))
  189639. {
  189640. png_textp text_ptr;
  189641. png_charp key;
  189642. int comp_flag;
  189643. png_charp lang;
  189644. png_charp lang_key;
  189645. png_charp text;
  189646. int ret;
  189647. if (png_ptr->buffer_size < 4)
  189648. {
  189649. png_push_save_buffer(png_ptr);
  189650. return;
  189651. }
  189652. png_push_crc_finish(png_ptr);
  189653. #if defined(PNG_MAX_MALLOC_64K)
  189654. if (png_ptr->skip_length)
  189655. return;
  189656. #endif
  189657. key = png_ptr->current_text;
  189658. for (lang = key; *lang; lang++)
  189659. /* empty loop */ ;
  189660. if (lang < key + png_ptr->current_text_size - 3)
  189661. lang++;
  189662. comp_flag = *lang++;
  189663. lang++; /* skip comp_type, always zero */
  189664. for (lang_key = lang; *lang_key; lang_key++)
  189665. /* empty loop */ ;
  189666. lang_key++; /* skip NUL separator */
  189667. text=lang_key;
  189668. if (lang_key < key + png_ptr->current_text_size - 1)
  189669. {
  189670. for (; *text; text++)
  189671. /* empty loop */ ;
  189672. }
  189673. if (text < key + png_ptr->current_text_size)
  189674. text++;
  189675. text_ptr = (png_textp)png_malloc(png_ptr,
  189676. (png_uint_32)png_sizeof(png_text));
  189677. text_ptr->compression = comp_flag + 2;
  189678. text_ptr->key = key;
  189679. text_ptr->lang = lang;
  189680. text_ptr->lang_key = lang_key;
  189681. text_ptr->text = text;
  189682. text_ptr->text_length = 0;
  189683. text_ptr->itxt_length = png_strlen(text);
  189684. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189685. png_ptr->current_text = NULL;
  189686. png_free(png_ptr, text_ptr);
  189687. if (ret)
  189688. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189689. }
  189690. }
  189691. #endif
  189692. /* This function is called when we haven't found a handler for this
  189693. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189694. * name or a critical chunk), the chunk is (currently) silently ignored.
  189695. */
  189696. void /* PRIVATE */
  189697. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189698. length)
  189699. {
  189700. png_uint_32 skip=0;
  189701. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189702. if (!(png_ptr->chunk_name[0] & 0x20))
  189703. {
  189704. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189705. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189706. PNG_HANDLE_CHUNK_ALWAYS
  189707. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189708. && png_ptr->read_user_chunk_fn == NULL
  189709. #endif
  189710. )
  189711. #endif
  189712. png_chunk_error(png_ptr, "unknown critical chunk");
  189713. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189714. }
  189715. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189716. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189717. {
  189718. #ifdef PNG_MAX_MALLOC_64K
  189719. if (length > (png_uint_32)65535L)
  189720. {
  189721. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189722. skip = length - (png_uint_32)65535L;
  189723. length = (png_uint_32)65535L;
  189724. }
  189725. #endif
  189726. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189727. (png_charp)png_ptr->chunk_name, 5);
  189728. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189729. png_ptr->unknown_chunk.size = (png_size_t)length;
  189730. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189731. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189732. if(png_ptr->read_user_chunk_fn != NULL)
  189733. {
  189734. /* callback to user unknown chunk handler */
  189735. int ret;
  189736. ret = (*(png_ptr->read_user_chunk_fn))
  189737. (png_ptr, &png_ptr->unknown_chunk);
  189738. if (ret < 0)
  189739. png_chunk_error(png_ptr, "error in user chunk");
  189740. if (ret == 0)
  189741. {
  189742. if (!(png_ptr->chunk_name[0] & 0x20))
  189743. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189744. PNG_HANDLE_CHUNK_ALWAYS)
  189745. png_chunk_error(png_ptr, "unknown critical chunk");
  189746. png_set_unknown_chunks(png_ptr, info_ptr,
  189747. &png_ptr->unknown_chunk, 1);
  189748. }
  189749. }
  189750. #else
  189751. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189752. #endif
  189753. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189754. png_ptr->unknown_chunk.data = NULL;
  189755. }
  189756. else
  189757. #endif
  189758. skip=length;
  189759. png_push_crc_skip(png_ptr, skip);
  189760. }
  189761. void /* PRIVATE */
  189762. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189763. {
  189764. if (png_ptr->info_fn != NULL)
  189765. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189766. }
  189767. void /* PRIVATE */
  189768. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189769. {
  189770. if (png_ptr->end_fn != NULL)
  189771. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189772. }
  189773. void /* PRIVATE */
  189774. png_push_have_row(png_structp png_ptr, png_bytep row)
  189775. {
  189776. if (png_ptr->row_fn != NULL)
  189777. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189778. (int)png_ptr->pass);
  189779. }
  189780. void PNGAPI
  189781. png_progressive_combine_row (png_structp png_ptr,
  189782. png_bytep old_row, png_bytep new_row)
  189783. {
  189784. #ifdef PNG_USE_LOCAL_ARRAYS
  189785. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189786. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189787. #endif
  189788. if(png_ptr == NULL) return;
  189789. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189790. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189791. }
  189792. void PNGAPI
  189793. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189794. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189795. png_progressive_end_ptr end_fn)
  189796. {
  189797. if(png_ptr == NULL) return;
  189798. png_ptr->info_fn = info_fn;
  189799. png_ptr->row_fn = row_fn;
  189800. png_ptr->end_fn = end_fn;
  189801. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189802. }
  189803. png_voidp PNGAPI
  189804. png_get_progressive_ptr(png_structp png_ptr)
  189805. {
  189806. if(png_ptr == NULL) return (NULL);
  189807. return png_ptr->io_ptr;
  189808. }
  189809. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189810. /*** End of inlined file: pngpread.c ***/
  189811. /*** Start of inlined file: pngrio.c ***/
  189812. /* pngrio.c - functions for data input
  189813. *
  189814. * Last changed in libpng 1.2.13 November 13, 2006
  189815. * For conditions of distribution and use, see copyright notice in png.h
  189816. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189817. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189818. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189819. *
  189820. * This file provides a location for all input. Users who need
  189821. * special handling are expected to write a function that has the same
  189822. * arguments as this and performs a similar function, but that possibly
  189823. * has a different input method. Note that you shouldn't change this
  189824. * function, but rather write a replacement function and then make
  189825. * libpng use it at run time with png_set_read_fn(...).
  189826. */
  189827. #define PNG_INTERNAL
  189828. #if defined(PNG_READ_SUPPORTED)
  189829. /* Read the data from whatever input you are using. The default routine
  189830. reads from a file pointer. Note that this routine sometimes gets called
  189831. with very small lengths, so you should implement some kind of simple
  189832. buffering if you are using unbuffered reads. This should never be asked
  189833. to read more then 64K on a 16 bit machine. */
  189834. void /* PRIVATE */
  189835. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189836. {
  189837. png_debug1(4,"reading %d bytes\n", (int)length);
  189838. if (png_ptr->read_data_fn != NULL)
  189839. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189840. else
  189841. png_error(png_ptr, "Call to NULL read function");
  189842. }
  189843. #if !defined(PNG_NO_STDIO)
  189844. /* This is the function that does the actual reading of data. If you are
  189845. not reading from a standard C stream, you should create a replacement
  189846. read_data function and use it at run time with png_set_read_fn(), rather
  189847. than changing the library. */
  189848. #ifndef USE_FAR_KEYWORD
  189849. void PNGAPI
  189850. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189851. {
  189852. png_size_t check;
  189853. if(png_ptr == NULL) return;
  189854. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189855. * instead of an int, which is what fread() actually returns.
  189856. */
  189857. #if defined(_WIN32_WCE)
  189858. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189859. check = 0;
  189860. #else
  189861. check = (png_size_t)fread(data, (png_size_t)1, length,
  189862. (png_FILE_p)png_ptr->io_ptr);
  189863. #endif
  189864. if (check != length)
  189865. png_error(png_ptr, "Read Error");
  189866. }
  189867. #else
  189868. /* this is the model-independent version. Since the standard I/O library
  189869. can't handle far buffers in the medium and small models, we have to copy
  189870. the data.
  189871. */
  189872. #define NEAR_BUF_SIZE 1024
  189873. #define MIN(a,b) (a <= b ? a : b)
  189874. static void PNGAPI
  189875. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189876. {
  189877. int check;
  189878. png_byte *n_data;
  189879. png_FILE_p io_ptr;
  189880. if(png_ptr == NULL) return;
  189881. /* Check if data really is near. If so, use usual code. */
  189882. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189883. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189884. if ((png_bytep)n_data == data)
  189885. {
  189886. #if defined(_WIN32_WCE)
  189887. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189888. check = 0;
  189889. #else
  189890. check = fread(n_data, 1, length, io_ptr);
  189891. #endif
  189892. }
  189893. else
  189894. {
  189895. png_byte buf[NEAR_BUF_SIZE];
  189896. png_size_t read, remaining, err;
  189897. check = 0;
  189898. remaining = length;
  189899. do
  189900. {
  189901. read = MIN(NEAR_BUF_SIZE, remaining);
  189902. #if defined(_WIN32_WCE)
  189903. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189904. err = 0;
  189905. #else
  189906. err = fread(buf, (png_size_t)1, read, io_ptr);
  189907. #endif
  189908. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189909. if(err != read)
  189910. break;
  189911. else
  189912. check += err;
  189913. data += read;
  189914. remaining -= read;
  189915. }
  189916. while (remaining != 0);
  189917. }
  189918. if ((png_uint_32)check != (png_uint_32)length)
  189919. png_error(png_ptr, "read Error");
  189920. }
  189921. #endif
  189922. #endif
  189923. /* This function allows the application to supply a new input function
  189924. for libpng if standard C streams aren't being used.
  189925. This function takes as its arguments:
  189926. png_ptr - pointer to a png input data structure
  189927. io_ptr - pointer to user supplied structure containing info about
  189928. the input functions. May be NULL.
  189929. read_data_fn - pointer to a new input function that takes as its
  189930. arguments a pointer to a png_struct, a pointer to
  189931. a location where input data can be stored, and a 32-bit
  189932. unsigned int that is the number of bytes to be read.
  189933. To exit and output any fatal error messages the new write
  189934. function should call png_error(png_ptr, "Error msg"). */
  189935. void PNGAPI
  189936. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189937. png_rw_ptr read_data_fn)
  189938. {
  189939. if(png_ptr == NULL) return;
  189940. png_ptr->io_ptr = io_ptr;
  189941. #if !defined(PNG_NO_STDIO)
  189942. if (read_data_fn != NULL)
  189943. png_ptr->read_data_fn = read_data_fn;
  189944. else
  189945. png_ptr->read_data_fn = png_default_read_data;
  189946. #else
  189947. png_ptr->read_data_fn = read_data_fn;
  189948. #endif
  189949. /* It is an error to write to a read device */
  189950. if (png_ptr->write_data_fn != NULL)
  189951. {
  189952. png_ptr->write_data_fn = NULL;
  189953. png_warning(png_ptr,
  189954. "It's an error to set both read_data_fn and write_data_fn in the ");
  189955. png_warning(png_ptr,
  189956. "same structure. Resetting write_data_fn to NULL.");
  189957. }
  189958. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189959. png_ptr->output_flush_fn = NULL;
  189960. #endif
  189961. }
  189962. #endif /* PNG_READ_SUPPORTED */
  189963. /*** End of inlined file: pngrio.c ***/
  189964. /*** Start of inlined file: pngrtran.c ***/
  189965. /* pngrtran.c - transforms the data in a row for PNG readers
  189966. *
  189967. * Last changed in libpng 1.2.21 [October 4, 2007]
  189968. * For conditions of distribution and use, see copyright notice in png.h
  189969. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189970. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189971. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189972. *
  189973. * This file contains functions optionally called by an application
  189974. * in order to tell libpng how to handle data when reading a PNG.
  189975. * Transformations that are used in both reading and writing are
  189976. * in pngtrans.c.
  189977. */
  189978. #define PNG_INTERNAL
  189979. #if defined(PNG_READ_SUPPORTED)
  189980. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189981. void PNGAPI
  189982. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189983. {
  189984. png_debug(1, "in png_set_crc_action\n");
  189985. /* Tell libpng how we react to CRC errors in critical chunks */
  189986. if(png_ptr == NULL) return;
  189987. switch (crit_action)
  189988. {
  189989. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189990. break;
  189991. case PNG_CRC_WARN_USE: /* warn/use data */
  189992. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189993. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189994. break;
  189995. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189996. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189997. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189998. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189999. break;
  190000. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190001. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190002. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190003. case PNG_CRC_DEFAULT:
  190004. default:
  190005. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190006. break;
  190007. }
  190008. switch (ancil_action)
  190009. {
  190010. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190011. break;
  190012. case PNG_CRC_WARN_USE: /* warn/use data */
  190013. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190014. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190015. break;
  190016. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190017. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190018. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190019. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190020. break;
  190021. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190022. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190023. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190024. break;
  190025. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190026. case PNG_CRC_DEFAULT:
  190027. default:
  190028. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190029. break;
  190030. }
  190031. }
  190032. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190033. defined(PNG_FLOATING_POINT_SUPPORTED)
  190034. /* handle alpha and tRNS via a background color */
  190035. void PNGAPI
  190036. png_set_background(png_structp png_ptr,
  190037. png_color_16p background_color, int background_gamma_code,
  190038. int need_expand, double background_gamma)
  190039. {
  190040. png_debug(1, "in png_set_background\n");
  190041. if(png_ptr == NULL) return;
  190042. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190043. {
  190044. png_warning(png_ptr, "Application must supply a known background gamma");
  190045. return;
  190046. }
  190047. png_ptr->transformations |= PNG_BACKGROUND;
  190048. png_memcpy(&(png_ptr->background), background_color,
  190049. png_sizeof(png_color_16));
  190050. png_ptr->background_gamma = (float)background_gamma;
  190051. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190052. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190053. }
  190054. #endif
  190055. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190056. /* strip 16 bit depth files to 8 bit depth */
  190057. void PNGAPI
  190058. png_set_strip_16(png_structp png_ptr)
  190059. {
  190060. png_debug(1, "in png_set_strip_16\n");
  190061. if(png_ptr == NULL) return;
  190062. png_ptr->transformations |= PNG_16_TO_8;
  190063. }
  190064. #endif
  190065. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190066. void PNGAPI
  190067. png_set_strip_alpha(png_structp png_ptr)
  190068. {
  190069. png_debug(1, "in png_set_strip_alpha\n");
  190070. if(png_ptr == NULL) return;
  190071. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190072. }
  190073. #endif
  190074. #if defined(PNG_READ_DITHER_SUPPORTED)
  190075. /* Dither file to 8 bit. Supply a palette, the current number
  190076. * of elements in the palette, the maximum number of elements
  190077. * allowed, and a histogram if possible. If the current number
  190078. * of colors is greater then the maximum number, the palette will be
  190079. * modified to fit in the maximum number. "full_dither" indicates
  190080. * whether we need a dithering cube set up for RGB images, or if we
  190081. * simply are reducing the number of colors in a paletted image.
  190082. */
  190083. typedef struct png_dsort_struct
  190084. {
  190085. struct png_dsort_struct FAR * next;
  190086. png_byte left;
  190087. png_byte right;
  190088. } png_dsort;
  190089. typedef png_dsort FAR * png_dsortp;
  190090. typedef png_dsort FAR * FAR * png_dsortpp;
  190091. void PNGAPI
  190092. png_set_dither(png_structp png_ptr, png_colorp palette,
  190093. int num_palette, int maximum_colors, png_uint_16p histogram,
  190094. int full_dither)
  190095. {
  190096. png_debug(1, "in png_set_dither\n");
  190097. if(png_ptr == NULL) return;
  190098. png_ptr->transformations |= PNG_DITHER;
  190099. if (!full_dither)
  190100. {
  190101. int i;
  190102. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190103. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190104. for (i = 0; i < num_palette; i++)
  190105. png_ptr->dither_index[i] = (png_byte)i;
  190106. }
  190107. if (num_palette > maximum_colors)
  190108. {
  190109. if (histogram != NULL)
  190110. {
  190111. /* This is easy enough, just throw out the least used colors.
  190112. Perhaps not the best solution, but good enough. */
  190113. int i;
  190114. /* initialize an array to sort colors */
  190115. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190116. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190117. /* initialize the dither_sort array */
  190118. for (i = 0; i < num_palette; i++)
  190119. png_ptr->dither_sort[i] = (png_byte)i;
  190120. /* Find the least used palette entries by starting a
  190121. bubble sort, and running it until we have sorted
  190122. out enough colors. Note that we don't care about
  190123. sorting all the colors, just finding which are
  190124. least used. */
  190125. for (i = num_palette - 1; i >= maximum_colors; i--)
  190126. {
  190127. int done; /* to stop early if the list is pre-sorted */
  190128. int j;
  190129. done = 1;
  190130. for (j = 0; j < i; j++)
  190131. {
  190132. if (histogram[png_ptr->dither_sort[j]]
  190133. < histogram[png_ptr->dither_sort[j + 1]])
  190134. {
  190135. png_byte t;
  190136. t = png_ptr->dither_sort[j];
  190137. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190138. png_ptr->dither_sort[j + 1] = t;
  190139. done = 0;
  190140. }
  190141. }
  190142. if (done)
  190143. break;
  190144. }
  190145. /* swap the palette around, and set up a table, if necessary */
  190146. if (full_dither)
  190147. {
  190148. int j = num_palette;
  190149. /* put all the useful colors within the max, but don't
  190150. move the others */
  190151. for (i = 0; i < maximum_colors; i++)
  190152. {
  190153. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190154. {
  190155. do
  190156. j--;
  190157. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190158. palette[i] = palette[j];
  190159. }
  190160. }
  190161. }
  190162. else
  190163. {
  190164. int j = num_palette;
  190165. /* move all the used colors inside the max limit, and
  190166. develop a translation table */
  190167. for (i = 0; i < maximum_colors; i++)
  190168. {
  190169. /* only move the colors we need to */
  190170. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190171. {
  190172. png_color tmp_color;
  190173. do
  190174. j--;
  190175. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190176. tmp_color = palette[j];
  190177. palette[j] = palette[i];
  190178. palette[i] = tmp_color;
  190179. /* indicate where the color went */
  190180. png_ptr->dither_index[j] = (png_byte)i;
  190181. png_ptr->dither_index[i] = (png_byte)j;
  190182. }
  190183. }
  190184. /* find closest color for those colors we are not using */
  190185. for (i = 0; i < num_palette; i++)
  190186. {
  190187. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190188. {
  190189. int min_d, k, min_k, d_index;
  190190. /* find the closest color to one we threw out */
  190191. d_index = png_ptr->dither_index[i];
  190192. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190193. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190194. {
  190195. int d;
  190196. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190197. if (d < min_d)
  190198. {
  190199. min_d = d;
  190200. min_k = k;
  190201. }
  190202. }
  190203. /* point to closest color */
  190204. png_ptr->dither_index[i] = (png_byte)min_k;
  190205. }
  190206. }
  190207. }
  190208. png_free(png_ptr, png_ptr->dither_sort);
  190209. png_ptr->dither_sort=NULL;
  190210. }
  190211. else
  190212. {
  190213. /* This is much harder to do simply (and quickly). Perhaps
  190214. we need to go through a median cut routine, but those
  190215. don't always behave themselves with only a few colors
  190216. as input. So we will just find the closest two colors,
  190217. and throw out one of them (chosen somewhat randomly).
  190218. [We don't understand this at all, so if someone wants to
  190219. work on improving it, be our guest - AED, GRP]
  190220. */
  190221. int i;
  190222. int max_d;
  190223. int num_new_palette;
  190224. png_dsortp t;
  190225. png_dsortpp hash;
  190226. t=NULL;
  190227. /* initialize palette index arrays */
  190228. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190229. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190230. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190231. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190232. /* initialize the sort array */
  190233. for (i = 0; i < num_palette; i++)
  190234. {
  190235. png_ptr->index_to_palette[i] = (png_byte)i;
  190236. png_ptr->palette_to_index[i] = (png_byte)i;
  190237. }
  190238. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190239. png_sizeof (png_dsortp)));
  190240. for (i = 0; i < 769; i++)
  190241. hash[i] = NULL;
  190242. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190243. num_new_palette = num_palette;
  190244. /* initial wild guess at how far apart the farthest pixel
  190245. pair we will be eliminating will be. Larger
  190246. numbers mean more areas will be allocated, Smaller
  190247. numbers run the risk of not saving enough data, and
  190248. having to do this all over again.
  190249. I have not done extensive checking on this number.
  190250. */
  190251. max_d = 96;
  190252. while (num_new_palette > maximum_colors)
  190253. {
  190254. for (i = 0; i < num_new_palette - 1; i++)
  190255. {
  190256. int j;
  190257. for (j = i + 1; j < num_new_palette; j++)
  190258. {
  190259. int d;
  190260. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190261. if (d <= max_d)
  190262. {
  190263. t = (png_dsortp)png_malloc_warn(png_ptr,
  190264. (png_uint_32)(png_sizeof(png_dsort)));
  190265. if (t == NULL)
  190266. break;
  190267. t->next = hash[d];
  190268. t->left = (png_byte)i;
  190269. t->right = (png_byte)j;
  190270. hash[d] = t;
  190271. }
  190272. }
  190273. if (t == NULL)
  190274. break;
  190275. }
  190276. if (t != NULL)
  190277. for (i = 0; i <= max_d; i++)
  190278. {
  190279. if (hash[i] != NULL)
  190280. {
  190281. png_dsortp p;
  190282. for (p = hash[i]; p; p = p->next)
  190283. {
  190284. if ((int)png_ptr->index_to_palette[p->left]
  190285. < num_new_palette &&
  190286. (int)png_ptr->index_to_palette[p->right]
  190287. < num_new_palette)
  190288. {
  190289. int j, next_j;
  190290. if (num_new_palette & 0x01)
  190291. {
  190292. j = p->left;
  190293. next_j = p->right;
  190294. }
  190295. else
  190296. {
  190297. j = p->right;
  190298. next_j = p->left;
  190299. }
  190300. num_new_palette--;
  190301. palette[png_ptr->index_to_palette[j]]
  190302. = palette[num_new_palette];
  190303. if (!full_dither)
  190304. {
  190305. int k;
  190306. for (k = 0; k < num_palette; k++)
  190307. {
  190308. if (png_ptr->dither_index[k] ==
  190309. png_ptr->index_to_palette[j])
  190310. png_ptr->dither_index[k] =
  190311. png_ptr->index_to_palette[next_j];
  190312. if ((int)png_ptr->dither_index[k] ==
  190313. num_new_palette)
  190314. png_ptr->dither_index[k] =
  190315. png_ptr->index_to_palette[j];
  190316. }
  190317. }
  190318. png_ptr->index_to_palette[png_ptr->palette_to_index
  190319. [num_new_palette]] = png_ptr->index_to_palette[j];
  190320. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190321. = png_ptr->palette_to_index[num_new_palette];
  190322. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190323. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190324. }
  190325. if (num_new_palette <= maximum_colors)
  190326. break;
  190327. }
  190328. if (num_new_palette <= maximum_colors)
  190329. break;
  190330. }
  190331. }
  190332. for (i = 0; i < 769; i++)
  190333. {
  190334. if (hash[i] != NULL)
  190335. {
  190336. png_dsortp p = hash[i];
  190337. while (p)
  190338. {
  190339. t = p->next;
  190340. png_free(png_ptr, p);
  190341. p = t;
  190342. }
  190343. }
  190344. hash[i] = 0;
  190345. }
  190346. max_d += 96;
  190347. }
  190348. png_free(png_ptr, hash);
  190349. png_free(png_ptr, png_ptr->palette_to_index);
  190350. png_free(png_ptr, png_ptr->index_to_palette);
  190351. png_ptr->palette_to_index=NULL;
  190352. png_ptr->index_to_palette=NULL;
  190353. }
  190354. num_palette = maximum_colors;
  190355. }
  190356. if (png_ptr->palette == NULL)
  190357. {
  190358. png_ptr->palette = palette;
  190359. }
  190360. png_ptr->num_palette = (png_uint_16)num_palette;
  190361. if (full_dither)
  190362. {
  190363. int i;
  190364. png_bytep distance;
  190365. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190366. PNG_DITHER_BLUE_BITS;
  190367. int num_red = (1 << PNG_DITHER_RED_BITS);
  190368. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190369. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190370. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190371. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190372. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190373. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190374. png_sizeof (png_byte));
  190375. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190376. png_sizeof(png_byte)));
  190377. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190378. for (i = 0; i < num_palette; i++)
  190379. {
  190380. int ir, ig, ib;
  190381. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190382. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190383. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190384. for (ir = 0; ir < num_red; ir++)
  190385. {
  190386. /* int dr = abs(ir - r); */
  190387. int dr = ((ir > r) ? ir - r : r - ir);
  190388. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190389. for (ig = 0; ig < num_green; ig++)
  190390. {
  190391. /* int dg = abs(ig - g); */
  190392. int dg = ((ig > g) ? ig - g : g - ig);
  190393. int dt = dr + dg;
  190394. int dm = ((dr > dg) ? dr : dg);
  190395. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190396. for (ib = 0; ib < num_blue; ib++)
  190397. {
  190398. int d_index = index_g | ib;
  190399. /* int db = abs(ib - b); */
  190400. int db = ((ib > b) ? ib - b : b - ib);
  190401. int dmax = ((dm > db) ? dm : db);
  190402. int d = dmax + dt + db;
  190403. if (d < (int)distance[d_index])
  190404. {
  190405. distance[d_index] = (png_byte)d;
  190406. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190407. }
  190408. }
  190409. }
  190410. }
  190411. }
  190412. png_free(png_ptr, distance);
  190413. }
  190414. }
  190415. #endif
  190416. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190417. /* Transform the image from the file_gamma to the screen_gamma. We
  190418. * only do transformations on images where the file_gamma and screen_gamma
  190419. * are not close reciprocals, otherwise it slows things down slightly, and
  190420. * also needlessly introduces small errors.
  190421. *
  190422. * We will turn off gamma transformation later if no semitransparent entries
  190423. * are present in the tRNS array for palette images. We can't do it here
  190424. * because we don't necessarily have the tRNS chunk yet.
  190425. */
  190426. void PNGAPI
  190427. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190428. {
  190429. png_debug(1, "in png_set_gamma\n");
  190430. if(png_ptr == NULL) return;
  190431. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190432. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190433. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190434. png_ptr->transformations |= PNG_GAMMA;
  190435. png_ptr->gamma = (float)file_gamma;
  190436. png_ptr->screen_gamma = (float)scrn_gamma;
  190437. }
  190438. #endif
  190439. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190440. /* Expand paletted images to RGB, expand grayscale images of
  190441. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190442. * to alpha channels.
  190443. */
  190444. void PNGAPI
  190445. png_set_expand(png_structp png_ptr)
  190446. {
  190447. png_debug(1, "in png_set_expand\n");
  190448. if(png_ptr == NULL) return;
  190449. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190450. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190451. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190452. #endif
  190453. }
  190454. /* GRR 19990627: the following three functions currently are identical
  190455. * to png_set_expand(). However, it is entirely reasonable that someone
  190456. * might wish to expand an indexed image to RGB but *not* expand a single,
  190457. * fully transparent palette entry to a full alpha channel--perhaps instead
  190458. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190459. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190460. * IOW, a future version of the library may make the transformations flag
  190461. * a bit more fine-grained, with separate bits for each of these three
  190462. * functions.
  190463. *
  190464. * More to the point, these functions make it obvious what libpng will be
  190465. * doing, whereas "expand" can (and does) mean any number of things.
  190466. *
  190467. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190468. * to expand only the sample depth but not to expand the tRNS to alpha.
  190469. */
  190470. /* Expand paletted images to RGB. */
  190471. void PNGAPI
  190472. png_set_palette_to_rgb(png_structp png_ptr)
  190473. {
  190474. png_debug(1, "in png_set_palette_to_rgb\n");
  190475. if(png_ptr == NULL) return;
  190476. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190477. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190478. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190479. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190480. #endif
  190481. }
  190482. #if !defined(PNG_1_0_X)
  190483. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190484. void PNGAPI
  190485. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190486. {
  190487. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190488. if(png_ptr == NULL) return;
  190489. png_ptr->transformations |= PNG_EXPAND;
  190490. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190491. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190492. #endif
  190493. }
  190494. #endif
  190495. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190496. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190497. /* Deprecated as of libpng-1.2.9 */
  190498. void PNGAPI
  190499. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190500. {
  190501. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190502. if(png_ptr == NULL) return;
  190503. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190504. }
  190505. #endif
  190506. /* Expand tRNS chunks to alpha channels. */
  190507. void PNGAPI
  190508. png_set_tRNS_to_alpha(png_structp png_ptr)
  190509. {
  190510. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190511. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190512. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190513. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190514. #endif
  190515. }
  190516. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190517. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190518. void PNGAPI
  190519. png_set_gray_to_rgb(png_structp png_ptr)
  190520. {
  190521. png_debug(1, "in png_set_gray_to_rgb\n");
  190522. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190523. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190524. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190525. #endif
  190526. }
  190527. #endif
  190528. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190529. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190530. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190531. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190532. */
  190533. void PNGAPI
  190534. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190535. double green)
  190536. {
  190537. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190538. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190539. if(png_ptr == NULL) return;
  190540. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190541. }
  190542. #endif
  190543. void PNGAPI
  190544. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190545. png_fixed_point red, png_fixed_point green)
  190546. {
  190547. png_debug(1, "in png_set_rgb_to_gray\n");
  190548. if(png_ptr == NULL) return;
  190549. switch(error_action)
  190550. {
  190551. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190552. break;
  190553. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190554. break;
  190555. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190556. }
  190557. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190558. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190559. png_ptr->transformations |= PNG_EXPAND;
  190560. #else
  190561. {
  190562. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190563. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190564. }
  190565. #endif
  190566. {
  190567. png_uint_16 red_int, green_int;
  190568. if(red < 0 || green < 0)
  190569. {
  190570. red_int = 6968; /* .212671 * 32768 + .5 */
  190571. green_int = 23434; /* .715160 * 32768 + .5 */
  190572. }
  190573. else if(red + green < 100000L)
  190574. {
  190575. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190576. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190577. }
  190578. else
  190579. {
  190580. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190581. red_int = 6968;
  190582. green_int = 23434;
  190583. }
  190584. png_ptr->rgb_to_gray_red_coeff = red_int;
  190585. png_ptr->rgb_to_gray_green_coeff = green_int;
  190586. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190587. }
  190588. }
  190589. #endif
  190590. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190591. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190592. defined(PNG_LEGACY_SUPPORTED)
  190593. void PNGAPI
  190594. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190595. read_user_transform_fn)
  190596. {
  190597. png_debug(1, "in png_set_read_user_transform_fn\n");
  190598. if(png_ptr == NULL) return;
  190599. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190600. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190601. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190602. #endif
  190603. #ifdef PNG_LEGACY_SUPPORTED
  190604. if(read_user_transform_fn)
  190605. png_warning(png_ptr,
  190606. "This version of libpng does not support user transforms");
  190607. #endif
  190608. }
  190609. #endif
  190610. /* Initialize everything needed for the read. This includes modifying
  190611. * the palette.
  190612. */
  190613. void /* PRIVATE */
  190614. png_init_read_transformations(png_structp png_ptr)
  190615. {
  190616. png_debug(1, "in png_init_read_transformations\n");
  190617. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190618. if(png_ptr != NULL)
  190619. #endif
  190620. {
  190621. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190622. || defined(PNG_READ_GAMMA_SUPPORTED)
  190623. int color_type = png_ptr->color_type;
  190624. #endif
  190625. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190626. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190627. /* Detect gray background and attempt to enable optimization
  190628. * for gray --> RGB case */
  190629. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190630. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190631. * background color might actually be gray yet not be flagged as such.
  190632. * This is not a problem for the current code, which uses
  190633. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190634. * png_do_gray_to_rgb() transformation.
  190635. */
  190636. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190637. !(color_type & PNG_COLOR_MASK_COLOR))
  190638. {
  190639. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190640. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190641. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190642. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190643. png_ptr->background.red == png_ptr->background.green &&
  190644. png_ptr->background.red == png_ptr->background.blue)
  190645. {
  190646. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190647. png_ptr->background.gray = png_ptr->background.red;
  190648. }
  190649. #endif
  190650. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190651. (png_ptr->transformations & PNG_EXPAND))
  190652. {
  190653. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190654. {
  190655. /* expand background and tRNS chunks */
  190656. switch (png_ptr->bit_depth)
  190657. {
  190658. case 1:
  190659. png_ptr->background.gray *= (png_uint_16)0xff;
  190660. png_ptr->background.red = png_ptr->background.green
  190661. = png_ptr->background.blue = png_ptr->background.gray;
  190662. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190663. {
  190664. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190665. png_ptr->trans_values.red = png_ptr->trans_values.green
  190666. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190667. }
  190668. break;
  190669. case 2:
  190670. png_ptr->background.gray *= (png_uint_16)0x55;
  190671. png_ptr->background.red = png_ptr->background.green
  190672. = png_ptr->background.blue = png_ptr->background.gray;
  190673. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190674. {
  190675. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190676. png_ptr->trans_values.red = png_ptr->trans_values.green
  190677. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190678. }
  190679. break;
  190680. case 4:
  190681. png_ptr->background.gray *= (png_uint_16)0x11;
  190682. png_ptr->background.red = png_ptr->background.green
  190683. = png_ptr->background.blue = png_ptr->background.gray;
  190684. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190685. {
  190686. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190687. png_ptr->trans_values.red = png_ptr->trans_values.green
  190688. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190689. }
  190690. break;
  190691. case 8:
  190692. case 16:
  190693. png_ptr->background.red = png_ptr->background.green
  190694. = png_ptr->background.blue = png_ptr->background.gray;
  190695. break;
  190696. }
  190697. }
  190698. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190699. {
  190700. png_ptr->background.red =
  190701. png_ptr->palette[png_ptr->background.index].red;
  190702. png_ptr->background.green =
  190703. png_ptr->palette[png_ptr->background.index].green;
  190704. png_ptr->background.blue =
  190705. png_ptr->palette[png_ptr->background.index].blue;
  190706. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190707. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190708. {
  190709. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190710. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190711. #endif
  190712. {
  190713. /* invert the alpha channel (in tRNS) unless the pixels are
  190714. going to be expanded, in which case leave it for later */
  190715. int i,istop;
  190716. istop=(int)png_ptr->num_trans;
  190717. for (i=0; i<istop; i++)
  190718. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190719. }
  190720. }
  190721. #endif
  190722. }
  190723. }
  190724. #endif
  190725. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190726. png_ptr->background_1 = png_ptr->background;
  190727. #endif
  190728. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190729. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190730. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190731. < PNG_GAMMA_THRESHOLD))
  190732. {
  190733. int i,k;
  190734. k=0;
  190735. for (i=0; i<png_ptr->num_trans; i++)
  190736. {
  190737. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190738. k=1; /* partial transparency is present */
  190739. }
  190740. if (k == 0)
  190741. png_ptr->transformations &= (~PNG_GAMMA);
  190742. }
  190743. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190744. png_ptr->gamma != 0.0)
  190745. {
  190746. png_build_gamma_table(png_ptr);
  190747. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190748. if (png_ptr->transformations & PNG_BACKGROUND)
  190749. {
  190750. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190751. {
  190752. /* could skip if no transparency and
  190753. */
  190754. png_color back, back_1;
  190755. png_colorp palette = png_ptr->palette;
  190756. int num_palette = png_ptr->num_palette;
  190757. int i;
  190758. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190759. {
  190760. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190761. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190762. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190763. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190764. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190765. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190766. }
  190767. else
  190768. {
  190769. double g, gs;
  190770. switch (png_ptr->background_gamma_type)
  190771. {
  190772. case PNG_BACKGROUND_GAMMA_SCREEN:
  190773. g = (png_ptr->screen_gamma);
  190774. gs = 1.0;
  190775. break;
  190776. case PNG_BACKGROUND_GAMMA_FILE:
  190777. g = 1.0 / (png_ptr->gamma);
  190778. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190779. break;
  190780. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190781. g = 1.0 / (png_ptr->background_gamma);
  190782. gs = 1.0 / (png_ptr->background_gamma *
  190783. png_ptr->screen_gamma);
  190784. break;
  190785. default:
  190786. g = 1.0; /* back_1 */
  190787. gs = 1.0; /* back */
  190788. }
  190789. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190790. {
  190791. back.red = (png_byte)png_ptr->background.red;
  190792. back.green = (png_byte)png_ptr->background.green;
  190793. back.blue = (png_byte)png_ptr->background.blue;
  190794. }
  190795. else
  190796. {
  190797. back.red = (png_byte)(pow(
  190798. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190799. back.green = (png_byte)(pow(
  190800. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190801. back.blue = (png_byte)(pow(
  190802. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190803. }
  190804. back_1.red = (png_byte)(pow(
  190805. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190806. back_1.green = (png_byte)(pow(
  190807. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190808. back_1.blue = (png_byte)(pow(
  190809. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190810. }
  190811. for (i = 0; i < num_palette; i++)
  190812. {
  190813. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190814. {
  190815. if (png_ptr->trans[i] == 0)
  190816. {
  190817. palette[i] = back;
  190818. }
  190819. else /* if (png_ptr->trans[i] != 0xff) */
  190820. {
  190821. png_byte v, w;
  190822. v = png_ptr->gamma_to_1[palette[i].red];
  190823. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190824. palette[i].red = png_ptr->gamma_from_1[w];
  190825. v = png_ptr->gamma_to_1[palette[i].green];
  190826. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190827. palette[i].green = png_ptr->gamma_from_1[w];
  190828. v = png_ptr->gamma_to_1[palette[i].blue];
  190829. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190830. palette[i].blue = png_ptr->gamma_from_1[w];
  190831. }
  190832. }
  190833. else
  190834. {
  190835. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190836. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190837. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190838. }
  190839. }
  190840. }
  190841. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190842. else
  190843. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190844. {
  190845. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190846. double g = 1.0;
  190847. double gs = 1.0;
  190848. switch (png_ptr->background_gamma_type)
  190849. {
  190850. case PNG_BACKGROUND_GAMMA_SCREEN:
  190851. g = (png_ptr->screen_gamma);
  190852. gs = 1.0;
  190853. break;
  190854. case PNG_BACKGROUND_GAMMA_FILE:
  190855. g = 1.0 / (png_ptr->gamma);
  190856. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190857. break;
  190858. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190859. g = 1.0 / (png_ptr->background_gamma);
  190860. gs = 1.0 / (png_ptr->background_gamma *
  190861. png_ptr->screen_gamma);
  190862. break;
  190863. }
  190864. png_ptr->background_1.gray = (png_uint_16)(pow(
  190865. (double)png_ptr->background.gray / m, g) * m + .5);
  190866. png_ptr->background.gray = (png_uint_16)(pow(
  190867. (double)png_ptr->background.gray / m, gs) * m + .5);
  190868. if ((png_ptr->background.red != png_ptr->background.green) ||
  190869. (png_ptr->background.red != png_ptr->background.blue) ||
  190870. (png_ptr->background.red != png_ptr->background.gray))
  190871. {
  190872. /* RGB or RGBA with color background */
  190873. png_ptr->background_1.red = (png_uint_16)(pow(
  190874. (double)png_ptr->background.red / m, g) * m + .5);
  190875. png_ptr->background_1.green = (png_uint_16)(pow(
  190876. (double)png_ptr->background.green / m, g) * m + .5);
  190877. png_ptr->background_1.blue = (png_uint_16)(pow(
  190878. (double)png_ptr->background.blue / m, g) * m + .5);
  190879. png_ptr->background.red = (png_uint_16)(pow(
  190880. (double)png_ptr->background.red / m, gs) * m + .5);
  190881. png_ptr->background.green = (png_uint_16)(pow(
  190882. (double)png_ptr->background.green / m, gs) * m + .5);
  190883. png_ptr->background.blue = (png_uint_16)(pow(
  190884. (double)png_ptr->background.blue / m, gs) * m + .5);
  190885. }
  190886. else
  190887. {
  190888. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190889. png_ptr->background_1.red = png_ptr->background_1.green
  190890. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190891. png_ptr->background.red = png_ptr->background.green
  190892. = png_ptr->background.blue = png_ptr->background.gray;
  190893. }
  190894. }
  190895. }
  190896. else
  190897. /* transformation does not include PNG_BACKGROUND */
  190898. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190899. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190900. {
  190901. png_colorp palette = png_ptr->palette;
  190902. int num_palette = png_ptr->num_palette;
  190903. int i;
  190904. for (i = 0; i < num_palette; i++)
  190905. {
  190906. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190907. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190908. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190909. }
  190910. }
  190911. }
  190912. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190913. else
  190914. #endif
  190915. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190916. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190917. /* No GAMMA transformation */
  190918. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190919. (color_type == PNG_COLOR_TYPE_PALETTE))
  190920. {
  190921. int i;
  190922. int istop = (int)png_ptr->num_trans;
  190923. png_color back;
  190924. png_colorp palette = png_ptr->palette;
  190925. back.red = (png_byte)png_ptr->background.red;
  190926. back.green = (png_byte)png_ptr->background.green;
  190927. back.blue = (png_byte)png_ptr->background.blue;
  190928. for (i = 0; i < istop; i++)
  190929. {
  190930. if (png_ptr->trans[i] == 0)
  190931. {
  190932. palette[i] = back;
  190933. }
  190934. else if (png_ptr->trans[i] != 0xff)
  190935. {
  190936. /* The png_composite() macro is defined in png.h */
  190937. png_composite(palette[i].red, palette[i].red,
  190938. png_ptr->trans[i], back.red);
  190939. png_composite(palette[i].green, palette[i].green,
  190940. png_ptr->trans[i], back.green);
  190941. png_composite(palette[i].blue, palette[i].blue,
  190942. png_ptr->trans[i], back.blue);
  190943. }
  190944. }
  190945. }
  190946. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190947. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190948. if ((png_ptr->transformations & PNG_SHIFT) &&
  190949. (color_type == PNG_COLOR_TYPE_PALETTE))
  190950. {
  190951. png_uint_16 i;
  190952. png_uint_16 istop = png_ptr->num_palette;
  190953. int sr = 8 - png_ptr->sig_bit.red;
  190954. int sg = 8 - png_ptr->sig_bit.green;
  190955. int sb = 8 - png_ptr->sig_bit.blue;
  190956. if (sr < 0 || sr > 8)
  190957. sr = 0;
  190958. if (sg < 0 || sg > 8)
  190959. sg = 0;
  190960. if (sb < 0 || sb > 8)
  190961. sb = 0;
  190962. for (i = 0; i < istop; i++)
  190963. {
  190964. png_ptr->palette[i].red >>= sr;
  190965. png_ptr->palette[i].green >>= sg;
  190966. png_ptr->palette[i].blue >>= sb;
  190967. }
  190968. }
  190969. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190970. }
  190971. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190972. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190973. if(png_ptr)
  190974. return;
  190975. #endif
  190976. }
  190977. /* Modify the info structure to reflect the transformations. The
  190978. * info should be updated so a PNG file could be written with it,
  190979. * assuming the transformations result in valid PNG data.
  190980. */
  190981. void /* PRIVATE */
  190982. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190983. {
  190984. png_debug(1, "in png_read_transform_info\n");
  190985. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190986. if (png_ptr->transformations & PNG_EXPAND)
  190987. {
  190988. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190989. {
  190990. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190991. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190992. else
  190993. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190994. info_ptr->bit_depth = 8;
  190995. info_ptr->num_trans = 0;
  190996. }
  190997. else
  190998. {
  190999. if (png_ptr->num_trans)
  191000. {
  191001. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191002. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191003. else
  191004. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191005. }
  191006. if (info_ptr->bit_depth < 8)
  191007. info_ptr->bit_depth = 8;
  191008. info_ptr->num_trans = 0;
  191009. }
  191010. }
  191011. #endif
  191012. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191013. if (png_ptr->transformations & PNG_BACKGROUND)
  191014. {
  191015. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191016. info_ptr->num_trans = 0;
  191017. info_ptr->background = png_ptr->background;
  191018. }
  191019. #endif
  191020. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191021. if (png_ptr->transformations & PNG_GAMMA)
  191022. {
  191023. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191024. info_ptr->gamma = png_ptr->gamma;
  191025. #endif
  191026. #ifdef PNG_FIXED_POINT_SUPPORTED
  191027. info_ptr->int_gamma = png_ptr->int_gamma;
  191028. #endif
  191029. }
  191030. #endif
  191031. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191032. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191033. info_ptr->bit_depth = 8;
  191034. #endif
  191035. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191036. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191037. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191038. #endif
  191039. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191040. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191041. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191042. #endif
  191043. #if defined(PNG_READ_DITHER_SUPPORTED)
  191044. if (png_ptr->transformations & PNG_DITHER)
  191045. {
  191046. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191047. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191048. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191049. {
  191050. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191051. }
  191052. }
  191053. #endif
  191054. #if defined(PNG_READ_PACK_SUPPORTED)
  191055. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191056. info_ptr->bit_depth = 8;
  191057. #endif
  191058. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191059. info_ptr->channels = 1;
  191060. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191061. info_ptr->channels = 3;
  191062. else
  191063. info_ptr->channels = 1;
  191064. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191065. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191066. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191067. #endif
  191068. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191069. info_ptr->channels++;
  191070. #if defined(PNG_READ_FILLER_SUPPORTED)
  191071. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191072. if ((png_ptr->transformations & PNG_FILLER) &&
  191073. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191074. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191075. {
  191076. info_ptr->channels++;
  191077. /* if adding a true alpha channel not just filler */
  191078. #if !defined(PNG_1_0_X)
  191079. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191080. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191081. #endif
  191082. }
  191083. #endif
  191084. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191085. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191086. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191087. {
  191088. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191089. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191090. if(info_ptr->channels < png_ptr->user_transform_channels)
  191091. info_ptr->channels = png_ptr->user_transform_channels;
  191092. }
  191093. #endif
  191094. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191095. info_ptr->bit_depth);
  191096. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191097. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191098. if(png_ptr)
  191099. return;
  191100. #endif
  191101. }
  191102. /* Transform the row. The order of transformations is significant,
  191103. * and is very touchy. If you add a transformation, take care to
  191104. * decide how it fits in with the other transformations here.
  191105. */
  191106. void /* PRIVATE */
  191107. png_do_read_transformations(png_structp png_ptr)
  191108. {
  191109. png_debug(1, "in png_do_read_transformations\n");
  191110. if (png_ptr->row_buf == NULL)
  191111. {
  191112. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191113. char msg[50];
  191114. png_snprintf2(msg, 50,
  191115. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191116. png_ptr->pass);
  191117. png_error(png_ptr, msg);
  191118. #else
  191119. png_error(png_ptr, "NULL row buffer");
  191120. #endif
  191121. }
  191122. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191123. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191124. /* Application has failed to call either png_read_start_image()
  191125. * or png_read_update_info() after setting transforms that expand
  191126. * pixels. This check added to libpng-1.2.19 */
  191127. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191128. png_error(png_ptr, "Uninitialized row");
  191129. #else
  191130. png_warning(png_ptr, "Uninitialized row");
  191131. #endif
  191132. #endif
  191133. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191134. if (png_ptr->transformations & PNG_EXPAND)
  191135. {
  191136. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191137. {
  191138. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191139. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191140. }
  191141. else
  191142. {
  191143. if (png_ptr->num_trans &&
  191144. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191145. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191146. &(png_ptr->trans_values));
  191147. else
  191148. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191149. NULL);
  191150. }
  191151. }
  191152. #endif
  191153. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191154. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191155. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191156. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191157. #endif
  191158. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191159. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191160. {
  191161. int rgb_error =
  191162. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191163. if(rgb_error)
  191164. {
  191165. png_ptr->rgb_to_gray_status=1;
  191166. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191167. PNG_RGB_TO_GRAY_WARN)
  191168. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191169. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191170. PNG_RGB_TO_GRAY_ERR)
  191171. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191172. }
  191173. }
  191174. #endif
  191175. /*
  191176. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191177. In most cases, the "simple transparency" should be done prior to doing
  191178. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191179. pixel is transparent. You would also need to make sure that the
  191180. transparency information is upgraded to RGB.
  191181. To summarize, the current flow is:
  191182. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191183. with background "in place" if transparent,
  191184. convert to RGB if necessary
  191185. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191186. convert to RGB if necessary
  191187. To support RGB backgrounds for gray images we need:
  191188. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191189. 3 or 6 bytes and composite with background
  191190. "in place" if transparent (3x compare/pixel
  191191. compared to doing composite with gray bkgrnd)
  191192. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191193. remove alpha bytes (3x float operations/pixel
  191194. compared with composite on gray background)
  191195. Greg's change will do this. The reason it wasn't done before is for
  191196. performance, as this increases the per-pixel operations. If we would check
  191197. in advance if the background was gray or RGB, and position the gray-to-RGB
  191198. transform appropriately, then it would save a lot of work/time.
  191199. */
  191200. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191201. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191202. * for performance reasons */
  191203. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191204. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191205. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191206. #endif
  191207. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191208. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191209. ((png_ptr->num_trans != 0 ) ||
  191210. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191211. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191212. &(png_ptr->trans_values), &(png_ptr->background)
  191213. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191214. , &(png_ptr->background_1),
  191215. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191216. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191217. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191218. png_ptr->gamma_shift
  191219. #endif
  191220. );
  191221. #endif
  191222. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191223. if ((png_ptr->transformations & PNG_GAMMA) &&
  191224. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191225. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191226. ((png_ptr->num_trans != 0) ||
  191227. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191228. #endif
  191229. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191230. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191231. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191232. png_ptr->gamma_shift);
  191233. #endif
  191234. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191235. if (png_ptr->transformations & PNG_16_TO_8)
  191236. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191237. #endif
  191238. #if defined(PNG_READ_DITHER_SUPPORTED)
  191239. if (png_ptr->transformations & PNG_DITHER)
  191240. {
  191241. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191242. png_ptr->palette_lookup, png_ptr->dither_index);
  191243. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191244. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191245. }
  191246. #endif
  191247. #if defined(PNG_READ_INVERT_SUPPORTED)
  191248. if (png_ptr->transformations & PNG_INVERT_MONO)
  191249. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191250. #endif
  191251. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191252. if (png_ptr->transformations & PNG_SHIFT)
  191253. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191254. &(png_ptr->shift));
  191255. #endif
  191256. #if defined(PNG_READ_PACK_SUPPORTED)
  191257. if (png_ptr->transformations & PNG_PACK)
  191258. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191259. #endif
  191260. #if defined(PNG_READ_BGR_SUPPORTED)
  191261. if (png_ptr->transformations & PNG_BGR)
  191262. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191263. #endif
  191264. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191265. if (png_ptr->transformations & PNG_PACKSWAP)
  191266. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191267. #endif
  191268. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191269. /* if gray -> RGB, do so now only if we did not do so above */
  191270. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191271. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191272. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191273. #endif
  191274. #if defined(PNG_READ_FILLER_SUPPORTED)
  191275. if (png_ptr->transformations & PNG_FILLER)
  191276. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191277. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191278. #endif
  191279. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191280. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191281. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191282. #endif
  191283. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191284. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191285. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191286. #endif
  191287. #if defined(PNG_READ_SWAP_SUPPORTED)
  191288. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191289. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191290. #endif
  191291. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191292. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191293. {
  191294. if(png_ptr->read_user_transform_fn != NULL)
  191295. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191296. (png_ptr, /* png_ptr */
  191297. &(png_ptr->row_info), /* row_info: */
  191298. /* png_uint_32 width; width of row */
  191299. /* png_uint_32 rowbytes; number of bytes in row */
  191300. /* png_byte color_type; color type of pixels */
  191301. /* png_byte bit_depth; bit depth of samples */
  191302. /* png_byte channels; number of channels (1-4) */
  191303. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191304. png_ptr->row_buf + 1); /* start of pixel data for row */
  191305. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191306. if(png_ptr->user_transform_depth)
  191307. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191308. if(png_ptr->user_transform_channels)
  191309. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191310. #endif
  191311. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191312. png_ptr->row_info.channels);
  191313. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191314. png_ptr->row_info.width);
  191315. }
  191316. #endif
  191317. }
  191318. #if defined(PNG_READ_PACK_SUPPORTED)
  191319. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191320. * without changing the actual values. Thus, if you had a row with
  191321. * a bit depth of 1, you would end up with bytes that only contained
  191322. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191323. * png_do_shift() after this.
  191324. */
  191325. void /* PRIVATE */
  191326. png_do_unpack(png_row_infop row_info, png_bytep row)
  191327. {
  191328. png_debug(1, "in png_do_unpack\n");
  191329. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191330. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191331. #else
  191332. if (row_info->bit_depth < 8)
  191333. #endif
  191334. {
  191335. png_uint_32 i;
  191336. png_uint_32 row_width=row_info->width;
  191337. switch (row_info->bit_depth)
  191338. {
  191339. case 1:
  191340. {
  191341. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191342. png_bytep dp = row + (png_size_t)row_width - 1;
  191343. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191344. for (i = 0; i < row_width; i++)
  191345. {
  191346. *dp = (png_byte)((*sp >> shift) & 0x01);
  191347. if (shift == 7)
  191348. {
  191349. shift = 0;
  191350. sp--;
  191351. }
  191352. else
  191353. shift++;
  191354. dp--;
  191355. }
  191356. break;
  191357. }
  191358. case 2:
  191359. {
  191360. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191361. png_bytep dp = row + (png_size_t)row_width - 1;
  191362. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191363. for (i = 0; i < row_width; i++)
  191364. {
  191365. *dp = (png_byte)((*sp >> shift) & 0x03);
  191366. if (shift == 6)
  191367. {
  191368. shift = 0;
  191369. sp--;
  191370. }
  191371. else
  191372. shift += 2;
  191373. dp--;
  191374. }
  191375. break;
  191376. }
  191377. case 4:
  191378. {
  191379. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191380. png_bytep dp = row + (png_size_t)row_width - 1;
  191381. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191382. for (i = 0; i < row_width; i++)
  191383. {
  191384. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191385. if (shift == 4)
  191386. {
  191387. shift = 0;
  191388. sp--;
  191389. }
  191390. else
  191391. shift = 4;
  191392. dp--;
  191393. }
  191394. break;
  191395. }
  191396. }
  191397. row_info->bit_depth = 8;
  191398. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191399. row_info->rowbytes = row_width * row_info->channels;
  191400. }
  191401. }
  191402. #endif
  191403. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191404. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191405. * pixels back to their significant bits values. Thus, if you have
  191406. * a row of bit depth 8, but only 5 are significant, this will shift
  191407. * the values back to 0 through 31.
  191408. */
  191409. void /* PRIVATE */
  191410. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191411. {
  191412. png_debug(1, "in png_do_unshift\n");
  191413. if (
  191414. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191415. row != NULL && row_info != NULL && sig_bits != NULL &&
  191416. #endif
  191417. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191418. {
  191419. int shift[4];
  191420. int channels = 0;
  191421. int c;
  191422. png_uint_16 value = 0;
  191423. png_uint_32 row_width = row_info->width;
  191424. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191425. {
  191426. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191427. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191428. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191429. }
  191430. else
  191431. {
  191432. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191433. }
  191434. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191435. {
  191436. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191437. }
  191438. for (c = 0; c < channels; c++)
  191439. {
  191440. if (shift[c] <= 0)
  191441. shift[c] = 0;
  191442. else
  191443. value = 1;
  191444. }
  191445. if (!value)
  191446. return;
  191447. switch (row_info->bit_depth)
  191448. {
  191449. case 2:
  191450. {
  191451. png_bytep bp;
  191452. png_uint_32 i;
  191453. png_uint_32 istop = row_info->rowbytes;
  191454. for (bp = row, i = 0; i < istop; i++)
  191455. {
  191456. *bp >>= 1;
  191457. *bp++ &= 0x55;
  191458. }
  191459. break;
  191460. }
  191461. case 4:
  191462. {
  191463. png_bytep bp = row;
  191464. png_uint_32 i;
  191465. png_uint_32 istop = row_info->rowbytes;
  191466. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191467. (png_byte)((int)0xf >> shift[0]));
  191468. for (i = 0; i < istop; i++)
  191469. {
  191470. *bp >>= shift[0];
  191471. *bp++ &= mask;
  191472. }
  191473. break;
  191474. }
  191475. case 8:
  191476. {
  191477. png_bytep bp = row;
  191478. png_uint_32 i;
  191479. png_uint_32 istop = row_width * channels;
  191480. for (i = 0; i < istop; i++)
  191481. {
  191482. *bp++ >>= shift[i%channels];
  191483. }
  191484. break;
  191485. }
  191486. case 16:
  191487. {
  191488. png_bytep bp = row;
  191489. png_uint_32 i;
  191490. png_uint_32 istop = channels * row_width;
  191491. for (i = 0; i < istop; i++)
  191492. {
  191493. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191494. value >>= shift[i%channels];
  191495. *bp++ = (png_byte)(value >> 8);
  191496. *bp++ = (png_byte)(value & 0xff);
  191497. }
  191498. break;
  191499. }
  191500. }
  191501. }
  191502. }
  191503. #endif
  191504. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191505. /* chop rows of bit depth 16 down to 8 */
  191506. void /* PRIVATE */
  191507. png_do_chop(png_row_infop row_info, png_bytep row)
  191508. {
  191509. png_debug(1, "in png_do_chop\n");
  191510. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191511. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191512. #else
  191513. if (row_info->bit_depth == 16)
  191514. #endif
  191515. {
  191516. png_bytep sp = row;
  191517. png_bytep dp = row;
  191518. png_uint_32 i;
  191519. png_uint_32 istop = row_info->width * row_info->channels;
  191520. for (i = 0; i<istop; i++, sp += 2, dp++)
  191521. {
  191522. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191523. /* This does a more accurate scaling of the 16-bit color
  191524. * value, rather than a simple low-byte truncation.
  191525. *
  191526. * What the ideal calculation should be:
  191527. * *dp = (((((png_uint_32)(*sp) << 8) |
  191528. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191529. *
  191530. * GRR: no, I think this is what it really should be:
  191531. * *dp = (((((png_uint_32)(*sp) << 8) |
  191532. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191533. *
  191534. * GRR: here's the exact calculation with shifts:
  191535. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191536. * *dp = (temp - (temp >> 8)) >> 8;
  191537. *
  191538. * Approximate calculation with shift/add instead of multiply/divide:
  191539. * *dp = ((((png_uint_32)(*sp) << 8) |
  191540. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191541. *
  191542. * What we actually do to avoid extra shifting and conversion:
  191543. */
  191544. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191545. #else
  191546. /* Simply discard the low order byte */
  191547. *dp = *sp;
  191548. #endif
  191549. }
  191550. row_info->bit_depth = 8;
  191551. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191552. row_info->rowbytes = row_info->width * row_info->channels;
  191553. }
  191554. }
  191555. #endif
  191556. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191557. void /* PRIVATE */
  191558. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191559. {
  191560. png_debug(1, "in png_do_read_swap_alpha\n");
  191561. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191562. if (row != NULL && row_info != NULL)
  191563. #endif
  191564. {
  191565. png_uint_32 row_width = row_info->width;
  191566. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191567. {
  191568. /* This converts from RGBA to ARGB */
  191569. if (row_info->bit_depth == 8)
  191570. {
  191571. png_bytep sp = row + row_info->rowbytes;
  191572. png_bytep dp = sp;
  191573. png_byte save;
  191574. png_uint_32 i;
  191575. for (i = 0; i < row_width; i++)
  191576. {
  191577. save = *(--sp);
  191578. *(--dp) = *(--sp);
  191579. *(--dp) = *(--sp);
  191580. *(--dp) = *(--sp);
  191581. *(--dp) = save;
  191582. }
  191583. }
  191584. /* This converts from RRGGBBAA to AARRGGBB */
  191585. else
  191586. {
  191587. png_bytep sp = row + row_info->rowbytes;
  191588. png_bytep dp = sp;
  191589. png_byte save[2];
  191590. png_uint_32 i;
  191591. for (i = 0; i < row_width; i++)
  191592. {
  191593. save[0] = *(--sp);
  191594. save[1] = *(--sp);
  191595. *(--dp) = *(--sp);
  191596. *(--dp) = *(--sp);
  191597. *(--dp) = *(--sp);
  191598. *(--dp) = *(--sp);
  191599. *(--dp) = *(--sp);
  191600. *(--dp) = *(--sp);
  191601. *(--dp) = save[0];
  191602. *(--dp) = save[1];
  191603. }
  191604. }
  191605. }
  191606. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191607. {
  191608. /* This converts from GA to AG */
  191609. if (row_info->bit_depth == 8)
  191610. {
  191611. png_bytep sp = row + row_info->rowbytes;
  191612. png_bytep dp = sp;
  191613. png_byte save;
  191614. png_uint_32 i;
  191615. for (i = 0; i < row_width; i++)
  191616. {
  191617. save = *(--sp);
  191618. *(--dp) = *(--sp);
  191619. *(--dp) = save;
  191620. }
  191621. }
  191622. /* This converts from GGAA to AAGG */
  191623. else
  191624. {
  191625. png_bytep sp = row + row_info->rowbytes;
  191626. png_bytep dp = sp;
  191627. png_byte save[2];
  191628. png_uint_32 i;
  191629. for (i = 0; i < row_width; i++)
  191630. {
  191631. save[0] = *(--sp);
  191632. save[1] = *(--sp);
  191633. *(--dp) = *(--sp);
  191634. *(--dp) = *(--sp);
  191635. *(--dp) = save[0];
  191636. *(--dp) = save[1];
  191637. }
  191638. }
  191639. }
  191640. }
  191641. }
  191642. #endif
  191643. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191644. void /* PRIVATE */
  191645. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191646. {
  191647. png_debug(1, "in png_do_read_invert_alpha\n");
  191648. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191649. if (row != NULL && row_info != NULL)
  191650. #endif
  191651. {
  191652. png_uint_32 row_width = row_info->width;
  191653. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191654. {
  191655. /* This inverts the alpha channel in RGBA */
  191656. if (row_info->bit_depth == 8)
  191657. {
  191658. png_bytep sp = row + row_info->rowbytes;
  191659. png_bytep dp = sp;
  191660. png_uint_32 i;
  191661. for (i = 0; i < row_width; i++)
  191662. {
  191663. *(--dp) = (png_byte)(255 - *(--sp));
  191664. /* This does nothing:
  191665. *(--dp) = *(--sp);
  191666. *(--dp) = *(--sp);
  191667. *(--dp) = *(--sp);
  191668. We can replace it with:
  191669. */
  191670. sp-=3;
  191671. dp=sp;
  191672. }
  191673. }
  191674. /* This inverts the alpha channel in RRGGBBAA */
  191675. else
  191676. {
  191677. png_bytep sp = row + row_info->rowbytes;
  191678. png_bytep dp = sp;
  191679. png_uint_32 i;
  191680. for (i = 0; i < row_width; i++)
  191681. {
  191682. *(--dp) = (png_byte)(255 - *(--sp));
  191683. *(--dp) = (png_byte)(255 - *(--sp));
  191684. /* This does nothing:
  191685. *(--dp) = *(--sp);
  191686. *(--dp) = *(--sp);
  191687. *(--dp) = *(--sp);
  191688. *(--dp) = *(--sp);
  191689. *(--dp) = *(--sp);
  191690. *(--dp) = *(--sp);
  191691. We can replace it with:
  191692. */
  191693. sp-=6;
  191694. dp=sp;
  191695. }
  191696. }
  191697. }
  191698. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191699. {
  191700. /* This inverts the alpha channel in GA */
  191701. if (row_info->bit_depth == 8)
  191702. {
  191703. png_bytep sp = row + row_info->rowbytes;
  191704. png_bytep dp = sp;
  191705. png_uint_32 i;
  191706. for (i = 0; i < row_width; i++)
  191707. {
  191708. *(--dp) = (png_byte)(255 - *(--sp));
  191709. *(--dp) = *(--sp);
  191710. }
  191711. }
  191712. /* This inverts the alpha channel in GGAA */
  191713. else
  191714. {
  191715. png_bytep sp = row + row_info->rowbytes;
  191716. png_bytep dp = sp;
  191717. png_uint_32 i;
  191718. for (i = 0; i < row_width; i++)
  191719. {
  191720. *(--dp) = (png_byte)(255 - *(--sp));
  191721. *(--dp) = (png_byte)(255 - *(--sp));
  191722. /*
  191723. *(--dp) = *(--sp);
  191724. *(--dp) = *(--sp);
  191725. */
  191726. sp-=2;
  191727. dp=sp;
  191728. }
  191729. }
  191730. }
  191731. }
  191732. }
  191733. #endif
  191734. #if defined(PNG_READ_FILLER_SUPPORTED)
  191735. /* Add filler channel if we have RGB color */
  191736. void /* PRIVATE */
  191737. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191738. png_uint_32 filler, png_uint_32 flags)
  191739. {
  191740. png_uint_32 i;
  191741. png_uint_32 row_width = row_info->width;
  191742. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191743. png_byte lo_filler = (png_byte)(filler & 0xff);
  191744. png_debug(1, "in png_do_read_filler\n");
  191745. if (
  191746. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191747. row != NULL && row_info != NULL &&
  191748. #endif
  191749. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191750. {
  191751. if(row_info->bit_depth == 8)
  191752. {
  191753. /* This changes the data from G to GX */
  191754. if (flags & PNG_FLAG_FILLER_AFTER)
  191755. {
  191756. png_bytep sp = row + (png_size_t)row_width;
  191757. png_bytep dp = sp + (png_size_t)row_width;
  191758. for (i = 1; i < row_width; i++)
  191759. {
  191760. *(--dp) = lo_filler;
  191761. *(--dp) = *(--sp);
  191762. }
  191763. *(--dp) = lo_filler;
  191764. row_info->channels = 2;
  191765. row_info->pixel_depth = 16;
  191766. row_info->rowbytes = row_width * 2;
  191767. }
  191768. /* This changes the data from G to XG */
  191769. else
  191770. {
  191771. png_bytep sp = row + (png_size_t)row_width;
  191772. png_bytep dp = sp + (png_size_t)row_width;
  191773. for (i = 0; i < row_width; i++)
  191774. {
  191775. *(--dp) = *(--sp);
  191776. *(--dp) = lo_filler;
  191777. }
  191778. row_info->channels = 2;
  191779. row_info->pixel_depth = 16;
  191780. row_info->rowbytes = row_width * 2;
  191781. }
  191782. }
  191783. else if(row_info->bit_depth == 16)
  191784. {
  191785. /* This changes the data from GG to GGXX */
  191786. if (flags & PNG_FLAG_FILLER_AFTER)
  191787. {
  191788. png_bytep sp = row + (png_size_t)row_width * 2;
  191789. png_bytep dp = sp + (png_size_t)row_width * 2;
  191790. for (i = 1; i < row_width; i++)
  191791. {
  191792. *(--dp) = hi_filler;
  191793. *(--dp) = lo_filler;
  191794. *(--dp) = *(--sp);
  191795. *(--dp) = *(--sp);
  191796. }
  191797. *(--dp) = hi_filler;
  191798. *(--dp) = lo_filler;
  191799. row_info->channels = 2;
  191800. row_info->pixel_depth = 32;
  191801. row_info->rowbytes = row_width * 4;
  191802. }
  191803. /* This changes the data from GG to XXGG */
  191804. else
  191805. {
  191806. png_bytep sp = row + (png_size_t)row_width * 2;
  191807. png_bytep dp = sp + (png_size_t)row_width * 2;
  191808. for (i = 0; i < row_width; i++)
  191809. {
  191810. *(--dp) = *(--sp);
  191811. *(--dp) = *(--sp);
  191812. *(--dp) = hi_filler;
  191813. *(--dp) = lo_filler;
  191814. }
  191815. row_info->channels = 2;
  191816. row_info->pixel_depth = 32;
  191817. row_info->rowbytes = row_width * 4;
  191818. }
  191819. }
  191820. } /* COLOR_TYPE == GRAY */
  191821. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191822. {
  191823. if(row_info->bit_depth == 8)
  191824. {
  191825. /* This changes the data from RGB to RGBX */
  191826. if (flags & PNG_FLAG_FILLER_AFTER)
  191827. {
  191828. png_bytep sp = row + (png_size_t)row_width * 3;
  191829. png_bytep dp = sp + (png_size_t)row_width;
  191830. for (i = 1; i < row_width; i++)
  191831. {
  191832. *(--dp) = lo_filler;
  191833. *(--dp) = *(--sp);
  191834. *(--dp) = *(--sp);
  191835. *(--dp) = *(--sp);
  191836. }
  191837. *(--dp) = lo_filler;
  191838. row_info->channels = 4;
  191839. row_info->pixel_depth = 32;
  191840. row_info->rowbytes = row_width * 4;
  191841. }
  191842. /* This changes the data from RGB to XRGB */
  191843. else
  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 = 0; i < row_width; i++)
  191848. {
  191849. *(--dp) = *(--sp);
  191850. *(--dp) = *(--sp);
  191851. *(--dp) = *(--sp);
  191852. *(--dp) = lo_filler;
  191853. }
  191854. row_info->channels = 4;
  191855. row_info->pixel_depth = 32;
  191856. row_info->rowbytes = row_width * 4;
  191857. }
  191858. }
  191859. else if(row_info->bit_depth == 16)
  191860. {
  191861. /* This changes the data from RRGGBB to RRGGBBXX */
  191862. if (flags & PNG_FLAG_FILLER_AFTER)
  191863. {
  191864. png_bytep sp = row + (png_size_t)row_width * 6;
  191865. png_bytep dp = sp + (png_size_t)row_width * 2;
  191866. for (i = 1; i < row_width; i++)
  191867. {
  191868. *(--dp) = hi_filler;
  191869. *(--dp) = lo_filler;
  191870. *(--dp) = *(--sp);
  191871. *(--dp) = *(--sp);
  191872. *(--dp) = *(--sp);
  191873. *(--dp) = *(--sp);
  191874. *(--dp) = *(--sp);
  191875. *(--dp) = *(--sp);
  191876. }
  191877. *(--dp) = hi_filler;
  191878. *(--dp) = lo_filler;
  191879. row_info->channels = 4;
  191880. row_info->pixel_depth = 64;
  191881. row_info->rowbytes = row_width * 8;
  191882. }
  191883. /* This changes the data from RRGGBB to XXRRGGBB */
  191884. else
  191885. {
  191886. png_bytep sp = row + (png_size_t)row_width * 6;
  191887. png_bytep dp = sp + (png_size_t)row_width * 2;
  191888. for (i = 0; i < row_width; i++)
  191889. {
  191890. *(--dp) = *(--sp);
  191891. *(--dp) = *(--sp);
  191892. *(--dp) = *(--sp);
  191893. *(--dp) = *(--sp);
  191894. *(--dp) = *(--sp);
  191895. *(--dp) = *(--sp);
  191896. *(--dp) = hi_filler;
  191897. *(--dp) = lo_filler;
  191898. }
  191899. row_info->channels = 4;
  191900. row_info->pixel_depth = 64;
  191901. row_info->rowbytes = row_width * 8;
  191902. }
  191903. }
  191904. } /* COLOR_TYPE == RGB */
  191905. }
  191906. #endif
  191907. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191908. /* expand grayscale files to RGB, with or without alpha */
  191909. void /* PRIVATE */
  191910. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191911. {
  191912. png_uint_32 i;
  191913. png_uint_32 row_width = row_info->width;
  191914. png_debug(1, "in png_do_gray_to_rgb\n");
  191915. if (row_info->bit_depth >= 8 &&
  191916. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191917. row != NULL && row_info != NULL &&
  191918. #endif
  191919. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191920. {
  191921. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191922. {
  191923. if (row_info->bit_depth == 8)
  191924. {
  191925. png_bytep sp = row + (png_size_t)row_width - 1;
  191926. png_bytep dp = sp + (png_size_t)row_width * 2;
  191927. for (i = 0; i < row_width; i++)
  191928. {
  191929. *(dp--) = *sp;
  191930. *(dp--) = *sp;
  191931. *(dp--) = *(sp--);
  191932. }
  191933. }
  191934. else
  191935. {
  191936. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191937. png_bytep dp = sp + (png_size_t)row_width * 4;
  191938. for (i = 0; i < row_width; i++)
  191939. {
  191940. *(dp--) = *sp;
  191941. *(dp--) = *(sp - 1);
  191942. *(dp--) = *sp;
  191943. *(dp--) = *(sp - 1);
  191944. *(dp--) = *(sp--);
  191945. *(dp--) = *(sp--);
  191946. }
  191947. }
  191948. }
  191949. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191950. {
  191951. if (row_info->bit_depth == 8)
  191952. {
  191953. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191954. png_bytep dp = sp + (png_size_t)row_width * 2;
  191955. for (i = 0; i < row_width; i++)
  191956. {
  191957. *(dp--) = *(sp--);
  191958. *(dp--) = *sp;
  191959. *(dp--) = *sp;
  191960. *(dp--) = *(sp--);
  191961. }
  191962. }
  191963. else
  191964. {
  191965. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191966. png_bytep dp = sp + (png_size_t)row_width * 4;
  191967. for (i = 0; i < row_width; i++)
  191968. {
  191969. *(dp--) = *(sp--);
  191970. *(dp--) = *(sp--);
  191971. *(dp--) = *sp;
  191972. *(dp--) = *(sp - 1);
  191973. *(dp--) = *sp;
  191974. *(dp--) = *(sp - 1);
  191975. *(dp--) = *(sp--);
  191976. *(dp--) = *(sp--);
  191977. }
  191978. }
  191979. }
  191980. row_info->channels += (png_byte)2;
  191981. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191982. row_info->pixel_depth = (png_byte)(row_info->channels *
  191983. row_info->bit_depth);
  191984. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191985. }
  191986. }
  191987. #endif
  191988. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191989. /* reduce RGB files to grayscale, with or without alpha
  191990. * using the equation given in Poynton's ColorFAQ at
  191991. * <http://www.inforamp.net/~poynton/>
  191992. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191993. *
  191994. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191995. *
  191996. * We approximate this with
  191997. *
  191998. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191999. *
  192000. * which can be expressed with integers as
  192001. *
  192002. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192003. *
  192004. * The calculation is to be done in a linear colorspace.
  192005. *
  192006. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192007. */
  192008. int /* PRIVATE */
  192009. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192010. {
  192011. png_uint_32 i;
  192012. png_uint_32 row_width = row_info->width;
  192013. int rgb_error = 0;
  192014. png_debug(1, "in png_do_rgb_to_gray\n");
  192015. if (
  192016. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192017. row != NULL && row_info != NULL &&
  192018. #endif
  192019. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192020. {
  192021. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192022. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192023. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192024. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192025. {
  192026. if (row_info->bit_depth == 8)
  192027. {
  192028. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192029. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192030. {
  192031. png_bytep sp = row;
  192032. png_bytep dp = row;
  192033. for (i = 0; i < row_width; i++)
  192034. {
  192035. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192036. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192037. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192038. if(red != green || red != blue)
  192039. {
  192040. rgb_error |= 1;
  192041. *(dp++) = png_ptr->gamma_from_1[
  192042. (rc*red+gc*green+bc*blue)>>15];
  192043. }
  192044. else
  192045. *(dp++) = *(sp-1);
  192046. }
  192047. }
  192048. else
  192049. #endif
  192050. {
  192051. png_bytep sp = row;
  192052. png_bytep dp = row;
  192053. for (i = 0; i < row_width; i++)
  192054. {
  192055. png_byte red = *(sp++);
  192056. png_byte green = *(sp++);
  192057. png_byte blue = *(sp++);
  192058. if(red != green || red != blue)
  192059. {
  192060. rgb_error |= 1;
  192061. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192062. }
  192063. else
  192064. *(dp++) = *(sp-1);
  192065. }
  192066. }
  192067. }
  192068. else /* RGB bit_depth == 16 */
  192069. {
  192070. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192071. if (png_ptr->gamma_16_to_1 != NULL &&
  192072. png_ptr->gamma_16_from_1 != NULL)
  192073. {
  192074. png_bytep sp = row;
  192075. png_bytep dp = row;
  192076. for (i = 0; i < row_width; i++)
  192077. {
  192078. png_uint_16 red, green, blue, w;
  192079. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192080. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192081. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192082. if(red == green && red == blue)
  192083. w = red;
  192084. else
  192085. {
  192086. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192087. png_ptr->gamma_shift][red>>8];
  192088. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192089. png_ptr->gamma_shift][green>>8];
  192090. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192091. png_ptr->gamma_shift][blue>>8];
  192092. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192093. + bc*blue_1)>>15);
  192094. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192095. png_ptr->gamma_shift][gray16 >> 8];
  192096. rgb_error |= 1;
  192097. }
  192098. *(dp++) = (png_byte)((w>>8) & 0xff);
  192099. *(dp++) = (png_byte)(w & 0xff);
  192100. }
  192101. }
  192102. else
  192103. #endif
  192104. {
  192105. png_bytep sp = row;
  192106. png_bytep dp = row;
  192107. for (i = 0; i < row_width; i++)
  192108. {
  192109. png_uint_16 red, green, blue, gray16;
  192110. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192111. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192112. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192113. if(red != green || red != blue)
  192114. rgb_error |= 1;
  192115. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192116. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192117. *(dp++) = (png_byte)(gray16 & 0xff);
  192118. }
  192119. }
  192120. }
  192121. }
  192122. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192123. {
  192124. if (row_info->bit_depth == 8)
  192125. {
  192126. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192127. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192128. {
  192129. png_bytep sp = row;
  192130. png_bytep dp = row;
  192131. for (i = 0; i < row_width; i++)
  192132. {
  192133. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192134. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192135. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192136. if(red != green || red != blue)
  192137. rgb_error |= 1;
  192138. *(dp++) = png_ptr->gamma_from_1
  192139. [(rc*red + gc*green + bc*blue)>>15];
  192140. *(dp++) = *(sp++); /* alpha */
  192141. }
  192142. }
  192143. else
  192144. #endif
  192145. {
  192146. png_bytep sp = row;
  192147. png_bytep dp = row;
  192148. for (i = 0; i < row_width; i++)
  192149. {
  192150. png_byte red = *(sp++);
  192151. png_byte green = *(sp++);
  192152. png_byte blue = *(sp++);
  192153. if(red != green || red != blue)
  192154. rgb_error |= 1;
  192155. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192156. *(dp++) = *(sp++); /* alpha */
  192157. }
  192158. }
  192159. }
  192160. else /* RGBA bit_depth == 16 */
  192161. {
  192162. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192163. if (png_ptr->gamma_16_to_1 != NULL &&
  192164. png_ptr->gamma_16_from_1 != NULL)
  192165. {
  192166. png_bytep sp = row;
  192167. png_bytep dp = row;
  192168. for (i = 0; i < row_width; i++)
  192169. {
  192170. png_uint_16 red, green, blue, w;
  192171. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192172. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192173. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192174. if(red == green && red == blue)
  192175. w = red;
  192176. else
  192177. {
  192178. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192179. png_ptr->gamma_shift][red>>8];
  192180. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192181. png_ptr->gamma_shift][green>>8];
  192182. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192183. png_ptr->gamma_shift][blue>>8];
  192184. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192185. + gc * green_1 + bc * blue_1)>>15);
  192186. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192187. png_ptr->gamma_shift][gray16 >> 8];
  192188. rgb_error |= 1;
  192189. }
  192190. *(dp++) = (png_byte)((w>>8) & 0xff);
  192191. *(dp++) = (png_byte)(w & 0xff);
  192192. *(dp++) = *(sp++); /* alpha */
  192193. *(dp++) = *(sp++);
  192194. }
  192195. }
  192196. else
  192197. #endif
  192198. {
  192199. png_bytep sp = row;
  192200. png_bytep dp = row;
  192201. for (i = 0; i < row_width; i++)
  192202. {
  192203. png_uint_16 red, green, blue, gray16;
  192204. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192205. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192206. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192207. if(red != green || red != blue)
  192208. rgb_error |= 1;
  192209. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192210. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192211. *(dp++) = (png_byte)(gray16 & 0xff);
  192212. *(dp++) = *(sp++); /* alpha */
  192213. *(dp++) = *(sp++);
  192214. }
  192215. }
  192216. }
  192217. }
  192218. row_info->channels -= (png_byte)2;
  192219. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192220. row_info->pixel_depth = (png_byte)(row_info->channels *
  192221. row_info->bit_depth);
  192222. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192223. }
  192224. return rgb_error;
  192225. }
  192226. #endif
  192227. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192228. * large of png_color. This lets grayscale images be treated as
  192229. * paletted. Most useful for gamma correction and simplification
  192230. * of code.
  192231. */
  192232. void PNGAPI
  192233. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192234. {
  192235. int num_palette;
  192236. int color_inc;
  192237. int i;
  192238. int v;
  192239. png_debug(1, "in png_do_build_grayscale_palette\n");
  192240. if (palette == NULL)
  192241. return;
  192242. switch (bit_depth)
  192243. {
  192244. case 1:
  192245. num_palette = 2;
  192246. color_inc = 0xff;
  192247. break;
  192248. case 2:
  192249. num_palette = 4;
  192250. color_inc = 0x55;
  192251. break;
  192252. case 4:
  192253. num_palette = 16;
  192254. color_inc = 0x11;
  192255. break;
  192256. case 8:
  192257. num_palette = 256;
  192258. color_inc = 1;
  192259. break;
  192260. default:
  192261. num_palette = 0;
  192262. color_inc = 0;
  192263. break;
  192264. }
  192265. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192266. {
  192267. palette[i].red = (png_byte)v;
  192268. palette[i].green = (png_byte)v;
  192269. palette[i].blue = (png_byte)v;
  192270. }
  192271. }
  192272. /* This function is currently unused. Do we really need it? */
  192273. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192274. void /* PRIVATE */
  192275. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192276. int num_palette)
  192277. {
  192278. png_debug(1, "in png_correct_palette\n");
  192279. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192280. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192281. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192282. {
  192283. png_color back, back_1;
  192284. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192285. {
  192286. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192287. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192288. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192289. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192290. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192291. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192292. }
  192293. else
  192294. {
  192295. double g;
  192296. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192297. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192298. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192299. {
  192300. back.red = png_ptr->background.red;
  192301. back.green = png_ptr->background.green;
  192302. back.blue = png_ptr->background.blue;
  192303. }
  192304. else
  192305. {
  192306. back.red =
  192307. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192308. 255.0 + 0.5);
  192309. back.green =
  192310. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192311. 255.0 + 0.5);
  192312. back.blue =
  192313. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192314. 255.0 + 0.5);
  192315. }
  192316. g = 1.0 / png_ptr->background_gamma;
  192317. back_1.red =
  192318. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192319. 255.0 + 0.5);
  192320. back_1.green =
  192321. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192322. 255.0 + 0.5);
  192323. back_1.blue =
  192324. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192325. 255.0 + 0.5);
  192326. }
  192327. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192328. {
  192329. png_uint_32 i;
  192330. for (i = 0; i < (png_uint_32)num_palette; i++)
  192331. {
  192332. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192333. {
  192334. palette[i] = back;
  192335. }
  192336. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192337. {
  192338. png_byte v, w;
  192339. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192340. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192341. palette[i].red = png_ptr->gamma_from_1[w];
  192342. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192343. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192344. palette[i].green = png_ptr->gamma_from_1[w];
  192345. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192346. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192347. palette[i].blue = png_ptr->gamma_from_1[w];
  192348. }
  192349. else
  192350. {
  192351. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192352. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192353. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192354. }
  192355. }
  192356. }
  192357. else
  192358. {
  192359. int i;
  192360. for (i = 0; i < num_palette; i++)
  192361. {
  192362. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192363. {
  192364. palette[i] = back;
  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. }
  192375. else
  192376. #endif
  192377. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192378. if (png_ptr->transformations & PNG_GAMMA)
  192379. {
  192380. int i;
  192381. for (i = 0; i < num_palette; i++)
  192382. {
  192383. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192384. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192385. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192386. }
  192387. }
  192388. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192389. else
  192390. #endif
  192391. #endif
  192392. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192393. if (png_ptr->transformations & PNG_BACKGROUND)
  192394. {
  192395. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192396. {
  192397. png_color back;
  192398. back.red = (png_byte)png_ptr->background.red;
  192399. back.green = (png_byte)png_ptr->background.green;
  192400. back.blue = (png_byte)png_ptr->background.blue;
  192401. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192402. {
  192403. if (png_ptr->trans[i] == 0)
  192404. {
  192405. palette[i].red = back.red;
  192406. palette[i].green = back.green;
  192407. palette[i].blue = back.blue;
  192408. }
  192409. else if (png_ptr->trans[i] != 0xff)
  192410. {
  192411. png_composite(palette[i].red, png_ptr->palette[i].red,
  192412. png_ptr->trans[i], back.red);
  192413. png_composite(palette[i].green, png_ptr->palette[i].green,
  192414. png_ptr->trans[i], back.green);
  192415. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192416. png_ptr->trans[i], back.blue);
  192417. }
  192418. }
  192419. }
  192420. else /* assume grayscale palette (what else could it be?) */
  192421. {
  192422. int i;
  192423. for (i = 0; i < num_palette; i++)
  192424. {
  192425. if (i == (png_byte)png_ptr->trans_values.gray)
  192426. {
  192427. palette[i].red = (png_byte)png_ptr->background.red;
  192428. palette[i].green = (png_byte)png_ptr->background.green;
  192429. palette[i].blue = (png_byte)png_ptr->background.blue;
  192430. }
  192431. }
  192432. }
  192433. }
  192434. #endif
  192435. }
  192436. #endif
  192437. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192438. /* Replace any alpha or transparency with the supplied background color.
  192439. * "background" is already in the screen gamma, while "background_1" is
  192440. * at a gamma of 1.0. Paletted files have already been taken care of.
  192441. */
  192442. void /* PRIVATE */
  192443. png_do_background(png_row_infop row_info, png_bytep row,
  192444. png_color_16p trans_values, png_color_16p background
  192445. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192446. , png_color_16p background_1,
  192447. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192448. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192449. png_uint_16pp gamma_16_to_1, int gamma_shift
  192450. #endif
  192451. )
  192452. {
  192453. png_bytep sp, dp;
  192454. png_uint_32 i;
  192455. png_uint_32 row_width=row_info->width;
  192456. int shift;
  192457. png_debug(1, "in png_do_background\n");
  192458. if (background != NULL &&
  192459. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192460. row != NULL && row_info != NULL &&
  192461. #endif
  192462. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192463. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192464. {
  192465. switch (row_info->color_type)
  192466. {
  192467. case PNG_COLOR_TYPE_GRAY:
  192468. {
  192469. switch (row_info->bit_depth)
  192470. {
  192471. case 1:
  192472. {
  192473. sp = row;
  192474. shift = 7;
  192475. for (i = 0; i < row_width; i++)
  192476. {
  192477. if ((png_uint_16)((*sp >> shift) & 0x01)
  192478. == trans_values->gray)
  192479. {
  192480. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192481. *sp |= (png_byte)(background->gray << shift);
  192482. }
  192483. if (!shift)
  192484. {
  192485. shift = 7;
  192486. sp++;
  192487. }
  192488. else
  192489. shift--;
  192490. }
  192491. break;
  192492. }
  192493. case 2:
  192494. {
  192495. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192496. if (gamma_table != NULL)
  192497. {
  192498. sp = row;
  192499. shift = 6;
  192500. for (i = 0; i < row_width; i++)
  192501. {
  192502. if ((png_uint_16)((*sp >> shift) & 0x03)
  192503. == trans_values->gray)
  192504. {
  192505. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192506. *sp |= (png_byte)(background->gray << shift);
  192507. }
  192508. else
  192509. {
  192510. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192511. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192512. (p << 4) | (p << 6)] >> 6) & 0x03);
  192513. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192514. *sp |= (png_byte)(g << shift);
  192515. }
  192516. if (!shift)
  192517. {
  192518. shift = 6;
  192519. sp++;
  192520. }
  192521. else
  192522. shift -= 2;
  192523. }
  192524. }
  192525. else
  192526. #endif
  192527. {
  192528. sp = row;
  192529. shift = 6;
  192530. for (i = 0; i < row_width; i++)
  192531. {
  192532. if ((png_uint_16)((*sp >> shift) & 0x03)
  192533. == trans_values->gray)
  192534. {
  192535. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192536. *sp |= (png_byte)(background->gray << shift);
  192537. }
  192538. if (!shift)
  192539. {
  192540. shift = 6;
  192541. sp++;
  192542. }
  192543. else
  192544. shift -= 2;
  192545. }
  192546. }
  192547. break;
  192548. }
  192549. case 4:
  192550. {
  192551. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192552. if (gamma_table != NULL)
  192553. {
  192554. sp = row;
  192555. shift = 4;
  192556. for (i = 0; i < row_width; i++)
  192557. {
  192558. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192559. == trans_values->gray)
  192560. {
  192561. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192562. *sp |= (png_byte)(background->gray << shift);
  192563. }
  192564. else
  192565. {
  192566. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192567. png_byte g = (png_byte)((gamma_table[p |
  192568. (p << 4)] >> 4) & 0x0f);
  192569. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192570. *sp |= (png_byte)(g << shift);
  192571. }
  192572. if (!shift)
  192573. {
  192574. shift = 4;
  192575. sp++;
  192576. }
  192577. else
  192578. shift -= 4;
  192579. }
  192580. }
  192581. else
  192582. #endif
  192583. {
  192584. sp = row;
  192585. shift = 4;
  192586. for (i = 0; i < row_width; i++)
  192587. {
  192588. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192589. == trans_values->gray)
  192590. {
  192591. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192592. *sp |= (png_byte)(background->gray << shift);
  192593. }
  192594. if (!shift)
  192595. {
  192596. shift = 4;
  192597. sp++;
  192598. }
  192599. else
  192600. shift -= 4;
  192601. }
  192602. }
  192603. break;
  192604. }
  192605. case 8:
  192606. {
  192607. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192608. if (gamma_table != NULL)
  192609. {
  192610. sp = row;
  192611. for (i = 0; i < row_width; i++, sp++)
  192612. {
  192613. if (*sp == trans_values->gray)
  192614. {
  192615. *sp = (png_byte)background->gray;
  192616. }
  192617. else
  192618. {
  192619. *sp = gamma_table[*sp];
  192620. }
  192621. }
  192622. }
  192623. else
  192624. #endif
  192625. {
  192626. sp = row;
  192627. for (i = 0; i < row_width; i++, sp++)
  192628. {
  192629. if (*sp == trans_values->gray)
  192630. {
  192631. *sp = (png_byte)background->gray;
  192632. }
  192633. }
  192634. }
  192635. break;
  192636. }
  192637. case 16:
  192638. {
  192639. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192640. if (gamma_16 != NULL)
  192641. {
  192642. sp = row;
  192643. for (i = 0; i < row_width; i++, sp += 2)
  192644. {
  192645. png_uint_16 v;
  192646. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192647. if (v == trans_values->gray)
  192648. {
  192649. /* background is already in screen gamma */
  192650. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192651. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192652. }
  192653. else
  192654. {
  192655. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192656. *sp = (png_byte)((v >> 8) & 0xff);
  192657. *(sp + 1) = (png_byte)(v & 0xff);
  192658. }
  192659. }
  192660. }
  192661. else
  192662. #endif
  192663. {
  192664. sp = row;
  192665. for (i = 0; i < row_width; i++, sp += 2)
  192666. {
  192667. png_uint_16 v;
  192668. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192669. if (v == trans_values->gray)
  192670. {
  192671. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192672. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192673. }
  192674. }
  192675. }
  192676. break;
  192677. }
  192678. }
  192679. break;
  192680. }
  192681. case PNG_COLOR_TYPE_RGB:
  192682. {
  192683. if (row_info->bit_depth == 8)
  192684. {
  192685. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192686. if (gamma_table != NULL)
  192687. {
  192688. sp = row;
  192689. for (i = 0; i < row_width; i++, sp += 3)
  192690. {
  192691. if (*sp == trans_values->red &&
  192692. *(sp + 1) == trans_values->green &&
  192693. *(sp + 2) == trans_values->blue)
  192694. {
  192695. *sp = (png_byte)background->red;
  192696. *(sp + 1) = (png_byte)background->green;
  192697. *(sp + 2) = (png_byte)background->blue;
  192698. }
  192699. else
  192700. {
  192701. *sp = gamma_table[*sp];
  192702. *(sp + 1) = gamma_table[*(sp + 1)];
  192703. *(sp + 2) = gamma_table[*(sp + 2)];
  192704. }
  192705. }
  192706. }
  192707. else
  192708. #endif
  192709. {
  192710. sp = row;
  192711. for (i = 0; i < row_width; i++, sp += 3)
  192712. {
  192713. if (*sp == trans_values->red &&
  192714. *(sp + 1) == trans_values->green &&
  192715. *(sp + 2) == trans_values->blue)
  192716. {
  192717. *sp = (png_byte)background->red;
  192718. *(sp + 1) = (png_byte)background->green;
  192719. *(sp + 2) = (png_byte)background->blue;
  192720. }
  192721. }
  192722. }
  192723. }
  192724. else /* if (row_info->bit_depth == 16) */
  192725. {
  192726. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192727. if (gamma_16 != NULL)
  192728. {
  192729. sp = row;
  192730. for (i = 0; i < row_width; i++, sp += 6)
  192731. {
  192732. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192733. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192734. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192735. if (r == trans_values->red && g == trans_values->green &&
  192736. b == trans_values->blue)
  192737. {
  192738. /* background is already in screen gamma */
  192739. *sp = (png_byte)((background->red >> 8) & 0xff);
  192740. *(sp + 1) = (png_byte)(background->red & 0xff);
  192741. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192742. *(sp + 3) = (png_byte)(background->green & 0xff);
  192743. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192744. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192745. }
  192746. else
  192747. {
  192748. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192749. *sp = (png_byte)((v >> 8) & 0xff);
  192750. *(sp + 1) = (png_byte)(v & 0xff);
  192751. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192752. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192753. *(sp + 3) = (png_byte)(v & 0xff);
  192754. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192755. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192756. *(sp + 5) = (png_byte)(v & 0xff);
  192757. }
  192758. }
  192759. }
  192760. else
  192761. #endif
  192762. {
  192763. sp = row;
  192764. for (i = 0; i < row_width; i++, sp += 6)
  192765. {
  192766. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192767. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192768. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192769. if (r == trans_values->red && g == trans_values->green &&
  192770. b == trans_values->blue)
  192771. {
  192772. *sp = (png_byte)((background->red >> 8) & 0xff);
  192773. *(sp + 1) = (png_byte)(background->red & 0xff);
  192774. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192775. *(sp + 3) = (png_byte)(background->green & 0xff);
  192776. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192777. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192778. }
  192779. }
  192780. }
  192781. }
  192782. break;
  192783. }
  192784. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192785. {
  192786. if (row_info->bit_depth == 8)
  192787. {
  192788. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192789. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192790. gamma_table != NULL)
  192791. {
  192792. sp = row;
  192793. dp = row;
  192794. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192795. {
  192796. png_uint_16 a = *(sp + 1);
  192797. if (a == 0xff)
  192798. {
  192799. *dp = gamma_table[*sp];
  192800. }
  192801. else if (a == 0)
  192802. {
  192803. /* background is already in screen gamma */
  192804. *dp = (png_byte)background->gray;
  192805. }
  192806. else
  192807. {
  192808. png_byte v, w;
  192809. v = gamma_to_1[*sp];
  192810. png_composite(w, v, a, background_1->gray);
  192811. *dp = gamma_from_1[w];
  192812. }
  192813. }
  192814. }
  192815. else
  192816. #endif
  192817. {
  192818. sp = row;
  192819. dp = row;
  192820. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192821. {
  192822. png_byte a = *(sp + 1);
  192823. if (a == 0xff)
  192824. {
  192825. *dp = *sp;
  192826. }
  192827. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192828. else if (a == 0)
  192829. {
  192830. *dp = (png_byte)background->gray;
  192831. }
  192832. else
  192833. {
  192834. png_composite(*dp, *sp, a, background_1->gray);
  192835. }
  192836. #else
  192837. *dp = (png_byte)background->gray;
  192838. #endif
  192839. }
  192840. }
  192841. }
  192842. else /* if (png_ptr->bit_depth == 16) */
  192843. {
  192844. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192845. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192846. gamma_16_to_1 != NULL)
  192847. {
  192848. sp = row;
  192849. dp = row;
  192850. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192851. {
  192852. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192853. if (a == (png_uint_16)0xffff)
  192854. {
  192855. png_uint_16 v;
  192856. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192857. *dp = (png_byte)((v >> 8) & 0xff);
  192858. *(dp + 1) = (png_byte)(v & 0xff);
  192859. }
  192860. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192861. else if (a == 0)
  192862. #else
  192863. else
  192864. #endif
  192865. {
  192866. /* background is already in screen gamma */
  192867. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192868. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192869. }
  192870. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192871. else
  192872. {
  192873. png_uint_16 g, v, w;
  192874. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192875. png_composite_16(v, g, a, background_1->gray);
  192876. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192877. *dp = (png_byte)((w >> 8) & 0xff);
  192878. *(dp + 1) = (png_byte)(w & 0xff);
  192879. }
  192880. #endif
  192881. }
  192882. }
  192883. else
  192884. #endif
  192885. {
  192886. sp = row;
  192887. dp = row;
  192888. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192889. {
  192890. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192891. if (a == (png_uint_16)0xffff)
  192892. {
  192893. png_memcpy(dp, sp, 2);
  192894. }
  192895. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192896. else if (a == 0)
  192897. #else
  192898. else
  192899. #endif
  192900. {
  192901. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192902. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192903. }
  192904. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192905. else
  192906. {
  192907. png_uint_16 g, v;
  192908. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192909. png_composite_16(v, g, a, background_1->gray);
  192910. *dp = (png_byte)((v >> 8) & 0xff);
  192911. *(dp + 1) = (png_byte)(v & 0xff);
  192912. }
  192913. #endif
  192914. }
  192915. }
  192916. }
  192917. break;
  192918. }
  192919. case PNG_COLOR_TYPE_RGB_ALPHA:
  192920. {
  192921. if (row_info->bit_depth == 8)
  192922. {
  192923. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192924. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192925. gamma_table != NULL)
  192926. {
  192927. sp = row;
  192928. dp = row;
  192929. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192930. {
  192931. png_byte a = *(sp + 3);
  192932. if (a == 0xff)
  192933. {
  192934. *dp = gamma_table[*sp];
  192935. *(dp + 1) = gamma_table[*(sp + 1)];
  192936. *(dp + 2) = gamma_table[*(sp + 2)];
  192937. }
  192938. else if (a == 0)
  192939. {
  192940. /* background is already in screen gamma */
  192941. *dp = (png_byte)background->red;
  192942. *(dp + 1) = (png_byte)background->green;
  192943. *(dp + 2) = (png_byte)background->blue;
  192944. }
  192945. else
  192946. {
  192947. png_byte v, w;
  192948. v = gamma_to_1[*sp];
  192949. png_composite(w, v, a, background_1->red);
  192950. *dp = gamma_from_1[w];
  192951. v = gamma_to_1[*(sp + 1)];
  192952. png_composite(w, v, a, background_1->green);
  192953. *(dp + 1) = gamma_from_1[w];
  192954. v = gamma_to_1[*(sp + 2)];
  192955. png_composite(w, v, a, background_1->blue);
  192956. *(dp + 2) = gamma_from_1[w];
  192957. }
  192958. }
  192959. }
  192960. else
  192961. #endif
  192962. {
  192963. sp = row;
  192964. dp = row;
  192965. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192966. {
  192967. png_byte a = *(sp + 3);
  192968. if (a == 0xff)
  192969. {
  192970. *dp = *sp;
  192971. *(dp + 1) = *(sp + 1);
  192972. *(dp + 2) = *(sp + 2);
  192973. }
  192974. else if (a == 0)
  192975. {
  192976. *dp = (png_byte)background->red;
  192977. *(dp + 1) = (png_byte)background->green;
  192978. *(dp + 2) = (png_byte)background->blue;
  192979. }
  192980. else
  192981. {
  192982. png_composite(*dp, *sp, a, background->red);
  192983. png_composite(*(dp + 1), *(sp + 1), a,
  192984. background->green);
  192985. png_composite(*(dp + 2), *(sp + 2), a,
  192986. background->blue);
  192987. }
  192988. }
  192989. }
  192990. }
  192991. else /* if (row_info->bit_depth == 16) */
  192992. {
  192993. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192994. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192995. gamma_16_to_1 != NULL)
  192996. {
  192997. sp = row;
  192998. dp = row;
  192999. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193000. {
  193001. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193002. << 8) + (png_uint_16)(*(sp + 7)));
  193003. if (a == (png_uint_16)0xffff)
  193004. {
  193005. png_uint_16 v;
  193006. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193007. *dp = (png_byte)((v >> 8) & 0xff);
  193008. *(dp + 1) = (png_byte)(v & 0xff);
  193009. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193010. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193011. *(dp + 3) = (png_byte)(v & 0xff);
  193012. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193013. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193014. *(dp + 5) = (png_byte)(v & 0xff);
  193015. }
  193016. else if (a == 0)
  193017. {
  193018. /* background is already in screen gamma */
  193019. *dp = (png_byte)((background->red >> 8) & 0xff);
  193020. *(dp + 1) = (png_byte)(background->red & 0xff);
  193021. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193022. *(dp + 3) = (png_byte)(background->green & 0xff);
  193023. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193024. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193025. }
  193026. else
  193027. {
  193028. png_uint_16 v, w, x;
  193029. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193030. png_composite_16(w, v, a, background_1->red);
  193031. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193032. *dp = (png_byte)((x >> 8) & 0xff);
  193033. *(dp + 1) = (png_byte)(x & 0xff);
  193034. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193035. png_composite_16(w, v, a, background_1->green);
  193036. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193037. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193038. *(dp + 3) = (png_byte)(x & 0xff);
  193039. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193040. png_composite_16(w, v, a, background_1->blue);
  193041. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193042. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193043. *(dp + 5) = (png_byte)(x & 0xff);
  193044. }
  193045. }
  193046. }
  193047. else
  193048. #endif
  193049. {
  193050. sp = row;
  193051. dp = row;
  193052. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193053. {
  193054. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193055. << 8) + (png_uint_16)(*(sp + 7)));
  193056. if (a == (png_uint_16)0xffff)
  193057. {
  193058. png_memcpy(dp, sp, 6);
  193059. }
  193060. else if (a == 0)
  193061. {
  193062. *dp = (png_byte)((background->red >> 8) & 0xff);
  193063. *(dp + 1) = (png_byte)(background->red & 0xff);
  193064. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193065. *(dp + 3) = (png_byte)(background->green & 0xff);
  193066. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193067. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193068. }
  193069. else
  193070. {
  193071. png_uint_16 v;
  193072. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193073. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193074. + *(sp + 3));
  193075. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193076. + *(sp + 5));
  193077. png_composite_16(v, r, a, background->red);
  193078. *dp = (png_byte)((v >> 8) & 0xff);
  193079. *(dp + 1) = (png_byte)(v & 0xff);
  193080. png_composite_16(v, g, a, background->green);
  193081. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193082. *(dp + 3) = (png_byte)(v & 0xff);
  193083. png_composite_16(v, b, a, background->blue);
  193084. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193085. *(dp + 5) = (png_byte)(v & 0xff);
  193086. }
  193087. }
  193088. }
  193089. }
  193090. break;
  193091. }
  193092. }
  193093. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193094. {
  193095. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193096. row_info->channels--;
  193097. row_info->pixel_depth = (png_byte)(row_info->channels *
  193098. row_info->bit_depth);
  193099. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193100. }
  193101. }
  193102. }
  193103. #endif
  193104. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193105. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193106. * you do this after you deal with the transparency issue on grayscale
  193107. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193108. * is 16, use gamma_16_table and gamma_shift. Build these with
  193109. * build_gamma_table().
  193110. */
  193111. void /* PRIVATE */
  193112. png_do_gamma(png_row_infop row_info, png_bytep row,
  193113. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193114. int gamma_shift)
  193115. {
  193116. png_bytep sp;
  193117. png_uint_32 i;
  193118. png_uint_32 row_width=row_info->width;
  193119. png_debug(1, "in png_do_gamma\n");
  193120. if (
  193121. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193122. row != NULL && row_info != NULL &&
  193123. #endif
  193124. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193125. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193126. {
  193127. switch (row_info->color_type)
  193128. {
  193129. case PNG_COLOR_TYPE_RGB:
  193130. {
  193131. if (row_info->bit_depth == 8)
  193132. {
  193133. sp = row;
  193134. for (i = 0; i < row_width; i++)
  193135. {
  193136. *sp = gamma_table[*sp];
  193137. sp++;
  193138. *sp = gamma_table[*sp];
  193139. sp++;
  193140. *sp = gamma_table[*sp];
  193141. sp++;
  193142. }
  193143. }
  193144. else /* if (row_info->bit_depth == 16) */
  193145. {
  193146. sp = row;
  193147. for (i = 0; i < row_width; i++)
  193148. {
  193149. png_uint_16 v;
  193150. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193151. *sp = (png_byte)((v >> 8) & 0xff);
  193152. *(sp + 1) = (png_byte)(v & 0xff);
  193153. sp += 2;
  193154. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193155. *sp = (png_byte)((v >> 8) & 0xff);
  193156. *(sp + 1) = (png_byte)(v & 0xff);
  193157. sp += 2;
  193158. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193159. *sp = (png_byte)((v >> 8) & 0xff);
  193160. *(sp + 1) = (png_byte)(v & 0xff);
  193161. sp += 2;
  193162. }
  193163. }
  193164. break;
  193165. }
  193166. case PNG_COLOR_TYPE_RGB_ALPHA:
  193167. {
  193168. if (row_info->bit_depth == 8)
  193169. {
  193170. sp = row;
  193171. for (i = 0; i < row_width; i++)
  193172. {
  193173. *sp = gamma_table[*sp];
  193174. sp++;
  193175. *sp = gamma_table[*sp];
  193176. sp++;
  193177. *sp = gamma_table[*sp];
  193178. sp++;
  193179. sp++;
  193180. }
  193181. }
  193182. else /* if (row_info->bit_depth == 16) */
  193183. {
  193184. sp = row;
  193185. for (i = 0; i < row_width; i++)
  193186. {
  193187. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193188. *sp = (png_byte)((v >> 8) & 0xff);
  193189. *(sp + 1) = (png_byte)(v & 0xff);
  193190. sp += 2;
  193191. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193192. *sp = (png_byte)((v >> 8) & 0xff);
  193193. *(sp + 1) = (png_byte)(v & 0xff);
  193194. sp += 2;
  193195. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193196. *sp = (png_byte)((v >> 8) & 0xff);
  193197. *(sp + 1) = (png_byte)(v & 0xff);
  193198. sp += 4;
  193199. }
  193200. }
  193201. break;
  193202. }
  193203. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193204. {
  193205. if (row_info->bit_depth == 8)
  193206. {
  193207. sp = row;
  193208. for (i = 0; i < row_width; i++)
  193209. {
  193210. *sp = gamma_table[*sp];
  193211. sp += 2;
  193212. }
  193213. }
  193214. else /* if (row_info->bit_depth == 16) */
  193215. {
  193216. sp = row;
  193217. for (i = 0; i < row_width; i++)
  193218. {
  193219. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193220. *sp = (png_byte)((v >> 8) & 0xff);
  193221. *(sp + 1) = (png_byte)(v & 0xff);
  193222. sp += 4;
  193223. }
  193224. }
  193225. break;
  193226. }
  193227. case PNG_COLOR_TYPE_GRAY:
  193228. {
  193229. if (row_info->bit_depth == 2)
  193230. {
  193231. sp = row;
  193232. for (i = 0; i < row_width; i += 4)
  193233. {
  193234. int a = *sp & 0xc0;
  193235. int b = *sp & 0x30;
  193236. int c = *sp & 0x0c;
  193237. int d = *sp & 0x03;
  193238. *sp = (png_byte)(
  193239. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193240. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193241. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193242. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193243. sp++;
  193244. }
  193245. }
  193246. if (row_info->bit_depth == 4)
  193247. {
  193248. sp = row;
  193249. for (i = 0; i < row_width; i += 2)
  193250. {
  193251. int msb = *sp & 0xf0;
  193252. int lsb = *sp & 0x0f;
  193253. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193254. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193255. sp++;
  193256. }
  193257. }
  193258. else if (row_info->bit_depth == 8)
  193259. {
  193260. sp = row;
  193261. for (i = 0; i < row_width; i++)
  193262. {
  193263. *sp = gamma_table[*sp];
  193264. sp++;
  193265. }
  193266. }
  193267. else if (row_info->bit_depth == 16)
  193268. {
  193269. sp = row;
  193270. for (i = 0; i < row_width; i++)
  193271. {
  193272. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193273. *sp = (png_byte)((v >> 8) & 0xff);
  193274. *(sp + 1) = (png_byte)(v & 0xff);
  193275. sp += 2;
  193276. }
  193277. }
  193278. break;
  193279. }
  193280. }
  193281. }
  193282. }
  193283. #endif
  193284. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193285. /* Expands a palette row to an RGB or RGBA row depending
  193286. * upon whether you supply trans and num_trans.
  193287. */
  193288. void /* PRIVATE */
  193289. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193290. png_colorp palette, png_bytep trans, int num_trans)
  193291. {
  193292. int shift, value;
  193293. png_bytep sp, dp;
  193294. png_uint_32 i;
  193295. png_uint_32 row_width=row_info->width;
  193296. png_debug(1, "in png_do_expand_palette\n");
  193297. if (
  193298. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193299. row != NULL && row_info != NULL &&
  193300. #endif
  193301. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193302. {
  193303. if (row_info->bit_depth < 8)
  193304. {
  193305. switch (row_info->bit_depth)
  193306. {
  193307. case 1:
  193308. {
  193309. sp = row + (png_size_t)((row_width - 1) >> 3);
  193310. dp = row + (png_size_t)row_width - 1;
  193311. shift = 7 - (int)((row_width + 7) & 0x07);
  193312. for (i = 0; i < row_width; i++)
  193313. {
  193314. if ((*sp >> shift) & 0x01)
  193315. *dp = 1;
  193316. else
  193317. *dp = 0;
  193318. if (shift == 7)
  193319. {
  193320. shift = 0;
  193321. sp--;
  193322. }
  193323. else
  193324. shift++;
  193325. dp--;
  193326. }
  193327. break;
  193328. }
  193329. case 2:
  193330. {
  193331. sp = row + (png_size_t)((row_width - 1) >> 2);
  193332. dp = row + (png_size_t)row_width - 1;
  193333. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193334. for (i = 0; i < row_width; i++)
  193335. {
  193336. value = (*sp >> shift) & 0x03;
  193337. *dp = (png_byte)value;
  193338. if (shift == 6)
  193339. {
  193340. shift = 0;
  193341. sp--;
  193342. }
  193343. else
  193344. shift += 2;
  193345. dp--;
  193346. }
  193347. break;
  193348. }
  193349. case 4:
  193350. {
  193351. sp = row + (png_size_t)((row_width - 1) >> 1);
  193352. dp = row + (png_size_t)row_width - 1;
  193353. shift = (int)((row_width & 0x01) << 2);
  193354. for (i = 0; i < row_width; i++)
  193355. {
  193356. value = (*sp >> shift) & 0x0f;
  193357. *dp = (png_byte)value;
  193358. if (shift == 4)
  193359. {
  193360. shift = 0;
  193361. sp--;
  193362. }
  193363. else
  193364. shift += 4;
  193365. dp--;
  193366. }
  193367. break;
  193368. }
  193369. }
  193370. row_info->bit_depth = 8;
  193371. row_info->pixel_depth = 8;
  193372. row_info->rowbytes = row_width;
  193373. }
  193374. switch (row_info->bit_depth)
  193375. {
  193376. case 8:
  193377. {
  193378. if (trans != NULL)
  193379. {
  193380. sp = row + (png_size_t)row_width - 1;
  193381. dp = row + (png_size_t)(row_width << 2) - 1;
  193382. for (i = 0; i < row_width; i++)
  193383. {
  193384. if ((int)(*sp) >= num_trans)
  193385. *dp-- = 0xff;
  193386. else
  193387. *dp-- = trans[*sp];
  193388. *dp-- = palette[*sp].blue;
  193389. *dp-- = palette[*sp].green;
  193390. *dp-- = palette[*sp].red;
  193391. sp--;
  193392. }
  193393. row_info->bit_depth = 8;
  193394. row_info->pixel_depth = 32;
  193395. row_info->rowbytes = row_width * 4;
  193396. row_info->color_type = 6;
  193397. row_info->channels = 4;
  193398. }
  193399. else
  193400. {
  193401. sp = row + (png_size_t)row_width - 1;
  193402. dp = row + (png_size_t)(row_width * 3) - 1;
  193403. for (i = 0; i < row_width; i++)
  193404. {
  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 = 24;
  193412. row_info->rowbytes = row_width * 3;
  193413. row_info->color_type = 2;
  193414. row_info->channels = 3;
  193415. }
  193416. break;
  193417. }
  193418. }
  193419. }
  193420. }
  193421. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193422. * expanded transparency value is supplied, an alpha channel is built.
  193423. */
  193424. void /* PRIVATE */
  193425. png_do_expand(png_row_infop row_info, png_bytep row,
  193426. png_color_16p trans_value)
  193427. {
  193428. int shift, value;
  193429. png_bytep sp, dp;
  193430. png_uint_32 i;
  193431. png_uint_32 row_width=row_info->width;
  193432. png_debug(1, "in png_do_expand\n");
  193433. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193434. if (row != NULL && row_info != NULL)
  193435. #endif
  193436. {
  193437. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193438. {
  193439. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193440. if (row_info->bit_depth < 8)
  193441. {
  193442. switch (row_info->bit_depth)
  193443. {
  193444. case 1:
  193445. {
  193446. gray = (png_uint_16)((gray&0x01)*0xff);
  193447. sp = row + (png_size_t)((row_width - 1) >> 3);
  193448. dp = row + (png_size_t)row_width - 1;
  193449. shift = 7 - (int)((row_width + 7) & 0x07);
  193450. for (i = 0; i < row_width; i++)
  193451. {
  193452. if ((*sp >> shift) & 0x01)
  193453. *dp = 0xff;
  193454. else
  193455. *dp = 0;
  193456. if (shift == 7)
  193457. {
  193458. shift = 0;
  193459. sp--;
  193460. }
  193461. else
  193462. shift++;
  193463. dp--;
  193464. }
  193465. break;
  193466. }
  193467. case 2:
  193468. {
  193469. gray = (png_uint_16)((gray&0x03)*0x55);
  193470. sp = row + (png_size_t)((row_width - 1) >> 2);
  193471. dp = row + (png_size_t)row_width - 1;
  193472. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193473. for (i = 0; i < row_width; i++)
  193474. {
  193475. value = (*sp >> shift) & 0x03;
  193476. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193477. (value << 6));
  193478. if (shift == 6)
  193479. {
  193480. shift = 0;
  193481. sp--;
  193482. }
  193483. else
  193484. shift += 2;
  193485. dp--;
  193486. }
  193487. break;
  193488. }
  193489. case 4:
  193490. {
  193491. gray = (png_uint_16)((gray&0x0f)*0x11);
  193492. sp = row + (png_size_t)((row_width - 1) >> 1);
  193493. dp = row + (png_size_t)row_width - 1;
  193494. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193495. for (i = 0; i < row_width; i++)
  193496. {
  193497. value = (*sp >> shift) & 0x0f;
  193498. *dp = (png_byte)(value | (value << 4));
  193499. if (shift == 4)
  193500. {
  193501. shift = 0;
  193502. sp--;
  193503. }
  193504. else
  193505. shift = 4;
  193506. dp--;
  193507. }
  193508. break;
  193509. }
  193510. }
  193511. row_info->bit_depth = 8;
  193512. row_info->pixel_depth = 8;
  193513. row_info->rowbytes = row_width;
  193514. }
  193515. if (trans_value != NULL)
  193516. {
  193517. if (row_info->bit_depth == 8)
  193518. {
  193519. gray = gray & 0xff;
  193520. sp = row + (png_size_t)row_width - 1;
  193521. dp = row + (png_size_t)(row_width << 1) - 1;
  193522. for (i = 0; i < row_width; i++)
  193523. {
  193524. if (*sp == gray)
  193525. *dp-- = 0;
  193526. else
  193527. *dp-- = 0xff;
  193528. *dp-- = *sp--;
  193529. }
  193530. }
  193531. else if (row_info->bit_depth == 16)
  193532. {
  193533. png_byte gray_high = (gray >> 8) & 0xff;
  193534. png_byte gray_low = gray & 0xff;
  193535. sp = row + row_info->rowbytes - 1;
  193536. dp = row + (row_info->rowbytes << 1) - 1;
  193537. for (i = 0; i < row_width; i++)
  193538. {
  193539. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193540. {
  193541. *dp-- = 0;
  193542. *dp-- = 0;
  193543. }
  193544. else
  193545. {
  193546. *dp-- = 0xff;
  193547. *dp-- = 0xff;
  193548. }
  193549. *dp-- = *sp--;
  193550. *dp-- = *sp--;
  193551. }
  193552. }
  193553. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193554. row_info->channels = 2;
  193555. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193556. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193557. row_width);
  193558. }
  193559. }
  193560. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193561. {
  193562. if (row_info->bit_depth == 8)
  193563. {
  193564. png_byte red = trans_value->red & 0xff;
  193565. png_byte green = trans_value->green & 0xff;
  193566. png_byte blue = trans_value->blue & 0xff;
  193567. sp = row + (png_size_t)row_info->rowbytes - 1;
  193568. dp = row + (png_size_t)(row_width << 2) - 1;
  193569. for (i = 0; i < row_width; i++)
  193570. {
  193571. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193572. *dp-- = 0;
  193573. else
  193574. *dp-- = 0xff;
  193575. *dp-- = *sp--;
  193576. *dp-- = *sp--;
  193577. *dp-- = *sp--;
  193578. }
  193579. }
  193580. else if (row_info->bit_depth == 16)
  193581. {
  193582. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193583. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193584. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193585. png_byte red_low = trans_value->red & 0xff;
  193586. png_byte green_low = trans_value->green & 0xff;
  193587. png_byte blue_low = trans_value->blue & 0xff;
  193588. sp = row + row_info->rowbytes - 1;
  193589. dp = row + (png_size_t)(row_width << 3) - 1;
  193590. for (i = 0; i < row_width; i++)
  193591. {
  193592. if (*(sp - 5) == red_high &&
  193593. *(sp - 4) == red_low &&
  193594. *(sp - 3) == green_high &&
  193595. *(sp - 2) == green_low &&
  193596. *(sp - 1) == blue_high &&
  193597. *(sp ) == blue_low)
  193598. {
  193599. *dp-- = 0;
  193600. *dp-- = 0;
  193601. }
  193602. else
  193603. {
  193604. *dp-- = 0xff;
  193605. *dp-- = 0xff;
  193606. }
  193607. *dp-- = *sp--;
  193608. *dp-- = *sp--;
  193609. *dp-- = *sp--;
  193610. *dp-- = *sp--;
  193611. *dp-- = *sp--;
  193612. *dp-- = *sp--;
  193613. }
  193614. }
  193615. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193616. row_info->channels = 4;
  193617. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193618. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193619. }
  193620. }
  193621. }
  193622. #endif
  193623. #if defined(PNG_READ_DITHER_SUPPORTED)
  193624. void /* PRIVATE */
  193625. png_do_dither(png_row_infop row_info, png_bytep row,
  193626. png_bytep palette_lookup, png_bytep dither_lookup)
  193627. {
  193628. png_bytep sp, dp;
  193629. png_uint_32 i;
  193630. png_uint_32 row_width=row_info->width;
  193631. png_debug(1, "in png_do_dither\n");
  193632. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193633. if (row != NULL && row_info != NULL)
  193634. #endif
  193635. {
  193636. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193637. palette_lookup && row_info->bit_depth == 8)
  193638. {
  193639. int r, g, b, p;
  193640. sp = row;
  193641. dp = row;
  193642. for (i = 0; i < row_width; i++)
  193643. {
  193644. r = *sp++;
  193645. g = *sp++;
  193646. b = *sp++;
  193647. /* this looks real messy, but the compiler will reduce
  193648. it down to a reasonable formula. For example, with
  193649. 5 bits per color, we get:
  193650. p = (((r >> 3) & 0x1f) << 10) |
  193651. (((g >> 3) & 0x1f) << 5) |
  193652. ((b >> 3) & 0x1f);
  193653. */
  193654. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193655. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193656. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193657. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193658. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193659. (PNG_DITHER_BLUE_BITS)) |
  193660. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193661. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193662. *dp++ = palette_lookup[p];
  193663. }
  193664. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193665. row_info->channels = 1;
  193666. row_info->pixel_depth = row_info->bit_depth;
  193667. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193668. }
  193669. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193670. palette_lookup != NULL && row_info->bit_depth == 8)
  193671. {
  193672. int r, g, b, p;
  193673. sp = row;
  193674. dp = row;
  193675. for (i = 0; i < row_width; i++)
  193676. {
  193677. r = *sp++;
  193678. g = *sp++;
  193679. b = *sp++;
  193680. sp++;
  193681. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193682. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193683. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193684. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193685. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193686. (PNG_DITHER_BLUE_BITS)) |
  193687. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193688. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193689. *dp++ = palette_lookup[p];
  193690. }
  193691. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193692. row_info->channels = 1;
  193693. row_info->pixel_depth = row_info->bit_depth;
  193694. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193695. }
  193696. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193697. dither_lookup && row_info->bit_depth == 8)
  193698. {
  193699. sp = row;
  193700. for (i = 0; i < row_width; i++, sp++)
  193701. {
  193702. *sp = dither_lookup[*sp];
  193703. }
  193704. }
  193705. }
  193706. }
  193707. #endif
  193708. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193709. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193710. static PNG_CONST int png_gamma_shift[] =
  193711. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193712. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193713. * tables, we don't make a full table if we are reducing to 8-bit in
  193714. * the future. Note also how the gamma_16 tables are segmented so that
  193715. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193716. */
  193717. void /* PRIVATE */
  193718. png_build_gamma_table(png_structp png_ptr)
  193719. {
  193720. png_debug(1, "in png_build_gamma_table\n");
  193721. if (png_ptr->bit_depth <= 8)
  193722. {
  193723. int i;
  193724. double g;
  193725. if (png_ptr->screen_gamma > .000001)
  193726. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193727. else
  193728. g = 1.0;
  193729. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193730. (png_uint_32)256);
  193731. for (i = 0; i < 256; i++)
  193732. {
  193733. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193734. g) * 255.0 + .5);
  193735. }
  193736. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193737. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193738. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193739. {
  193740. g = 1.0 / (png_ptr->gamma);
  193741. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193742. (png_uint_32)256);
  193743. for (i = 0; i < 256; i++)
  193744. {
  193745. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193746. g) * 255.0 + .5);
  193747. }
  193748. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193749. (png_uint_32)256);
  193750. if(png_ptr->screen_gamma > 0.000001)
  193751. g = 1.0 / png_ptr->screen_gamma;
  193752. else
  193753. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193754. for (i = 0; i < 256; i++)
  193755. {
  193756. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193757. g) * 255.0 + .5);
  193758. }
  193759. }
  193760. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193761. }
  193762. else
  193763. {
  193764. double g;
  193765. int i, j, shift, num;
  193766. int sig_bit;
  193767. png_uint_32 ig;
  193768. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193769. {
  193770. sig_bit = (int)png_ptr->sig_bit.red;
  193771. if ((int)png_ptr->sig_bit.green > sig_bit)
  193772. sig_bit = png_ptr->sig_bit.green;
  193773. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193774. sig_bit = png_ptr->sig_bit.blue;
  193775. }
  193776. else
  193777. {
  193778. sig_bit = (int)png_ptr->sig_bit.gray;
  193779. }
  193780. if (sig_bit > 0)
  193781. shift = 16 - sig_bit;
  193782. else
  193783. shift = 0;
  193784. if (png_ptr->transformations & PNG_16_TO_8)
  193785. {
  193786. if (shift < (16 - PNG_MAX_GAMMA_8))
  193787. shift = (16 - PNG_MAX_GAMMA_8);
  193788. }
  193789. if (shift > 8)
  193790. shift = 8;
  193791. if (shift < 0)
  193792. shift = 0;
  193793. png_ptr->gamma_shift = (png_byte)shift;
  193794. num = (1 << (8 - shift));
  193795. if (png_ptr->screen_gamma > .000001)
  193796. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193797. else
  193798. g = 1.0;
  193799. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193800. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193801. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193802. {
  193803. double fin, fout;
  193804. png_uint_32 last, max;
  193805. for (i = 0; i < num; i++)
  193806. {
  193807. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193808. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193809. }
  193810. g = 1.0 / g;
  193811. last = 0;
  193812. for (i = 0; i < 256; i++)
  193813. {
  193814. fout = ((double)i + 0.5) / 256.0;
  193815. fin = pow(fout, g);
  193816. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193817. while (last <= max)
  193818. {
  193819. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193820. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193821. (png_uint_16)i | ((png_uint_16)i << 8));
  193822. last++;
  193823. }
  193824. }
  193825. while (last < ((png_uint_32)num << 8))
  193826. {
  193827. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193828. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193829. last++;
  193830. }
  193831. }
  193832. else
  193833. {
  193834. for (i = 0; i < num; i++)
  193835. {
  193836. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193837. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193838. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193839. for (j = 0; j < 256; j++)
  193840. {
  193841. png_ptr->gamma_16_table[i][j] =
  193842. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193843. 65535.0, g) * 65535.0 + .5);
  193844. }
  193845. }
  193846. }
  193847. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193848. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193849. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193850. {
  193851. g = 1.0 / (png_ptr->gamma);
  193852. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193853. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193854. for (i = 0; i < num; i++)
  193855. {
  193856. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193857. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193858. ig = (((png_uint_32)i *
  193859. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193860. for (j = 0; j < 256; j++)
  193861. {
  193862. png_ptr->gamma_16_to_1[i][j] =
  193863. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193864. 65535.0, g) * 65535.0 + .5);
  193865. }
  193866. }
  193867. if(png_ptr->screen_gamma > 0.000001)
  193868. g = 1.0 / png_ptr->screen_gamma;
  193869. else
  193870. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193871. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193872. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193873. for (i = 0; i < num; i++)
  193874. {
  193875. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193876. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193877. ig = (((png_uint_32)i *
  193878. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193879. for (j = 0; j < 256; j++)
  193880. {
  193881. png_ptr->gamma_16_from_1[i][j] =
  193882. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193883. 65535.0, g) * 65535.0 + .5);
  193884. }
  193885. }
  193886. }
  193887. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193888. }
  193889. }
  193890. #endif
  193891. /* To do: install integer version of png_build_gamma_table here */
  193892. #endif
  193893. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193894. /* undoes intrapixel differencing */
  193895. void /* PRIVATE */
  193896. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193897. {
  193898. png_debug(1, "in png_do_read_intrapixel\n");
  193899. if (
  193900. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193901. row != NULL && row_info != NULL &&
  193902. #endif
  193903. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193904. {
  193905. int bytes_per_pixel;
  193906. png_uint_32 row_width = row_info->width;
  193907. if (row_info->bit_depth == 8)
  193908. {
  193909. png_bytep rp;
  193910. png_uint_32 i;
  193911. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193912. bytes_per_pixel = 3;
  193913. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193914. bytes_per_pixel = 4;
  193915. else
  193916. return;
  193917. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193918. {
  193919. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193920. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193921. }
  193922. }
  193923. else if (row_info->bit_depth == 16)
  193924. {
  193925. png_bytep rp;
  193926. png_uint_32 i;
  193927. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193928. bytes_per_pixel = 6;
  193929. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193930. bytes_per_pixel = 8;
  193931. else
  193932. return;
  193933. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193934. {
  193935. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193936. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193937. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193938. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193939. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193940. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193941. *(rp+1) = (png_byte)(red & 0xff);
  193942. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193943. *(rp+5) = (png_byte)(blue & 0xff);
  193944. }
  193945. }
  193946. }
  193947. }
  193948. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193949. #endif /* PNG_READ_SUPPORTED */
  193950. /*** End of inlined file: pngrtran.c ***/
  193951. /*** Start of inlined file: pngrutil.c ***/
  193952. /* pngrutil.c - utilities to read a PNG file
  193953. *
  193954. * Last changed in libpng 1.2.21 [October 4, 2007]
  193955. * For conditions of distribution and use, see copyright notice in png.h
  193956. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193957. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193958. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193959. *
  193960. * This file contains routines that are only called from within
  193961. * libpng itself during the course of reading an image.
  193962. */
  193963. #define PNG_INTERNAL
  193964. #if defined(PNG_READ_SUPPORTED)
  193965. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193966. # define WIN32_WCE_OLD
  193967. #endif
  193968. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193969. # if defined(WIN32_WCE_OLD)
  193970. /* strtod() function is not supported on WindowsCE */
  193971. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193972. {
  193973. double result = 0;
  193974. int len;
  193975. wchar_t *str, *end;
  193976. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193977. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193978. if ( NULL != str )
  193979. {
  193980. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193981. result = wcstod(str, &end);
  193982. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193983. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193984. png_free(png_ptr, str);
  193985. }
  193986. return result;
  193987. }
  193988. # else
  193989. # define png_strtod(p,a,b) strtod(a,b)
  193990. # endif
  193991. #endif
  193992. png_uint_32 PNGAPI
  193993. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193994. {
  193995. png_uint_32 i = png_get_uint_32(buf);
  193996. if (i > PNG_UINT_31_MAX)
  193997. png_error(png_ptr, "PNG unsigned integer out of range.");
  193998. return (i);
  193999. }
  194000. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194001. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194002. png_uint_32 PNGAPI
  194003. png_get_uint_32(png_bytep buf)
  194004. {
  194005. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194006. ((png_uint_32)(*(buf + 1)) << 16) +
  194007. ((png_uint_32)(*(buf + 2)) << 8) +
  194008. (png_uint_32)(*(buf + 3));
  194009. return (i);
  194010. }
  194011. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194012. * data is stored in the PNG file in two's complement format, and it is
  194013. * assumed that the machine format for signed integers is the same. */
  194014. png_int_32 PNGAPI
  194015. png_get_int_32(png_bytep buf)
  194016. {
  194017. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194018. ((png_int_32)(*(buf + 1)) << 16) +
  194019. ((png_int_32)(*(buf + 2)) << 8) +
  194020. (png_int_32)(*(buf + 3));
  194021. return (i);
  194022. }
  194023. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194024. png_uint_16 PNGAPI
  194025. png_get_uint_16(png_bytep buf)
  194026. {
  194027. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194028. (png_uint_16)(*(buf + 1)));
  194029. return (i);
  194030. }
  194031. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194032. /* Read data, and (optionally) run it through the CRC. */
  194033. void /* PRIVATE */
  194034. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194035. {
  194036. if(png_ptr == NULL) return;
  194037. png_read_data(png_ptr, buf, length);
  194038. png_calculate_crc(png_ptr, buf, length);
  194039. }
  194040. /* Optionally skip data and then check the CRC. Depending on whether we
  194041. are reading a ancillary or critical chunk, and how the program has set
  194042. things up, we may calculate the CRC on the data and print a message.
  194043. Returns '1' if there was a CRC error, '0' otherwise. */
  194044. int /* PRIVATE */
  194045. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194046. {
  194047. png_size_t i;
  194048. png_size_t istop = png_ptr->zbuf_size;
  194049. for (i = (png_size_t)skip; i > istop; i -= istop)
  194050. {
  194051. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194052. }
  194053. if (i)
  194054. {
  194055. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194056. }
  194057. if (png_crc_error(png_ptr))
  194058. {
  194059. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194060. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194061. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194062. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194063. {
  194064. png_chunk_warning(png_ptr, "CRC error");
  194065. }
  194066. else
  194067. {
  194068. png_chunk_error(png_ptr, "CRC error");
  194069. }
  194070. return (1);
  194071. }
  194072. return (0);
  194073. }
  194074. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194075. the data it has read thus far. */
  194076. int /* PRIVATE */
  194077. png_crc_error(png_structp png_ptr)
  194078. {
  194079. png_byte crc_bytes[4];
  194080. png_uint_32 crc;
  194081. int need_crc = 1;
  194082. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194083. {
  194084. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194085. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194086. need_crc = 0;
  194087. }
  194088. else /* critical */
  194089. {
  194090. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194091. need_crc = 0;
  194092. }
  194093. png_read_data(png_ptr, crc_bytes, 4);
  194094. if (need_crc)
  194095. {
  194096. crc = png_get_uint_32(crc_bytes);
  194097. return ((int)(crc != png_ptr->crc));
  194098. }
  194099. else
  194100. return (0);
  194101. }
  194102. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194103. defined(PNG_READ_iCCP_SUPPORTED)
  194104. /*
  194105. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194106. * points at an allocated area holding the contents of a chunk with a
  194107. * trailing compressed part. What we get back is an allocated area
  194108. * holding the original prefix part and an uncompressed version of the
  194109. * trailing part (the malloc area passed in is freed).
  194110. */
  194111. png_charp /* PRIVATE */
  194112. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194113. png_charp chunkdata, png_size_t chunklength,
  194114. png_size_t prefix_size, png_size_t *newlength)
  194115. {
  194116. static PNG_CONST char msg[] = "Error decoding compressed text";
  194117. png_charp text;
  194118. png_size_t text_size;
  194119. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194120. {
  194121. int ret = Z_OK;
  194122. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194123. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194124. png_ptr->zstream.next_out = png_ptr->zbuf;
  194125. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194126. text_size = 0;
  194127. text = NULL;
  194128. while (png_ptr->zstream.avail_in)
  194129. {
  194130. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194131. if (ret != Z_OK && ret != Z_STREAM_END)
  194132. {
  194133. if (png_ptr->zstream.msg != NULL)
  194134. png_warning(png_ptr, png_ptr->zstream.msg);
  194135. else
  194136. png_warning(png_ptr, msg);
  194137. inflateReset(&png_ptr->zstream);
  194138. png_ptr->zstream.avail_in = 0;
  194139. if (text == NULL)
  194140. {
  194141. text_size = prefix_size + png_sizeof(msg) + 1;
  194142. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194143. if (text == NULL)
  194144. {
  194145. png_free(png_ptr,chunkdata);
  194146. png_error(png_ptr,"Not enough memory to decompress chunk");
  194147. }
  194148. png_memcpy(text, chunkdata, prefix_size);
  194149. }
  194150. text[text_size - 1] = 0x00;
  194151. /* Copy what we can of the error message into the text chunk */
  194152. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194153. text_size = png_sizeof(msg) > text_size ? text_size :
  194154. png_sizeof(msg);
  194155. png_memcpy(text + prefix_size, msg, text_size + 1);
  194156. break;
  194157. }
  194158. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194159. {
  194160. if (text == NULL)
  194161. {
  194162. text_size = prefix_size +
  194163. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194164. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194165. if (text == NULL)
  194166. {
  194167. png_free(png_ptr,chunkdata);
  194168. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194169. }
  194170. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194171. text_size - prefix_size);
  194172. png_memcpy(text, chunkdata, prefix_size);
  194173. *(text + text_size) = 0x00;
  194174. }
  194175. else
  194176. {
  194177. png_charp tmp;
  194178. tmp = text;
  194179. text = (png_charp)png_malloc_warn(png_ptr,
  194180. (png_uint_32)(text_size +
  194181. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194182. if (text == NULL)
  194183. {
  194184. png_free(png_ptr, tmp);
  194185. png_free(png_ptr, chunkdata);
  194186. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194187. }
  194188. png_memcpy(text, tmp, text_size);
  194189. png_free(png_ptr, tmp);
  194190. png_memcpy(text + text_size, png_ptr->zbuf,
  194191. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194192. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194193. *(text + text_size) = 0x00;
  194194. }
  194195. if (ret == Z_STREAM_END)
  194196. break;
  194197. else
  194198. {
  194199. png_ptr->zstream.next_out = png_ptr->zbuf;
  194200. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194201. }
  194202. }
  194203. }
  194204. if (ret != Z_STREAM_END)
  194205. {
  194206. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194207. char umsg[52];
  194208. if (ret == Z_BUF_ERROR)
  194209. png_snprintf(umsg, 52,
  194210. "Buffer error in compressed datastream in %s chunk",
  194211. png_ptr->chunk_name);
  194212. else if (ret == Z_DATA_ERROR)
  194213. png_snprintf(umsg, 52,
  194214. "Data error in compressed datastream in %s chunk",
  194215. png_ptr->chunk_name);
  194216. else
  194217. png_snprintf(umsg, 52,
  194218. "Incomplete compressed datastream in %s chunk",
  194219. png_ptr->chunk_name);
  194220. png_warning(png_ptr, umsg);
  194221. #else
  194222. png_warning(png_ptr,
  194223. "Incomplete compressed datastream in chunk other than IDAT");
  194224. #endif
  194225. text_size=prefix_size;
  194226. if (text == NULL)
  194227. {
  194228. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194229. if (text == NULL)
  194230. {
  194231. png_free(png_ptr, chunkdata);
  194232. png_error(png_ptr,"Not enough memory for text.");
  194233. }
  194234. png_memcpy(text, chunkdata, prefix_size);
  194235. }
  194236. *(text + text_size) = 0x00;
  194237. }
  194238. inflateReset(&png_ptr->zstream);
  194239. png_ptr->zstream.avail_in = 0;
  194240. png_free(png_ptr, chunkdata);
  194241. chunkdata = text;
  194242. *newlength=text_size;
  194243. }
  194244. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194245. {
  194246. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194247. char umsg[50];
  194248. png_snprintf(umsg, 50,
  194249. "Unknown zTXt compression type %d", comp_type);
  194250. png_warning(png_ptr, umsg);
  194251. #else
  194252. png_warning(png_ptr, "Unknown zTXt compression type");
  194253. #endif
  194254. *(chunkdata + prefix_size) = 0x00;
  194255. *newlength=prefix_size;
  194256. }
  194257. return chunkdata;
  194258. }
  194259. #endif
  194260. /* read and check the IDHR chunk */
  194261. void /* PRIVATE */
  194262. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194263. {
  194264. png_byte buf[13];
  194265. png_uint_32 width, height;
  194266. int bit_depth, color_type, compression_type, filter_type;
  194267. int interlace_type;
  194268. png_debug(1, "in png_handle_IHDR\n");
  194269. if (png_ptr->mode & PNG_HAVE_IHDR)
  194270. png_error(png_ptr, "Out of place IHDR");
  194271. /* check the length */
  194272. if (length != 13)
  194273. png_error(png_ptr, "Invalid IHDR chunk");
  194274. png_ptr->mode |= PNG_HAVE_IHDR;
  194275. png_crc_read(png_ptr, buf, 13);
  194276. png_crc_finish(png_ptr, 0);
  194277. width = png_get_uint_31(png_ptr, buf);
  194278. height = png_get_uint_31(png_ptr, buf + 4);
  194279. bit_depth = buf[8];
  194280. color_type = buf[9];
  194281. compression_type = buf[10];
  194282. filter_type = buf[11];
  194283. interlace_type = buf[12];
  194284. /* set internal variables */
  194285. png_ptr->width = width;
  194286. png_ptr->height = height;
  194287. png_ptr->bit_depth = (png_byte)bit_depth;
  194288. png_ptr->interlaced = (png_byte)interlace_type;
  194289. png_ptr->color_type = (png_byte)color_type;
  194290. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194291. png_ptr->filter_type = (png_byte)filter_type;
  194292. #endif
  194293. png_ptr->compression_type = (png_byte)compression_type;
  194294. /* find number of channels */
  194295. switch (png_ptr->color_type)
  194296. {
  194297. case PNG_COLOR_TYPE_GRAY:
  194298. case PNG_COLOR_TYPE_PALETTE:
  194299. png_ptr->channels = 1;
  194300. break;
  194301. case PNG_COLOR_TYPE_RGB:
  194302. png_ptr->channels = 3;
  194303. break;
  194304. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194305. png_ptr->channels = 2;
  194306. break;
  194307. case PNG_COLOR_TYPE_RGB_ALPHA:
  194308. png_ptr->channels = 4;
  194309. break;
  194310. }
  194311. /* set up other useful info */
  194312. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194313. png_ptr->channels);
  194314. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194315. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194316. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194317. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194318. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194319. color_type, interlace_type, compression_type, filter_type);
  194320. }
  194321. /* read and check the palette */
  194322. void /* PRIVATE */
  194323. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194324. {
  194325. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194326. int num, i;
  194327. #ifndef PNG_NO_POINTER_INDEXING
  194328. png_colorp pal_ptr;
  194329. #endif
  194330. png_debug(1, "in png_handle_PLTE\n");
  194331. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194332. png_error(png_ptr, "Missing IHDR before PLTE");
  194333. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194334. {
  194335. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194336. png_crc_finish(png_ptr, length);
  194337. return;
  194338. }
  194339. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194340. png_error(png_ptr, "Duplicate PLTE chunk");
  194341. png_ptr->mode |= PNG_HAVE_PLTE;
  194342. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194343. {
  194344. png_warning(png_ptr,
  194345. "Ignoring PLTE chunk in grayscale PNG");
  194346. png_crc_finish(png_ptr, length);
  194347. return;
  194348. }
  194349. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194350. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194351. {
  194352. png_crc_finish(png_ptr, length);
  194353. return;
  194354. }
  194355. #endif
  194356. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194357. {
  194358. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194359. {
  194360. png_warning(png_ptr, "Invalid palette chunk");
  194361. png_crc_finish(png_ptr, length);
  194362. return;
  194363. }
  194364. else
  194365. {
  194366. png_error(png_ptr, "Invalid palette chunk");
  194367. }
  194368. }
  194369. num = (int)length / 3;
  194370. #ifndef PNG_NO_POINTER_INDEXING
  194371. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194372. {
  194373. png_byte buf[3];
  194374. png_crc_read(png_ptr, buf, 3);
  194375. pal_ptr->red = buf[0];
  194376. pal_ptr->green = buf[1];
  194377. pal_ptr->blue = buf[2];
  194378. }
  194379. #else
  194380. for (i = 0; i < num; i++)
  194381. {
  194382. png_byte buf[3];
  194383. png_crc_read(png_ptr, buf, 3);
  194384. /* don't depend upon png_color being any order */
  194385. palette[i].red = buf[0];
  194386. palette[i].green = buf[1];
  194387. palette[i].blue = buf[2];
  194388. }
  194389. #endif
  194390. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194391. whatever the normal CRC configuration tells us. However, if we
  194392. have an RGB image, the PLTE can be considered ancillary, so
  194393. we will act as though it is. */
  194394. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194395. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194396. #endif
  194397. {
  194398. png_crc_finish(png_ptr, 0);
  194399. }
  194400. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194401. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194402. {
  194403. /* If we don't want to use the data from an ancillary chunk,
  194404. we have two options: an error abort, or a warning and we
  194405. ignore the data in this chunk (which should be OK, since
  194406. it's considered ancillary for a RGB or RGBA image). */
  194407. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194408. {
  194409. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194410. {
  194411. png_chunk_error(png_ptr, "CRC error");
  194412. }
  194413. else
  194414. {
  194415. png_chunk_warning(png_ptr, "CRC error");
  194416. return;
  194417. }
  194418. }
  194419. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194420. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194421. {
  194422. png_chunk_warning(png_ptr, "CRC error");
  194423. }
  194424. }
  194425. #endif
  194426. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194427. #if defined(PNG_READ_tRNS_SUPPORTED)
  194428. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194429. {
  194430. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194431. {
  194432. if (png_ptr->num_trans > (png_uint_16)num)
  194433. {
  194434. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194435. png_ptr->num_trans = (png_uint_16)num;
  194436. }
  194437. if (info_ptr->num_trans > (png_uint_16)num)
  194438. {
  194439. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194440. info_ptr->num_trans = (png_uint_16)num;
  194441. }
  194442. }
  194443. }
  194444. #endif
  194445. }
  194446. void /* PRIVATE */
  194447. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194448. {
  194449. png_debug(1, "in png_handle_IEND\n");
  194450. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194451. {
  194452. png_error(png_ptr, "No image in file");
  194453. }
  194454. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194455. if (length != 0)
  194456. {
  194457. png_warning(png_ptr, "Incorrect IEND chunk length");
  194458. }
  194459. png_crc_finish(png_ptr, length);
  194460. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194461. }
  194462. #if defined(PNG_READ_gAMA_SUPPORTED)
  194463. void /* PRIVATE */
  194464. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194465. {
  194466. png_fixed_point igamma;
  194467. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194468. float file_gamma;
  194469. #endif
  194470. png_byte buf[4];
  194471. png_debug(1, "in png_handle_gAMA\n");
  194472. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194473. png_error(png_ptr, "Missing IHDR before gAMA");
  194474. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194475. {
  194476. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194477. png_crc_finish(png_ptr, length);
  194478. return;
  194479. }
  194480. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194481. /* Should be an error, but we can cope with it */
  194482. png_warning(png_ptr, "Out of place gAMA chunk");
  194483. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194484. #if defined(PNG_READ_sRGB_SUPPORTED)
  194485. && !(info_ptr->valid & PNG_INFO_sRGB)
  194486. #endif
  194487. )
  194488. {
  194489. png_warning(png_ptr, "Duplicate gAMA chunk");
  194490. png_crc_finish(png_ptr, length);
  194491. return;
  194492. }
  194493. if (length != 4)
  194494. {
  194495. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194496. png_crc_finish(png_ptr, length);
  194497. return;
  194498. }
  194499. png_crc_read(png_ptr, buf, 4);
  194500. if (png_crc_finish(png_ptr, 0))
  194501. return;
  194502. igamma = (png_fixed_point)png_get_uint_32(buf);
  194503. /* check for zero gamma */
  194504. if (igamma == 0)
  194505. {
  194506. png_warning(png_ptr,
  194507. "Ignoring gAMA chunk with gamma=0");
  194508. return;
  194509. }
  194510. #if defined(PNG_READ_sRGB_SUPPORTED)
  194511. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194512. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194513. {
  194514. png_warning(png_ptr,
  194515. "Ignoring incorrect gAMA value when sRGB is also present");
  194516. #ifndef PNG_NO_CONSOLE_IO
  194517. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194518. #endif
  194519. return;
  194520. }
  194521. #endif /* PNG_READ_sRGB_SUPPORTED */
  194522. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194523. file_gamma = (float)igamma / (float)100000.0;
  194524. # ifdef PNG_READ_GAMMA_SUPPORTED
  194525. png_ptr->gamma = file_gamma;
  194526. # endif
  194527. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194528. #endif
  194529. #ifdef PNG_FIXED_POINT_SUPPORTED
  194530. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194531. #endif
  194532. }
  194533. #endif
  194534. #if defined(PNG_READ_sBIT_SUPPORTED)
  194535. void /* PRIVATE */
  194536. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194537. {
  194538. png_size_t truelen;
  194539. png_byte buf[4];
  194540. png_debug(1, "in png_handle_sBIT\n");
  194541. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194542. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194543. png_error(png_ptr, "Missing IHDR before sBIT");
  194544. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194545. {
  194546. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194547. png_crc_finish(png_ptr, length);
  194548. return;
  194549. }
  194550. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194551. {
  194552. /* Should be an error, but we can cope with it */
  194553. png_warning(png_ptr, "Out of place sBIT chunk");
  194554. }
  194555. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194556. {
  194557. png_warning(png_ptr, "Duplicate sBIT chunk");
  194558. png_crc_finish(png_ptr, length);
  194559. return;
  194560. }
  194561. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194562. truelen = 3;
  194563. else
  194564. truelen = (png_size_t)png_ptr->channels;
  194565. if (length != truelen || length > 4)
  194566. {
  194567. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194568. png_crc_finish(png_ptr, length);
  194569. return;
  194570. }
  194571. png_crc_read(png_ptr, buf, truelen);
  194572. if (png_crc_finish(png_ptr, 0))
  194573. return;
  194574. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194575. {
  194576. png_ptr->sig_bit.red = buf[0];
  194577. png_ptr->sig_bit.green = buf[1];
  194578. png_ptr->sig_bit.blue = buf[2];
  194579. png_ptr->sig_bit.alpha = buf[3];
  194580. }
  194581. else
  194582. {
  194583. png_ptr->sig_bit.gray = buf[0];
  194584. png_ptr->sig_bit.red = buf[0];
  194585. png_ptr->sig_bit.green = buf[0];
  194586. png_ptr->sig_bit.blue = buf[0];
  194587. png_ptr->sig_bit.alpha = buf[1];
  194588. }
  194589. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194590. }
  194591. #endif
  194592. #if defined(PNG_READ_cHRM_SUPPORTED)
  194593. void /* PRIVATE */
  194594. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194595. {
  194596. png_byte buf[4];
  194597. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194598. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194599. #endif
  194600. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194601. int_y_green, int_x_blue, int_y_blue;
  194602. png_uint_32 uint_x, uint_y;
  194603. png_debug(1, "in png_handle_cHRM\n");
  194604. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194605. png_error(png_ptr, "Missing IHDR before cHRM");
  194606. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194607. {
  194608. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194609. png_crc_finish(png_ptr, length);
  194610. return;
  194611. }
  194612. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194613. /* Should be an error, but we can cope with it */
  194614. png_warning(png_ptr, "Missing PLTE before cHRM");
  194615. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194616. #if defined(PNG_READ_sRGB_SUPPORTED)
  194617. && !(info_ptr->valid & PNG_INFO_sRGB)
  194618. #endif
  194619. )
  194620. {
  194621. png_warning(png_ptr, "Duplicate cHRM chunk");
  194622. png_crc_finish(png_ptr, length);
  194623. return;
  194624. }
  194625. if (length != 32)
  194626. {
  194627. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194628. png_crc_finish(png_ptr, length);
  194629. return;
  194630. }
  194631. png_crc_read(png_ptr, buf, 4);
  194632. uint_x = png_get_uint_32(buf);
  194633. png_crc_read(png_ptr, buf, 4);
  194634. uint_y = png_get_uint_32(buf);
  194635. if (uint_x > 80000L || uint_y > 80000L ||
  194636. uint_x + uint_y > 100000L)
  194637. {
  194638. png_warning(png_ptr, "Invalid cHRM white point");
  194639. png_crc_finish(png_ptr, 24);
  194640. return;
  194641. }
  194642. int_x_white = (png_fixed_point)uint_x;
  194643. int_y_white = (png_fixed_point)uint_y;
  194644. png_crc_read(png_ptr, buf, 4);
  194645. uint_x = png_get_uint_32(buf);
  194646. png_crc_read(png_ptr, buf, 4);
  194647. uint_y = png_get_uint_32(buf);
  194648. if (uint_x + uint_y > 100000L)
  194649. {
  194650. png_warning(png_ptr, "Invalid cHRM red point");
  194651. png_crc_finish(png_ptr, 16);
  194652. return;
  194653. }
  194654. int_x_red = (png_fixed_point)uint_x;
  194655. int_y_red = (png_fixed_point)uint_y;
  194656. png_crc_read(png_ptr, buf, 4);
  194657. uint_x = png_get_uint_32(buf);
  194658. png_crc_read(png_ptr, buf, 4);
  194659. uint_y = png_get_uint_32(buf);
  194660. if (uint_x + uint_y > 100000L)
  194661. {
  194662. png_warning(png_ptr, "Invalid cHRM green point");
  194663. png_crc_finish(png_ptr, 8);
  194664. return;
  194665. }
  194666. int_x_green = (png_fixed_point)uint_x;
  194667. int_y_green = (png_fixed_point)uint_y;
  194668. png_crc_read(png_ptr, buf, 4);
  194669. uint_x = png_get_uint_32(buf);
  194670. png_crc_read(png_ptr, buf, 4);
  194671. uint_y = png_get_uint_32(buf);
  194672. if (uint_x + uint_y > 100000L)
  194673. {
  194674. png_warning(png_ptr, "Invalid cHRM blue point");
  194675. png_crc_finish(png_ptr, 0);
  194676. return;
  194677. }
  194678. int_x_blue = (png_fixed_point)uint_x;
  194679. int_y_blue = (png_fixed_point)uint_y;
  194680. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194681. white_x = (float)int_x_white / (float)100000.0;
  194682. white_y = (float)int_y_white / (float)100000.0;
  194683. red_x = (float)int_x_red / (float)100000.0;
  194684. red_y = (float)int_y_red / (float)100000.0;
  194685. green_x = (float)int_x_green / (float)100000.0;
  194686. green_y = (float)int_y_green / (float)100000.0;
  194687. blue_x = (float)int_x_blue / (float)100000.0;
  194688. blue_y = (float)int_y_blue / (float)100000.0;
  194689. #endif
  194690. #if defined(PNG_READ_sRGB_SUPPORTED)
  194691. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194692. {
  194693. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194694. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194695. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194696. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194697. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194698. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194699. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194700. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194701. {
  194702. png_warning(png_ptr,
  194703. "Ignoring incorrect cHRM value when sRGB is also present");
  194704. #ifndef PNG_NO_CONSOLE_IO
  194705. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194706. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194707. white_x, white_y, red_x, red_y);
  194708. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194709. green_x, green_y, blue_x, blue_y);
  194710. #else
  194711. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194712. int_x_white, int_y_white, int_x_red, int_y_red);
  194713. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194714. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194715. #endif
  194716. #endif /* PNG_NO_CONSOLE_IO */
  194717. }
  194718. png_crc_finish(png_ptr, 0);
  194719. return;
  194720. }
  194721. #endif /* PNG_READ_sRGB_SUPPORTED */
  194722. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194723. png_set_cHRM(png_ptr, info_ptr,
  194724. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194725. #endif
  194726. #ifdef PNG_FIXED_POINT_SUPPORTED
  194727. png_set_cHRM_fixed(png_ptr, info_ptr,
  194728. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194729. int_y_green, int_x_blue, int_y_blue);
  194730. #endif
  194731. if (png_crc_finish(png_ptr, 0))
  194732. return;
  194733. }
  194734. #endif
  194735. #if defined(PNG_READ_sRGB_SUPPORTED)
  194736. void /* PRIVATE */
  194737. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194738. {
  194739. int intent;
  194740. png_byte buf[1];
  194741. png_debug(1, "in png_handle_sRGB\n");
  194742. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194743. png_error(png_ptr, "Missing IHDR before sRGB");
  194744. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194745. {
  194746. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194747. png_crc_finish(png_ptr, length);
  194748. return;
  194749. }
  194750. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194751. /* Should be an error, but we can cope with it */
  194752. png_warning(png_ptr, "Out of place sRGB chunk");
  194753. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194754. {
  194755. png_warning(png_ptr, "Duplicate sRGB chunk");
  194756. png_crc_finish(png_ptr, length);
  194757. return;
  194758. }
  194759. if (length != 1)
  194760. {
  194761. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194762. png_crc_finish(png_ptr, length);
  194763. return;
  194764. }
  194765. png_crc_read(png_ptr, buf, 1);
  194766. if (png_crc_finish(png_ptr, 0))
  194767. return;
  194768. intent = buf[0];
  194769. /* check for bad intent */
  194770. if (intent >= PNG_sRGB_INTENT_LAST)
  194771. {
  194772. png_warning(png_ptr, "Unknown sRGB intent");
  194773. return;
  194774. }
  194775. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194776. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194777. {
  194778. png_fixed_point igamma;
  194779. #ifdef PNG_FIXED_POINT_SUPPORTED
  194780. igamma=info_ptr->int_gamma;
  194781. #else
  194782. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194783. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194784. # endif
  194785. #endif
  194786. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194787. {
  194788. png_warning(png_ptr,
  194789. "Ignoring incorrect gAMA value when sRGB is also present");
  194790. #ifndef PNG_NO_CONSOLE_IO
  194791. # ifdef PNG_FIXED_POINT_SUPPORTED
  194792. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194793. # else
  194794. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194795. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194796. # endif
  194797. # endif
  194798. #endif
  194799. }
  194800. }
  194801. #endif /* PNG_READ_gAMA_SUPPORTED */
  194802. #ifdef PNG_READ_cHRM_SUPPORTED
  194803. #ifdef PNG_FIXED_POINT_SUPPORTED
  194804. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194805. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194806. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194807. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194808. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194809. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194810. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194811. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194812. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194813. {
  194814. png_warning(png_ptr,
  194815. "Ignoring incorrect cHRM value when sRGB is also present");
  194816. }
  194817. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194818. #endif /* PNG_READ_cHRM_SUPPORTED */
  194819. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194820. }
  194821. #endif /* PNG_READ_sRGB_SUPPORTED */
  194822. #if defined(PNG_READ_iCCP_SUPPORTED)
  194823. void /* PRIVATE */
  194824. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194825. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194826. {
  194827. png_charp chunkdata;
  194828. png_byte compression_type;
  194829. png_bytep pC;
  194830. png_charp profile;
  194831. png_uint_32 skip = 0;
  194832. png_uint_32 profile_size, profile_length;
  194833. png_size_t slength, prefix_length, data_length;
  194834. png_debug(1, "in png_handle_iCCP\n");
  194835. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194836. png_error(png_ptr, "Missing IHDR before iCCP");
  194837. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194838. {
  194839. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194840. png_crc_finish(png_ptr, length);
  194841. return;
  194842. }
  194843. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194844. /* Should be an error, but we can cope with it */
  194845. png_warning(png_ptr, "Out of place iCCP chunk");
  194846. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194847. {
  194848. png_warning(png_ptr, "Duplicate iCCP chunk");
  194849. png_crc_finish(png_ptr, length);
  194850. return;
  194851. }
  194852. #ifdef PNG_MAX_MALLOC_64K
  194853. if (length > (png_uint_32)65535L)
  194854. {
  194855. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194856. skip = length - (png_uint_32)65535L;
  194857. length = (png_uint_32)65535L;
  194858. }
  194859. #endif
  194860. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194861. slength = (png_size_t)length;
  194862. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194863. if (png_crc_finish(png_ptr, skip))
  194864. {
  194865. png_free(png_ptr, chunkdata);
  194866. return;
  194867. }
  194868. chunkdata[slength] = 0x00;
  194869. for (profile = chunkdata; *profile; profile++)
  194870. /* empty loop to find end of name */ ;
  194871. ++profile;
  194872. /* there should be at least one zero (the compression type byte)
  194873. following the separator, and we should be on it */
  194874. if ( profile >= chunkdata + slength - 1)
  194875. {
  194876. png_free(png_ptr, chunkdata);
  194877. png_warning(png_ptr, "Malformed iCCP chunk");
  194878. return;
  194879. }
  194880. /* compression_type should always be zero */
  194881. compression_type = *profile++;
  194882. if (compression_type)
  194883. {
  194884. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194885. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194886. wrote nonzero) */
  194887. }
  194888. prefix_length = profile - chunkdata;
  194889. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194890. slength, prefix_length, &data_length);
  194891. profile_length = data_length - prefix_length;
  194892. if ( prefix_length > data_length || profile_length < 4)
  194893. {
  194894. png_free(png_ptr, chunkdata);
  194895. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194896. return;
  194897. }
  194898. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194899. pC = (png_bytep)(chunkdata+prefix_length);
  194900. profile_size = ((*(pC ))<<24) |
  194901. ((*(pC+1))<<16) |
  194902. ((*(pC+2))<< 8) |
  194903. ((*(pC+3)) );
  194904. if(profile_size < profile_length)
  194905. profile_length = profile_size;
  194906. if(profile_size > profile_length)
  194907. {
  194908. png_free(png_ptr, chunkdata);
  194909. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194910. return;
  194911. }
  194912. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194913. chunkdata + prefix_length, profile_length);
  194914. png_free(png_ptr, chunkdata);
  194915. }
  194916. #endif /* PNG_READ_iCCP_SUPPORTED */
  194917. #if defined(PNG_READ_sPLT_SUPPORTED)
  194918. void /* PRIVATE */
  194919. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194920. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194921. {
  194922. png_bytep chunkdata;
  194923. png_bytep entry_start;
  194924. png_sPLT_t new_palette;
  194925. #ifdef PNG_NO_POINTER_INDEXING
  194926. png_sPLT_entryp pp;
  194927. #endif
  194928. int data_length, entry_size, i;
  194929. png_uint_32 skip = 0;
  194930. png_size_t slength;
  194931. png_debug(1, "in png_handle_sPLT\n");
  194932. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194933. png_error(png_ptr, "Missing IHDR before sPLT");
  194934. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194935. {
  194936. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194937. png_crc_finish(png_ptr, length);
  194938. return;
  194939. }
  194940. #ifdef PNG_MAX_MALLOC_64K
  194941. if (length > (png_uint_32)65535L)
  194942. {
  194943. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194944. skip = length - (png_uint_32)65535L;
  194945. length = (png_uint_32)65535L;
  194946. }
  194947. #endif
  194948. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194949. slength = (png_size_t)length;
  194950. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194951. if (png_crc_finish(png_ptr, skip))
  194952. {
  194953. png_free(png_ptr, chunkdata);
  194954. return;
  194955. }
  194956. chunkdata[slength] = 0x00;
  194957. for (entry_start = chunkdata; *entry_start; entry_start++)
  194958. /* empty loop to find end of name */ ;
  194959. ++entry_start;
  194960. /* a sample depth should follow the separator, and we should be on it */
  194961. if (entry_start > chunkdata + slength - 2)
  194962. {
  194963. png_free(png_ptr, chunkdata);
  194964. png_warning(png_ptr, "malformed sPLT chunk");
  194965. return;
  194966. }
  194967. new_palette.depth = *entry_start++;
  194968. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194969. data_length = (slength - (entry_start - chunkdata));
  194970. /* integrity-check the data length */
  194971. if (data_length % entry_size)
  194972. {
  194973. png_free(png_ptr, chunkdata);
  194974. png_warning(png_ptr, "sPLT chunk has bad length");
  194975. return;
  194976. }
  194977. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194978. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194979. png_sizeof(png_sPLT_entry)))
  194980. {
  194981. png_warning(png_ptr, "sPLT chunk too long");
  194982. return;
  194983. }
  194984. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194985. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194986. if (new_palette.entries == NULL)
  194987. {
  194988. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194989. return;
  194990. }
  194991. #ifndef PNG_NO_POINTER_INDEXING
  194992. for (i = 0; i < new_palette.nentries; i++)
  194993. {
  194994. png_sPLT_entryp pp = new_palette.entries + i;
  194995. if (new_palette.depth == 8)
  194996. {
  194997. pp->red = *entry_start++;
  194998. pp->green = *entry_start++;
  194999. pp->blue = *entry_start++;
  195000. pp->alpha = *entry_start++;
  195001. }
  195002. else
  195003. {
  195004. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195005. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195006. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195007. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195008. }
  195009. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195010. }
  195011. #else
  195012. pp = new_palette.entries;
  195013. for (i = 0; i < new_palette.nentries; i++)
  195014. {
  195015. if (new_palette.depth == 8)
  195016. {
  195017. pp[i].red = *entry_start++;
  195018. pp[i].green = *entry_start++;
  195019. pp[i].blue = *entry_start++;
  195020. pp[i].alpha = *entry_start++;
  195021. }
  195022. else
  195023. {
  195024. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195025. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195026. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195027. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195028. }
  195029. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195030. }
  195031. #endif
  195032. /* discard all chunk data except the name and stash that */
  195033. new_palette.name = (png_charp)chunkdata;
  195034. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195035. png_free(png_ptr, chunkdata);
  195036. png_free(png_ptr, new_palette.entries);
  195037. }
  195038. #endif /* PNG_READ_sPLT_SUPPORTED */
  195039. #if defined(PNG_READ_tRNS_SUPPORTED)
  195040. void /* PRIVATE */
  195041. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195042. {
  195043. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195044. int bit_mask;
  195045. png_debug(1, "in png_handle_tRNS\n");
  195046. /* For non-indexed color, mask off any bits in the tRNS value that
  195047. * exceed the bit depth. Some creators were writing extra bits there.
  195048. * This is not needed for indexed color. */
  195049. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195050. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195051. png_error(png_ptr, "Missing IHDR before tRNS");
  195052. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195053. {
  195054. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195055. png_crc_finish(png_ptr, length);
  195056. return;
  195057. }
  195058. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195059. {
  195060. png_warning(png_ptr, "Duplicate tRNS chunk");
  195061. png_crc_finish(png_ptr, length);
  195062. return;
  195063. }
  195064. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195065. {
  195066. png_byte buf[2];
  195067. if (length != 2)
  195068. {
  195069. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195070. png_crc_finish(png_ptr, length);
  195071. return;
  195072. }
  195073. png_crc_read(png_ptr, buf, 2);
  195074. png_ptr->num_trans = 1;
  195075. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195076. }
  195077. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195078. {
  195079. png_byte buf[6];
  195080. if (length != 6)
  195081. {
  195082. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195083. png_crc_finish(png_ptr, length);
  195084. return;
  195085. }
  195086. png_crc_read(png_ptr, buf, (png_size_t)length);
  195087. png_ptr->num_trans = 1;
  195088. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195089. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195090. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195091. }
  195092. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195093. {
  195094. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195095. {
  195096. /* Should be an error, but we can cope with it. */
  195097. png_warning(png_ptr, "Missing PLTE before tRNS");
  195098. }
  195099. if (length > (png_uint_32)png_ptr->num_palette ||
  195100. length > PNG_MAX_PALETTE_LENGTH)
  195101. {
  195102. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195103. png_crc_finish(png_ptr, length);
  195104. return;
  195105. }
  195106. if (length == 0)
  195107. {
  195108. png_warning(png_ptr, "Zero length tRNS chunk");
  195109. png_crc_finish(png_ptr, length);
  195110. return;
  195111. }
  195112. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195113. png_ptr->num_trans = (png_uint_16)length;
  195114. }
  195115. else
  195116. {
  195117. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195118. png_crc_finish(png_ptr, length);
  195119. return;
  195120. }
  195121. if (png_crc_finish(png_ptr, 0))
  195122. {
  195123. png_ptr->num_trans = 0;
  195124. return;
  195125. }
  195126. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195127. &(png_ptr->trans_values));
  195128. }
  195129. #endif
  195130. #if defined(PNG_READ_bKGD_SUPPORTED)
  195131. void /* PRIVATE */
  195132. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195133. {
  195134. png_size_t truelen;
  195135. png_byte buf[6];
  195136. png_debug(1, "in png_handle_bKGD\n");
  195137. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195138. png_error(png_ptr, "Missing IHDR before bKGD");
  195139. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195140. {
  195141. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195142. png_crc_finish(png_ptr, length);
  195143. return;
  195144. }
  195145. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195146. !(png_ptr->mode & PNG_HAVE_PLTE))
  195147. {
  195148. png_warning(png_ptr, "Missing PLTE before bKGD");
  195149. png_crc_finish(png_ptr, length);
  195150. return;
  195151. }
  195152. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195153. {
  195154. png_warning(png_ptr, "Duplicate bKGD chunk");
  195155. png_crc_finish(png_ptr, length);
  195156. return;
  195157. }
  195158. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195159. truelen = 1;
  195160. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195161. truelen = 6;
  195162. else
  195163. truelen = 2;
  195164. if (length != truelen)
  195165. {
  195166. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195167. png_crc_finish(png_ptr, length);
  195168. return;
  195169. }
  195170. png_crc_read(png_ptr, buf, truelen);
  195171. if (png_crc_finish(png_ptr, 0))
  195172. return;
  195173. /* We convert the index value into RGB components so that we can allow
  195174. * arbitrary RGB values for background when we have transparency, and
  195175. * so it is easy to determine the RGB values of the background color
  195176. * from the info_ptr struct. */
  195177. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195178. {
  195179. png_ptr->background.index = buf[0];
  195180. if(info_ptr->num_palette)
  195181. {
  195182. if(buf[0] > info_ptr->num_palette)
  195183. {
  195184. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195185. return;
  195186. }
  195187. png_ptr->background.red =
  195188. (png_uint_16)png_ptr->palette[buf[0]].red;
  195189. png_ptr->background.green =
  195190. (png_uint_16)png_ptr->palette[buf[0]].green;
  195191. png_ptr->background.blue =
  195192. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195193. }
  195194. }
  195195. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195196. {
  195197. png_ptr->background.red =
  195198. png_ptr->background.green =
  195199. png_ptr->background.blue =
  195200. png_ptr->background.gray = png_get_uint_16(buf);
  195201. }
  195202. else
  195203. {
  195204. png_ptr->background.red = png_get_uint_16(buf);
  195205. png_ptr->background.green = png_get_uint_16(buf + 2);
  195206. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195207. }
  195208. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195209. }
  195210. #endif
  195211. #if defined(PNG_READ_hIST_SUPPORTED)
  195212. void /* PRIVATE */
  195213. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195214. {
  195215. unsigned int num, i;
  195216. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195217. png_debug(1, "in png_handle_hIST\n");
  195218. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195219. png_error(png_ptr, "Missing IHDR before hIST");
  195220. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195221. {
  195222. png_warning(png_ptr, "Invalid hIST after IDAT");
  195223. png_crc_finish(png_ptr, length);
  195224. return;
  195225. }
  195226. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195227. {
  195228. png_warning(png_ptr, "Missing PLTE before hIST");
  195229. png_crc_finish(png_ptr, length);
  195230. return;
  195231. }
  195232. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195233. {
  195234. png_warning(png_ptr, "Duplicate hIST chunk");
  195235. png_crc_finish(png_ptr, length);
  195236. return;
  195237. }
  195238. num = length / 2 ;
  195239. if (num != (unsigned int) png_ptr->num_palette || num >
  195240. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195241. {
  195242. png_warning(png_ptr, "Incorrect hIST chunk length");
  195243. png_crc_finish(png_ptr, length);
  195244. return;
  195245. }
  195246. for (i = 0; i < num; i++)
  195247. {
  195248. png_byte buf[2];
  195249. png_crc_read(png_ptr, buf, 2);
  195250. readbuf[i] = png_get_uint_16(buf);
  195251. }
  195252. if (png_crc_finish(png_ptr, 0))
  195253. return;
  195254. png_set_hIST(png_ptr, info_ptr, readbuf);
  195255. }
  195256. #endif
  195257. #if defined(PNG_READ_pHYs_SUPPORTED)
  195258. void /* PRIVATE */
  195259. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195260. {
  195261. png_byte buf[9];
  195262. png_uint_32 res_x, res_y;
  195263. int unit_type;
  195264. png_debug(1, "in png_handle_pHYs\n");
  195265. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195266. png_error(png_ptr, "Missing IHDR before pHYs");
  195267. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195268. {
  195269. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195270. png_crc_finish(png_ptr, length);
  195271. return;
  195272. }
  195273. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195274. {
  195275. png_warning(png_ptr, "Duplicate pHYs chunk");
  195276. png_crc_finish(png_ptr, length);
  195277. return;
  195278. }
  195279. if (length != 9)
  195280. {
  195281. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195282. png_crc_finish(png_ptr, length);
  195283. return;
  195284. }
  195285. png_crc_read(png_ptr, buf, 9);
  195286. if (png_crc_finish(png_ptr, 0))
  195287. return;
  195288. res_x = png_get_uint_32(buf);
  195289. res_y = png_get_uint_32(buf + 4);
  195290. unit_type = buf[8];
  195291. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195292. }
  195293. #endif
  195294. #if defined(PNG_READ_oFFs_SUPPORTED)
  195295. void /* PRIVATE */
  195296. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195297. {
  195298. png_byte buf[9];
  195299. png_int_32 offset_x, offset_y;
  195300. int unit_type;
  195301. png_debug(1, "in png_handle_oFFs\n");
  195302. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195303. png_error(png_ptr, "Missing IHDR before oFFs");
  195304. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195305. {
  195306. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195307. png_crc_finish(png_ptr, length);
  195308. return;
  195309. }
  195310. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195311. {
  195312. png_warning(png_ptr, "Duplicate oFFs chunk");
  195313. png_crc_finish(png_ptr, length);
  195314. return;
  195315. }
  195316. if (length != 9)
  195317. {
  195318. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195319. png_crc_finish(png_ptr, length);
  195320. return;
  195321. }
  195322. png_crc_read(png_ptr, buf, 9);
  195323. if (png_crc_finish(png_ptr, 0))
  195324. return;
  195325. offset_x = png_get_int_32(buf);
  195326. offset_y = png_get_int_32(buf + 4);
  195327. unit_type = buf[8];
  195328. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195329. }
  195330. #endif
  195331. #if defined(PNG_READ_pCAL_SUPPORTED)
  195332. /* read the pCAL chunk (described in the PNG Extensions document) */
  195333. void /* PRIVATE */
  195334. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195335. {
  195336. png_charp purpose;
  195337. png_int_32 X0, X1;
  195338. png_byte type, nparams;
  195339. png_charp buf, units, endptr;
  195340. png_charpp params;
  195341. png_size_t slength;
  195342. int i;
  195343. png_debug(1, "in png_handle_pCAL\n");
  195344. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195345. png_error(png_ptr, "Missing IHDR before pCAL");
  195346. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195347. {
  195348. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195349. png_crc_finish(png_ptr, length);
  195350. return;
  195351. }
  195352. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195353. {
  195354. png_warning(png_ptr, "Duplicate pCAL chunk");
  195355. png_crc_finish(png_ptr, length);
  195356. return;
  195357. }
  195358. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195359. length + 1);
  195360. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195361. if (purpose == NULL)
  195362. {
  195363. png_warning(png_ptr, "No memory for pCAL purpose.");
  195364. return;
  195365. }
  195366. slength = (png_size_t)length;
  195367. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195368. if (png_crc_finish(png_ptr, 0))
  195369. {
  195370. png_free(png_ptr, purpose);
  195371. return;
  195372. }
  195373. purpose[slength] = 0x00; /* null terminate the last string */
  195374. png_debug(3, "Finding end of pCAL purpose string\n");
  195375. for (buf = purpose; *buf; buf++)
  195376. /* empty loop */ ;
  195377. endptr = purpose + slength;
  195378. /* We need to have at least 12 bytes after the purpose string
  195379. in order to get the parameter information. */
  195380. if (endptr <= buf + 12)
  195381. {
  195382. png_warning(png_ptr, "Invalid pCAL data");
  195383. png_free(png_ptr, purpose);
  195384. return;
  195385. }
  195386. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195387. X0 = png_get_int_32((png_bytep)buf+1);
  195388. X1 = png_get_int_32((png_bytep)buf+5);
  195389. type = buf[9];
  195390. nparams = buf[10];
  195391. units = buf + 11;
  195392. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195393. /* Check that we have the right number of parameters for known
  195394. equation types. */
  195395. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195396. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195397. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195398. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195399. {
  195400. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195401. png_free(png_ptr, purpose);
  195402. return;
  195403. }
  195404. else if (type >= PNG_EQUATION_LAST)
  195405. {
  195406. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195407. }
  195408. for (buf = units; *buf; buf++)
  195409. /* Empty loop to move past the units string. */ ;
  195410. png_debug(3, "Allocating pCAL parameters array\n");
  195411. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195412. *png_sizeof(png_charp))) ;
  195413. if (params == NULL)
  195414. {
  195415. png_free(png_ptr, purpose);
  195416. png_warning(png_ptr, "No memory for pCAL params.");
  195417. return;
  195418. }
  195419. /* Get pointers to the start of each parameter string. */
  195420. for (i = 0; i < (int)nparams; i++)
  195421. {
  195422. buf++; /* Skip the null string terminator from previous parameter. */
  195423. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195424. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195425. /* Empty loop to move past each parameter string */ ;
  195426. /* Make sure we haven't run out of data yet */
  195427. if (buf > endptr)
  195428. {
  195429. png_warning(png_ptr, "Invalid pCAL data");
  195430. png_free(png_ptr, purpose);
  195431. png_free(png_ptr, params);
  195432. return;
  195433. }
  195434. }
  195435. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195436. units, params);
  195437. png_free(png_ptr, purpose);
  195438. png_free(png_ptr, params);
  195439. }
  195440. #endif
  195441. #if defined(PNG_READ_sCAL_SUPPORTED)
  195442. /* read the sCAL chunk */
  195443. void /* PRIVATE */
  195444. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195445. {
  195446. png_charp buffer, ep;
  195447. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195448. double width, height;
  195449. png_charp vp;
  195450. #else
  195451. #ifdef PNG_FIXED_POINT_SUPPORTED
  195452. png_charp swidth, sheight;
  195453. #endif
  195454. #endif
  195455. png_size_t slength;
  195456. png_debug(1, "in png_handle_sCAL\n");
  195457. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195458. png_error(png_ptr, "Missing IHDR before sCAL");
  195459. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195460. {
  195461. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195462. png_crc_finish(png_ptr, length);
  195463. return;
  195464. }
  195465. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195466. {
  195467. png_warning(png_ptr, "Duplicate sCAL chunk");
  195468. png_crc_finish(png_ptr, length);
  195469. return;
  195470. }
  195471. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195472. length + 1);
  195473. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195474. if (buffer == NULL)
  195475. {
  195476. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195477. return;
  195478. }
  195479. slength = (png_size_t)length;
  195480. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195481. if (png_crc_finish(png_ptr, 0))
  195482. {
  195483. png_free(png_ptr, buffer);
  195484. return;
  195485. }
  195486. buffer[slength] = 0x00; /* null terminate the last string */
  195487. ep = buffer + 1; /* skip unit byte */
  195488. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195489. width = png_strtod(png_ptr, ep, &vp);
  195490. if (*vp)
  195491. {
  195492. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195493. return;
  195494. }
  195495. #else
  195496. #ifdef PNG_FIXED_POINT_SUPPORTED
  195497. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195498. if (swidth == NULL)
  195499. {
  195500. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195501. return;
  195502. }
  195503. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195504. #endif
  195505. #endif
  195506. for (ep = buffer; *ep; ep++)
  195507. /* empty loop */ ;
  195508. ep++;
  195509. if (buffer + slength < ep)
  195510. {
  195511. png_warning(png_ptr, "Truncated sCAL chunk");
  195512. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195513. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195514. png_free(png_ptr, swidth);
  195515. #endif
  195516. png_free(png_ptr, buffer);
  195517. return;
  195518. }
  195519. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195520. height = png_strtod(png_ptr, ep, &vp);
  195521. if (*vp)
  195522. {
  195523. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195524. return;
  195525. }
  195526. #else
  195527. #ifdef PNG_FIXED_POINT_SUPPORTED
  195528. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195529. if (swidth == NULL)
  195530. {
  195531. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195532. return;
  195533. }
  195534. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195535. #endif
  195536. #endif
  195537. if (buffer + slength < ep
  195538. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195539. || width <= 0. || height <= 0.
  195540. #endif
  195541. )
  195542. {
  195543. png_warning(png_ptr, "Invalid sCAL data");
  195544. png_free(png_ptr, buffer);
  195545. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195546. png_free(png_ptr, swidth);
  195547. png_free(png_ptr, sheight);
  195548. #endif
  195549. return;
  195550. }
  195551. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195552. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195553. #else
  195554. #ifdef PNG_FIXED_POINT_SUPPORTED
  195555. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195556. #endif
  195557. #endif
  195558. png_free(png_ptr, buffer);
  195559. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195560. png_free(png_ptr, swidth);
  195561. png_free(png_ptr, sheight);
  195562. #endif
  195563. }
  195564. #endif
  195565. #if defined(PNG_READ_tIME_SUPPORTED)
  195566. void /* PRIVATE */
  195567. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195568. {
  195569. png_byte buf[7];
  195570. png_time mod_time;
  195571. png_debug(1, "in png_handle_tIME\n");
  195572. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195573. png_error(png_ptr, "Out of place tIME chunk");
  195574. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195575. {
  195576. png_warning(png_ptr, "Duplicate tIME chunk");
  195577. png_crc_finish(png_ptr, length);
  195578. return;
  195579. }
  195580. if (png_ptr->mode & PNG_HAVE_IDAT)
  195581. png_ptr->mode |= PNG_AFTER_IDAT;
  195582. if (length != 7)
  195583. {
  195584. png_warning(png_ptr, "Incorrect tIME chunk length");
  195585. png_crc_finish(png_ptr, length);
  195586. return;
  195587. }
  195588. png_crc_read(png_ptr, buf, 7);
  195589. if (png_crc_finish(png_ptr, 0))
  195590. return;
  195591. mod_time.second = buf[6];
  195592. mod_time.minute = buf[5];
  195593. mod_time.hour = buf[4];
  195594. mod_time.day = buf[3];
  195595. mod_time.month = buf[2];
  195596. mod_time.year = png_get_uint_16(buf);
  195597. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195598. }
  195599. #endif
  195600. #if defined(PNG_READ_tEXt_SUPPORTED)
  195601. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195602. void /* PRIVATE */
  195603. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195604. {
  195605. png_textp text_ptr;
  195606. png_charp key;
  195607. png_charp text;
  195608. png_uint_32 skip = 0;
  195609. png_size_t slength;
  195610. int ret;
  195611. png_debug(1, "in png_handle_tEXt\n");
  195612. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195613. png_error(png_ptr, "Missing IHDR before tEXt");
  195614. if (png_ptr->mode & PNG_HAVE_IDAT)
  195615. png_ptr->mode |= PNG_AFTER_IDAT;
  195616. #ifdef PNG_MAX_MALLOC_64K
  195617. if (length > (png_uint_32)65535L)
  195618. {
  195619. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195620. skip = length - (png_uint_32)65535L;
  195621. length = (png_uint_32)65535L;
  195622. }
  195623. #endif
  195624. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195625. if (key == NULL)
  195626. {
  195627. png_warning(png_ptr, "No memory to process text chunk.");
  195628. return;
  195629. }
  195630. slength = (png_size_t)length;
  195631. png_crc_read(png_ptr, (png_bytep)key, slength);
  195632. if (png_crc_finish(png_ptr, skip))
  195633. {
  195634. png_free(png_ptr, key);
  195635. return;
  195636. }
  195637. key[slength] = 0x00;
  195638. for (text = key; *text; text++)
  195639. /* empty loop to find end of key */ ;
  195640. if (text != key + slength)
  195641. text++;
  195642. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195643. (png_uint_32)png_sizeof(png_text));
  195644. if (text_ptr == NULL)
  195645. {
  195646. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195647. png_free(png_ptr, key);
  195648. return;
  195649. }
  195650. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195651. text_ptr->key = key;
  195652. #ifdef PNG_iTXt_SUPPORTED
  195653. text_ptr->lang = NULL;
  195654. text_ptr->lang_key = NULL;
  195655. text_ptr->itxt_length = 0;
  195656. #endif
  195657. text_ptr->text = text;
  195658. text_ptr->text_length = png_strlen(text);
  195659. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195660. png_free(png_ptr, key);
  195661. png_free(png_ptr, text_ptr);
  195662. if (ret)
  195663. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195664. }
  195665. #endif
  195666. #if defined(PNG_READ_zTXt_SUPPORTED)
  195667. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195668. void /* PRIVATE */
  195669. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195670. {
  195671. png_textp text_ptr;
  195672. png_charp chunkdata;
  195673. png_charp text;
  195674. int comp_type;
  195675. int ret;
  195676. png_size_t slength, prefix_len, data_len;
  195677. png_debug(1, "in png_handle_zTXt\n");
  195678. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195679. png_error(png_ptr, "Missing IHDR before zTXt");
  195680. if (png_ptr->mode & PNG_HAVE_IDAT)
  195681. png_ptr->mode |= PNG_AFTER_IDAT;
  195682. #ifdef PNG_MAX_MALLOC_64K
  195683. /* We will no doubt have problems with chunks even half this size, but
  195684. there is no hard and fast rule to tell us where to stop. */
  195685. if (length > (png_uint_32)65535L)
  195686. {
  195687. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195688. png_crc_finish(png_ptr, length);
  195689. return;
  195690. }
  195691. #endif
  195692. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195693. if (chunkdata == NULL)
  195694. {
  195695. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195696. return;
  195697. }
  195698. slength = (png_size_t)length;
  195699. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195700. if (png_crc_finish(png_ptr, 0))
  195701. {
  195702. png_free(png_ptr, chunkdata);
  195703. return;
  195704. }
  195705. chunkdata[slength] = 0x00;
  195706. for (text = chunkdata; *text; text++)
  195707. /* empty loop */ ;
  195708. /* zTXt must have some text after the chunkdataword */
  195709. if (text >= chunkdata + slength - 2)
  195710. {
  195711. png_warning(png_ptr, "Truncated zTXt chunk");
  195712. png_free(png_ptr, chunkdata);
  195713. return;
  195714. }
  195715. else
  195716. {
  195717. comp_type = *(++text);
  195718. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195719. {
  195720. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195721. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195722. }
  195723. text++; /* skip the compression_method byte */
  195724. }
  195725. prefix_len = text - chunkdata;
  195726. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195727. (png_size_t)length, prefix_len, &data_len);
  195728. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195729. (png_uint_32)png_sizeof(png_text));
  195730. if (text_ptr == NULL)
  195731. {
  195732. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195733. png_free(png_ptr, chunkdata);
  195734. return;
  195735. }
  195736. text_ptr->compression = comp_type;
  195737. text_ptr->key = chunkdata;
  195738. #ifdef PNG_iTXt_SUPPORTED
  195739. text_ptr->lang = NULL;
  195740. text_ptr->lang_key = NULL;
  195741. text_ptr->itxt_length = 0;
  195742. #endif
  195743. text_ptr->text = chunkdata + prefix_len;
  195744. text_ptr->text_length = data_len;
  195745. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195746. png_free(png_ptr, text_ptr);
  195747. png_free(png_ptr, chunkdata);
  195748. if (ret)
  195749. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195750. }
  195751. #endif
  195752. #if defined(PNG_READ_iTXt_SUPPORTED)
  195753. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195754. void /* PRIVATE */
  195755. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195756. {
  195757. png_textp text_ptr;
  195758. png_charp chunkdata;
  195759. png_charp key, lang, text, lang_key;
  195760. int comp_flag;
  195761. int comp_type = 0;
  195762. int ret;
  195763. png_size_t slength, prefix_len, data_len;
  195764. png_debug(1, "in png_handle_iTXt\n");
  195765. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195766. png_error(png_ptr, "Missing IHDR before iTXt");
  195767. if (png_ptr->mode & PNG_HAVE_IDAT)
  195768. png_ptr->mode |= PNG_AFTER_IDAT;
  195769. #ifdef PNG_MAX_MALLOC_64K
  195770. /* We will no doubt have problems with chunks even half this size, but
  195771. there is no hard and fast rule to tell us where to stop. */
  195772. if (length > (png_uint_32)65535L)
  195773. {
  195774. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195775. png_crc_finish(png_ptr, length);
  195776. return;
  195777. }
  195778. #endif
  195779. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195780. if (chunkdata == NULL)
  195781. {
  195782. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195783. return;
  195784. }
  195785. slength = (png_size_t)length;
  195786. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195787. if (png_crc_finish(png_ptr, 0))
  195788. {
  195789. png_free(png_ptr, chunkdata);
  195790. return;
  195791. }
  195792. chunkdata[slength] = 0x00;
  195793. for (lang = chunkdata; *lang; lang++)
  195794. /* empty loop */ ;
  195795. lang++; /* skip NUL separator */
  195796. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195797. translated keyword (possibly empty), and possibly some text after the
  195798. keyword */
  195799. if (lang >= chunkdata + slength - 3)
  195800. {
  195801. png_warning(png_ptr, "Truncated iTXt chunk");
  195802. png_free(png_ptr, chunkdata);
  195803. return;
  195804. }
  195805. else
  195806. {
  195807. comp_flag = *lang++;
  195808. comp_type = *lang++;
  195809. }
  195810. for (lang_key = lang; *lang_key; lang_key++)
  195811. /* empty loop */ ;
  195812. lang_key++; /* skip NUL separator */
  195813. if (lang_key >= chunkdata + slength)
  195814. {
  195815. png_warning(png_ptr, "Truncated iTXt chunk");
  195816. png_free(png_ptr, chunkdata);
  195817. return;
  195818. }
  195819. for (text = lang_key; *text; text++)
  195820. /* empty loop */ ;
  195821. text++; /* skip NUL separator */
  195822. if (text >= chunkdata + slength)
  195823. {
  195824. png_warning(png_ptr, "Malformed iTXt chunk");
  195825. png_free(png_ptr, chunkdata);
  195826. return;
  195827. }
  195828. prefix_len = text - chunkdata;
  195829. key=chunkdata;
  195830. if (comp_flag)
  195831. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195832. (size_t)length, prefix_len, &data_len);
  195833. else
  195834. data_len=png_strlen(chunkdata + prefix_len);
  195835. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195836. (png_uint_32)png_sizeof(png_text));
  195837. if (text_ptr == NULL)
  195838. {
  195839. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195840. png_free(png_ptr, chunkdata);
  195841. return;
  195842. }
  195843. text_ptr->compression = (int)comp_flag + 1;
  195844. text_ptr->lang_key = chunkdata+(lang_key-key);
  195845. text_ptr->lang = chunkdata+(lang-key);
  195846. text_ptr->itxt_length = data_len;
  195847. text_ptr->text_length = 0;
  195848. text_ptr->key = chunkdata;
  195849. text_ptr->text = chunkdata + prefix_len;
  195850. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195851. png_free(png_ptr, text_ptr);
  195852. png_free(png_ptr, chunkdata);
  195853. if (ret)
  195854. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195855. }
  195856. #endif
  195857. /* This function is called when we haven't found a handler for a
  195858. chunk. If there isn't a problem with the chunk itself (ie bad
  195859. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195860. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195861. case it will be saved away to be written out later. */
  195862. void /* PRIVATE */
  195863. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195864. {
  195865. png_uint_32 skip = 0;
  195866. png_debug(1, "in png_handle_unknown\n");
  195867. if (png_ptr->mode & PNG_HAVE_IDAT)
  195868. {
  195869. #ifdef PNG_USE_LOCAL_ARRAYS
  195870. PNG_CONST PNG_IDAT;
  195871. #endif
  195872. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195873. png_ptr->mode |= PNG_AFTER_IDAT;
  195874. }
  195875. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195876. if (!(png_ptr->chunk_name[0] & 0x20))
  195877. {
  195878. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195879. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195880. PNG_HANDLE_CHUNK_ALWAYS
  195881. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195882. && png_ptr->read_user_chunk_fn == NULL
  195883. #endif
  195884. )
  195885. #endif
  195886. png_chunk_error(png_ptr, "unknown critical chunk");
  195887. }
  195888. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195889. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195890. (png_ptr->read_user_chunk_fn != NULL))
  195891. {
  195892. #ifdef PNG_MAX_MALLOC_64K
  195893. if (length > (png_uint_32)65535L)
  195894. {
  195895. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195896. skip = length - (png_uint_32)65535L;
  195897. length = (png_uint_32)65535L;
  195898. }
  195899. #endif
  195900. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195901. (png_charp)png_ptr->chunk_name, 5);
  195902. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195903. png_ptr->unknown_chunk.size = (png_size_t)length;
  195904. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195905. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195906. if(png_ptr->read_user_chunk_fn != NULL)
  195907. {
  195908. /* callback to user unknown chunk handler */
  195909. int ret;
  195910. ret = (*(png_ptr->read_user_chunk_fn))
  195911. (png_ptr, &png_ptr->unknown_chunk);
  195912. if (ret < 0)
  195913. png_chunk_error(png_ptr, "error in user chunk");
  195914. if (ret == 0)
  195915. {
  195916. if (!(png_ptr->chunk_name[0] & 0x20))
  195917. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195918. PNG_HANDLE_CHUNK_ALWAYS)
  195919. png_chunk_error(png_ptr, "unknown critical chunk");
  195920. png_set_unknown_chunks(png_ptr, info_ptr,
  195921. &png_ptr->unknown_chunk, 1);
  195922. }
  195923. }
  195924. #else
  195925. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195926. #endif
  195927. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195928. png_ptr->unknown_chunk.data = NULL;
  195929. }
  195930. else
  195931. #endif
  195932. skip = length;
  195933. png_crc_finish(png_ptr, skip);
  195934. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195935. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195936. #endif
  195937. }
  195938. /* This function is called to verify that a chunk name is valid.
  195939. This function can't have the "critical chunk check" incorporated
  195940. into it, since in the future we will need to be able to call user
  195941. functions to handle unknown critical chunks after we check that
  195942. the chunk name itself is valid. */
  195943. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195944. void /* PRIVATE */
  195945. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195946. {
  195947. png_debug(1, "in png_check_chunk_name\n");
  195948. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195949. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195950. {
  195951. png_chunk_error(png_ptr, "invalid chunk type");
  195952. }
  195953. }
  195954. /* Combines the row recently read in with the existing pixels in the
  195955. row. This routine takes care of alpha and transparency if requested.
  195956. This routine also handles the two methods of progressive display
  195957. of interlaced images, depending on the mask value.
  195958. The mask value describes which pixels are to be combined with
  195959. the row. The pattern always repeats every 8 pixels, so just 8
  195960. bits are needed. A one indicates the pixel is to be combined,
  195961. a zero indicates the pixel is to be skipped. This is in addition
  195962. to any alpha or transparency value associated with the pixel. If
  195963. you want all pixels to be combined, pass 0xff (255) in mask. */
  195964. void /* PRIVATE */
  195965. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195966. {
  195967. png_debug(1,"in png_combine_row\n");
  195968. if (mask == 0xff)
  195969. {
  195970. png_memcpy(row, png_ptr->row_buf + 1,
  195971. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195972. }
  195973. else
  195974. {
  195975. switch (png_ptr->row_info.pixel_depth)
  195976. {
  195977. case 1:
  195978. {
  195979. png_bytep sp = png_ptr->row_buf + 1;
  195980. png_bytep dp = row;
  195981. int s_inc, s_start, s_end;
  195982. int m = 0x80;
  195983. int shift;
  195984. png_uint_32 i;
  195985. png_uint_32 row_width = png_ptr->width;
  195986. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195987. if (png_ptr->transformations & PNG_PACKSWAP)
  195988. {
  195989. s_start = 0;
  195990. s_end = 7;
  195991. s_inc = 1;
  195992. }
  195993. else
  195994. #endif
  195995. {
  195996. s_start = 7;
  195997. s_end = 0;
  195998. s_inc = -1;
  195999. }
  196000. shift = s_start;
  196001. for (i = 0; i < row_width; i++)
  196002. {
  196003. if (m & mask)
  196004. {
  196005. int value;
  196006. value = (*sp >> shift) & 0x01;
  196007. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196008. *dp |= (png_byte)(value << shift);
  196009. }
  196010. if (shift == s_end)
  196011. {
  196012. shift = s_start;
  196013. sp++;
  196014. dp++;
  196015. }
  196016. else
  196017. shift += s_inc;
  196018. if (m == 1)
  196019. m = 0x80;
  196020. else
  196021. m >>= 1;
  196022. }
  196023. break;
  196024. }
  196025. case 2:
  196026. {
  196027. png_bytep sp = png_ptr->row_buf + 1;
  196028. png_bytep dp = row;
  196029. int s_start, s_end, s_inc;
  196030. int m = 0x80;
  196031. int shift;
  196032. png_uint_32 i;
  196033. png_uint_32 row_width = png_ptr->width;
  196034. int value;
  196035. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196036. if (png_ptr->transformations & PNG_PACKSWAP)
  196037. {
  196038. s_start = 0;
  196039. s_end = 6;
  196040. s_inc = 2;
  196041. }
  196042. else
  196043. #endif
  196044. {
  196045. s_start = 6;
  196046. s_end = 0;
  196047. s_inc = -2;
  196048. }
  196049. shift = s_start;
  196050. for (i = 0; i < row_width; i++)
  196051. {
  196052. if (m & mask)
  196053. {
  196054. value = (*sp >> shift) & 0x03;
  196055. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196056. *dp |= (png_byte)(value << shift);
  196057. }
  196058. if (shift == s_end)
  196059. {
  196060. shift = s_start;
  196061. sp++;
  196062. dp++;
  196063. }
  196064. else
  196065. shift += s_inc;
  196066. if (m == 1)
  196067. m = 0x80;
  196068. else
  196069. m >>= 1;
  196070. }
  196071. break;
  196072. }
  196073. case 4:
  196074. {
  196075. png_bytep sp = png_ptr->row_buf + 1;
  196076. png_bytep dp = row;
  196077. int s_start, s_end, s_inc;
  196078. int m = 0x80;
  196079. int shift;
  196080. png_uint_32 i;
  196081. png_uint_32 row_width = png_ptr->width;
  196082. int value;
  196083. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196084. if (png_ptr->transformations & PNG_PACKSWAP)
  196085. {
  196086. s_start = 0;
  196087. s_end = 4;
  196088. s_inc = 4;
  196089. }
  196090. else
  196091. #endif
  196092. {
  196093. s_start = 4;
  196094. s_end = 0;
  196095. s_inc = -4;
  196096. }
  196097. shift = s_start;
  196098. for (i = 0; i < row_width; i++)
  196099. {
  196100. if (m & mask)
  196101. {
  196102. value = (*sp >> shift) & 0xf;
  196103. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196104. *dp |= (png_byte)(value << shift);
  196105. }
  196106. if (shift == s_end)
  196107. {
  196108. shift = s_start;
  196109. sp++;
  196110. dp++;
  196111. }
  196112. else
  196113. shift += s_inc;
  196114. if (m == 1)
  196115. m = 0x80;
  196116. else
  196117. m >>= 1;
  196118. }
  196119. break;
  196120. }
  196121. default:
  196122. {
  196123. png_bytep sp = png_ptr->row_buf + 1;
  196124. png_bytep dp = row;
  196125. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196126. png_uint_32 i;
  196127. png_uint_32 row_width = png_ptr->width;
  196128. png_byte m = 0x80;
  196129. for (i = 0; i < row_width; i++)
  196130. {
  196131. if (m & mask)
  196132. {
  196133. png_memcpy(dp, sp, pixel_bytes);
  196134. }
  196135. sp += pixel_bytes;
  196136. dp += pixel_bytes;
  196137. if (m == 1)
  196138. m = 0x80;
  196139. else
  196140. m >>= 1;
  196141. }
  196142. break;
  196143. }
  196144. }
  196145. }
  196146. }
  196147. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196148. /* OLD pre-1.0.9 interface:
  196149. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196150. png_uint_32 transformations)
  196151. */
  196152. void /* PRIVATE */
  196153. png_do_read_interlace(png_structp png_ptr)
  196154. {
  196155. png_row_infop row_info = &(png_ptr->row_info);
  196156. png_bytep row = png_ptr->row_buf + 1;
  196157. int pass = png_ptr->pass;
  196158. png_uint_32 transformations = png_ptr->transformations;
  196159. #ifdef PNG_USE_LOCAL_ARRAYS
  196160. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196161. /* offset to next interlace block */
  196162. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196163. #endif
  196164. png_debug(1,"in png_do_read_interlace\n");
  196165. if (row != NULL && row_info != NULL)
  196166. {
  196167. png_uint_32 final_width;
  196168. final_width = row_info->width * png_pass_inc[pass];
  196169. switch (row_info->pixel_depth)
  196170. {
  196171. case 1:
  196172. {
  196173. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196174. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196175. int sshift, dshift;
  196176. int s_start, s_end, s_inc;
  196177. int jstop = png_pass_inc[pass];
  196178. png_byte v;
  196179. png_uint_32 i;
  196180. int j;
  196181. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196182. if (transformations & PNG_PACKSWAP)
  196183. {
  196184. sshift = (int)((row_info->width + 7) & 0x07);
  196185. dshift = (int)((final_width + 7) & 0x07);
  196186. s_start = 7;
  196187. s_end = 0;
  196188. s_inc = -1;
  196189. }
  196190. else
  196191. #endif
  196192. {
  196193. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196194. dshift = 7 - (int)((final_width + 7) & 0x07);
  196195. s_start = 0;
  196196. s_end = 7;
  196197. s_inc = 1;
  196198. }
  196199. for (i = 0; i < row_info->width; i++)
  196200. {
  196201. v = (png_byte)((*sp >> sshift) & 0x01);
  196202. for (j = 0; j < jstop; j++)
  196203. {
  196204. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196205. *dp |= (png_byte)(v << dshift);
  196206. if (dshift == s_end)
  196207. {
  196208. dshift = s_start;
  196209. dp--;
  196210. }
  196211. else
  196212. dshift += s_inc;
  196213. }
  196214. if (sshift == s_end)
  196215. {
  196216. sshift = s_start;
  196217. sp--;
  196218. }
  196219. else
  196220. sshift += s_inc;
  196221. }
  196222. break;
  196223. }
  196224. case 2:
  196225. {
  196226. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196227. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196228. int sshift, dshift;
  196229. int s_start, s_end, s_inc;
  196230. int jstop = png_pass_inc[pass];
  196231. png_uint_32 i;
  196232. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196233. if (transformations & PNG_PACKSWAP)
  196234. {
  196235. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196236. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196237. s_start = 6;
  196238. s_end = 0;
  196239. s_inc = -2;
  196240. }
  196241. else
  196242. #endif
  196243. {
  196244. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196245. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196246. s_start = 0;
  196247. s_end = 6;
  196248. s_inc = 2;
  196249. }
  196250. for (i = 0; i < row_info->width; i++)
  196251. {
  196252. png_byte v;
  196253. int j;
  196254. v = (png_byte)((*sp >> sshift) & 0x03);
  196255. for (j = 0; j < jstop; j++)
  196256. {
  196257. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196258. *dp |= (png_byte)(v << dshift);
  196259. if (dshift == s_end)
  196260. {
  196261. dshift = s_start;
  196262. dp--;
  196263. }
  196264. else
  196265. dshift += s_inc;
  196266. }
  196267. if (sshift == s_end)
  196268. {
  196269. sshift = s_start;
  196270. sp--;
  196271. }
  196272. else
  196273. sshift += s_inc;
  196274. }
  196275. break;
  196276. }
  196277. case 4:
  196278. {
  196279. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196280. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196281. int sshift, dshift;
  196282. int s_start, s_end, s_inc;
  196283. png_uint_32 i;
  196284. int jstop = png_pass_inc[pass];
  196285. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196286. if (transformations & PNG_PACKSWAP)
  196287. {
  196288. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196289. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196290. s_start = 4;
  196291. s_end = 0;
  196292. s_inc = -4;
  196293. }
  196294. else
  196295. #endif
  196296. {
  196297. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196298. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196299. s_start = 0;
  196300. s_end = 4;
  196301. s_inc = 4;
  196302. }
  196303. for (i = 0; i < row_info->width; i++)
  196304. {
  196305. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196306. int j;
  196307. for (j = 0; j < jstop; j++)
  196308. {
  196309. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196310. *dp |= (png_byte)(v << dshift);
  196311. if (dshift == s_end)
  196312. {
  196313. dshift = s_start;
  196314. dp--;
  196315. }
  196316. else
  196317. dshift += s_inc;
  196318. }
  196319. if (sshift == s_end)
  196320. {
  196321. sshift = s_start;
  196322. sp--;
  196323. }
  196324. else
  196325. sshift += s_inc;
  196326. }
  196327. break;
  196328. }
  196329. default:
  196330. {
  196331. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196332. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196333. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196334. int jstop = png_pass_inc[pass];
  196335. png_uint_32 i;
  196336. for (i = 0; i < row_info->width; i++)
  196337. {
  196338. png_byte v[8];
  196339. int j;
  196340. png_memcpy(v, sp, pixel_bytes);
  196341. for (j = 0; j < jstop; j++)
  196342. {
  196343. png_memcpy(dp, v, pixel_bytes);
  196344. dp -= pixel_bytes;
  196345. }
  196346. sp -= pixel_bytes;
  196347. }
  196348. break;
  196349. }
  196350. }
  196351. row_info->width = final_width;
  196352. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196353. }
  196354. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196355. transformations = transformations; /* silence compiler warning */
  196356. #endif
  196357. }
  196358. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196359. void /* PRIVATE */
  196360. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196361. png_bytep prev_row, int filter)
  196362. {
  196363. png_debug(1, "in png_read_filter_row\n");
  196364. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196365. switch (filter)
  196366. {
  196367. case PNG_FILTER_VALUE_NONE:
  196368. break;
  196369. case PNG_FILTER_VALUE_SUB:
  196370. {
  196371. png_uint_32 i;
  196372. png_uint_32 istop = row_info->rowbytes;
  196373. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196374. png_bytep rp = row + bpp;
  196375. png_bytep lp = row;
  196376. for (i = bpp; i < istop; i++)
  196377. {
  196378. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196379. rp++;
  196380. }
  196381. break;
  196382. }
  196383. case PNG_FILTER_VALUE_UP:
  196384. {
  196385. png_uint_32 i;
  196386. png_uint_32 istop = row_info->rowbytes;
  196387. png_bytep rp = row;
  196388. png_bytep pp = prev_row;
  196389. for (i = 0; i < istop; i++)
  196390. {
  196391. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196392. rp++;
  196393. }
  196394. break;
  196395. }
  196396. case PNG_FILTER_VALUE_AVG:
  196397. {
  196398. png_uint_32 i;
  196399. png_bytep rp = row;
  196400. png_bytep pp = prev_row;
  196401. png_bytep lp = row;
  196402. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196403. png_uint_32 istop = row_info->rowbytes - bpp;
  196404. for (i = 0; i < bpp; i++)
  196405. {
  196406. *rp = (png_byte)(((int)(*rp) +
  196407. ((int)(*pp++) / 2 )) & 0xff);
  196408. rp++;
  196409. }
  196410. for (i = 0; i < istop; i++)
  196411. {
  196412. *rp = (png_byte)(((int)(*rp) +
  196413. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196414. rp++;
  196415. }
  196416. break;
  196417. }
  196418. case PNG_FILTER_VALUE_PAETH:
  196419. {
  196420. png_uint_32 i;
  196421. png_bytep rp = row;
  196422. png_bytep pp = prev_row;
  196423. png_bytep lp = row;
  196424. png_bytep cp = prev_row;
  196425. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196426. png_uint_32 istop=row_info->rowbytes - bpp;
  196427. for (i = 0; i < bpp; i++)
  196428. {
  196429. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196430. rp++;
  196431. }
  196432. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196433. {
  196434. int a, b, c, pa, pb, pc, p;
  196435. a = *lp++;
  196436. b = *pp++;
  196437. c = *cp++;
  196438. p = b - c;
  196439. pc = a - c;
  196440. #ifdef PNG_USE_ABS
  196441. pa = abs(p);
  196442. pb = abs(pc);
  196443. pc = abs(p + pc);
  196444. #else
  196445. pa = p < 0 ? -p : p;
  196446. pb = pc < 0 ? -pc : pc;
  196447. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196448. #endif
  196449. /*
  196450. if (pa <= pb && pa <= pc)
  196451. p = a;
  196452. else if (pb <= pc)
  196453. p = b;
  196454. else
  196455. p = c;
  196456. */
  196457. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196458. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196459. rp++;
  196460. }
  196461. break;
  196462. }
  196463. default:
  196464. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196465. *row=0;
  196466. break;
  196467. }
  196468. }
  196469. void /* PRIVATE */
  196470. png_read_finish_row(png_structp png_ptr)
  196471. {
  196472. #ifdef PNG_USE_LOCAL_ARRAYS
  196473. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196474. /* start of interlace block */
  196475. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196476. /* offset to next interlace block */
  196477. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196478. /* start of interlace block in the y direction */
  196479. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196480. /* offset to next interlace block in the y direction */
  196481. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196482. #endif
  196483. png_debug(1, "in png_read_finish_row\n");
  196484. png_ptr->row_number++;
  196485. if (png_ptr->row_number < png_ptr->num_rows)
  196486. return;
  196487. if (png_ptr->interlaced)
  196488. {
  196489. png_ptr->row_number = 0;
  196490. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196491. png_ptr->rowbytes + 1);
  196492. do
  196493. {
  196494. png_ptr->pass++;
  196495. if (png_ptr->pass >= 7)
  196496. break;
  196497. png_ptr->iwidth = (png_ptr->width +
  196498. png_pass_inc[png_ptr->pass] - 1 -
  196499. png_pass_start[png_ptr->pass]) /
  196500. png_pass_inc[png_ptr->pass];
  196501. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196502. png_ptr->iwidth) + 1;
  196503. if (!(png_ptr->transformations & PNG_INTERLACE))
  196504. {
  196505. png_ptr->num_rows = (png_ptr->height +
  196506. png_pass_yinc[png_ptr->pass] - 1 -
  196507. png_pass_ystart[png_ptr->pass]) /
  196508. png_pass_yinc[png_ptr->pass];
  196509. if (!(png_ptr->num_rows))
  196510. continue;
  196511. }
  196512. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196513. break;
  196514. } while (png_ptr->iwidth == 0);
  196515. if (png_ptr->pass < 7)
  196516. return;
  196517. }
  196518. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196519. {
  196520. #ifdef PNG_USE_LOCAL_ARRAYS
  196521. PNG_CONST PNG_IDAT;
  196522. #endif
  196523. char extra;
  196524. int ret;
  196525. png_ptr->zstream.next_out = (Bytef *)&extra;
  196526. png_ptr->zstream.avail_out = (uInt)1;
  196527. for(;;)
  196528. {
  196529. if (!(png_ptr->zstream.avail_in))
  196530. {
  196531. while (!png_ptr->idat_size)
  196532. {
  196533. png_byte chunk_length[4];
  196534. png_crc_finish(png_ptr, 0);
  196535. png_read_data(png_ptr, chunk_length, 4);
  196536. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196537. png_reset_crc(png_ptr);
  196538. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196539. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196540. png_error(png_ptr, "Not enough image data");
  196541. }
  196542. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196543. png_ptr->zstream.next_in = png_ptr->zbuf;
  196544. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196545. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196546. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196547. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196548. }
  196549. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196550. if (ret == Z_STREAM_END)
  196551. {
  196552. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196553. png_ptr->idat_size)
  196554. png_warning(png_ptr, "Extra compressed data");
  196555. png_ptr->mode |= PNG_AFTER_IDAT;
  196556. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196557. break;
  196558. }
  196559. if (ret != Z_OK)
  196560. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196561. "Decompression Error");
  196562. if (!(png_ptr->zstream.avail_out))
  196563. {
  196564. png_warning(png_ptr, "Extra compressed data.");
  196565. png_ptr->mode |= PNG_AFTER_IDAT;
  196566. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196567. break;
  196568. }
  196569. }
  196570. png_ptr->zstream.avail_out = 0;
  196571. }
  196572. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196573. png_warning(png_ptr, "Extra compression data");
  196574. inflateReset(&png_ptr->zstream);
  196575. png_ptr->mode |= PNG_AFTER_IDAT;
  196576. }
  196577. void /* PRIVATE */
  196578. png_read_start_row(png_structp png_ptr)
  196579. {
  196580. #ifdef PNG_USE_LOCAL_ARRAYS
  196581. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196582. /* start of interlace block */
  196583. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196584. /* offset to next interlace block */
  196585. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196586. /* start of interlace block in the y direction */
  196587. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196588. /* offset to next interlace block in the y direction */
  196589. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196590. #endif
  196591. int max_pixel_depth;
  196592. png_uint_32 row_bytes;
  196593. png_debug(1, "in png_read_start_row\n");
  196594. png_ptr->zstream.avail_in = 0;
  196595. png_init_read_transformations(png_ptr);
  196596. if (png_ptr->interlaced)
  196597. {
  196598. if (!(png_ptr->transformations & PNG_INTERLACE))
  196599. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196600. png_pass_ystart[0]) / png_pass_yinc[0];
  196601. else
  196602. png_ptr->num_rows = png_ptr->height;
  196603. png_ptr->iwidth = (png_ptr->width +
  196604. png_pass_inc[png_ptr->pass] - 1 -
  196605. png_pass_start[png_ptr->pass]) /
  196606. png_pass_inc[png_ptr->pass];
  196607. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196608. png_ptr->irowbytes = (png_size_t)row_bytes;
  196609. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196610. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196611. }
  196612. else
  196613. {
  196614. png_ptr->num_rows = png_ptr->height;
  196615. png_ptr->iwidth = png_ptr->width;
  196616. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196617. }
  196618. max_pixel_depth = png_ptr->pixel_depth;
  196619. #if defined(PNG_READ_PACK_SUPPORTED)
  196620. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196621. max_pixel_depth = 8;
  196622. #endif
  196623. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196624. if (png_ptr->transformations & PNG_EXPAND)
  196625. {
  196626. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196627. {
  196628. if (png_ptr->num_trans)
  196629. max_pixel_depth = 32;
  196630. else
  196631. max_pixel_depth = 24;
  196632. }
  196633. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196634. {
  196635. if (max_pixel_depth < 8)
  196636. max_pixel_depth = 8;
  196637. if (png_ptr->num_trans)
  196638. max_pixel_depth *= 2;
  196639. }
  196640. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196641. {
  196642. if (png_ptr->num_trans)
  196643. {
  196644. max_pixel_depth *= 4;
  196645. max_pixel_depth /= 3;
  196646. }
  196647. }
  196648. }
  196649. #endif
  196650. #if defined(PNG_READ_FILLER_SUPPORTED)
  196651. if (png_ptr->transformations & (PNG_FILLER))
  196652. {
  196653. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196654. max_pixel_depth = 32;
  196655. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196656. {
  196657. if (max_pixel_depth <= 8)
  196658. max_pixel_depth = 16;
  196659. else
  196660. max_pixel_depth = 32;
  196661. }
  196662. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196663. {
  196664. if (max_pixel_depth <= 32)
  196665. max_pixel_depth = 32;
  196666. else
  196667. max_pixel_depth = 64;
  196668. }
  196669. }
  196670. #endif
  196671. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196672. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196673. {
  196674. if (
  196675. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196676. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196677. #endif
  196678. #if defined(PNG_READ_FILLER_SUPPORTED)
  196679. (png_ptr->transformations & (PNG_FILLER)) ||
  196680. #endif
  196681. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196682. {
  196683. if (max_pixel_depth <= 16)
  196684. max_pixel_depth = 32;
  196685. else
  196686. max_pixel_depth = 64;
  196687. }
  196688. else
  196689. {
  196690. if (max_pixel_depth <= 8)
  196691. {
  196692. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196693. max_pixel_depth = 32;
  196694. else
  196695. max_pixel_depth = 24;
  196696. }
  196697. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196698. max_pixel_depth = 64;
  196699. else
  196700. max_pixel_depth = 48;
  196701. }
  196702. }
  196703. #endif
  196704. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196705. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196706. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196707. {
  196708. int user_pixel_depth=png_ptr->user_transform_depth*
  196709. png_ptr->user_transform_channels;
  196710. if(user_pixel_depth > max_pixel_depth)
  196711. max_pixel_depth=user_pixel_depth;
  196712. }
  196713. #endif
  196714. /* align the width on the next larger 8 pixels. Mainly used
  196715. for interlacing */
  196716. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196717. /* calculate the maximum bytes needed, adding a byte and a pixel
  196718. for safety's sake */
  196719. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196720. 1 + ((max_pixel_depth + 7) >> 3);
  196721. #ifdef PNG_MAX_MALLOC_64K
  196722. if (row_bytes > (png_uint_32)65536L)
  196723. png_error(png_ptr, "This image requires a row greater than 64KB");
  196724. #endif
  196725. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196726. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196727. #ifdef PNG_MAX_MALLOC_64K
  196728. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196729. png_error(png_ptr, "This image requires a row greater than 64KB");
  196730. #endif
  196731. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196732. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196733. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196734. png_ptr->rowbytes + 1));
  196735. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196736. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196737. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196738. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196739. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196740. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196741. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196742. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196743. }
  196744. #endif /* PNG_READ_SUPPORTED */
  196745. /*** End of inlined file: pngrutil.c ***/
  196746. /*** Start of inlined file: pngset.c ***/
  196747. /* pngset.c - storage of image information into info struct
  196748. *
  196749. * Last changed in libpng 1.2.21 [October 4, 2007]
  196750. * For conditions of distribution and use, see copyright notice in png.h
  196751. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196752. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196753. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196754. *
  196755. * The functions here are used during reads to store data from the file
  196756. * into the info struct, and during writes to store application data
  196757. * into the info struct for writing into the file. This abstracts the
  196758. * info struct and allows us to change the structure in the future.
  196759. */
  196760. #define PNG_INTERNAL
  196761. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196762. #if defined(PNG_bKGD_SUPPORTED)
  196763. void PNGAPI
  196764. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196765. {
  196766. png_debug1(1, "in %s storage function\n", "bKGD");
  196767. if (png_ptr == NULL || info_ptr == NULL)
  196768. return;
  196769. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196770. info_ptr->valid |= PNG_INFO_bKGD;
  196771. }
  196772. #endif
  196773. #if defined(PNG_cHRM_SUPPORTED)
  196774. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196775. void PNGAPI
  196776. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196777. double white_x, double white_y, double red_x, double red_y,
  196778. double green_x, double green_y, double blue_x, double blue_y)
  196779. {
  196780. png_debug1(1, "in %s storage function\n", "cHRM");
  196781. if (png_ptr == NULL || info_ptr == NULL)
  196782. return;
  196783. if (white_x < 0.0 || white_y < 0.0 ||
  196784. red_x < 0.0 || red_y < 0.0 ||
  196785. green_x < 0.0 || green_y < 0.0 ||
  196786. blue_x < 0.0 || blue_y < 0.0)
  196787. {
  196788. png_warning(png_ptr,
  196789. "Ignoring attempt to set negative chromaticity value");
  196790. return;
  196791. }
  196792. if (white_x > 21474.83 || white_y > 21474.83 ||
  196793. red_x > 21474.83 || red_y > 21474.83 ||
  196794. green_x > 21474.83 || green_y > 21474.83 ||
  196795. blue_x > 21474.83 || blue_y > 21474.83)
  196796. {
  196797. png_warning(png_ptr,
  196798. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196799. return;
  196800. }
  196801. info_ptr->x_white = (float)white_x;
  196802. info_ptr->y_white = (float)white_y;
  196803. info_ptr->x_red = (float)red_x;
  196804. info_ptr->y_red = (float)red_y;
  196805. info_ptr->x_green = (float)green_x;
  196806. info_ptr->y_green = (float)green_y;
  196807. info_ptr->x_blue = (float)blue_x;
  196808. info_ptr->y_blue = (float)blue_y;
  196809. #ifdef PNG_FIXED_POINT_SUPPORTED
  196810. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196811. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196812. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196813. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196814. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196815. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196816. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196817. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196818. #endif
  196819. info_ptr->valid |= PNG_INFO_cHRM;
  196820. }
  196821. #endif
  196822. #ifdef PNG_FIXED_POINT_SUPPORTED
  196823. void PNGAPI
  196824. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196825. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196826. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196827. png_fixed_point blue_x, png_fixed_point blue_y)
  196828. {
  196829. png_debug1(1, "in %s storage function\n", "cHRM");
  196830. if (png_ptr == NULL || info_ptr == NULL)
  196831. return;
  196832. if (white_x < 0 || white_y < 0 ||
  196833. red_x < 0 || red_y < 0 ||
  196834. green_x < 0 || green_y < 0 ||
  196835. blue_x < 0 || blue_y < 0)
  196836. {
  196837. png_warning(png_ptr,
  196838. "Ignoring attempt to set negative chromaticity value");
  196839. return;
  196840. }
  196841. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196842. if (white_x > (double) PNG_UINT_31_MAX ||
  196843. white_y > (double) PNG_UINT_31_MAX ||
  196844. red_x > (double) PNG_UINT_31_MAX ||
  196845. red_y > (double) PNG_UINT_31_MAX ||
  196846. green_x > (double) PNG_UINT_31_MAX ||
  196847. green_y > (double) PNG_UINT_31_MAX ||
  196848. blue_x > (double) PNG_UINT_31_MAX ||
  196849. blue_y > (double) PNG_UINT_31_MAX)
  196850. #else
  196851. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196852. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196853. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196854. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196855. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196856. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196857. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196858. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196859. #endif
  196860. {
  196861. png_warning(png_ptr,
  196862. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196863. return;
  196864. }
  196865. info_ptr->int_x_white = white_x;
  196866. info_ptr->int_y_white = white_y;
  196867. info_ptr->int_x_red = red_x;
  196868. info_ptr->int_y_red = red_y;
  196869. info_ptr->int_x_green = green_x;
  196870. info_ptr->int_y_green = green_y;
  196871. info_ptr->int_x_blue = blue_x;
  196872. info_ptr->int_y_blue = blue_y;
  196873. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196874. info_ptr->x_white = (float)(white_x/100000.);
  196875. info_ptr->y_white = (float)(white_y/100000.);
  196876. info_ptr->x_red = (float)( red_x/100000.);
  196877. info_ptr->y_red = (float)( red_y/100000.);
  196878. info_ptr->x_green = (float)(green_x/100000.);
  196879. info_ptr->y_green = (float)(green_y/100000.);
  196880. info_ptr->x_blue = (float)( blue_x/100000.);
  196881. info_ptr->y_blue = (float)( blue_y/100000.);
  196882. #endif
  196883. info_ptr->valid |= PNG_INFO_cHRM;
  196884. }
  196885. #endif
  196886. #endif
  196887. #if defined(PNG_gAMA_SUPPORTED)
  196888. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196889. void PNGAPI
  196890. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196891. {
  196892. double gamma;
  196893. png_debug1(1, "in %s storage function\n", "gAMA");
  196894. if (png_ptr == NULL || info_ptr == NULL)
  196895. return;
  196896. /* Check for overflow */
  196897. if (file_gamma > 21474.83)
  196898. {
  196899. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196900. gamma=21474.83;
  196901. }
  196902. else
  196903. gamma=file_gamma;
  196904. info_ptr->gamma = (float)gamma;
  196905. #ifdef PNG_FIXED_POINT_SUPPORTED
  196906. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196907. #endif
  196908. info_ptr->valid |= PNG_INFO_gAMA;
  196909. if(gamma == 0.0)
  196910. png_warning(png_ptr, "Setting gamma=0");
  196911. }
  196912. #endif
  196913. void PNGAPI
  196914. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196915. int_gamma)
  196916. {
  196917. png_fixed_point gamma;
  196918. png_debug1(1, "in %s storage function\n", "gAMA");
  196919. if (png_ptr == NULL || info_ptr == NULL)
  196920. return;
  196921. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196922. {
  196923. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196924. gamma=PNG_UINT_31_MAX;
  196925. }
  196926. else
  196927. {
  196928. if (int_gamma < 0)
  196929. {
  196930. png_warning(png_ptr, "Setting negative gamma to zero");
  196931. gamma=0;
  196932. }
  196933. else
  196934. gamma=int_gamma;
  196935. }
  196936. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196937. info_ptr->gamma = (float)(gamma/100000.);
  196938. #endif
  196939. #ifdef PNG_FIXED_POINT_SUPPORTED
  196940. info_ptr->int_gamma = gamma;
  196941. #endif
  196942. info_ptr->valid |= PNG_INFO_gAMA;
  196943. if(gamma == 0)
  196944. png_warning(png_ptr, "Setting gamma=0");
  196945. }
  196946. #endif
  196947. #if defined(PNG_hIST_SUPPORTED)
  196948. void PNGAPI
  196949. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196950. {
  196951. int i;
  196952. png_debug1(1, "in %s storage function\n", "hIST");
  196953. if (png_ptr == NULL || info_ptr == NULL)
  196954. return;
  196955. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196956. > PNG_MAX_PALETTE_LENGTH)
  196957. {
  196958. png_warning(png_ptr,
  196959. "Invalid palette size, hIST allocation skipped.");
  196960. return;
  196961. }
  196962. #ifdef PNG_FREE_ME_SUPPORTED
  196963. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196964. #endif
  196965. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196966. 1.2.1 */
  196967. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196968. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196969. if (png_ptr->hist == NULL)
  196970. {
  196971. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196972. return;
  196973. }
  196974. for (i = 0; i < info_ptr->num_palette; i++)
  196975. png_ptr->hist[i] = hist[i];
  196976. info_ptr->hist = png_ptr->hist;
  196977. info_ptr->valid |= PNG_INFO_hIST;
  196978. #ifdef PNG_FREE_ME_SUPPORTED
  196979. info_ptr->free_me |= PNG_FREE_HIST;
  196980. #else
  196981. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196982. #endif
  196983. }
  196984. #endif
  196985. void PNGAPI
  196986. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196987. png_uint_32 width, png_uint_32 height, int bit_depth,
  196988. int color_type, int interlace_type, int compression_type,
  196989. int filter_type)
  196990. {
  196991. png_debug1(1, "in %s storage function\n", "IHDR");
  196992. if (png_ptr == NULL || info_ptr == NULL)
  196993. return;
  196994. /* check for width and height valid values */
  196995. if (width == 0 || height == 0)
  196996. png_error(png_ptr, "Image width or height is zero in IHDR");
  196997. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196998. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196999. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197000. #else
  197001. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197002. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197003. #endif
  197004. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197005. png_error(png_ptr, "Invalid image size in IHDR");
  197006. if ( width > (PNG_UINT_32_MAX
  197007. >> 3) /* 8-byte RGBA pixels */
  197008. - 64 /* bigrowbuf hack */
  197009. - 1 /* filter byte */
  197010. - 7*8 /* rounding of width to multiple of 8 pixels */
  197011. - 8) /* extra max_pixel_depth pad */
  197012. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197013. /* check other values */
  197014. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197015. bit_depth != 8 && bit_depth != 16)
  197016. png_error(png_ptr, "Invalid bit depth in IHDR");
  197017. if (color_type < 0 || color_type == 1 ||
  197018. color_type == 5 || color_type > 6)
  197019. png_error(png_ptr, "Invalid color type in IHDR");
  197020. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197021. ((color_type == PNG_COLOR_TYPE_RGB ||
  197022. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197023. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197024. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197025. if (interlace_type >= PNG_INTERLACE_LAST)
  197026. png_error(png_ptr, "Unknown interlace method in IHDR");
  197027. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197028. png_error(png_ptr, "Unknown compression method in IHDR");
  197029. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197030. /* Accept filter_method 64 (intrapixel differencing) only if
  197031. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197032. * 2. Libpng did not read a PNG signature (this filter_method is only
  197033. * used in PNG datastreams that are embedded in MNG datastreams) and
  197034. * 3. The application called png_permit_mng_features with a mask that
  197035. * included PNG_FLAG_MNG_FILTER_64 and
  197036. * 4. The filter_method is 64 and
  197037. * 5. The color_type is RGB or RGBA
  197038. */
  197039. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197040. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197041. if(filter_type != PNG_FILTER_TYPE_BASE)
  197042. {
  197043. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197044. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197045. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197046. (color_type == PNG_COLOR_TYPE_RGB ||
  197047. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197048. png_error(png_ptr, "Unknown filter method in IHDR");
  197049. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197050. png_warning(png_ptr, "Invalid filter method in IHDR");
  197051. }
  197052. #else
  197053. if(filter_type != PNG_FILTER_TYPE_BASE)
  197054. png_error(png_ptr, "Unknown filter method in IHDR");
  197055. #endif
  197056. info_ptr->width = width;
  197057. info_ptr->height = height;
  197058. info_ptr->bit_depth = (png_byte)bit_depth;
  197059. info_ptr->color_type =(png_byte) color_type;
  197060. info_ptr->compression_type = (png_byte)compression_type;
  197061. info_ptr->filter_type = (png_byte)filter_type;
  197062. info_ptr->interlace_type = (png_byte)interlace_type;
  197063. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197064. info_ptr->channels = 1;
  197065. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197066. info_ptr->channels = 3;
  197067. else
  197068. info_ptr->channels = 1;
  197069. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197070. info_ptr->channels++;
  197071. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197072. /* check for potential overflow */
  197073. if (width > (PNG_UINT_32_MAX
  197074. >> 3) /* 8-byte RGBA pixels */
  197075. - 64 /* bigrowbuf hack */
  197076. - 1 /* filter byte */
  197077. - 7*8 /* rounding of width to multiple of 8 pixels */
  197078. - 8) /* extra max_pixel_depth pad */
  197079. info_ptr->rowbytes = (png_size_t)0;
  197080. else
  197081. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197082. }
  197083. #if defined(PNG_oFFs_SUPPORTED)
  197084. void PNGAPI
  197085. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197086. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197087. {
  197088. png_debug1(1, "in %s storage function\n", "oFFs");
  197089. if (png_ptr == NULL || info_ptr == NULL)
  197090. return;
  197091. info_ptr->x_offset = offset_x;
  197092. info_ptr->y_offset = offset_y;
  197093. info_ptr->offset_unit_type = (png_byte)unit_type;
  197094. info_ptr->valid |= PNG_INFO_oFFs;
  197095. }
  197096. #endif
  197097. #if defined(PNG_pCAL_SUPPORTED)
  197098. void PNGAPI
  197099. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197100. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197101. png_charp units, png_charpp params)
  197102. {
  197103. png_uint_32 length;
  197104. int i;
  197105. png_debug1(1, "in %s storage function\n", "pCAL");
  197106. if (png_ptr == NULL || info_ptr == NULL)
  197107. return;
  197108. length = png_strlen(purpose) + 1;
  197109. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197110. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197111. if (info_ptr->pcal_purpose == NULL)
  197112. {
  197113. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197114. return;
  197115. }
  197116. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197117. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197118. info_ptr->pcal_X0 = X0;
  197119. info_ptr->pcal_X1 = X1;
  197120. info_ptr->pcal_type = (png_byte)type;
  197121. info_ptr->pcal_nparams = (png_byte)nparams;
  197122. length = png_strlen(units) + 1;
  197123. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197124. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197125. if (info_ptr->pcal_units == NULL)
  197126. {
  197127. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197128. return;
  197129. }
  197130. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197131. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197132. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197133. if (info_ptr->pcal_params == NULL)
  197134. {
  197135. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197136. return;
  197137. }
  197138. info_ptr->pcal_params[nparams] = NULL;
  197139. for (i = 0; i < nparams; i++)
  197140. {
  197141. length = png_strlen(params[i]) + 1;
  197142. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197143. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197144. if (info_ptr->pcal_params[i] == NULL)
  197145. {
  197146. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197147. return;
  197148. }
  197149. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197150. }
  197151. info_ptr->valid |= PNG_INFO_pCAL;
  197152. #ifdef PNG_FREE_ME_SUPPORTED
  197153. info_ptr->free_me |= PNG_FREE_PCAL;
  197154. #endif
  197155. }
  197156. #endif
  197157. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197158. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197159. void PNGAPI
  197160. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197161. int unit, double width, double height)
  197162. {
  197163. png_debug1(1, "in %s storage function\n", "sCAL");
  197164. if (png_ptr == NULL || info_ptr == NULL)
  197165. return;
  197166. info_ptr->scal_unit = (png_byte)unit;
  197167. info_ptr->scal_pixel_width = width;
  197168. info_ptr->scal_pixel_height = height;
  197169. info_ptr->valid |= PNG_INFO_sCAL;
  197170. }
  197171. #else
  197172. #ifdef PNG_FIXED_POINT_SUPPORTED
  197173. void PNGAPI
  197174. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197175. int unit, png_charp swidth, png_charp sheight)
  197176. {
  197177. png_uint_32 length;
  197178. png_debug1(1, "in %s storage function\n", "sCAL");
  197179. if (png_ptr == NULL || info_ptr == NULL)
  197180. return;
  197181. info_ptr->scal_unit = (png_byte)unit;
  197182. length = png_strlen(swidth) + 1;
  197183. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197184. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197185. if (info_ptr->scal_s_width == NULL)
  197186. {
  197187. png_warning(png_ptr,
  197188. "Memory allocation failed while processing sCAL.");
  197189. }
  197190. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197191. length = png_strlen(sheight) + 1;
  197192. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197193. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197194. if (info_ptr->scal_s_height == NULL)
  197195. {
  197196. png_free (png_ptr, info_ptr->scal_s_width);
  197197. png_warning(png_ptr,
  197198. "Memory allocation failed while processing sCAL.");
  197199. }
  197200. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197201. info_ptr->valid |= PNG_INFO_sCAL;
  197202. #ifdef PNG_FREE_ME_SUPPORTED
  197203. info_ptr->free_me |= PNG_FREE_SCAL;
  197204. #endif
  197205. }
  197206. #endif
  197207. #endif
  197208. #endif
  197209. #if defined(PNG_pHYs_SUPPORTED)
  197210. void PNGAPI
  197211. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197212. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197213. {
  197214. png_debug1(1, "in %s storage function\n", "pHYs");
  197215. if (png_ptr == NULL || info_ptr == NULL)
  197216. return;
  197217. info_ptr->x_pixels_per_unit = res_x;
  197218. info_ptr->y_pixels_per_unit = res_y;
  197219. info_ptr->phys_unit_type = (png_byte)unit_type;
  197220. info_ptr->valid |= PNG_INFO_pHYs;
  197221. }
  197222. #endif
  197223. void PNGAPI
  197224. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197225. png_colorp palette, int num_palette)
  197226. {
  197227. png_debug1(1, "in %s storage function\n", "PLTE");
  197228. if (png_ptr == NULL || info_ptr == NULL)
  197229. return;
  197230. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197231. {
  197232. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197233. png_error(png_ptr, "Invalid palette length");
  197234. else
  197235. {
  197236. png_warning(png_ptr, "Invalid palette length");
  197237. return;
  197238. }
  197239. }
  197240. /*
  197241. * It may not actually be necessary to set png_ptr->palette here;
  197242. * we do it for backward compatibility with the way the png_handle_tRNS
  197243. * function used to do the allocation.
  197244. */
  197245. #ifdef PNG_FREE_ME_SUPPORTED
  197246. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197247. #endif
  197248. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197249. of num_palette entries,
  197250. in case of an invalid PNG file that has too-large sample values. */
  197251. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197252. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197253. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197254. png_sizeof(png_color));
  197255. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197256. info_ptr->palette = png_ptr->palette;
  197257. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197258. #ifdef PNG_FREE_ME_SUPPORTED
  197259. info_ptr->free_me |= PNG_FREE_PLTE;
  197260. #else
  197261. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197262. #endif
  197263. info_ptr->valid |= PNG_INFO_PLTE;
  197264. }
  197265. #if defined(PNG_sBIT_SUPPORTED)
  197266. void PNGAPI
  197267. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197268. png_color_8p sig_bit)
  197269. {
  197270. png_debug1(1, "in %s storage function\n", "sBIT");
  197271. if (png_ptr == NULL || info_ptr == NULL)
  197272. return;
  197273. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197274. info_ptr->valid |= PNG_INFO_sBIT;
  197275. }
  197276. #endif
  197277. #if defined(PNG_sRGB_SUPPORTED)
  197278. void PNGAPI
  197279. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197280. {
  197281. png_debug1(1, "in %s storage function\n", "sRGB");
  197282. if (png_ptr == NULL || info_ptr == NULL)
  197283. return;
  197284. info_ptr->srgb_intent = (png_byte)intent;
  197285. info_ptr->valid |= PNG_INFO_sRGB;
  197286. }
  197287. void PNGAPI
  197288. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197289. int intent)
  197290. {
  197291. #if defined(PNG_gAMA_SUPPORTED)
  197292. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197293. float file_gamma;
  197294. #endif
  197295. #ifdef PNG_FIXED_POINT_SUPPORTED
  197296. png_fixed_point int_file_gamma;
  197297. #endif
  197298. #endif
  197299. #if defined(PNG_cHRM_SUPPORTED)
  197300. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197301. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197302. #endif
  197303. #ifdef PNG_FIXED_POINT_SUPPORTED
  197304. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197305. int_green_y, int_blue_x, int_blue_y;
  197306. #endif
  197307. #endif
  197308. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197309. if (png_ptr == NULL || info_ptr == NULL)
  197310. return;
  197311. png_set_sRGB(png_ptr, info_ptr, intent);
  197312. #if defined(PNG_gAMA_SUPPORTED)
  197313. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197314. file_gamma = (float).45455;
  197315. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197316. #endif
  197317. #ifdef PNG_FIXED_POINT_SUPPORTED
  197318. int_file_gamma = 45455L;
  197319. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197320. #endif
  197321. #endif
  197322. #if defined(PNG_cHRM_SUPPORTED)
  197323. #ifdef PNG_FIXED_POINT_SUPPORTED
  197324. int_white_x = 31270L;
  197325. int_white_y = 32900L;
  197326. int_red_x = 64000L;
  197327. int_red_y = 33000L;
  197328. int_green_x = 30000L;
  197329. int_green_y = 60000L;
  197330. int_blue_x = 15000L;
  197331. int_blue_y = 6000L;
  197332. png_set_cHRM_fixed(png_ptr, info_ptr,
  197333. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197334. int_blue_x, int_blue_y);
  197335. #endif
  197336. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197337. white_x = (float).3127;
  197338. white_y = (float).3290;
  197339. red_x = (float).64;
  197340. red_y = (float).33;
  197341. green_x = (float).30;
  197342. green_y = (float).60;
  197343. blue_x = (float).15;
  197344. blue_y = (float).06;
  197345. png_set_cHRM(png_ptr, info_ptr,
  197346. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197347. #endif
  197348. #endif
  197349. }
  197350. #endif
  197351. #if defined(PNG_iCCP_SUPPORTED)
  197352. void PNGAPI
  197353. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197354. png_charp name, int compression_type,
  197355. png_charp profile, png_uint_32 proflen)
  197356. {
  197357. png_charp new_iccp_name;
  197358. png_charp new_iccp_profile;
  197359. png_debug1(1, "in %s storage function\n", "iCCP");
  197360. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197361. return;
  197362. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197363. if (new_iccp_name == NULL)
  197364. {
  197365. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197366. return;
  197367. }
  197368. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197369. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197370. if (new_iccp_profile == NULL)
  197371. {
  197372. png_free (png_ptr, new_iccp_name);
  197373. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197374. return;
  197375. }
  197376. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197377. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197378. info_ptr->iccp_proflen = proflen;
  197379. info_ptr->iccp_name = new_iccp_name;
  197380. info_ptr->iccp_profile = new_iccp_profile;
  197381. /* Compression is always zero but is here so the API and info structure
  197382. * does not have to change if we introduce multiple compression types */
  197383. info_ptr->iccp_compression = (png_byte)compression_type;
  197384. #ifdef PNG_FREE_ME_SUPPORTED
  197385. info_ptr->free_me |= PNG_FREE_ICCP;
  197386. #endif
  197387. info_ptr->valid |= PNG_INFO_iCCP;
  197388. }
  197389. #endif
  197390. #if defined(PNG_TEXT_SUPPORTED)
  197391. void PNGAPI
  197392. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197393. int num_text)
  197394. {
  197395. int ret;
  197396. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197397. if (ret)
  197398. png_error(png_ptr, "Insufficient memory to store text");
  197399. }
  197400. int /* PRIVATE */
  197401. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197402. int num_text)
  197403. {
  197404. int i;
  197405. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197406. "text" : (png_const_charp)png_ptr->chunk_name));
  197407. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197408. return(0);
  197409. /* Make sure we have enough space in the "text" array in info_struct
  197410. * to hold all of the incoming text_ptr objects.
  197411. */
  197412. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197413. {
  197414. if (info_ptr->text != NULL)
  197415. {
  197416. png_textp old_text;
  197417. int old_max;
  197418. old_max = info_ptr->max_text;
  197419. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197420. old_text = info_ptr->text;
  197421. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197422. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197423. if (info_ptr->text == NULL)
  197424. {
  197425. png_free(png_ptr, old_text);
  197426. return(1);
  197427. }
  197428. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197429. png_sizeof(png_text)));
  197430. png_free(png_ptr, old_text);
  197431. }
  197432. else
  197433. {
  197434. info_ptr->max_text = num_text + 8;
  197435. info_ptr->num_text = 0;
  197436. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197437. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197438. if (info_ptr->text == NULL)
  197439. return(1);
  197440. #ifdef PNG_FREE_ME_SUPPORTED
  197441. info_ptr->free_me |= PNG_FREE_TEXT;
  197442. #endif
  197443. }
  197444. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197445. info_ptr->max_text);
  197446. }
  197447. for (i = 0; i < num_text; i++)
  197448. {
  197449. png_size_t text_length,key_len;
  197450. png_size_t lang_len,lang_key_len;
  197451. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197452. if (text_ptr[i].key == NULL)
  197453. continue;
  197454. key_len = png_strlen(text_ptr[i].key);
  197455. if(text_ptr[i].compression <= 0)
  197456. {
  197457. lang_len = 0;
  197458. lang_key_len = 0;
  197459. }
  197460. else
  197461. #ifdef PNG_iTXt_SUPPORTED
  197462. {
  197463. /* set iTXt data */
  197464. if (text_ptr[i].lang != NULL)
  197465. lang_len = png_strlen(text_ptr[i].lang);
  197466. else
  197467. lang_len = 0;
  197468. if (text_ptr[i].lang_key != NULL)
  197469. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197470. else
  197471. lang_key_len = 0;
  197472. }
  197473. #else
  197474. {
  197475. png_warning(png_ptr, "iTXt chunk not supported.");
  197476. continue;
  197477. }
  197478. #endif
  197479. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197480. {
  197481. text_length = 0;
  197482. #ifdef PNG_iTXt_SUPPORTED
  197483. if(text_ptr[i].compression > 0)
  197484. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197485. else
  197486. #endif
  197487. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197488. }
  197489. else
  197490. {
  197491. text_length = png_strlen(text_ptr[i].text);
  197492. textp->compression = text_ptr[i].compression;
  197493. }
  197494. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197495. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197496. if (textp->key == NULL)
  197497. return(1);
  197498. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197499. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197500. (int)textp->key);
  197501. png_memcpy(textp->key, text_ptr[i].key,
  197502. (png_size_t)(key_len));
  197503. *(textp->key+key_len) = '\0';
  197504. #ifdef PNG_iTXt_SUPPORTED
  197505. if (text_ptr[i].compression > 0)
  197506. {
  197507. textp->lang=textp->key + key_len + 1;
  197508. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197509. *(textp->lang+lang_len) = '\0';
  197510. textp->lang_key=textp->lang + lang_len + 1;
  197511. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197512. *(textp->lang_key+lang_key_len) = '\0';
  197513. textp->text=textp->lang_key + lang_key_len + 1;
  197514. }
  197515. else
  197516. #endif
  197517. {
  197518. #ifdef PNG_iTXt_SUPPORTED
  197519. textp->lang=NULL;
  197520. textp->lang_key=NULL;
  197521. #endif
  197522. textp->text=textp->key + key_len + 1;
  197523. }
  197524. if(text_length)
  197525. png_memcpy(textp->text, text_ptr[i].text,
  197526. (png_size_t)(text_length));
  197527. *(textp->text+text_length) = '\0';
  197528. #ifdef PNG_iTXt_SUPPORTED
  197529. if(textp->compression > 0)
  197530. {
  197531. textp->text_length = 0;
  197532. textp->itxt_length = text_length;
  197533. }
  197534. else
  197535. #endif
  197536. {
  197537. textp->text_length = text_length;
  197538. #ifdef PNG_iTXt_SUPPORTED
  197539. textp->itxt_length = 0;
  197540. #endif
  197541. }
  197542. info_ptr->num_text++;
  197543. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197544. }
  197545. return(0);
  197546. }
  197547. #endif
  197548. #if defined(PNG_tIME_SUPPORTED)
  197549. void PNGAPI
  197550. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197551. {
  197552. png_debug1(1, "in %s storage function\n", "tIME");
  197553. if (png_ptr == NULL || info_ptr == NULL ||
  197554. (png_ptr->mode & PNG_WROTE_tIME))
  197555. return;
  197556. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197557. info_ptr->valid |= PNG_INFO_tIME;
  197558. }
  197559. #endif
  197560. #if defined(PNG_tRNS_SUPPORTED)
  197561. void PNGAPI
  197562. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197563. png_bytep trans, int num_trans, png_color_16p trans_values)
  197564. {
  197565. png_debug1(1, "in %s storage function\n", "tRNS");
  197566. if (png_ptr == NULL || info_ptr == NULL)
  197567. return;
  197568. if (trans != NULL)
  197569. {
  197570. /*
  197571. * It may not actually be necessary to set png_ptr->trans here;
  197572. * we do it for backward compatibility with the way the png_handle_tRNS
  197573. * function used to do the allocation.
  197574. */
  197575. #ifdef PNG_FREE_ME_SUPPORTED
  197576. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197577. #endif
  197578. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197579. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197580. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197581. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197582. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197583. #ifdef PNG_FREE_ME_SUPPORTED
  197584. info_ptr->free_me |= PNG_FREE_TRNS;
  197585. #else
  197586. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197587. #endif
  197588. }
  197589. if (trans_values != NULL)
  197590. {
  197591. png_memcpy(&(info_ptr->trans_values), trans_values,
  197592. png_sizeof(png_color_16));
  197593. if (num_trans == 0)
  197594. num_trans = 1;
  197595. }
  197596. info_ptr->num_trans = (png_uint_16)num_trans;
  197597. info_ptr->valid |= PNG_INFO_tRNS;
  197598. }
  197599. #endif
  197600. #if defined(PNG_sPLT_SUPPORTED)
  197601. void PNGAPI
  197602. png_set_sPLT(png_structp png_ptr,
  197603. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197604. {
  197605. png_sPLT_tp np;
  197606. int i;
  197607. if (png_ptr == NULL || info_ptr == NULL)
  197608. return;
  197609. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197610. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197611. if (np == NULL)
  197612. {
  197613. png_warning(png_ptr, "No memory for sPLT palettes.");
  197614. return;
  197615. }
  197616. png_memcpy(np, info_ptr->splt_palettes,
  197617. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197618. png_free(png_ptr, info_ptr->splt_palettes);
  197619. info_ptr->splt_palettes=NULL;
  197620. for (i = 0; i < nentries; i++)
  197621. {
  197622. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197623. png_sPLT_tp from = entries + i;
  197624. to->name = (png_charp)png_malloc_warn(png_ptr,
  197625. png_strlen(from->name) + 1);
  197626. if (to->name == NULL)
  197627. {
  197628. png_warning(png_ptr,
  197629. "Out of memory while processing sPLT chunk");
  197630. }
  197631. /* TODO: use png_malloc_warn */
  197632. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197633. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197634. from->nentries * png_sizeof(png_sPLT_entry));
  197635. /* TODO: use png_malloc_warn */
  197636. png_memcpy(to->entries, from->entries,
  197637. from->nentries * png_sizeof(png_sPLT_entry));
  197638. if (to->entries == NULL)
  197639. {
  197640. png_warning(png_ptr,
  197641. "Out of memory while processing sPLT chunk");
  197642. png_free(png_ptr,to->name);
  197643. to->name = NULL;
  197644. }
  197645. to->nentries = from->nentries;
  197646. to->depth = from->depth;
  197647. }
  197648. info_ptr->splt_palettes = np;
  197649. info_ptr->splt_palettes_num += nentries;
  197650. info_ptr->valid |= PNG_INFO_sPLT;
  197651. #ifdef PNG_FREE_ME_SUPPORTED
  197652. info_ptr->free_me |= PNG_FREE_SPLT;
  197653. #endif
  197654. }
  197655. #endif /* PNG_sPLT_SUPPORTED */
  197656. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197657. void PNGAPI
  197658. png_set_unknown_chunks(png_structp png_ptr,
  197659. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197660. {
  197661. png_unknown_chunkp np;
  197662. int i;
  197663. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197664. return;
  197665. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197666. (info_ptr->unknown_chunks_num + num_unknowns) *
  197667. png_sizeof(png_unknown_chunk));
  197668. if (np == NULL)
  197669. {
  197670. png_warning(png_ptr,
  197671. "Out of memory while processing unknown chunk.");
  197672. return;
  197673. }
  197674. png_memcpy(np, info_ptr->unknown_chunks,
  197675. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197676. png_free(png_ptr, info_ptr->unknown_chunks);
  197677. info_ptr->unknown_chunks=NULL;
  197678. for (i = 0; i < num_unknowns; i++)
  197679. {
  197680. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197681. png_unknown_chunkp from = unknowns + i;
  197682. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197683. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197684. if (to->data == NULL)
  197685. {
  197686. png_warning(png_ptr,
  197687. "Out of memory while processing unknown chunk.");
  197688. }
  197689. else
  197690. {
  197691. png_memcpy(to->data, from->data, from->size);
  197692. to->size = from->size;
  197693. /* note our location in the read or write sequence */
  197694. to->location = (png_byte)(png_ptr->mode & 0xff);
  197695. }
  197696. }
  197697. info_ptr->unknown_chunks = np;
  197698. info_ptr->unknown_chunks_num += num_unknowns;
  197699. #ifdef PNG_FREE_ME_SUPPORTED
  197700. info_ptr->free_me |= PNG_FREE_UNKN;
  197701. #endif
  197702. }
  197703. void PNGAPI
  197704. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197705. int chunk, int location)
  197706. {
  197707. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197708. (int)info_ptr->unknown_chunks_num)
  197709. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197710. }
  197711. #endif
  197712. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197713. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197714. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197715. void PNGAPI
  197716. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197717. {
  197718. /* This function is deprecated in favor of png_permit_mng_features()
  197719. and will be removed from libpng-1.3.0 */
  197720. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197721. if (png_ptr == NULL)
  197722. return;
  197723. png_ptr->mng_features_permitted = (png_byte)
  197724. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197725. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197726. }
  197727. #endif
  197728. #endif
  197729. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197730. png_uint_32 PNGAPI
  197731. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197732. {
  197733. png_debug(1, "in png_permit_mng_features\n");
  197734. if (png_ptr == NULL)
  197735. return (png_uint_32)0;
  197736. png_ptr->mng_features_permitted =
  197737. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197738. return (png_uint_32)png_ptr->mng_features_permitted;
  197739. }
  197740. #endif
  197741. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197742. void PNGAPI
  197743. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197744. chunk_list, int num_chunks)
  197745. {
  197746. png_bytep new_list, p;
  197747. int i, old_num_chunks;
  197748. if (png_ptr == NULL)
  197749. return;
  197750. if (num_chunks == 0)
  197751. {
  197752. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197753. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197754. else
  197755. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197756. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197757. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197758. else
  197759. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197760. return;
  197761. }
  197762. if (chunk_list == NULL)
  197763. return;
  197764. old_num_chunks=png_ptr->num_chunk_list;
  197765. new_list=(png_bytep)png_malloc(png_ptr,
  197766. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197767. if(png_ptr->chunk_list != NULL)
  197768. {
  197769. png_memcpy(new_list, png_ptr->chunk_list,
  197770. (png_size_t)(5*old_num_chunks));
  197771. png_free(png_ptr, png_ptr->chunk_list);
  197772. png_ptr->chunk_list=NULL;
  197773. }
  197774. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197775. (png_size_t)(5*num_chunks));
  197776. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197777. *p=(png_byte)keep;
  197778. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197779. png_ptr->chunk_list=new_list;
  197780. #ifdef PNG_FREE_ME_SUPPORTED
  197781. png_ptr->free_me |= PNG_FREE_LIST;
  197782. #endif
  197783. }
  197784. #endif
  197785. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197786. void PNGAPI
  197787. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197788. png_user_chunk_ptr read_user_chunk_fn)
  197789. {
  197790. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197791. if (png_ptr == NULL)
  197792. return;
  197793. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197794. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197795. }
  197796. #endif
  197797. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197798. void PNGAPI
  197799. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197800. {
  197801. png_debug1(1, "in %s storage function\n", "rows");
  197802. if (png_ptr == NULL || info_ptr == NULL)
  197803. return;
  197804. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197805. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197806. info_ptr->row_pointers = row_pointers;
  197807. if(row_pointers)
  197808. info_ptr->valid |= PNG_INFO_IDAT;
  197809. }
  197810. #endif
  197811. #ifdef PNG_WRITE_SUPPORTED
  197812. void PNGAPI
  197813. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197814. {
  197815. if (png_ptr == NULL)
  197816. return;
  197817. if(png_ptr->zbuf)
  197818. png_free(png_ptr, png_ptr->zbuf);
  197819. png_ptr->zbuf_size = (png_size_t)size;
  197820. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197821. png_ptr->zstream.next_out = png_ptr->zbuf;
  197822. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197823. }
  197824. #endif
  197825. void PNGAPI
  197826. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197827. {
  197828. if (png_ptr && info_ptr)
  197829. info_ptr->valid &= ~(mask);
  197830. }
  197831. #ifndef PNG_1_0_X
  197832. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197833. /* function was added to libpng 1.2.0 and should always exist by default */
  197834. void PNGAPI
  197835. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197836. {
  197837. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197838. if (png_ptr != NULL)
  197839. png_ptr->asm_flags = 0;
  197840. }
  197841. /* this function was added to libpng 1.2.0 */
  197842. void PNGAPI
  197843. png_set_mmx_thresholds (png_structp png_ptr,
  197844. png_byte,
  197845. png_uint_32)
  197846. {
  197847. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197848. if (png_ptr == NULL)
  197849. return;
  197850. }
  197851. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197852. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197853. /* this function was added to libpng 1.2.6 */
  197854. void PNGAPI
  197855. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197856. png_uint_32 user_height_max)
  197857. {
  197858. /* Images with dimensions larger than these limits will be
  197859. * rejected by png_set_IHDR(). To accept any PNG datastream
  197860. * regardless of dimensions, set both limits to 0x7ffffffL.
  197861. */
  197862. if(png_ptr == NULL) return;
  197863. png_ptr->user_width_max = user_width_max;
  197864. png_ptr->user_height_max = user_height_max;
  197865. }
  197866. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197867. #endif /* ?PNG_1_0_X */
  197868. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197869. /*** End of inlined file: pngset.c ***/
  197870. /*** Start of inlined file: pngtrans.c ***/
  197871. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197872. *
  197873. * Last changed in libpng 1.2.17 May 15, 2007
  197874. * For conditions of distribution and use, see copyright notice in png.h
  197875. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197876. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197877. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197878. */
  197879. #define PNG_INTERNAL
  197880. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197881. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197882. /* turn on BGR-to-RGB mapping */
  197883. void PNGAPI
  197884. png_set_bgr(png_structp png_ptr)
  197885. {
  197886. png_debug(1, "in png_set_bgr\n");
  197887. if(png_ptr == NULL) return;
  197888. png_ptr->transformations |= PNG_BGR;
  197889. }
  197890. #endif
  197891. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197892. /* turn on 16 bit byte swapping */
  197893. void PNGAPI
  197894. png_set_swap(png_structp png_ptr)
  197895. {
  197896. png_debug(1, "in png_set_swap\n");
  197897. if(png_ptr == NULL) return;
  197898. if (png_ptr->bit_depth == 16)
  197899. png_ptr->transformations |= PNG_SWAP_BYTES;
  197900. }
  197901. #endif
  197902. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197903. /* turn on pixel packing */
  197904. void PNGAPI
  197905. png_set_packing(png_structp png_ptr)
  197906. {
  197907. png_debug(1, "in png_set_packing\n");
  197908. if(png_ptr == NULL) return;
  197909. if (png_ptr->bit_depth < 8)
  197910. {
  197911. png_ptr->transformations |= PNG_PACK;
  197912. png_ptr->usr_bit_depth = 8;
  197913. }
  197914. }
  197915. #endif
  197916. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197917. /* turn on packed pixel swapping */
  197918. void PNGAPI
  197919. png_set_packswap(png_structp png_ptr)
  197920. {
  197921. png_debug(1, "in png_set_packswap\n");
  197922. if(png_ptr == NULL) return;
  197923. if (png_ptr->bit_depth < 8)
  197924. png_ptr->transformations |= PNG_PACKSWAP;
  197925. }
  197926. #endif
  197927. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197928. void PNGAPI
  197929. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197930. {
  197931. png_debug(1, "in png_set_shift\n");
  197932. if(png_ptr == NULL) return;
  197933. png_ptr->transformations |= PNG_SHIFT;
  197934. png_ptr->shift = *true_bits;
  197935. }
  197936. #endif
  197937. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197938. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197939. int PNGAPI
  197940. png_set_interlace_handling(png_structp png_ptr)
  197941. {
  197942. png_debug(1, "in png_set_interlace handling\n");
  197943. if (png_ptr && png_ptr->interlaced)
  197944. {
  197945. png_ptr->transformations |= PNG_INTERLACE;
  197946. return (7);
  197947. }
  197948. return (1);
  197949. }
  197950. #endif
  197951. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197952. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197953. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197954. * for 48-bit input data, as well as to avoid problems with some compilers
  197955. * that don't like bytes as parameters.
  197956. */
  197957. void PNGAPI
  197958. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197959. {
  197960. png_debug(1, "in png_set_filler\n");
  197961. if(png_ptr == NULL) return;
  197962. png_ptr->transformations |= PNG_FILLER;
  197963. png_ptr->filler = (png_byte)filler;
  197964. if (filler_loc == PNG_FILLER_AFTER)
  197965. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197966. else
  197967. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197968. /* This should probably go in the "do_read_filler" routine.
  197969. * I attempted to do that in libpng-1.0.1a but that caused problems
  197970. * so I restored it in libpng-1.0.2a
  197971. */
  197972. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197973. {
  197974. png_ptr->usr_channels = 4;
  197975. }
  197976. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197977. * a less-than-8-bit grayscale to GA? */
  197978. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197979. {
  197980. png_ptr->usr_channels = 2;
  197981. }
  197982. }
  197983. #if !defined(PNG_1_0_X)
  197984. /* Added to libpng-1.2.7 */
  197985. void PNGAPI
  197986. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197987. {
  197988. png_debug(1, "in png_set_add_alpha\n");
  197989. if(png_ptr == NULL) return;
  197990. png_set_filler(png_ptr, filler, filler_loc);
  197991. png_ptr->transformations |= PNG_ADD_ALPHA;
  197992. }
  197993. #endif
  197994. #endif
  197995. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197996. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197997. void PNGAPI
  197998. png_set_swap_alpha(png_structp png_ptr)
  197999. {
  198000. png_debug(1, "in png_set_swap_alpha\n");
  198001. if(png_ptr == NULL) return;
  198002. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198003. }
  198004. #endif
  198005. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198006. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198007. void PNGAPI
  198008. png_set_invert_alpha(png_structp png_ptr)
  198009. {
  198010. png_debug(1, "in png_set_invert_alpha\n");
  198011. if(png_ptr == NULL) return;
  198012. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198013. }
  198014. #endif
  198015. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198016. void PNGAPI
  198017. png_set_invert_mono(png_structp png_ptr)
  198018. {
  198019. png_debug(1, "in png_set_invert_mono\n");
  198020. if(png_ptr == NULL) return;
  198021. png_ptr->transformations |= PNG_INVERT_MONO;
  198022. }
  198023. /* invert monochrome grayscale data */
  198024. void /* PRIVATE */
  198025. png_do_invert(png_row_infop row_info, png_bytep row)
  198026. {
  198027. png_debug(1, "in png_do_invert\n");
  198028. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198029. * if (row_info->bit_depth == 1 &&
  198030. */
  198031. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198032. if (row == NULL || row_info == NULL)
  198033. return;
  198034. #endif
  198035. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198036. {
  198037. png_bytep rp = row;
  198038. png_uint_32 i;
  198039. png_uint_32 istop = row_info->rowbytes;
  198040. for (i = 0; i < istop; i++)
  198041. {
  198042. *rp = (png_byte)(~(*rp));
  198043. rp++;
  198044. }
  198045. }
  198046. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198047. row_info->bit_depth == 8)
  198048. {
  198049. png_bytep rp = row;
  198050. png_uint_32 i;
  198051. png_uint_32 istop = row_info->rowbytes;
  198052. for (i = 0; i < istop; i+=2)
  198053. {
  198054. *rp = (png_byte)(~(*rp));
  198055. rp+=2;
  198056. }
  198057. }
  198058. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198059. row_info->bit_depth == 16)
  198060. {
  198061. png_bytep rp = row;
  198062. png_uint_32 i;
  198063. png_uint_32 istop = row_info->rowbytes;
  198064. for (i = 0; i < istop; i+=4)
  198065. {
  198066. *rp = (png_byte)(~(*rp));
  198067. *(rp+1) = (png_byte)(~(*(rp+1)));
  198068. rp+=4;
  198069. }
  198070. }
  198071. }
  198072. #endif
  198073. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198074. /* swaps byte order on 16 bit depth images */
  198075. void /* PRIVATE */
  198076. png_do_swap(png_row_infop row_info, png_bytep row)
  198077. {
  198078. png_debug(1, "in png_do_swap\n");
  198079. if (
  198080. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198081. row != NULL && row_info != NULL &&
  198082. #endif
  198083. row_info->bit_depth == 16)
  198084. {
  198085. png_bytep rp = row;
  198086. png_uint_32 i;
  198087. png_uint_32 istop= row_info->width * row_info->channels;
  198088. for (i = 0; i < istop; i++, rp += 2)
  198089. {
  198090. png_byte t = *rp;
  198091. *rp = *(rp + 1);
  198092. *(rp + 1) = t;
  198093. }
  198094. }
  198095. }
  198096. #endif
  198097. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198098. static PNG_CONST png_byte onebppswaptable[256] = {
  198099. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198100. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198101. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198102. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198103. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198104. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198105. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198106. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198107. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198108. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198109. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198110. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198111. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198112. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198113. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198114. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198115. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198116. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198117. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198118. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198119. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198120. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198121. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198122. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198123. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198124. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198125. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198126. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198127. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198128. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198129. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198130. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198131. };
  198132. static PNG_CONST png_byte twobppswaptable[256] = {
  198133. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198134. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198135. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198136. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198137. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198138. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198139. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198140. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198141. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198142. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198143. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198144. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198145. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198146. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198147. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198148. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198149. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198150. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198151. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198152. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198153. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198154. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198155. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198156. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198157. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198158. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198159. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198160. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198161. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198162. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198163. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198164. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198165. };
  198166. static PNG_CONST png_byte fourbppswaptable[256] = {
  198167. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198168. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198169. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198170. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198171. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198172. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198173. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198174. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198175. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198176. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198177. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198178. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198179. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198180. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198181. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198182. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198183. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198184. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198185. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198186. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198187. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198188. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198189. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198190. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198191. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198192. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198193. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198194. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198195. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198196. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198197. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198198. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198199. };
  198200. /* swaps pixel packing order within bytes */
  198201. void /* PRIVATE */
  198202. png_do_packswap(png_row_infop row_info, png_bytep row)
  198203. {
  198204. png_debug(1, "in png_do_packswap\n");
  198205. if (
  198206. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198207. row != NULL && row_info != NULL &&
  198208. #endif
  198209. row_info->bit_depth < 8)
  198210. {
  198211. png_bytep rp, end, table;
  198212. end = row + row_info->rowbytes;
  198213. if (row_info->bit_depth == 1)
  198214. table = (png_bytep)onebppswaptable;
  198215. else if (row_info->bit_depth == 2)
  198216. table = (png_bytep)twobppswaptable;
  198217. else if (row_info->bit_depth == 4)
  198218. table = (png_bytep)fourbppswaptable;
  198219. else
  198220. return;
  198221. for (rp = row; rp < end; rp++)
  198222. *rp = table[*rp];
  198223. }
  198224. }
  198225. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198226. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198227. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198228. /* remove filler or alpha byte(s) */
  198229. void /* PRIVATE */
  198230. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198231. {
  198232. png_debug(1, "in png_do_strip_filler\n");
  198233. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198234. if (row != NULL && row_info != NULL)
  198235. #endif
  198236. {
  198237. png_bytep sp=row;
  198238. png_bytep dp=row;
  198239. png_uint_32 row_width=row_info->width;
  198240. png_uint_32 i;
  198241. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198242. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198243. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198244. row_info->channels == 4)
  198245. {
  198246. if (row_info->bit_depth == 8)
  198247. {
  198248. /* This converts from RGBX or RGBA to RGB */
  198249. if (flags & PNG_FLAG_FILLER_AFTER)
  198250. {
  198251. dp+=3; sp+=4;
  198252. for (i = 1; i < row_width; i++)
  198253. {
  198254. *dp++ = *sp++;
  198255. *dp++ = *sp++;
  198256. *dp++ = *sp++;
  198257. sp++;
  198258. }
  198259. }
  198260. /* This converts from XRGB or ARGB to RGB */
  198261. else
  198262. {
  198263. for (i = 0; i < row_width; i++)
  198264. {
  198265. sp++;
  198266. *dp++ = *sp++;
  198267. *dp++ = *sp++;
  198268. *dp++ = *sp++;
  198269. }
  198270. }
  198271. row_info->pixel_depth = 24;
  198272. row_info->rowbytes = row_width * 3;
  198273. }
  198274. else /* if (row_info->bit_depth == 16) */
  198275. {
  198276. if (flags & PNG_FLAG_FILLER_AFTER)
  198277. {
  198278. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198279. sp += 8; dp += 6;
  198280. for (i = 1; i < row_width; i++)
  198281. {
  198282. /* This could be (although png_memcpy is probably slower):
  198283. png_memcpy(dp, sp, 6);
  198284. sp += 8;
  198285. dp += 6;
  198286. */
  198287. *dp++ = *sp++;
  198288. *dp++ = *sp++;
  198289. *dp++ = *sp++;
  198290. *dp++ = *sp++;
  198291. *dp++ = *sp++;
  198292. *dp++ = *sp++;
  198293. sp += 2;
  198294. }
  198295. }
  198296. else
  198297. {
  198298. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198299. for (i = 0; i < row_width; i++)
  198300. {
  198301. /* This could be (although png_memcpy is probably slower):
  198302. png_memcpy(dp, sp, 6);
  198303. sp += 8;
  198304. dp += 6;
  198305. */
  198306. sp+=2;
  198307. *dp++ = *sp++;
  198308. *dp++ = *sp++;
  198309. *dp++ = *sp++;
  198310. *dp++ = *sp++;
  198311. *dp++ = *sp++;
  198312. *dp++ = *sp++;
  198313. }
  198314. }
  198315. row_info->pixel_depth = 48;
  198316. row_info->rowbytes = row_width * 6;
  198317. }
  198318. row_info->channels = 3;
  198319. }
  198320. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198321. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198322. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198323. row_info->channels == 2)
  198324. {
  198325. if (row_info->bit_depth == 8)
  198326. {
  198327. /* This converts from GX or GA to G */
  198328. if (flags & PNG_FLAG_FILLER_AFTER)
  198329. {
  198330. for (i = 0; i < row_width; i++)
  198331. {
  198332. *dp++ = *sp++;
  198333. sp++;
  198334. }
  198335. }
  198336. /* This converts from XG or AG to G */
  198337. else
  198338. {
  198339. for (i = 0; i < row_width; i++)
  198340. {
  198341. sp++;
  198342. *dp++ = *sp++;
  198343. }
  198344. }
  198345. row_info->pixel_depth = 8;
  198346. row_info->rowbytes = row_width;
  198347. }
  198348. else /* if (row_info->bit_depth == 16) */
  198349. {
  198350. if (flags & PNG_FLAG_FILLER_AFTER)
  198351. {
  198352. /* This converts from GGXX or GGAA to GG */
  198353. sp += 4; dp += 2;
  198354. for (i = 1; i < row_width; i++)
  198355. {
  198356. *dp++ = *sp++;
  198357. *dp++ = *sp++;
  198358. sp += 2;
  198359. }
  198360. }
  198361. else
  198362. {
  198363. /* This converts from XXGG or AAGG to GG */
  198364. for (i = 0; i < row_width; i++)
  198365. {
  198366. sp += 2;
  198367. *dp++ = *sp++;
  198368. *dp++ = *sp++;
  198369. }
  198370. }
  198371. row_info->pixel_depth = 16;
  198372. row_info->rowbytes = row_width * 2;
  198373. }
  198374. row_info->channels = 1;
  198375. }
  198376. if (flags & PNG_FLAG_STRIP_ALPHA)
  198377. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198378. }
  198379. }
  198380. #endif
  198381. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198382. /* swaps red and blue bytes within a pixel */
  198383. void /* PRIVATE */
  198384. png_do_bgr(png_row_infop row_info, png_bytep row)
  198385. {
  198386. png_debug(1, "in png_do_bgr\n");
  198387. if (
  198388. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198389. row != NULL && row_info != NULL &&
  198390. #endif
  198391. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198392. {
  198393. png_uint_32 row_width = row_info->width;
  198394. if (row_info->bit_depth == 8)
  198395. {
  198396. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198397. {
  198398. png_bytep rp;
  198399. png_uint_32 i;
  198400. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198401. {
  198402. png_byte save = *rp;
  198403. *rp = *(rp + 2);
  198404. *(rp + 2) = save;
  198405. }
  198406. }
  198407. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198408. {
  198409. png_bytep rp;
  198410. png_uint_32 i;
  198411. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198412. {
  198413. png_byte save = *rp;
  198414. *rp = *(rp + 2);
  198415. *(rp + 2) = save;
  198416. }
  198417. }
  198418. }
  198419. else if (row_info->bit_depth == 16)
  198420. {
  198421. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198422. {
  198423. png_bytep rp;
  198424. png_uint_32 i;
  198425. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198426. {
  198427. png_byte save = *rp;
  198428. *rp = *(rp + 4);
  198429. *(rp + 4) = save;
  198430. save = *(rp + 1);
  198431. *(rp + 1) = *(rp + 5);
  198432. *(rp + 5) = save;
  198433. }
  198434. }
  198435. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198436. {
  198437. png_bytep rp;
  198438. png_uint_32 i;
  198439. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198440. {
  198441. png_byte save = *rp;
  198442. *rp = *(rp + 4);
  198443. *(rp + 4) = save;
  198444. save = *(rp + 1);
  198445. *(rp + 1) = *(rp + 5);
  198446. *(rp + 5) = save;
  198447. }
  198448. }
  198449. }
  198450. }
  198451. }
  198452. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198453. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198454. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198455. defined(PNG_LEGACY_SUPPORTED)
  198456. void PNGAPI
  198457. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198458. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198459. {
  198460. png_debug(1, "in png_set_user_transform_info\n");
  198461. if(png_ptr == NULL) return;
  198462. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198463. png_ptr->user_transform_ptr = user_transform_ptr;
  198464. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198465. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198466. #else
  198467. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198468. png_warning(png_ptr,
  198469. "This version of libpng does not support user transform info");
  198470. #endif
  198471. }
  198472. #endif
  198473. /* This function returns a pointer to the user_transform_ptr associated with
  198474. * the user transform functions. The application should free any memory
  198475. * associated with this pointer before png_write_destroy and png_read_destroy
  198476. * are called.
  198477. */
  198478. png_voidp PNGAPI
  198479. png_get_user_transform_ptr(png_structp png_ptr)
  198480. {
  198481. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198482. if (png_ptr == NULL) return (NULL);
  198483. return ((png_voidp)png_ptr->user_transform_ptr);
  198484. #else
  198485. return (NULL);
  198486. #endif
  198487. }
  198488. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198489. /*** End of inlined file: pngtrans.c ***/
  198490. /*** Start of inlined file: pngwio.c ***/
  198491. /* pngwio.c - functions for data output
  198492. *
  198493. * Last changed in libpng 1.2.13 November 13, 2006
  198494. * For conditions of distribution and use, see copyright notice in png.h
  198495. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198496. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198497. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198498. *
  198499. * This file provides a location for all output. Users who need
  198500. * special handling are expected to write functions that have the same
  198501. * arguments as these and perform similar functions, but that possibly
  198502. * use different output methods. Note that you shouldn't change these
  198503. * functions, but rather write replacement functions and then change
  198504. * them at run time with png_set_write_fn(...).
  198505. */
  198506. #define PNG_INTERNAL
  198507. #ifdef PNG_WRITE_SUPPORTED
  198508. /* Write the data to whatever output you are using. The default routine
  198509. writes to a file pointer. Note that this routine sometimes gets called
  198510. with very small lengths, so you should implement some kind of simple
  198511. buffering if you are using unbuffered writes. This should never be asked
  198512. to write more than 64K on a 16 bit machine. */
  198513. void /* PRIVATE */
  198514. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198515. {
  198516. if (png_ptr->write_data_fn != NULL )
  198517. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198518. else
  198519. png_error(png_ptr, "Call to NULL write function");
  198520. }
  198521. #if !defined(PNG_NO_STDIO)
  198522. /* This is the function that does the actual writing of data. If you are
  198523. not writing to a standard C stream, you should create a replacement
  198524. write_data function and use it at run time with png_set_write_fn(), rather
  198525. than changing the library. */
  198526. #ifndef USE_FAR_KEYWORD
  198527. void PNGAPI
  198528. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198529. {
  198530. png_uint_32 check;
  198531. if(png_ptr == NULL) return;
  198532. #if defined(_WIN32_WCE)
  198533. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198534. check = 0;
  198535. #else
  198536. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198537. #endif
  198538. if (check != length)
  198539. png_error(png_ptr, "Write Error");
  198540. }
  198541. #else
  198542. /* this is the model-independent version. Since the standard I/O library
  198543. can't handle far buffers in the medium and small models, we have to copy
  198544. the data.
  198545. */
  198546. #define NEAR_BUF_SIZE 1024
  198547. #define MIN(a,b) (a <= b ? a : b)
  198548. void PNGAPI
  198549. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198550. {
  198551. png_uint_32 check;
  198552. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198553. png_FILE_p io_ptr;
  198554. if(png_ptr == NULL) return;
  198555. /* Check if data really is near. If so, use usual code. */
  198556. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198557. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198558. if ((png_bytep)near_data == data)
  198559. {
  198560. #if defined(_WIN32_WCE)
  198561. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198562. check = 0;
  198563. #else
  198564. check = fwrite(near_data, 1, length, io_ptr);
  198565. #endif
  198566. }
  198567. else
  198568. {
  198569. png_byte buf[NEAR_BUF_SIZE];
  198570. png_size_t written, remaining, err;
  198571. check = 0;
  198572. remaining = length;
  198573. do
  198574. {
  198575. written = MIN(NEAR_BUF_SIZE, remaining);
  198576. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198577. #if defined(_WIN32_WCE)
  198578. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198579. err = 0;
  198580. #else
  198581. err = fwrite(buf, 1, written, io_ptr);
  198582. #endif
  198583. if (err != written)
  198584. break;
  198585. else
  198586. check += err;
  198587. data += written;
  198588. remaining -= written;
  198589. }
  198590. while (remaining != 0);
  198591. }
  198592. if (check != length)
  198593. png_error(png_ptr, "Write Error");
  198594. }
  198595. #endif
  198596. #endif
  198597. /* This function is called to output any data pending writing (normally
  198598. to disk). After png_flush is called, there should be no data pending
  198599. writing in any buffers. */
  198600. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198601. void /* PRIVATE */
  198602. png_flush(png_structp png_ptr)
  198603. {
  198604. if (png_ptr->output_flush_fn != NULL)
  198605. (*(png_ptr->output_flush_fn))(png_ptr);
  198606. }
  198607. #if !defined(PNG_NO_STDIO)
  198608. void PNGAPI
  198609. png_default_flush(png_structp png_ptr)
  198610. {
  198611. #if !defined(_WIN32_WCE)
  198612. png_FILE_p io_ptr;
  198613. #endif
  198614. if(png_ptr == NULL) return;
  198615. #if !defined(_WIN32_WCE)
  198616. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198617. if (io_ptr != NULL)
  198618. fflush(io_ptr);
  198619. #endif
  198620. }
  198621. #endif
  198622. #endif
  198623. /* This function allows the application to supply new output functions for
  198624. libpng if standard C streams aren't being used.
  198625. This function takes as its arguments:
  198626. png_ptr - pointer to a png output data structure
  198627. io_ptr - pointer to user supplied structure containing info about
  198628. the output functions. May be NULL.
  198629. write_data_fn - pointer to a new output function that takes as its
  198630. arguments a pointer to a png_struct, a pointer to
  198631. data to be written, and a 32-bit unsigned int that is
  198632. the number of bytes to be written. The new write
  198633. function should call png_error(png_ptr, "Error msg")
  198634. to exit and output any fatal error messages.
  198635. flush_data_fn - pointer to a new flush function that takes as its
  198636. arguments a pointer to a png_struct. After a call to
  198637. the flush function, there should be no data in any buffers
  198638. or pending transmission. If the output method doesn't do
  198639. any buffering of ouput, a function prototype must still be
  198640. supplied although it doesn't have to do anything. If
  198641. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198642. time, output_flush_fn will be ignored, although it must be
  198643. supplied for compatibility. */
  198644. void PNGAPI
  198645. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198646. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198647. {
  198648. if(png_ptr == NULL) return;
  198649. png_ptr->io_ptr = io_ptr;
  198650. #if !defined(PNG_NO_STDIO)
  198651. if (write_data_fn != NULL)
  198652. png_ptr->write_data_fn = write_data_fn;
  198653. else
  198654. png_ptr->write_data_fn = png_default_write_data;
  198655. #else
  198656. png_ptr->write_data_fn = write_data_fn;
  198657. #endif
  198658. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198659. #if !defined(PNG_NO_STDIO)
  198660. if (output_flush_fn != NULL)
  198661. png_ptr->output_flush_fn = output_flush_fn;
  198662. else
  198663. png_ptr->output_flush_fn = png_default_flush;
  198664. #else
  198665. png_ptr->output_flush_fn = output_flush_fn;
  198666. #endif
  198667. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198668. /* It is an error to read while writing a png file */
  198669. if (png_ptr->read_data_fn != NULL)
  198670. {
  198671. png_ptr->read_data_fn = NULL;
  198672. png_warning(png_ptr,
  198673. "Attempted to set both read_data_fn and write_data_fn in");
  198674. png_warning(png_ptr,
  198675. "the same structure. Resetting read_data_fn to NULL.");
  198676. }
  198677. }
  198678. #if defined(USE_FAR_KEYWORD)
  198679. #if defined(_MSC_VER)
  198680. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198681. {
  198682. void *near_ptr;
  198683. void FAR *far_ptr;
  198684. FP_OFF(near_ptr) = FP_OFF(ptr);
  198685. far_ptr = (void FAR *)near_ptr;
  198686. if(check != 0)
  198687. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198688. png_error(png_ptr,"segment lost in conversion");
  198689. return(near_ptr);
  198690. }
  198691. # else
  198692. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198693. {
  198694. void *near_ptr;
  198695. void FAR *far_ptr;
  198696. near_ptr = (void FAR *)ptr;
  198697. far_ptr = (void FAR *)near_ptr;
  198698. if(check != 0)
  198699. if(far_ptr != ptr)
  198700. png_error(png_ptr,"segment lost in conversion");
  198701. return(near_ptr);
  198702. }
  198703. # endif
  198704. # endif
  198705. #endif /* PNG_WRITE_SUPPORTED */
  198706. /*** End of inlined file: pngwio.c ***/
  198707. /*** Start of inlined file: pngwrite.c ***/
  198708. /* pngwrite.c - general routines to write a PNG file
  198709. *
  198710. * Last changed in libpng 1.2.15 January 5, 2007
  198711. * For conditions of distribution and use, see copyright notice in png.h
  198712. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198713. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198714. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198715. */
  198716. /* get internal access to png.h */
  198717. #define PNG_INTERNAL
  198718. #ifdef PNG_WRITE_SUPPORTED
  198719. /* Writes all the PNG information. This is the suggested way to use the
  198720. * library. If you have a new chunk to add, make a function to write it,
  198721. * and put it in the correct location here. If you want the chunk written
  198722. * after the image data, put it in png_write_end(). I strongly encourage
  198723. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198724. * the chunk, as that will keep the code from breaking if you want to just
  198725. * write a plain PNG file. If you have long comments, I suggest writing
  198726. * them in png_write_end(), and compressing them.
  198727. */
  198728. void PNGAPI
  198729. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198730. {
  198731. png_debug(1, "in png_write_info_before_PLTE\n");
  198732. if (png_ptr == NULL || info_ptr == NULL)
  198733. return;
  198734. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198735. {
  198736. png_write_sig(png_ptr); /* write PNG signature */
  198737. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198738. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198739. {
  198740. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198741. png_ptr->mng_features_permitted=0;
  198742. }
  198743. #endif
  198744. /* write IHDR information. */
  198745. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198746. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198747. info_ptr->filter_type,
  198748. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198749. info_ptr->interlace_type);
  198750. #else
  198751. 0);
  198752. #endif
  198753. /* the rest of these check to see if the valid field has the appropriate
  198754. flag set, and if it does, writes the chunk. */
  198755. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198756. if (info_ptr->valid & PNG_INFO_gAMA)
  198757. {
  198758. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198759. png_write_gAMA(png_ptr, info_ptr->gamma);
  198760. #else
  198761. #ifdef PNG_FIXED_POINT_SUPPORTED
  198762. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198763. # endif
  198764. #endif
  198765. }
  198766. #endif
  198767. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198768. if (info_ptr->valid & PNG_INFO_sRGB)
  198769. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198770. #endif
  198771. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198772. if (info_ptr->valid & PNG_INFO_iCCP)
  198773. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198774. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198775. #endif
  198776. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198777. if (info_ptr->valid & PNG_INFO_sBIT)
  198778. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198779. #endif
  198780. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198781. if (info_ptr->valid & PNG_INFO_cHRM)
  198782. {
  198783. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198784. png_write_cHRM(png_ptr,
  198785. info_ptr->x_white, info_ptr->y_white,
  198786. info_ptr->x_red, info_ptr->y_red,
  198787. info_ptr->x_green, info_ptr->y_green,
  198788. info_ptr->x_blue, info_ptr->y_blue);
  198789. #else
  198790. # ifdef PNG_FIXED_POINT_SUPPORTED
  198791. png_write_cHRM_fixed(png_ptr,
  198792. info_ptr->int_x_white, info_ptr->int_y_white,
  198793. info_ptr->int_x_red, info_ptr->int_y_red,
  198794. info_ptr->int_x_green, info_ptr->int_y_green,
  198795. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198796. # endif
  198797. #endif
  198798. }
  198799. #endif
  198800. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198801. if (info_ptr->unknown_chunks_num)
  198802. {
  198803. png_unknown_chunk *up;
  198804. png_debug(5, "writing extra chunks\n");
  198805. for (up = info_ptr->unknown_chunks;
  198806. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198807. up++)
  198808. {
  198809. int keep=png_handle_as_unknown(png_ptr, up->name);
  198810. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198811. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198812. !(up->location & PNG_HAVE_IDAT) &&
  198813. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198814. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198815. {
  198816. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198817. }
  198818. }
  198819. }
  198820. #endif
  198821. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198822. }
  198823. }
  198824. void PNGAPI
  198825. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198826. {
  198827. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198828. int i;
  198829. #endif
  198830. png_debug(1, "in png_write_info\n");
  198831. if (png_ptr == NULL || info_ptr == NULL)
  198832. return;
  198833. png_write_info_before_PLTE(png_ptr, info_ptr);
  198834. if (info_ptr->valid & PNG_INFO_PLTE)
  198835. png_write_PLTE(png_ptr, info_ptr->palette,
  198836. (png_uint_32)info_ptr->num_palette);
  198837. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198838. png_error(png_ptr, "Valid palette required for paletted images");
  198839. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198840. if (info_ptr->valid & PNG_INFO_tRNS)
  198841. {
  198842. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198843. /* invert the alpha channel (in tRNS) */
  198844. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198845. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198846. {
  198847. int j;
  198848. for (j=0; j<(int)info_ptr->num_trans; j++)
  198849. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198850. }
  198851. #endif
  198852. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198853. info_ptr->num_trans, info_ptr->color_type);
  198854. }
  198855. #endif
  198856. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198857. if (info_ptr->valid & PNG_INFO_bKGD)
  198858. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198859. #endif
  198860. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198861. if (info_ptr->valid & PNG_INFO_hIST)
  198862. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198863. #endif
  198864. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198865. if (info_ptr->valid & PNG_INFO_oFFs)
  198866. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198867. info_ptr->offset_unit_type);
  198868. #endif
  198869. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198870. if (info_ptr->valid & PNG_INFO_pCAL)
  198871. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198872. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198873. info_ptr->pcal_units, info_ptr->pcal_params);
  198874. #endif
  198875. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198876. if (info_ptr->valid & PNG_INFO_sCAL)
  198877. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198878. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198879. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198880. #else
  198881. #ifdef PNG_FIXED_POINT_SUPPORTED
  198882. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198883. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198884. #else
  198885. png_warning(png_ptr,
  198886. "png_write_sCAL not supported; sCAL chunk not written.");
  198887. #endif
  198888. #endif
  198889. #endif
  198890. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198891. if (info_ptr->valid & PNG_INFO_pHYs)
  198892. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198893. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198894. #endif
  198895. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198896. if (info_ptr->valid & PNG_INFO_tIME)
  198897. {
  198898. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198899. png_ptr->mode |= PNG_WROTE_tIME;
  198900. }
  198901. #endif
  198902. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198903. if (info_ptr->valid & PNG_INFO_sPLT)
  198904. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198905. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198906. #endif
  198907. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198908. /* Check to see if we need to write text chunks */
  198909. for (i = 0; i < info_ptr->num_text; i++)
  198910. {
  198911. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198912. info_ptr->text[i].compression);
  198913. /* an internationalized chunk? */
  198914. if (info_ptr->text[i].compression > 0)
  198915. {
  198916. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198917. /* write international chunk */
  198918. png_write_iTXt(png_ptr,
  198919. info_ptr->text[i].compression,
  198920. info_ptr->text[i].key,
  198921. info_ptr->text[i].lang,
  198922. info_ptr->text[i].lang_key,
  198923. info_ptr->text[i].text);
  198924. #else
  198925. png_warning(png_ptr, "Unable to write international text");
  198926. #endif
  198927. /* Mark this chunk as written */
  198928. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198929. }
  198930. /* If we want a compressed text chunk */
  198931. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198932. {
  198933. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198934. /* write compressed chunk */
  198935. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198936. info_ptr->text[i].text, 0,
  198937. info_ptr->text[i].compression);
  198938. #else
  198939. png_warning(png_ptr, "Unable to write compressed text");
  198940. #endif
  198941. /* Mark this chunk as written */
  198942. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198943. }
  198944. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198945. {
  198946. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198947. /* write uncompressed chunk */
  198948. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198949. info_ptr->text[i].text,
  198950. 0);
  198951. #else
  198952. png_warning(png_ptr, "Unable to write uncompressed text");
  198953. #endif
  198954. /* Mark this chunk as written */
  198955. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198956. }
  198957. }
  198958. #endif
  198959. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198960. if (info_ptr->unknown_chunks_num)
  198961. {
  198962. png_unknown_chunk *up;
  198963. png_debug(5, "writing extra chunks\n");
  198964. for (up = info_ptr->unknown_chunks;
  198965. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198966. up++)
  198967. {
  198968. int keep=png_handle_as_unknown(png_ptr, up->name);
  198969. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198970. up->location && (up->location & PNG_HAVE_PLTE) &&
  198971. !(up->location & PNG_HAVE_IDAT) &&
  198972. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198973. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198974. {
  198975. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198976. }
  198977. }
  198978. }
  198979. #endif
  198980. }
  198981. /* Writes the end of the PNG file. If you don't want to write comments or
  198982. * time information, you can pass NULL for info. If you already wrote these
  198983. * in png_write_info(), do not write them again here. If you have long
  198984. * comments, I suggest writing them here, and compressing them.
  198985. */
  198986. void PNGAPI
  198987. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198988. {
  198989. png_debug(1, "in png_write_end\n");
  198990. if (png_ptr == NULL)
  198991. return;
  198992. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198993. png_error(png_ptr, "No IDATs written into file");
  198994. /* see if user wants us to write information chunks */
  198995. if (info_ptr != NULL)
  198996. {
  198997. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198998. int i; /* local index variable */
  198999. #endif
  199000. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199001. /* check to see if user has supplied a time chunk */
  199002. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199003. !(png_ptr->mode & PNG_WROTE_tIME))
  199004. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199005. #endif
  199006. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199007. /* loop through comment chunks */
  199008. for (i = 0; i < info_ptr->num_text; i++)
  199009. {
  199010. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199011. info_ptr->text[i].compression);
  199012. /* an internationalized chunk? */
  199013. if (info_ptr->text[i].compression > 0)
  199014. {
  199015. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199016. /* write international chunk */
  199017. png_write_iTXt(png_ptr,
  199018. info_ptr->text[i].compression,
  199019. info_ptr->text[i].key,
  199020. info_ptr->text[i].lang,
  199021. info_ptr->text[i].lang_key,
  199022. info_ptr->text[i].text);
  199023. #else
  199024. png_warning(png_ptr, "Unable to write international text");
  199025. #endif
  199026. /* Mark this chunk as written */
  199027. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199028. }
  199029. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199030. {
  199031. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199032. /* write compressed chunk */
  199033. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199034. info_ptr->text[i].text, 0,
  199035. info_ptr->text[i].compression);
  199036. #else
  199037. png_warning(png_ptr, "Unable to write compressed text");
  199038. #endif
  199039. /* Mark this chunk as written */
  199040. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199041. }
  199042. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199043. {
  199044. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199045. /* write uncompressed chunk */
  199046. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199047. info_ptr->text[i].text, 0);
  199048. #else
  199049. png_warning(png_ptr, "Unable to write uncompressed text");
  199050. #endif
  199051. /* Mark this chunk as written */
  199052. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199053. }
  199054. }
  199055. #endif
  199056. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199057. if (info_ptr->unknown_chunks_num)
  199058. {
  199059. png_unknown_chunk *up;
  199060. png_debug(5, "writing extra chunks\n");
  199061. for (up = info_ptr->unknown_chunks;
  199062. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199063. up++)
  199064. {
  199065. int keep=png_handle_as_unknown(png_ptr, up->name);
  199066. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199067. up->location && (up->location & PNG_AFTER_IDAT) &&
  199068. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199069. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199070. {
  199071. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199072. }
  199073. }
  199074. }
  199075. #endif
  199076. }
  199077. png_ptr->mode |= PNG_AFTER_IDAT;
  199078. /* write end of PNG file */
  199079. png_write_IEND(png_ptr);
  199080. }
  199081. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199082. #if !defined(_WIN32_WCE)
  199083. /* "time.h" functions are not supported on WindowsCE */
  199084. void PNGAPI
  199085. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199086. {
  199087. png_debug(1, "in png_convert_from_struct_tm\n");
  199088. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199089. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199090. ptime->day = (png_byte)ttime->tm_mday;
  199091. ptime->hour = (png_byte)ttime->tm_hour;
  199092. ptime->minute = (png_byte)ttime->tm_min;
  199093. ptime->second = (png_byte)ttime->tm_sec;
  199094. }
  199095. void PNGAPI
  199096. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199097. {
  199098. struct tm *tbuf;
  199099. png_debug(1, "in png_convert_from_time_t\n");
  199100. tbuf = gmtime(&ttime);
  199101. png_convert_from_struct_tm(ptime, tbuf);
  199102. }
  199103. #endif
  199104. #endif
  199105. /* Initialize png_ptr structure, and allocate any memory needed */
  199106. png_structp PNGAPI
  199107. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199108. png_error_ptr error_fn, png_error_ptr warn_fn)
  199109. {
  199110. #ifdef PNG_USER_MEM_SUPPORTED
  199111. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199112. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199113. }
  199114. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199115. png_structp PNGAPI
  199116. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199117. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199118. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199119. {
  199120. #endif /* PNG_USER_MEM_SUPPORTED */
  199121. png_structp png_ptr;
  199122. #ifdef PNG_SETJMP_SUPPORTED
  199123. #ifdef USE_FAR_KEYWORD
  199124. jmp_buf jmpbuf;
  199125. #endif
  199126. #endif
  199127. int i;
  199128. png_debug(1, "in png_create_write_struct\n");
  199129. #ifdef PNG_USER_MEM_SUPPORTED
  199130. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199131. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199132. #else
  199133. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199134. #endif /* PNG_USER_MEM_SUPPORTED */
  199135. if (png_ptr == NULL)
  199136. return (NULL);
  199137. /* added at libpng-1.2.6 */
  199138. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199139. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199140. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199141. #endif
  199142. #ifdef PNG_SETJMP_SUPPORTED
  199143. #ifdef USE_FAR_KEYWORD
  199144. if (setjmp(jmpbuf))
  199145. #else
  199146. if (setjmp(png_ptr->jmpbuf))
  199147. #endif
  199148. {
  199149. png_free(png_ptr, png_ptr->zbuf);
  199150. png_ptr->zbuf=NULL;
  199151. png_destroy_struct(png_ptr);
  199152. return (NULL);
  199153. }
  199154. #ifdef USE_FAR_KEYWORD
  199155. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199156. #endif
  199157. #endif
  199158. #ifdef PNG_USER_MEM_SUPPORTED
  199159. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199160. #endif /* PNG_USER_MEM_SUPPORTED */
  199161. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199162. i=0;
  199163. do
  199164. {
  199165. if(user_png_ver[i] != png_libpng_ver[i])
  199166. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199167. } while (png_libpng_ver[i++]);
  199168. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199169. {
  199170. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199171. * we must recompile any applications that use any older library version.
  199172. * For versions after libpng 1.0, we will be compatible, so we need
  199173. * only check the first digit.
  199174. */
  199175. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199176. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199177. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199178. {
  199179. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199180. char msg[80];
  199181. if (user_png_ver)
  199182. {
  199183. png_snprintf(msg, 80,
  199184. "Application was compiled with png.h from libpng-%.20s",
  199185. user_png_ver);
  199186. png_warning(png_ptr, msg);
  199187. }
  199188. png_snprintf(msg, 80,
  199189. "Application is running with png.c from libpng-%.20s",
  199190. png_libpng_ver);
  199191. png_warning(png_ptr, msg);
  199192. #endif
  199193. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199194. png_ptr->flags=0;
  199195. #endif
  199196. png_error(png_ptr,
  199197. "Incompatible libpng version in application and library");
  199198. }
  199199. }
  199200. /* initialize zbuf - compression buffer */
  199201. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199202. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199203. (png_uint_32)png_ptr->zbuf_size);
  199204. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199205. png_flush_ptr_NULL);
  199206. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199207. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199208. 1, png_doublep_NULL, png_doublep_NULL);
  199209. #endif
  199210. #ifdef PNG_SETJMP_SUPPORTED
  199211. /* Applications that neglect to set up their own setjmp() and then encounter
  199212. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199213. abort instead of returning. */
  199214. #ifdef USE_FAR_KEYWORD
  199215. if (setjmp(jmpbuf))
  199216. PNG_ABORT();
  199217. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199218. #else
  199219. if (setjmp(png_ptr->jmpbuf))
  199220. PNG_ABORT();
  199221. #endif
  199222. #endif
  199223. return (png_ptr);
  199224. }
  199225. /* Initialize png_ptr structure, and allocate any memory needed */
  199226. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199227. /* Deprecated. */
  199228. #undef png_write_init
  199229. void PNGAPI
  199230. png_write_init(png_structp png_ptr)
  199231. {
  199232. /* We only come here via pre-1.0.7-compiled applications */
  199233. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199234. }
  199235. void PNGAPI
  199236. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199237. png_size_t png_struct_size, png_size_t png_info_size)
  199238. {
  199239. /* We only come here via pre-1.0.12-compiled applications */
  199240. if(png_ptr == NULL) return;
  199241. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199242. if(png_sizeof(png_struct) > png_struct_size ||
  199243. png_sizeof(png_info) > png_info_size)
  199244. {
  199245. char msg[80];
  199246. png_ptr->warning_fn=NULL;
  199247. if (user_png_ver)
  199248. {
  199249. png_snprintf(msg, 80,
  199250. "Application was compiled with png.h from libpng-%.20s",
  199251. user_png_ver);
  199252. png_warning(png_ptr, msg);
  199253. }
  199254. png_snprintf(msg, 80,
  199255. "Application is running with png.c from libpng-%.20s",
  199256. png_libpng_ver);
  199257. png_warning(png_ptr, msg);
  199258. }
  199259. #endif
  199260. if(png_sizeof(png_struct) > png_struct_size)
  199261. {
  199262. png_ptr->error_fn=NULL;
  199263. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199264. png_ptr->flags=0;
  199265. #endif
  199266. png_error(png_ptr,
  199267. "The png struct allocated by the application for writing is too small.");
  199268. }
  199269. if(png_sizeof(png_info) > png_info_size)
  199270. {
  199271. png_ptr->error_fn=NULL;
  199272. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199273. png_ptr->flags=0;
  199274. #endif
  199275. png_error(png_ptr,
  199276. "The info struct allocated by the application for writing is too small.");
  199277. }
  199278. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199279. }
  199280. #endif /* PNG_1_0_X || PNG_1_2_X */
  199281. void PNGAPI
  199282. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199283. png_size_t png_struct_size)
  199284. {
  199285. png_structp png_ptr=*ptr_ptr;
  199286. #ifdef PNG_SETJMP_SUPPORTED
  199287. jmp_buf tmp_jmp; /* to save current jump buffer */
  199288. #endif
  199289. int i = 0;
  199290. if (png_ptr == NULL)
  199291. return;
  199292. do
  199293. {
  199294. if (user_png_ver[i] != png_libpng_ver[i])
  199295. {
  199296. #ifdef PNG_LEGACY_SUPPORTED
  199297. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199298. #else
  199299. png_ptr->warning_fn=NULL;
  199300. png_warning(png_ptr,
  199301. "Application uses deprecated png_write_init() and should be recompiled.");
  199302. break;
  199303. #endif
  199304. }
  199305. } while (png_libpng_ver[i++]);
  199306. png_debug(1, "in png_write_init_3\n");
  199307. #ifdef PNG_SETJMP_SUPPORTED
  199308. /* save jump buffer and error functions */
  199309. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199310. #endif
  199311. if (png_sizeof(png_struct) > png_struct_size)
  199312. {
  199313. png_destroy_struct(png_ptr);
  199314. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199315. *ptr_ptr = png_ptr;
  199316. }
  199317. /* reset all variables to 0 */
  199318. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199319. /* added at libpng-1.2.6 */
  199320. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199321. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199322. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199323. #endif
  199324. #ifdef PNG_SETJMP_SUPPORTED
  199325. /* restore jump buffer */
  199326. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199327. #endif
  199328. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199329. png_flush_ptr_NULL);
  199330. /* initialize zbuf - compression buffer */
  199331. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199332. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199333. (png_uint_32)png_ptr->zbuf_size);
  199334. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199335. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199336. 1, png_doublep_NULL, png_doublep_NULL);
  199337. #endif
  199338. }
  199339. /* Write a few rows of image data. If the image is interlaced,
  199340. * either you will have to write the 7 sub images, or, if you
  199341. * have called png_set_interlace_handling(), you will have to
  199342. * "write" the image seven times.
  199343. */
  199344. void PNGAPI
  199345. png_write_rows(png_structp png_ptr, png_bytepp row,
  199346. png_uint_32 num_rows)
  199347. {
  199348. png_uint_32 i; /* row counter */
  199349. png_bytepp rp; /* row pointer */
  199350. png_debug(1, "in png_write_rows\n");
  199351. if (png_ptr == NULL)
  199352. return;
  199353. /* loop through the rows */
  199354. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199355. {
  199356. png_write_row(png_ptr, *rp);
  199357. }
  199358. }
  199359. /* Write the image. You only need to call this function once, even
  199360. * if you are writing an interlaced image.
  199361. */
  199362. void PNGAPI
  199363. png_write_image(png_structp png_ptr, png_bytepp image)
  199364. {
  199365. png_uint_32 i; /* row index */
  199366. int pass, num_pass; /* pass variables */
  199367. png_bytepp rp; /* points to current row */
  199368. if (png_ptr == NULL)
  199369. return;
  199370. png_debug(1, "in png_write_image\n");
  199371. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199372. /* intialize interlace handling. If image is not interlaced,
  199373. this will set pass to 1 */
  199374. num_pass = png_set_interlace_handling(png_ptr);
  199375. #else
  199376. num_pass = 1;
  199377. #endif
  199378. /* loop through passes */
  199379. for (pass = 0; pass < num_pass; pass++)
  199380. {
  199381. /* loop through image */
  199382. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199383. {
  199384. png_write_row(png_ptr, *rp);
  199385. }
  199386. }
  199387. }
  199388. /* called by user to write a row of image data */
  199389. void PNGAPI
  199390. png_write_row(png_structp png_ptr, png_bytep row)
  199391. {
  199392. if (png_ptr == NULL)
  199393. return;
  199394. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199395. png_ptr->row_number, png_ptr->pass);
  199396. /* initialize transformations and other stuff if first time */
  199397. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199398. {
  199399. /* make sure we wrote the header info */
  199400. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199401. png_error(png_ptr,
  199402. "png_write_info was never called before png_write_row.");
  199403. /* check for transforms that have been set but were defined out */
  199404. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199405. if (png_ptr->transformations & PNG_INVERT_MONO)
  199406. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199407. #endif
  199408. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199409. if (png_ptr->transformations & PNG_FILLER)
  199410. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199411. #endif
  199412. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199413. if (png_ptr->transformations & PNG_PACKSWAP)
  199414. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199415. #endif
  199416. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199417. if (png_ptr->transformations & PNG_PACK)
  199418. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199419. #endif
  199420. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199421. if (png_ptr->transformations & PNG_SHIFT)
  199422. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199423. #endif
  199424. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199425. if (png_ptr->transformations & PNG_BGR)
  199426. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199427. #endif
  199428. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199429. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199430. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199431. #endif
  199432. png_write_start_row(png_ptr);
  199433. }
  199434. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199435. /* if interlaced and not interested in row, return */
  199436. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199437. {
  199438. switch (png_ptr->pass)
  199439. {
  199440. case 0:
  199441. if (png_ptr->row_number & 0x07)
  199442. {
  199443. png_write_finish_row(png_ptr);
  199444. return;
  199445. }
  199446. break;
  199447. case 1:
  199448. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199449. {
  199450. png_write_finish_row(png_ptr);
  199451. return;
  199452. }
  199453. break;
  199454. case 2:
  199455. if ((png_ptr->row_number & 0x07) != 4)
  199456. {
  199457. png_write_finish_row(png_ptr);
  199458. return;
  199459. }
  199460. break;
  199461. case 3:
  199462. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199463. {
  199464. png_write_finish_row(png_ptr);
  199465. return;
  199466. }
  199467. break;
  199468. case 4:
  199469. if ((png_ptr->row_number & 0x03) != 2)
  199470. {
  199471. png_write_finish_row(png_ptr);
  199472. return;
  199473. }
  199474. break;
  199475. case 5:
  199476. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199477. {
  199478. png_write_finish_row(png_ptr);
  199479. return;
  199480. }
  199481. break;
  199482. case 6:
  199483. if (!(png_ptr->row_number & 0x01))
  199484. {
  199485. png_write_finish_row(png_ptr);
  199486. return;
  199487. }
  199488. break;
  199489. }
  199490. }
  199491. #endif
  199492. /* set up row info for transformations */
  199493. png_ptr->row_info.color_type = png_ptr->color_type;
  199494. png_ptr->row_info.width = png_ptr->usr_width;
  199495. png_ptr->row_info.channels = png_ptr->usr_channels;
  199496. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199497. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199498. png_ptr->row_info.channels);
  199499. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199500. png_ptr->row_info.width);
  199501. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199502. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199503. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199504. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199505. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199506. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199507. /* Copy user's row into buffer, leaving room for filter byte. */
  199508. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199509. png_ptr->row_info.rowbytes);
  199510. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199511. /* handle interlacing */
  199512. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199513. (png_ptr->transformations & PNG_INTERLACE))
  199514. {
  199515. png_do_write_interlace(&(png_ptr->row_info),
  199516. png_ptr->row_buf + 1, png_ptr->pass);
  199517. /* this should always get caught above, but still ... */
  199518. if (!(png_ptr->row_info.width))
  199519. {
  199520. png_write_finish_row(png_ptr);
  199521. return;
  199522. }
  199523. }
  199524. #endif
  199525. /* handle other transformations */
  199526. if (png_ptr->transformations)
  199527. png_do_write_transformations(png_ptr);
  199528. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199529. /* Write filter_method 64 (intrapixel differencing) only if
  199530. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199531. * 2. Libpng did not write a PNG signature (this filter_method is only
  199532. * used in PNG datastreams that are embedded in MNG datastreams) and
  199533. * 3. The application called png_permit_mng_features with a mask that
  199534. * included PNG_FLAG_MNG_FILTER_64 and
  199535. * 4. The filter_method is 64 and
  199536. * 5. The color_type is RGB or RGBA
  199537. */
  199538. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199539. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199540. {
  199541. /* Intrapixel differencing */
  199542. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199543. }
  199544. #endif
  199545. /* Find a filter if necessary, filter the row and write it out. */
  199546. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199547. if (png_ptr->write_row_fn != NULL)
  199548. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199549. }
  199550. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199551. /* Set the automatic flush interval or 0 to turn flushing off */
  199552. void PNGAPI
  199553. png_set_flush(png_structp png_ptr, int nrows)
  199554. {
  199555. png_debug(1, "in png_set_flush\n");
  199556. if (png_ptr == NULL)
  199557. return;
  199558. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199559. }
  199560. /* flush the current output buffers now */
  199561. void PNGAPI
  199562. png_write_flush(png_structp png_ptr)
  199563. {
  199564. int wrote_IDAT;
  199565. png_debug(1, "in png_write_flush\n");
  199566. if (png_ptr == NULL)
  199567. return;
  199568. /* We have already written out all of the data */
  199569. if (png_ptr->row_number >= png_ptr->num_rows)
  199570. return;
  199571. do
  199572. {
  199573. int ret;
  199574. /* compress the data */
  199575. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199576. wrote_IDAT = 0;
  199577. /* check for compression errors */
  199578. if (ret != Z_OK)
  199579. {
  199580. if (png_ptr->zstream.msg != NULL)
  199581. png_error(png_ptr, png_ptr->zstream.msg);
  199582. else
  199583. png_error(png_ptr, "zlib error");
  199584. }
  199585. if (!(png_ptr->zstream.avail_out))
  199586. {
  199587. /* write the IDAT and reset the zlib output buffer */
  199588. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199589. png_ptr->zbuf_size);
  199590. png_ptr->zstream.next_out = png_ptr->zbuf;
  199591. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199592. wrote_IDAT = 1;
  199593. }
  199594. } while(wrote_IDAT == 1);
  199595. /* If there is any data left to be output, write it into a new IDAT */
  199596. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199597. {
  199598. /* write the IDAT and reset the zlib output buffer */
  199599. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199600. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199601. png_ptr->zstream.next_out = png_ptr->zbuf;
  199602. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199603. }
  199604. png_ptr->flush_rows = 0;
  199605. png_flush(png_ptr);
  199606. }
  199607. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199608. /* free all memory used by the write */
  199609. void PNGAPI
  199610. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199611. {
  199612. png_structp png_ptr = NULL;
  199613. png_infop info_ptr = NULL;
  199614. #ifdef PNG_USER_MEM_SUPPORTED
  199615. png_free_ptr free_fn = NULL;
  199616. png_voidp mem_ptr = NULL;
  199617. #endif
  199618. png_debug(1, "in png_destroy_write_struct\n");
  199619. if (png_ptr_ptr != NULL)
  199620. {
  199621. png_ptr = *png_ptr_ptr;
  199622. #ifdef PNG_USER_MEM_SUPPORTED
  199623. free_fn = png_ptr->free_fn;
  199624. mem_ptr = png_ptr->mem_ptr;
  199625. #endif
  199626. }
  199627. if (info_ptr_ptr != NULL)
  199628. info_ptr = *info_ptr_ptr;
  199629. if (info_ptr != NULL)
  199630. {
  199631. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199632. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199633. if (png_ptr->num_chunk_list)
  199634. {
  199635. png_free(png_ptr, png_ptr->chunk_list);
  199636. png_ptr->chunk_list=NULL;
  199637. png_ptr->num_chunk_list=0;
  199638. }
  199639. #endif
  199640. #ifdef PNG_USER_MEM_SUPPORTED
  199641. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199642. (png_voidp)mem_ptr);
  199643. #else
  199644. png_destroy_struct((png_voidp)info_ptr);
  199645. #endif
  199646. *info_ptr_ptr = NULL;
  199647. }
  199648. if (png_ptr != NULL)
  199649. {
  199650. png_write_destroy(png_ptr);
  199651. #ifdef PNG_USER_MEM_SUPPORTED
  199652. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199653. (png_voidp)mem_ptr);
  199654. #else
  199655. png_destroy_struct((png_voidp)png_ptr);
  199656. #endif
  199657. *png_ptr_ptr = NULL;
  199658. }
  199659. }
  199660. /* Free any memory used in png_ptr struct (old method) */
  199661. void /* PRIVATE */
  199662. png_write_destroy(png_structp png_ptr)
  199663. {
  199664. #ifdef PNG_SETJMP_SUPPORTED
  199665. jmp_buf tmp_jmp; /* save jump buffer */
  199666. #endif
  199667. png_error_ptr error_fn;
  199668. png_error_ptr warning_fn;
  199669. png_voidp error_ptr;
  199670. #ifdef PNG_USER_MEM_SUPPORTED
  199671. png_free_ptr free_fn;
  199672. #endif
  199673. png_debug(1, "in png_write_destroy\n");
  199674. /* free any memory zlib uses */
  199675. deflateEnd(&png_ptr->zstream);
  199676. /* free our memory. png_free checks NULL for us. */
  199677. png_free(png_ptr, png_ptr->zbuf);
  199678. png_free(png_ptr, png_ptr->row_buf);
  199679. png_free(png_ptr, png_ptr->prev_row);
  199680. png_free(png_ptr, png_ptr->sub_row);
  199681. png_free(png_ptr, png_ptr->up_row);
  199682. png_free(png_ptr, png_ptr->avg_row);
  199683. png_free(png_ptr, png_ptr->paeth_row);
  199684. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199685. png_free(png_ptr, png_ptr->time_buffer);
  199686. #endif
  199687. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199688. png_free(png_ptr, png_ptr->prev_filters);
  199689. png_free(png_ptr, png_ptr->filter_weights);
  199690. png_free(png_ptr, png_ptr->inv_filter_weights);
  199691. png_free(png_ptr, png_ptr->filter_costs);
  199692. png_free(png_ptr, png_ptr->inv_filter_costs);
  199693. #endif
  199694. #ifdef PNG_SETJMP_SUPPORTED
  199695. /* reset structure */
  199696. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199697. #endif
  199698. error_fn = png_ptr->error_fn;
  199699. warning_fn = png_ptr->warning_fn;
  199700. error_ptr = png_ptr->error_ptr;
  199701. #ifdef PNG_USER_MEM_SUPPORTED
  199702. free_fn = png_ptr->free_fn;
  199703. #endif
  199704. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199705. png_ptr->error_fn = error_fn;
  199706. png_ptr->warning_fn = warning_fn;
  199707. png_ptr->error_ptr = error_ptr;
  199708. #ifdef PNG_USER_MEM_SUPPORTED
  199709. png_ptr->free_fn = free_fn;
  199710. #endif
  199711. #ifdef PNG_SETJMP_SUPPORTED
  199712. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199713. #endif
  199714. }
  199715. /* Allow the application to select one or more row filters to use. */
  199716. void PNGAPI
  199717. png_set_filter(png_structp png_ptr, int method, int filters)
  199718. {
  199719. png_debug(1, "in png_set_filter\n");
  199720. if (png_ptr == NULL)
  199721. return;
  199722. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199723. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199724. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199725. method = PNG_FILTER_TYPE_BASE;
  199726. #endif
  199727. if (method == PNG_FILTER_TYPE_BASE)
  199728. {
  199729. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199730. {
  199731. #ifndef PNG_NO_WRITE_FILTER
  199732. case 5:
  199733. case 6:
  199734. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199735. #endif /* PNG_NO_WRITE_FILTER */
  199736. case PNG_FILTER_VALUE_NONE:
  199737. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199738. #ifndef PNG_NO_WRITE_FILTER
  199739. case PNG_FILTER_VALUE_SUB:
  199740. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199741. case PNG_FILTER_VALUE_UP:
  199742. png_ptr->do_filter=PNG_FILTER_UP; break;
  199743. case PNG_FILTER_VALUE_AVG:
  199744. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199745. case PNG_FILTER_VALUE_PAETH:
  199746. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199747. default: png_ptr->do_filter = (png_byte)filters; break;
  199748. #else
  199749. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199750. #endif /* PNG_NO_WRITE_FILTER */
  199751. }
  199752. /* If we have allocated the row_buf, this means we have already started
  199753. * with the image and we should have allocated all of the filter buffers
  199754. * that have been selected. If prev_row isn't already allocated, then
  199755. * it is too late to start using the filters that need it, since we
  199756. * will be missing the data in the previous row. If an application
  199757. * wants to start and stop using particular filters during compression,
  199758. * it should start out with all of the filters, and then add and
  199759. * remove them after the start of compression.
  199760. */
  199761. if (png_ptr->row_buf != NULL)
  199762. {
  199763. #ifndef PNG_NO_WRITE_FILTER
  199764. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199765. {
  199766. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199767. (png_ptr->rowbytes + 1));
  199768. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199769. }
  199770. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199771. {
  199772. if (png_ptr->prev_row == NULL)
  199773. {
  199774. png_warning(png_ptr, "Can't add Up filter after starting");
  199775. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199776. }
  199777. else
  199778. {
  199779. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199780. (png_ptr->rowbytes + 1));
  199781. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199782. }
  199783. }
  199784. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199785. {
  199786. if (png_ptr->prev_row == NULL)
  199787. {
  199788. png_warning(png_ptr, "Can't add Average filter after starting");
  199789. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199790. }
  199791. else
  199792. {
  199793. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199794. (png_ptr->rowbytes + 1));
  199795. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199796. }
  199797. }
  199798. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199799. png_ptr->paeth_row == NULL)
  199800. {
  199801. if (png_ptr->prev_row == NULL)
  199802. {
  199803. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199804. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199805. }
  199806. else
  199807. {
  199808. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199809. (png_ptr->rowbytes + 1));
  199810. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199811. }
  199812. }
  199813. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199814. #endif /* PNG_NO_WRITE_FILTER */
  199815. png_ptr->do_filter = PNG_FILTER_NONE;
  199816. }
  199817. }
  199818. else
  199819. png_error(png_ptr, "Unknown custom filter method");
  199820. }
  199821. /* This allows us to influence the way in which libpng chooses the "best"
  199822. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199823. * differences metric is relatively fast and effective, there is some
  199824. * question as to whether it can be improved upon by trying to keep the
  199825. * filtered data going to zlib more consistent, hopefully resulting in
  199826. * better compression.
  199827. */
  199828. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199829. void PNGAPI
  199830. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199831. int num_weights, png_doublep filter_weights,
  199832. png_doublep filter_costs)
  199833. {
  199834. int i;
  199835. png_debug(1, "in png_set_filter_heuristics\n");
  199836. if (png_ptr == NULL)
  199837. return;
  199838. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199839. {
  199840. png_warning(png_ptr, "Unknown filter heuristic method");
  199841. return;
  199842. }
  199843. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199844. {
  199845. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199846. }
  199847. if (num_weights < 0 || filter_weights == NULL ||
  199848. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199849. {
  199850. num_weights = 0;
  199851. }
  199852. png_ptr->num_prev_filters = (png_byte)num_weights;
  199853. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199854. if (num_weights > 0)
  199855. {
  199856. if (png_ptr->prev_filters == NULL)
  199857. {
  199858. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199859. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199860. /* To make sure that the weighting starts out fairly */
  199861. for (i = 0; i < num_weights; i++)
  199862. {
  199863. png_ptr->prev_filters[i] = 255;
  199864. }
  199865. }
  199866. if (png_ptr->filter_weights == NULL)
  199867. {
  199868. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199869. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199870. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199871. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199872. for (i = 0; i < num_weights; i++)
  199873. {
  199874. png_ptr->inv_filter_weights[i] =
  199875. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199876. }
  199877. }
  199878. for (i = 0; i < num_weights; i++)
  199879. {
  199880. if (filter_weights[i] < 0.0)
  199881. {
  199882. png_ptr->inv_filter_weights[i] =
  199883. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199884. }
  199885. else
  199886. {
  199887. png_ptr->inv_filter_weights[i] =
  199888. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199889. png_ptr->filter_weights[i] =
  199890. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199891. }
  199892. }
  199893. }
  199894. /* If, in the future, there are other filter methods, this would
  199895. * need to be based on png_ptr->filter.
  199896. */
  199897. if (png_ptr->filter_costs == NULL)
  199898. {
  199899. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199900. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199901. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199902. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199903. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199904. {
  199905. png_ptr->inv_filter_costs[i] =
  199906. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199907. }
  199908. }
  199909. /* Here is where we set the relative costs of the different filters. We
  199910. * should take the desired compression level into account when setting
  199911. * the costs, so that Paeth, for instance, has a high relative cost at low
  199912. * compression levels, while it has a lower relative cost at higher
  199913. * compression settings. The filter types are in order of increasing
  199914. * relative cost, so it would be possible to do this with an algorithm.
  199915. */
  199916. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199917. {
  199918. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199919. {
  199920. png_ptr->inv_filter_costs[i] =
  199921. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199922. }
  199923. else if (filter_costs[i] >= 1.0)
  199924. {
  199925. png_ptr->inv_filter_costs[i] =
  199926. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199927. png_ptr->filter_costs[i] =
  199928. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199929. }
  199930. }
  199931. }
  199932. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199933. void PNGAPI
  199934. png_set_compression_level(png_structp png_ptr, int level)
  199935. {
  199936. png_debug(1, "in png_set_compression_level\n");
  199937. if (png_ptr == NULL)
  199938. return;
  199939. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199940. png_ptr->zlib_level = level;
  199941. }
  199942. void PNGAPI
  199943. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199944. {
  199945. png_debug(1, "in png_set_compression_mem_level\n");
  199946. if (png_ptr == NULL)
  199947. return;
  199948. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199949. png_ptr->zlib_mem_level = mem_level;
  199950. }
  199951. void PNGAPI
  199952. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199953. {
  199954. png_debug(1, "in png_set_compression_strategy\n");
  199955. if (png_ptr == NULL)
  199956. return;
  199957. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199958. png_ptr->zlib_strategy = strategy;
  199959. }
  199960. void PNGAPI
  199961. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199962. {
  199963. if (png_ptr == NULL)
  199964. return;
  199965. if (window_bits > 15)
  199966. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199967. else if (window_bits < 8)
  199968. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199969. #ifndef WBITS_8_OK
  199970. /* avoid libpng bug with 256-byte windows */
  199971. if (window_bits == 8)
  199972. {
  199973. png_warning(png_ptr, "Compression window is being reset to 512");
  199974. window_bits=9;
  199975. }
  199976. #endif
  199977. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199978. png_ptr->zlib_window_bits = window_bits;
  199979. }
  199980. void PNGAPI
  199981. png_set_compression_method(png_structp png_ptr, int method)
  199982. {
  199983. png_debug(1, "in png_set_compression_method\n");
  199984. if (png_ptr == NULL)
  199985. return;
  199986. if (method != 8)
  199987. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199988. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199989. png_ptr->zlib_method = method;
  199990. }
  199991. void PNGAPI
  199992. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199993. {
  199994. if (png_ptr == NULL)
  199995. return;
  199996. png_ptr->write_row_fn = write_row_fn;
  199997. }
  199998. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199999. void PNGAPI
  200000. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200001. write_user_transform_fn)
  200002. {
  200003. png_debug(1, "in png_set_write_user_transform_fn\n");
  200004. if (png_ptr == NULL)
  200005. return;
  200006. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200007. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200008. }
  200009. #endif
  200010. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200011. void PNGAPI
  200012. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200013. int transforms, voidp params)
  200014. {
  200015. if (png_ptr == NULL || info_ptr == NULL)
  200016. return;
  200017. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200018. /* invert the alpha channel from opacity to transparency */
  200019. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200020. png_set_invert_alpha(png_ptr);
  200021. #endif
  200022. /* Write the file header information. */
  200023. png_write_info(png_ptr, info_ptr);
  200024. /* ------ these transformations don't touch the info structure ------- */
  200025. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200026. /* invert monochrome pixels */
  200027. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200028. png_set_invert_mono(png_ptr);
  200029. #endif
  200030. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200031. /* Shift the pixels up to a legal bit depth and fill in
  200032. * as appropriate to correctly scale the image.
  200033. */
  200034. if ((transforms & PNG_TRANSFORM_SHIFT)
  200035. && (info_ptr->valid & PNG_INFO_sBIT))
  200036. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200037. #endif
  200038. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200039. /* pack pixels into bytes */
  200040. if (transforms & PNG_TRANSFORM_PACKING)
  200041. png_set_packing(png_ptr);
  200042. #endif
  200043. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200044. /* swap location of alpha bytes from ARGB to RGBA */
  200045. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200046. png_set_swap_alpha(png_ptr);
  200047. #endif
  200048. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200049. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200050. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200051. */
  200052. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200053. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200054. #endif
  200055. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200056. /* flip BGR pixels to RGB */
  200057. if (transforms & PNG_TRANSFORM_BGR)
  200058. png_set_bgr(png_ptr);
  200059. #endif
  200060. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200061. /* swap bytes of 16-bit files to most significant byte first */
  200062. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200063. png_set_swap(png_ptr);
  200064. #endif
  200065. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200066. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200067. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200068. png_set_packswap(png_ptr);
  200069. #endif
  200070. /* ----------------------- end of transformations ------------------- */
  200071. /* write the bits */
  200072. if (info_ptr->valid & PNG_INFO_IDAT)
  200073. png_write_image(png_ptr, info_ptr->row_pointers);
  200074. /* It is REQUIRED to call this to finish writing the rest of the file */
  200075. png_write_end(png_ptr, info_ptr);
  200076. transforms = transforms; /* quiet compiler warnings */
  200077. params = params;
  200078. }
  200079. #endif
  200080. #endif /* PNG_WRITE_SUPPORTED */
  200081. /*** End of inlined file: pngwrite.c ***/
  200082. /*** Start of inlined file: pngwtran.c ***/
  200083. /* pngwtran.c - transforms the data in a row for PNG writers
  200084. *
  200085. * Last changed in libpng 1.2.9 April 14, 2006
  200086. * For conditions of distribution and use, see copyright notice in png.h
  200087. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200088. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200089. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200090. */
  200091. #define PNG_INTERNAL
  200092. #ifdef PNG_WRITE_SUPPORTED
  200093. /* Transform the data according to the user's wishes. The order of
  200094. * transformations is significant.
  200095. */
  200096. void /* PRIVATE */
  200097. png_do_write_transformations(png_structp png_ptr)
  200098. {
  200099. png_debug(1, "in png_do_write_transformations\n");
  200100. if (png_ptr == NULL)
  200101. return;
  200102. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200103. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200104. if(png_ptr->write_user_transform_fn != NULL)
  200105. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200106. (png_ptr, /* png_ptr */
  200107. &(png_ptr->row_info), /* row_info: */
  200108. /* png_uint_32 width; width of row */
  200109. /* png_uint_32 rowbytes; number of bytes in row */
  200110. /* png_byte color_type; color type of pixels */
  200111. /* png_byte bit_depth; bit depth of samples */
  200112. /* png_byte channels; number of channels (1-4) */
  200113. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200114. png_ptr->row_buf + 1); /* start of pixel data for row */
  200115. #endif
  200116. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200117. if (png_ptr->transformations & PNG_FILLER)
  200118. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200119. png_ptr->flags);
  200120. #endif
  200121. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200122. if (png_ptr->transformations & PNG_PACKSWAP)
  200123. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200124. #endif
  200125. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200126. if (png_ptr->transformations & PNG_PACK)
  200127. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200128. (png_uint_32)png_ptr->bit_depth);
  200129. #endif
  200130. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200131. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200132. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200133. #endif
  200134. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200135. if (png_ptr->transformations & PNG_SHIFT)
  200136. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200137. &(png_ptr->shift));
  200138. #endif
  200139. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200140. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200141. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200142. #endif
  200143. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200144. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200145. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200146. #endif
  200147. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200148. if (png_ptr->transformations & PNG_BGR)
  200149. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200150. #endif
  200151. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200152. if (png_ptr->transformations & PNG_INVERT_MONO)
  200153. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200154. #endif
  200155. }
  200156. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200157. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200158. * row_info bit depth should be 8 (one pixel per byte). The channels
  200159. * should be 1 (this only happens on grayscale and paletted images).
  200160. */
  200161. void /* PRIVATE */
  200162. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200163. {
  200164. png_debug(1, "in png_do_pack\n");
  200165. if (row_info->bit_depth == 8 &&
  200166. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200167. row != NULL && row_info != NULL &&
  200168. #endif
  200169. row_info->channels == 1)
  200170. {
  200171. switch ((int)bit_depth)
  200172. {
  200173. case 1:
  200174. {
  200175. png_bytep sp, dp;
  200176. int mask, v;
  200177. png_uint_32 i;
  200178. png_uint_32 row_width = row_info->width;
  200179. sp = row;
  200180. dp = row;
  200181. mask = 0x80;
  200182. v = 0;
  200183. for (i = 0; i < row_width; i++)
  200184. {
  200185. if (*sp != 0)
  200186. v |= mask;
  200187. sp++;
  200188. if (mask > 1)
  200189. mask >>= 1;
  200190. else
  200191. {
  200192. mask = 0x80;
  200193. *dp = (png_byte)v;
  200194. dp++;
  200195. v = 0;
  200196. }
  200197. }
  200198. if (mask != 0x80)
  200199. *dp = (png_byte)v;
  200200. break;
  200201. }
  200202. case 2:
  200203. {
  200204. png_bytep sp, dp;
  200205. int shift, v;
  200206. png_uint_32 i;
  200207. png_uint_32 row_width = row_info->width;
  200208. sp = row;
  200209. dp = row;
  200210. shift = 6;
  200211. v = 0;
  200212. for (i = 0; i < row_width; i++)
  200213. {
  200214. png_byte value;
  200215. value = (png_byte)(*sp & 0x03);
  200216. v |= (value << shift);
  200217. if (shift == 0)
  200218. {
  200219. shift = 6;
  200220. *dp = (png_byte)v;
  200221. dp++;
  200222. v = 0;
  200223. }
  200224. else
  200225. shift -= 2;
  200226. sp++;
  200227. }
  200228. if (shift != 6)
  200229. *dp = (png_byte)v;
  200230. break;
  200231. }
  200232. case 4:
  200233. {
  200234. png_bytep sp, dp;
  200235. int shift, v;
  200236. png_uint_32 i;
  200237. png_uint_32 row_width = row_info->width;
  200238. sp = row;
  200239. dp = row;
  200240. shift = 4;
  200241. v = 0;
  200242. for (i = 0; i < row_width; i++)
  200243. {
  200244. png_byte value;
  200245. value = (png_byte)(*sp & 0x0f);
  200246. v |= (value << shift);
  200247. if (shift == 0)
  200248. {
  200249. shift = 4;
  200250. *dp = (png_byte)v;
  200251. dp++;
  200252. v = 0;
  200253. }
  200254. else
  200255. shift -= 4;
  200256. sp++;
  200257. }
  200258. if (shift != 4)
  200259. *dp = (png_byte)v;
  200260. break;
  200261. }
  200262. }
  200263. row_info->bit_depth = (png_byte)bit_depth;
  200264. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200265. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200266. row_info->width);
  200267. }
  200268. }
  200269. #endif
  200270. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200271. /* Shift pixel values to take advantage of whole range. Pass the
  200272. * true number of bits in bit_depth. The row should be packed
  200273. * according to row_info->bit_depth. Thus, if you had a row of
  200274. * bit depth 4, but the pixels only had values from 0 to 7, you
  200275. * would pass 3 as bit_depth, and this routine would translate the
  200276. * data to 0 to 15.
  200277. */
  200278. void /* PRIVATE */
  200279. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200280. {
  200281. png_debug(1, "in png_do_shift\n");
  200282. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200283. if (row != NULL && row_info != NULL &&
  200284. #else
  200285. if (
  200286. #endif
  200287. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200288. {
  200289. int shift_start[4], shift_dec[4];
  200290. int channels = 0;
  200291. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200292. {
  200293. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200294. shift_dec[channels] = bit_depth->red;
  200295. channels++;
  200296. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200297. shift_dec[channels] = bit_depth->green;
  200298. channels++;
  200299. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200300. shift_dec[channels] = bit_depth->blue;
  200301. channels++;
  200302. }
  200303. else
  200304. {
  200305. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200306. shift_dec[channels] = bit_depth->gray;
  200307. channels++;
  200308. }
  200309. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200310. {
  200311. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200312. shift_dec[channels] = bit_depth->alpha;
  200313. channels++;
  200314. }
  200315. /* with low row depths, could only be grayscale, so one channel */
  200316. if (row_info->bit_depth < 8)
  200317. {
  200318. png_bytep bp = row;
  200319. png_uint_32 i;
  200320. png_byte mask;
  200321. png_uint_32 row_bytes = row_info->rowbytes;
  200322. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200323. mask = 0x55;
  200324. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200325. mask = 0x11;
  200326. else
  200327. mask = 0xff;
  200328. for (i = 0; i < row_bytes; i++, bp++)
  200329. {
  200330. png_uint_16 v;
  200331. int j;
  200332. v = *bp;
  200333. *bp = 0;
  200334. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200335. {
  200336. if (j > 0)
  200337. *bp |= (png_byte)((v << j) & 0xff);
  200338. else
  200339. *bp |= (png_byte)((v >> (-j)) & mask);
  200340. }
  200341. }
  200342. }
  200343. else if (row_info->bit_depth == 8)
  200344. {
  200345. png_bytep bp = row;
  200346. png_uint_32 i;
  200347. png_uint_32 istop = channels * row_info->width;
  200348. for (i = 0; i < istop; i++, bp++)
  200349. {
  200350. png_uint_16 v;
  200351. int j;
  200352. int c = (int)(i%channels);
  200353. v = *bp;
  200354. *bp = 0;
  200355. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200356. {
  200357. if (j > 0)
  200358. *bp |= (png_byte)((v << j) & 0xff);
  200359. else
  200360. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200361. }
  200362. }
  200363. }
  200364. else
  200365. {
  200366. png_bytep bp;
  200367. png_uint_32 i;
  200368. png_uint_32 istop = channels * row_info->width;
  200369. for (bp = row, i = 0; i < istop; i++)
  200370. {
  200371. int c = (int)(i%channels);
  200372. png_uint_16 value, v;
  200373. int j;
  200374. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200375. value = 0;
  200376. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200377. {
  200378. if (j > 0)
  200379. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200380. else
  200381. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200382. }
  200383. *bp++ = (png_byte)(value >> 8);
  200384. *bp++ = (png_byte)(value & 0xff);
  200385. }
  200386. }
  200387. }
  200388. }
  200389. #endif
  200390. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200391. void /* PRIVATE */
  200392. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200393. {
  200394. png_debug(1, "in png_do_write_swap_alpha\n");
  200395. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200396. if (row != NULL && row_info != NULL)
  200397. #endif
  200398. {
  200399. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200400. {
  200401. /* This converts from ARGB to RGBA */
  200402. if (row_info->bit_depth == 8)
  200403. {
  200404. png_bytep sp, dp;
  200405. png_uint_32 i;
  200406. png_uint_32 row_width = row_info->width;
  200407. for (i = 0, sp = dp = row; i < row_width; i++)
  200408. {
  200409. png_byte save = *(sp++);
  200410. *(dp++) = *(sp++);
  200411. *(dp++) = *(sp++);
  200412. *(dp++) = *(sp++);
  200413. *(dp++) = save;
  200414. }
  200415. }
  200416. /* This converts from AARRGGBB to RRGGBBAA */
  200417. else
  200418. {
  200419. png_bytep sp, dp;
  200420. png_uint_32 i;
  200421. png_uint_32 row_width = row_info->width;
  200422. for (i = 0, sp = dp = row; i < row_width; i++)
  200423. {
  200424. png_byte save[2];
  200425. save[0] = *(sp++);
  200426. save[1] = *(sp++);
  200427. *(dp++) = *(sp++);
  200428. *(dp++) = *(sp++);
  200429. *(dp++) = *(sp++);
  200430. *(dp++) = *(sp++);
  200431. *(dp++) = *(sp++);
  200432. *(dp++) = *(sp++);
  200433. *(dp++) = save[0];
  200434. *(dp++) = save[1];
  200435. }
  200436. }
  200437. }
  200438. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200439. {
  200440. /* This converts from AG to GA */
  200441. if (row_info->bit_depth == 8)
  200442. {
  200443. png_bytep sp, dp;
  200444. png_uint_32 i;
  200445. png_uint_32 row_width = row_info->width;
  200446. for (i = 0, sp = dp = row; i < row_width; i++)
  200447. {
  200448. png_byte save = *(sp++);
  200449. *(dp++) = *(sp++);
  200450. *(dp++) = save;
  200451. }
  200452. }
  200453. /* This converts from AAGG to GGAA */
  200454. else
  200455. {
  200456. png_bytep sp, dp;
  200457. png_uint_32 i;
  200458. png_uint_32 row_width = row_info->width;
  200459. for (i = 0, sp = dp = row; i < row_width; i++)
  200460. {
  200461. png_byte save[2];
  200462. save[0] = *(sp++);
  200463. save[1] = *(sp++);
  200464. *(dp++) = *(sp++);
  200465. *(dp++) = *(sp++);
  200466. *(dp++) = save[0];
  200467. *(dp++) = save[1];
  200468. }
  200469. }
  200470. }
  200471. }
  200472. }
  200473. #endif
  200474. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200475. void /* PRIVATE */
  200476. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200477. {
  200478. png_debug(1, "in png_do_write_invert_alpha\n");
  200479. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200480. if (row != NULL && row_info != NULL)
  200481. #endif
  200482. {
  200483. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200484. {
  200485. /* This inverts the alpha channel in RGBA */
  200486. if (row_info->bit_depth == 8)
  200487. {
  200488. png_bytep sp, dp;
  200489. png_uint_32 i;
  200490. png_uint_32 row_width = row_info->width;
  200491. for (i = 0, sp = dp = row; i < row_width; i++)
  200492. {
  200493. /* does nothing
  200494. *(dp++) = *(sp++);
  200495. *(dp++) = *(sp++);
  200496. *(dp++) = *(sp++);
  200497. */
  200498. sp+=3; dp = sp;
  200499. *(dp++) = (png_byte)(255 - *(sp++));
  200500. }
  200501. }
  200502. /* This inverts the alpha channel in RRGGBBAA */
  200503. else
  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. *(dp++) = *(sp++);
  200515. *(dp++) = *(sp++);
  200516. *(dp++) = *(sp++);
  200517. */
  200518. sp+=6; dp = sp;
  200519. *(dp++) = (png_byte)(255 - *(sp++));
  200520. *(dp++) = (png_byte)(255 - *(sp++));
  200521. }
  200522. }
  200523. }
  200524. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200525. {
  200526. /* This inverts the alpha channel in GA */
  200527. if (row_info->bit_depth == 8)
  200528. {
  200529. png_bytep sp, dp;
  200530. png_uint_32 i;
  200531. png_uint_32 row_width = row_info->width;
  200532. for (i = 0, sp = dp = row; i < row_width; i++)
  200533. {
  200534. *(dp++) = *(sp++);
  200535. *(dp++) = (png_byte)(255 - *(sp++));
  200536. }
  200537. }
  200538. /* This inverts the alpha channel in GGAA */
  200539. else
  200540. {
  200541. png_bytep sp, dp;
  200542. png_uint_32 i;
  200543. png_uint_32 row_width = row_info->width;
  200544. for (i = 0, sp = dp = row; i < row_width; i++)
  200545. {
  200546. /* does nothing
  200547. *(dp++) = *(sp++);
  200548. *(dp++) = *(sp++);
  200549. */
  200550. sp+=2; dp = sp;
  200551. *(dp++) = (png_byte)(255 - *(sp++));
  200552. *(dp++) = (png_byte)(255 - *(sp++));
  200553. }
  200554. }
  200555. }
  200556. }
  200557. }
  200558. #endif
  200559. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200560. /* undoes intrapixel differencing */
  200561. void /* PRIVATE */
  200562. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200563. {
  200564. png_debug(1, "in png_do_write_intrapixel\n");
  200565. if (
  200566. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200567. row != NULL && row_info != NULL &&
  200568. #endif
  200569. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200570. {
  200571. int bytes_per_pixel;
  200572. png_uint_32 row_width = row_info->width;
  200573. if (row_info->bit_depth == 8)
  200574. {
  200575. png_bytep rp;
  200576. png_uint_32 i;
  200577. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200578. bytes_per_pixel = 3;
  200579. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200580. bytes_per_pixel = 4;
  200581. else
  200582. return;
  200583. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200584. {
  200585. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200586. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200587. }
  200588. }
  200589. else if (row_info->bit_depth == 16)
  200590. {
  200591. png_bytep rp;
  200592. png_uint_32 i;
  200593. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200594. bytes_per_pixel = 6;
  200595. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200596. bytes_per_pixel = 8;
  200597. else
  200598. return;
  200599. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200600. {
  200601. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200602. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200603. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200604. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200605. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200606. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200607. *(rp+1) = (png_byte)(red & 0xff);
  200608. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200609. *(rp+5) = (png_byte)(blue & 0xff);
  200610. }
  200611. }
  200612. }
  200613. }
  200614. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200615. #endif /* PNG_WRITE_SUPPORTED */
  200616. /*** End of inlined file: pngwtran.c ***/
  200617. /*** Start of inlined file: pngwutil.c ***/
  200618. /* pngwutil.c - utilities to write a PNG file
  200619. *
  200620. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200621. * For conditions of distribution and use, see copyright notice in png.h
  200622. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200623. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200624. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200625. */
  200626. #define PNG_INTERNAL
  200627. #ifdef PNG_WRITE_SUPPORTED
  200628. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200629. * with unsigned numbers for convenience, although one supported
  200630. * ancillary chunk uses signed (two's complement) numbers.
  200631. */
  200632. void PNGAPI
  200633. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200634. {
  200635. buf[0] = (png_byte)((i >> 24) & 0xff);
  200636. buf[1] = (png_byte)((i >> 16) & 0xff);
  200637. buf[2] = (png_byte)((i >> 8) & 0xff);
  200638. buf[3] = (png_byte)(i & 0xff);
  200639. }
  200640. /* The png_save_int_32 function assumes integers are stored in two's
  200641. * complement format. If this isn't the case, then this routine needs to
  200642. * be modified to write data in two's complement format.
  200643. */
  200644. void PNGAPI
  200645. png_save_int_32(png_bytep buf, png_int_32 i)
  200646. {
  200647. buf[0] = (png_byte)((i >> 24) & 0xff);
  200648. buf[1] = (png_byte)((i >> 16) & 0xff);
  200649. buf[2] = (png_byte)((i >> 8) & 0xff);
  200650. buf[3] = (png_byte)(i & 0xff);
  200651. }
  200652. /* Place a 16-bit number into a buffer in PNG byte order.
  200653. * The parameter is declared unsigned int, not png_uint_16,
  200654. * just to avoid potential problems on pre-ANSI C compilers.
  200655. */
  200656. void PNGAPI
  200657. png_save_uint_16(png_bytep buf, unsigned int i)
  200658. {
  200659. buf[0] = (png_byte)((i >> 8) & 0xff);
  200660. buf[1] = (png_byte)(i & 0xff);
  200661. }
  200662. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200663. * representing the chunk name. The array must be at least 4 bytes in
  200664. * length, and does not need to be null terminated. To be safe, pass the
  200665. * pre-defined chunk names here, and if you need a new one, define it
  200666. * where the others are defined. The length is the length of the data.
  200667. * All the data must be present. If that is not possible, use the
  200668. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200669. * functions instead.
  200670. */
  200671. void PNGAPI
  200672. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200673. png_bytep data, png_size_t length)
  200674. {
  200675. if(png_ptr == NULL) return;
  200676. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200677. png_write_chunk_data(png_ptr, data, length);
  200678. png_write_chunk_end(png_ptr);
  200679. }
  200680. /* Write the start of a PNG chunk. The type is the chunk type.
  200681. * The total_length is the sum of the lengths of all the data you will be
  200682. * passing in png_write_chunk_data().
  200683. */
  200684. void PNGAPI
  200685. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200686. png_uint_32 length)
  200687. {
  200688. png_byte buf[4];
  200689. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200690. if(png_ptr == NULL) return;
  200691. /* write the length */
  200692. png_save_uint_32(buf, length);
  200693. png_write_data(png_ptr, buf, (png_size_t)4);
  200694. /* write the chunk name */
  200695. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200696. /* reset the crc and run it over the chunk name */
  200697. png_reset_crc(png_ptr);
  200698. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200699. }
  200700. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200701. * Note that multiple calls to this function are allowed, and that the
  200702. * sum of the lengths from these calls *must* add up to the total_length
  200703. * given to png_write_chunk_start().
  200704. */
  200705. void PNGAPI
  200706. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200707. {
  200708. /* write the data, and run the CRC over it */
  200709. if(png_ptr == NULL) return;
  200710. if (data != NULL && length > 0)
  200711. {
  200712. png_calculate_crc(png_ptr, data, length);
  200713. png_write_data(png_ptr, data, length);
  200714. }
  200715. }
  200716. /* Finish a chunk started with png_write_chunk_start(). */
  200717. void PNGAPI
  200718. png_write_chunk_end(png_structp png_ptr)
  200719. {
  200720. png_byte buf[4];
  200721. if(png_ptr == NULL) return;
  200722. /* write the crc */
  200723. png_save_uint_32(buf, png_ptr->crc);
  200724. png_write_data(png_ptr, buf, (png_size_t)4);
  200725. }
  200726. /* Simple function to write the signature. If we have already written
  200727. * the magic bytes of the signature, or more likely, the PNG stream is
  200728. * being embedded into another stream and doesn't need its own signature,
  200729. * we should call png_set_sig_bytes() to tell libpng how many of the
  200730. * bytes have already been written.
  200731. */
  200732. void /* PRIVATE */
  200733. png_write_sig(png_structp png_ptr)
  200734. {
  200735. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200736. /* write the rest of the 8 byte signature */
  200737. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200738. (png_size_t)8 - png_ptr->sig_bytes);
  200739. if(png_ptr->sig_bytes < 3)
  200740. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200741. }
  200742. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200743. /*
  200744. * This pair of functions encapsulates the operation of (a) compressing a
  200745. * text string, and (b) issuing it later as a series of chunk data writes.
  200746. * The compression_state structure is shared context for these functions
  200747. * set up by the caller in order to make the whole mess thread-safe.
  200748. */
  200749. typedef struct
  200750. {
  200751. char *input; /* the uncompressed input data */
  200752. int input_len; /* its length */
  200753. int num_output_ptr; /* number of output pointers used */
  200754. int max_output_ptr; /* size of output_ptr */
  200755. png_charpp output_ptr; /* array of pointers to output */
  200756. } compression_state;
  200757. /* compress given text into storage in the png_ptr structure */
  200758. static int /* PRIVATE */
  200759. png_text_compress(png_structp png_ptr,
  200760. png_charp text, png_size_t text_len, int compression,
  200761. compression_state *comp)
  200762. {
  200763. int ret;
  200764. comp->num_output_ptr = 0;
  200765. comp->max_output_ptr = 0;
  200766. comp->output_ptr = NULL;
  200767. comp->input = NULL;
  200768. comp->input_len = 0;
  200769. /* we may just want to pass the text right through */
  200770. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200771. {
  200772. comp->input = text;
  200773. comp->input_len = text_len;
  200774. return((int)text_len);
  200775. }
  200776. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200777. {
  200778. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200779. char msg[50];
  200780. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200781. png_warning(png_ptr, msg);
  200782. #else
  200783. png_warning(png_ptr, "Unknown compression type");
  200784. #endif
  200785. }
  200786. /* We can't write the chunk until we find out how much data we have,
  200787. * which means we need to run the compressor first and save the
  200788. * output. This shouldn't be a problem, as the vast majority of
  200789. * comments should be reasonable, but we will set up an array of
  200790. * malloc'd pointers to be sure.
  200791. *
  200792. * If we knew the application was well behaved, we could simplify this
  200793. * greatly by assuming we can always malloc an output buffer large
  200794. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200795. * and malloc this directly. The only time this would be a bad idea is
  200796. * if we can't malloc more than 64K and we have 64K of random input
  200797. * data, or if the input string is incredibly large (although this
  200798. * wouldn't cause a failure, just a slowdown due to swapping).
  200799. */
  200800. /* set up the compression buffers */
  200801. png_ptr->zstream.avail_in = (uInt)text_len;
  200802. png_ptr->zstream.next_in = (Bytef *)text;
  200803. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200804. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200805. /* this is the same compression loop as in png_write_row() */
  200806. do
  200807. {
  200808. /* compress the data */
  200809. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200810. if (ret != Z_OK)
  200811. {
  200812. /* error */
  200813. if (png_ptr->zstream.msg != NULL)
  200814. png_error(png_ptr, png_ptr->zstream.msg);
  200815. else
  200816. png_error(png_ptr, "zlib error");
  200817. }
  200818. /* check to see if we need more room */
  200819. if (!(png_ptr->zstream.avail_out))
  200820. {
  200821. /* make sure the output array has room */
  200822. if (comp->num_output_ptr >= comp->max_output_ptr)
  200823. {
  200824. int old_max;
  200825. old_max = comp->max_output_ptr;
  200826. comp->max_output_ptr = comp->num_output_ptr + 4;
  200827. if (comp->output_ptr != NULL)
  200828. {
  200829. png_charpp old_ptr;
  200830. old_ptr = comp->output_ptr;
  200831. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200832. (png_uint_32)(comp->max_output_ptr *
  200833. png_sizeof (png_charpp)));
  200834. png_memcpy(comp->output_ptr, old_ptr, old_max
  200835. * png_sizeof (png_charp));
  200836. png_free(png_ptr, old_ptr);
  200837. }
  200838. else
  200839. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200840. (png_uint_32)(comp->max_output_ptr *
  200841. png_sizeof (png_charp)));
  200842. }
  200843. /* save the data */
  200844. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200845. (png_uint_32)png_ptr->zbuf_size);
  200846. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200847. png_ptr->zbuf_size);
  200848. comp->num_output_ptr++;
  200849. /* and reset the buffer */
  200850. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200851. png_ptr->zstream.next_out = png_ptr->zbuf;
  200852. }
  200853. /* continue until we don't have any more to compress */
  200854. } while (png_ptr->zstream.avail_in);
  200855. /* finish the compression */
  200856. do
  200857. {
  200858. /* tell zlib we are finished */
  200859. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200860. if (ret == Z_OK)
  200861. {
  200862. /* check to see if we need more room */
  200863. if (!(png_ptr->zstream.avail_out))
  200864. {
  200865. /* check to make sure our output array has room */
  200866. if (comp->num_output_ptr >= comp->max_output_ptr)
  200867. {
  200868. int old_max;
  200869. old_max = comp->max_output_ptr;
  200870. comp->max_output_ptr = comp->num_output_ptr + 4;
  200871. if (comp->output_ptr != NULL)
  200872. {
  200873. png_charpp old_ptr;
  200874. old_ptr = comp->output_ptr;
  200875. /* This could be optimized to realloc() */
  200876. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200877. (png_uint_32)(comp->max_output_ptr *
  200878. png_sizeof (png_charpp)));
  200879. png_memcpy(comp->output_ptr, old_ptr,
  200880. old_max * png_sizeof (png_charp));
  200881. png_free(png_ptr, old_ptr);
  200882. }
  200883. else
  200884. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200885. (png_uint_32)(comp->max_output_ptr *
  200886. png_sizeof (png_charp)));
  200887. }
  200888. /* save off the data */
  200889. comp->output_ptr[comp->num_output_ptr] =
  200890. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200891. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200892. png_ptr->zbuf_size);
  200893. comp->num_output_ptr++;
  200894. /* and reset the buffer pointers */
  200895. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200896. png_ptr->zstream.next_out = png_ptr->zbuf;
  200897. }
  200898. }
  200899. else if (ret != Z_STREAM_END)
  200900. {
  200901. /* we got an error */
  200902. if (png_ptr->zstream.msg != NULL)
  200903. png_error(png_ptr, png_ptr->zstream.msg);
  200904. else
  200905. png_error(png_ptr, "zlib error");
  200906. }
  200907. } while (ret != Z_STREAM_END);
  200908. /* text length is number of buffers plus last buffer */
  200909. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200910. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200911. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200912. return((int)text_len);
  200913. }
  200914. /* ship the compressed text out via chunk writes */
  200915. static void /* PRIVATE */
  200916. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200917. {
  200918. int i;
  200919. /* handle the no-compression case */
  200920. if (comp->input)
  200921. {
  200922. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200923. (png_size_t)comp->input_len);
  200924. return;
  200925. }
  200926. /* write saved output buffers, if any */
  200927. for (i = 0; i < comp->num_output_ptr; i++)
  200928. {
  200929. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200930. png_ptr->zbuf_size);
  200931. png_free(png_ptr, comp->output_ptr[i]);
  200932. comp->output_ptr[i]=NULL;
  200933. }
  200934. if (comp->max_output_ptr != 0)
  200935. png_free(png_ptr, comp->output_ptr);
  200936. comp->output_ptr=NULL;
  200937. /* write anything left in zbuf */
  200938. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200939. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200940. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200941. /* reset zlib for another zTXt/iTXt or image data */
  200942. deflateReset(&png_ptr->zstream);
  200943. png_ptr->zstream.data_type = Z_BINARY;
  200944. }
  200945. #endif
  200946. /* Write the IHDR chunk, and update the png_struct with the necessary
  200947. * information. Note that the rest of this code depends upon this
  200948. * information being correct.
  200949. */
  200950. void /* PRIVATE */
  200951. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200952. int bit_depth, int color_type, int compression_type, int filter_type,
  200953. int interlace_type)
  200954. {
  200955. #ifdef PNG_USE_LOCAL_ARRAYS
  200956. PNG_IHDR;
  200957. #endif
  200958. png_byte buf[13]; /* buffer to store the IHDR info */
  200959. png_debug(1, "in png_write_IHDR\n");
  200960. /* Check that we have valid input data from the application info */
  200961. switch (color_type)
  200962. {
  200963. case PNG_COLOR_TYPE_GRAY:
  200964. switch (bit_depth)
  200965. {
  200966. case 1:
  200967. case 2:
  200968. case 4:
  200969. case 8:
  200970. case 16: png_ptr->channels = 1; break;
  200971. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200972. }
  200973. break;
  200974. case PNG_COLOR_TYPE_RGB:
  200975. if (bit_depth != 8 && bit_depth != 16)
  200976. png_error(png_ptr, "Invalid bit depth for RGB image");
  200977. png_ptr->channels = 3;
  200978. break;
  200979. case PNG_COLOR_TYPE_PALETTE:
  200980. switch (bit_depth)
  200981. {
  200982. case 1:
  200983. case 2:
  200984. case 4:
  200985. case 8: png_ptr->channels = 1; break;
  200986. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200987. }
  200988. break;
  200989. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200990. if (bit_depth != 8 && bit_depth != 16)
  200991. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200992. png_ptr->channels = 2;
  200993. break;
  200994. case PNG_COLOR_TYPE_RGB_ALPHA:
  200995. if (bit_depth != 8 && bit_depth != 16)
  200996. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200997. png_ptr->channels = 4;
  200998. break;
  200999. default:
  201000. png_error(png_ptr, "Invalid image color type specified");
  201001. }
  201002. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201003. {
  201004. png_warning(png_ptr, "Invalid compression type specified");
  201005. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201006. }
  201007. /* Write filter_method 64 (intrapixel differencing) only if
  201008. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201009. * 2. Libpng did not write a PNG signature (this filter_method is only
  201010. * used in PNG datastreams that are embedded in MNG datastreams) and
  201011. * 3. The application called png_permit_mng_features with a mask that
  201012. * included PNG_FLAG_MNG_FILTER_64 and
  201013. * 4. The filter_method is 64 and
  201014. * 5. The color_type is RGB or RGBA
  201015. */
  201016. if (
  201017. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201018. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201019. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201020. (color_type == PNG_COLOR_TYPE_RGB ||
  201021. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201022. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201023. #endif
  201024. filter_type != PNG_FILTER_TYPE_BASE)
  201025. {
  201026. png_warning(png_ptr, "Invalid filter type specified");
  201027. filter_type = PNG_FILTER_TYPE_BASE;
  201028. }
  201029. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201030. if (interlace_type != PNG_INTERLACE_NONE &&
  201031. interlace_type != PNG_INTERLACE_ADAM7)
  201032. {
  201033. png_warning(png_ptr, "Invalid interlace type specified");
  201034. interlace_type = PNG_INTERLACE_ADAM7;
  201035. }
  201036. #else
  201037. interlace_type=PNG_INTERLACE_NONE;
  201038. #endif
  201039. /* save off the relevent information */
  201040. png_ptr->bit_depth = (png_byte)bit_depth;
  201041. png_ptr->color_type = (png_byte)color_type;
  201042. png_ptr->interlaced = (png_byte)interlace_type;
  201043. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201044. png_ptr->filter_type = (png_byte)filter_type;
  201045. #endif
  201046. png_ptr->compression_type = (png_byte)compression_type;
  201047. png_ptr->width = width;
  201048. png_ptr->height = height;
  201049. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201050. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201051. /* set the usr info, so any transformations can modify it */
  201052. png_ptr->usr_width = png_ptr->width;
  201053. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201054. png_ptr->usr_channels = png_ptr->channels;
  201055. /* pack the header information into the buffer */
  201056. png_save_uint_32(buf, width);
  201057. png_save_uint_32(buf + 4, height);
  201058. buf[8] = (png_byte)bit_depth;
  201059. buf[9] = (png_byte)color_type;
  201060. buf[10] = (png_byte)compression_type;
  201061. buf[11] = (png_byte)filter_type;
  201062. buf[12] = (png_byte)interlace_type;
  201063. /* write the chunk */
  201064. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201065. /* initialize zlib with PNG info */
  201066. png_ptr->zstream.zalloc = png_zalloc;
  201067. png_ptr->zstream.zfree = png_zfree;
  201068. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201069. if (!(png_ptr->do_filter))
  201070. {
  201071. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201072. png_ptr->bit_depth < 8)
  201073. png_ptr->do_filter = PNG_FILTER_NONE;
  201074. else
  201075. png_ptr->do_filter = PNG_ALL_FILTERS;
  201076. }
  201077. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201078. {
  201079. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201080. png_ptr->zlib_strategy = Z_FILTERED;
  201081. else
  201082. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201083. }
  201084. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201085. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201086. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201087. png_ptr->zlib_mem_level = 8;
  201088. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201089. png_ptr->zlib_window_bits = 15;
  201090. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201091. png_ptr->zlib_method = 8;
  201092. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201093. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201094. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201095. png_error(png_ptr, "zlib failed to initialize compressor");
  201096. png_ptr->zstream.next_out = png_ptr->zbuf;
  201097. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201098. /* libpng is not interested in zstream.data_type */
  201099. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201100. png_ptr->zstream.data_type = Z_BINARY;
  201101. png_ptr->mode = PNG_HAVE_IHDR;
  201102. }
  201103. /* write the palette. We are careful not to trust png_color to be in the
  201104. * correct order for PNG, so people can redefine it to any convenient
  201105. * structure.
  201106. */
  201107. void /* PRIVATE */
  201108. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201109. {
  201110. #ifdef PNG_USE_LOCAL_ARRAYS
  201111. PNG_PLTE;
  201112. #endif
  201113. png_uint_32 i;
  201114. png_colorp pal_ptr;
  201115. png_byte buf[3];
  201116. png_debug(1, "in png_write_PLTE\n");
  201117. if ((
  201118. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201119. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201120. #endif
  201121. num_pal == 0) || num_pal > 256)
  201122. {
  201123. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201124. {
  201125. png_error(png_ptr, "Invalid number of colors in palette");
  201126. }
  201127. else
  201128. {
  201129. png_warning(png_ptr, "Invalid number of colors in palette");
  201130. return;
  201131. }
  201132. }
  201133. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201134. {
  201135. png_warning(png_ptr,
  201136. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201137. return;
  201138. }
  201139. png_ptr->num_palette = (png_uint_16)num_pal;
  201140. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201141. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201142. #ifndef PNG_NO_POINTER_INDEXING
  201143. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201144. {
  201145. buf[0] = pal_ptr->red;
  201146. buf[1] = pal_ptr->green;
  201147. buf[2] = pal_ptr->blue;
  201148. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201149. }
  201150. #else
  201151. /* This is a little slower but some buggy compilers need to do this instead */
  201152. pal_ptr=palette;
  201153. for (i = 0; i < num_pal; i++)
  201154. {
  201155. buf[0] = pal_ptr[i].red;
  201156. buf[1] = pal_ptr[i].green;
  201157. buf[2] = pal_ptr[i].blue;
  201158. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201159. }
  201160. #endif
  201161. png_write_chunk_end(png_ptr);
  201162. png_ptr->mode |= PNG_HAVE_PLTE;
  201163. }
  201164. /* write an IDAT chunk */
  201165. void /* PRIVATE */
  201166. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201167. {
  201168. #ifdef PNG_USE_LOCAL_ARRAYS
  201169. PNG_IDAT;
  201170. #endif
  201171. png_debug(1, "in png_write_IDAT\n");
  201172. /* Optimize the CMF field in the zlib stream. */
  201173. /* This hack of the zlib stream is compliant to the stream specification. */
  201174. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201175. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201176. {
  201177. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201178. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201179. {
  201180. /* Avoid memory underflows and multiplication overflows. */
  201181. /* The conditions below are practically always satisfied;
  201182. however, they still must be checked. */
  201183. if (length >= 2 &&
  201184. png_ptr->height < 16384 && png_ptr->width < 16384)
  201185. {
  201186. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201187. ((png_ptr->width *
  201188. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201189. unsigned int z_cinfo = z_cmf >> 4;
  201190. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201191. while (uncompressed_idat_size <= half_z_window_size &&
  201192. half_z_window_size >= 256)
  201193. {
  201194. z_cinfo--;
  201195. half_z_window_size >>= 1;
  201196. }
  201197. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201198. if (data[0] != (png_byte)z_cmf)
  201199. {
  201200. data[0] = (png_byte)z_cmf;
  201201. data[1] &= 0xe0;
  201202. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201203. }
  201204. }
  201205. }
  201206. else
  201207. png_error(png_ptr,
  201208. "Invalid zlib compression method or flags in IDAT");
  201209. }
  201210. png_write_chunk(png_ptr, png_IDAT, data, length);
  201211. png_ptr->mode |= PNG_HAVE_IDAT;
  201212. }
  201213. /* write an IEND chunk */
  201214. void /* PRIVATE */
  201215. png_write_IEND(png_structp png_ptr)
  201216. {
  201217. #ifdef PNG_USE_LOCAL_ARRAYS
  201218. PNG_IEND;
  201219. #endif
  201220. png_debug(1, "in png_write_IEND\n");
  201221. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201222. (png_size_t)0);
  201223. png_ptr->mode |= PNG_HAVE_IEND;
  201224. }
  201225. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201226. /* write a gAMA chunk */
  201227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201228. void /* PRIVATE */
  201229. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201230. {
  201231. #ifdef PNG_USE_LOCAL_ARRAYS
  201232. PNG_gAMA;
  201233. #endif
  201234. png_uint_32 igamma;
  201235. png_byte buf[4];
  201236. png_debug(1, "in png_write_gAMA\n");
  201237. /* file_gamma is saved in 1/100,000ths */
  201238. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201239. png_save_uint_32(buf, igamma);
  201240. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201241. }
  201242. #endif
  201243. #ifdef PNG_FIXED_POINT_SUPPORTED
  201244. void /* PRIVATE */
  201245. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201246. {
  201247. #ifdef PNG_USE_LOCAL_ARRAYS
  201248. PNG_gAMA;
  201249. #endif
  201250. png_byte buf[4];
  201251. png_debug(1, "in png_write_gAMA\n");
  201252. /* file_gamma is saved in 1/100,000ths */
  201253. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201254. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201255. }
  201256. #endif
  201257. #endif
  201258. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201259. /* write a sRGB chunk */
  201260. void /* PRIVATE */
  201261. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201262. {
  201263. #ifdef PNG_USE_LOCAL_ARRAYS
  201264. PNG_sRGB;
  201265. #endif
  201266. png_byte buf[1];
  201267. png_debug(1, "in png_write_sRGB\n");
  201268. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201269. png_warning(png_ptr,
  201270. "Invalid sRGB rendering intent specified");
  201271. buf[0]=(png_byte)srgb_intent;
  201272. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201273. }
  201274. #endif
  201275. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201276. /* write an iCCP chunk */
  201277. void /* PRIVATE */
  201278. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201279. png_charp profile, int profile_len)
  201280. {
  201281. #ifdef PNG_USE_LOCAL_ARRAYS
  201282. PNG_iCCP;
  201283. #endif
  201284. png_size_t name_len;
  201285. png_charp new_name;
  201286. compression_state comp;
  201287. int embedded_profile_len = 0;
  201288. png_debug(1, "in png_write_iCCP\n");
  201289. comp.num_output_ptr = 0;
  201290. comp.max_output_ptr = 0;
  201291. comp.output_ptr = NULL;
  201292. comp.input = NULL;
  201293. comp.input_len = 0;
  201294. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201295. &new_name)) == 0)
  201296. {
  201297. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201298. return;
  201299. }
  201300. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201301. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201302. if (profile == NULL)
  201303. profile_len = 0;
  201304. if (profile_len > 3)
  201305. embedded_profile_len =
  201306. ((*( (png_bytep)profile ))<<24) |
  201307. ((*( (png_bytep)profile+1))<<16) |
  201308. ((*( (png_bytep)profile+2))<< 8) |
  201309. ((*( (png_bytep)profile+3)) );
  201310. if (profile_len < embedded_profile_len)
  201311. {
  201312. png_warning(png_ptr,
  201313. "Embedded profile length too large in iCCP chunk");
  201314. return;
  201315. }
  201316. if (profile_len > embedded_profile_len)
  201317. {
  201318. png_warning(png_ptr,
  201319. "Truncating profile to actual length in iCCP chunk");
  201320. profile_len = embedded_profile_len;
  201321. }
  201322. if (profile_len)
  201323. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201324. PNG_COMPRESSION_TYPE_BASE, &comp);
  201325. /* make sure we include the NULL after the name and the compression type */
  201326. png_write_chunk_start(png_ptr, png_iCCP,
  201327. (png_uint_32)name_len+profile_len+2);
  201328. new_name[name_len+1]=0x00;
  201329. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201330. if (profile_len)
  201331. png_write_compressed_data_out(png_ptr, &comp);
  201332. png_write_chunk_end(png_ptr);
  201333. png_free(png_ptr, new_name);
  201334. }
  201335. #endif
  201336. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201337. /* write a sPLT chunk */
  201338. void /* PRIVATE */
  201339. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201340. {
  201341. #ifdef PNG_USE_LOCAL_ARRAYS
  201342. PNG_sPLT;
  201343. #endif
  201344. png_size_t name_len;
  201345. png_charp new_name;
  201346. png_byte entrybuf[10];
  201347. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201348. int palette_size = entry_size * spalette->nentries;
  201349. png_sPLT_entryp ep;
  201350. #ifdef PNG_NO_POINTER_INDEXING
  201351. int i;
  201352. #endif
  201353. png_debug(1, "in png_write_sPLT\n");
  201354. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201355. spalette->name, &new_name))==0)
  201356. {
  201357. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201358. return;
  201359. }
  201360. /* make sure we include the NULL after the name */
  201361. png_write_chunk_start(png_ptr, png_sPLT,
  201362. (png_uint_32)(name_len + 2 + palette_size));
  201363. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201364. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201365. /* loop through each palette entry, writing appropriately */
  201366. #ifndef PNG_NO_POINTER_INDEXING
  201367. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201368. {
  201369. if (spalette->depth == 8)
  201370. {
  201371. entrybuf[0] = (png_byte)ep->red;
  201372. entrybuf[1] = (png_byte)ep->green;
  201373. entrybuf[2] = (png_byte)ep->blue;
  201374. entrybuf[3] = (png_byte)ep->alpha;
  201375. png_save_uint_16(entrybuf + 4, ep->frequency);
  201376. }
  201377. else
  201378. {
  201379. png_save_uint_16(entrybuf + 0, ep->red);
  201380. png_save_uint_16(entrybuf + 2, ep->green);
  201381. png_save_uint_16(entrybuf + 4, ep->blue);
  201382. png_save_uint_16(entrybuf + 6, ep->alpha);
  201383. png_save_uint_16(entrybuf + 8, ep->frequency);
  201384. }
  201385. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201386. }
  201387. #else
  201388. ep=spalette->entries;
  201389. for (i=0; i>spalette->nentries; i++)
  201390. {
  201391. if (spalette->depth == 8)
  201392. {
  201393. entrybuf[0] = (png_byte)ep[i].red;
  201394. entrybuf[1] = (png_byte)ep[i].green;
  201395. entrybuf[2] = (png_byte)ep[i].blue;
  201396. entrybuf[3] = (png_byte)ep[i].alpha;
  201397. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201398. }
  201399. else
  201400. {
  201401. png_save_uint_16(entrybuf + 0, ep[i].red);
  201402. png_save_uint_16(entrybuf + 2, ep[i].green);
  201403. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201404. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201405. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201406. }
  201407. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201408. }
  201409. #endif
  201410. png_write_chunk_end(png_ptr);
  201411. png_free(png_ptr, new_name);
  201412. }
  201413. #endif
  201414. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201415. /* write the sBIT chunk */
  201416. void /* PRIVATE */
  201417. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201418. {
  201419. #ifdef PNG_USE_LOCAL_ARRAYS
  201420. PNG_sBIT;
  201421. #endif
  201422. png_byte buf[4];
  201423. png_size_t size;
  201424. png_debug(1, "in png_write_sBIT\n");
  201425. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201426. if (color_type & PNG_COLOR_MASK_COLOR)
  201427. {
  201428. png_byte maxbits;
  201429. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201430. png_ptr->usr_bit_depth);
  201431. if (sbit->red == 0 || sbit->red > maxbits ||
  201432. sbit->green == 0 || sbit->green > maxbits ||
  201433. sbit->blue == 0 || sbit->blue > maxbits)
  201434. {
  201435. png_warning(png_ptr, "Invalid sBIT depth specified");
  201436. return;
  201437. }
  201438. buf[0] = sbit->red;
  201439. buf[1] = sbit->green;
  201440. buf[2] = sbit->blue;
  201441. size = 3;
  201442. }
  201443. else
  201444. {
  201445. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201446. {
  201447. png_warning(png_ptr, "Invalid sBIT depth specified");
  201448. return;
  201449. }
  201450. buf[0] = sbit->gray;
  201451. size = 1;
  201452. }
  201453. if (color_type & PNG_COLOR_MASK_ALPHA)
  201454. {
  201455. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201456. {
  201457. png_warning(png_ptr, "Invalid sBIT depth specified");
  201458. return;
  201459. }
  201460. buf[size++] = sbit->alpha;
  201461. }
  201462. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201463. }
  201464. #endif
  201465. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201466. /* write the cHRM chunk */
  201467. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201468. void /* PRIVATE */
  201469. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201470. double red_x, double red_y, double green_x, double green_y,
  201471. double blue_x, double blue_y)
  201472. {
  201473. #ifdef PNG_USE_LOCAL_ARRAYS
  201474. PNG_cHRM;
  201475. #endif
  201476. png_byte buf[32];
  201477. png_uint_32 itemp;
  201478. png_debug(1, "in png_write_cHRM\n");
  201479. /* each value is saved in 1/100,000ths */
  201480. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201481. white_x + white_y > 1.0)
  201482. {
  201483. png_warning(png_ptr, "Invalid cHRM white point specified");
  201484. #if !defined(PNG_NO_CONSOLE_IO)
  201485. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201486. #endif
  201487. return;
  201488. }
  201489. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201490. png_save_uint_32(buf, itemp);
  201491. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201492. png_save_uint_32(buf + 4, itemp);
  201493. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201494. {
  201495. png_warning(png_ptr, "Invalid cHRM red point specified");
  201496. return;
  201497. }
  201498. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201499. png_save_uint_32(buf + 8, itemp);
  201500. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201501. png_save_uint_32(buf + 12, itemp);
  201502. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201503. {
  201504. png_warning(png_ptr, "Invalid cHRM green point specified");
  201505. return;
  201506. }
  201507. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201508. png_save_uint_32(buf + 16, itemp);
  201509. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201510. png_save_uint_32(buf + 20, itemp);
  201511. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201512. {
  201513. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201514. return;
  201515. }
  201516. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201517. png_save_uint_32(buf + 24, itemp);
  201518. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201519. png_save_uint_32(buf + 28, itemp);
  201520. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201521. }
  201522. #endif
  201523. #ifdef PNG_FIXED_POINT_SUPPORTED
  201524. void /* PRIVATE */
  201525. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201526. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201527. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201528. png_fixed_point blue_y)
  201529. {
  201530. #ifdef PNG_USE_LOCAL_ARRAYS
  201531. PNG_cHRM;
  201532. #endif
  201533. png_byte buf[32];
  201534. png_debug(1, "in png_write_cHRM\n");
  201535. /* each value is saved in 1/100,000ths */
  201536. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201537. {
  201538. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201539. #if !defined(PNG_NO_CONSOLE_IO)
  201540. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201541. #endif
  201542. return;
  201543. }
  201544. png_save_uint_32(buf, (png_uint_32)white_x);
  201545. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201546. if (red_x + red_y > 100000L)
  201547. {
  201548. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201549. return;
  201550. }
  201551. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201552. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201553. if (green_x + green_y > 100000L)
  201554. {
  201555. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201556. return;
  201557. }
  201558. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201559. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201560. if (blue_x + blue_y > 100000L)
  201561. {
  201562. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201563. return;
  201564. }
  201565. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201566. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201567. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201568. }
  201569. #endif
  201570. #endif
  201571. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201572. /* write the tRNS chunk */
  201573. void /* PRIVATE */
  201574. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201575. int num_trans, int color_type)
  201576. {
  201577. #ifdef PNG_USE_LOCAL_ARRAYS
  201578. PNG_tRNS;
  201579. #endif
  201580. png_byte buf[6];
  201581. png_debug(1, "in png_write_tRNS\n");
  201582. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201583. {
  201584. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201585. {
  201586. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201587. return;
  201588. }
  201589. /* write the chunk out as it is */
  201590. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201591. }
  201592. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201593. {
  201594. /* one 16 bit value */
  201595. if(tran->gray >= (1 << png_ptr->bit_depth))
  201596. {
  201597. png_warning(png_ptr,
  201598. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201599. return;
  201600. }
  201601. png_save_uint_16(buf, tran->gray);
  201602. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201603. }
  201604. else if (color_type == PNG_COLOR_TYPE_RGB)
  201605. {
  201606. /* three 16 bit values */
  201607. png_save_uint_16(buf, tran->red);
  201608. png_save_uint_16(buf + 2, tran->green);
  201609. png_save_uint_16(buf + 4, tran->blue);
  201610. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201611. {
  201612. png_warning(png_ptr,
  201613. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201614. return;
  201615. }
  201616. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201617. }
  201618. else
  201619. {
  201620. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201621. }
  201622. }
  201623. #endif
  201624. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201625. /* write the background chunk */
  201626. void /* PRIVATE */
  201627. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201628. {
  201629. #ifdef PNG_USE_LOCAL_ARRAYS
  201630. PNG_bKGD;
  201631. #endif
  201632. png_byte buf[6];
  201633. png_debug(1, "in png_write_bKGD\n");
  201634. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201635. {
  201636. if (
  201637. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201638. (png_ptr->num_palette ||
  201639. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201640. #endif
  201641. back->index > png_ptr->num_palette)
  201642. {
  201643. png_warning(png_ptr, "Invalid background palette index");
  201644. return;
  201645. }
  201646. buf[0] = back->index;
  201647. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201648. }
  201649. else if (color_type & PNG_COLOR_MASK_COLOR)
  201650. {
  201651. png_save_uint_16(buf, back->red);
  201652. png_save_uint_16(buf + 2, back->green);
  201653. png_save_uint_16(buf + 4, back->blue);
  201654. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201655. {
  201656. png_warning(png_ptr,
  201657. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201658. return;
  201659. }
  201660. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201661. }
  201662. else
  201663. {
  201664. if(back->gray >= (1 << png_ptr->bit_depth))
  201665. {
  201666. png_warning(png_ptr,
  201667. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201668. return;
  201669. }
  201670. png_save_uint_16(buf, back->gray);
  201671. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201672. }
  201673. }
  201674. #endif
  201675. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201676. /* write the histogram */
  201677. void /* PRIVATE */
  201678. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201679. {
  201680. #ifdef PNG_USE_LOCAL_ARRAYS
  201681. PNG_hIST;
  201682. #endif
  201683. int i;
  201684. png_byte buf[3];
  201685. png_debug(1, "in png_write_hIST\n");
  201686. if (num_hist > (int)png_ptr->num_palette)
  201687. {
  201688. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201689. png_ptr->num_palette);
  201690. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201691. return;
  201692. }
  201693. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201694. for (i = 0; i < num_hist; i++)
  201695. {
  201696. png_save_uint_16(buf, hist[i]);
  201697. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201698. }
  201699. png_write_chunk_end(png_ptr);
  201700. }
  201701. #endif
  201702. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201703. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201704. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201705. * and if invalid, correct the keyword rather than discarding the entire
  201706. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201707. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201708. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201709. *
  201710. * The new_key is allocated to hold the corrected keyword and must be freed
  201711. * by the calling routine. This avoids problems with trying to write to
  201712. * static keywords without having to have duplicate copies of the strings.
  201713. */
  201714. png_size_t /* PRIVATE */
  201715. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201716. {
  201717. png_size_t key_len;
  201718. png_charp kp, dp;
  201719. int kflag;
  201720. int kwarn=0;
  201721. png_debug(1, "in png_check_keyword\n");
  201722. *new_key = NULL;
  201723. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201724. {
  201725. png_warning(png_ptr, "zero length keyword");
  201726. return ((png_size_t)0);
  201727. }
  201728. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201729. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201730. if (*new_key == NULL)
  201731. {
  201732. png_warning(png_ptr, "Out of memory while procesing keyword");
  201733. return ((png_size_t)0);
  201734. }
  201735. /* Replace non-printing characters with a blank and print a warning */
  201736. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201737. {
  201738. if ((png_byte)*kp < 0x20 ||
  201739. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201740. {
  201741. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201742. char msg[40];
  201743. png_snprintf(msg, 40,
  201744. "invalid keyword character 0x%02X", (png_byte)*kp);
  201745. png_warning(png_ptr, msg);
  201746. #else
  201747. png_warning(png_ptr, "invalid character in keyword");
  201748. #endif
  201749. *dp = ' ';
  201750. }
  201751. else
  201752. {
  201753. *dp = *kp;
  201754. }
  201755. }
  201756. *dp = '\0';
  201757. /* Remove any trailing white space. */
  201758. kp = *new_key + key_len - 1;
  201759. if (*kp == ' ')
  201760. {
  201761. png_warning(png_ptr, "trailing spaces removed from keyword");
  201762. while (*kp == ' ')
  201763. {
  201764. *(kp--) = '\0';
  201765. key_len--;
  201766. }
  201767. }
  201768. /* Remove any leading white space. */
  201769. kp = *new_key;
  201770. if (*kp == ' ')
  201771. {
  201772. png_warning(png_ptr, "leading spaces removed from keyword");
  201773. while (*kp == ' ')
  201774. {
  201775. kp++;
  201776. key_len--;
  201777. }
  201778. }
  201779. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201780. /* Remove multiple internal spaces. */
  201781. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201782. {
  201783. if (*kp == ' ' && kflag == 0)
  201784. {
  201785. *(dp++) = *kp;
  201786. kflag = 1;
  201787. }
  201788. else if (*kp == ' ')
  201789. {
  201790. key_len--;
  201791. kwarn=1;
  201792. }
  201793. else
  201794. {
  201795. *(dp++) = *kp;
  201796. kflag = 0;
  201797. }
  201798. }
  201799. *dp = '\0';
  201800. if(kwarn)
  201801. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201802. if (key_len == 0)
  201803. {
  201804. png_free(png_ptr, *new_key);
  201805. *new_key=NULL;
  201806. png_warning(png_ptr, "Zero length keyword");
  201807. }
  201808. if (key_len > 79)
  201809. {
  201810. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201811. new_key[79] = '\0';
  201812. key_len = 79;
  201813. }
  201814. return (key_len);
  201815. }
  201816. #endif
  201817. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201818. /* write a tEXt chunk */
  201819. void /* PRIVATE */
  201820. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201821. png_size_t text_len)
  201822. {
  201823. #ifdef PNG_USE_LOCAL_ARRAYS
  201824. PNG_tEXt;
  201825. #endif
  201826. png_size_t key_len;
  201827. png_charp new_key;
  201828. png_debug(1, "in png_write_tEXt\n");
  201829. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201830. {
  201831. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201832. return;
  201833. }
  201834. if (text == NULL || *text == '\0')
  201835. text_len = 0;
  201836. else
  201837. text_len = png_strlen(text);
  201838. /* make sure we include the 0 after the key */
  201839. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201840. /*
  201841. * We leave it to the application to meet PNG-1.0 requirements on the
  201842. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201843. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201844. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201845. */
  201846. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201847. if (text_len)
  201848. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201849. png_write_chunk_end(png_ptr);
  201850. png_free(png_ptr, new_key);
  201851. }
  201852. #endif
  201853. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201854. /* write a compressed text chunk */
  201855. void /* PRIVATE */
  201856. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201857. png_size_t text_len, int compression)
  201858. {
  201859. #ifdef PNG_USE_LOCAL_ARRAYS
  201860. PNG_zTXt;
  201861. #endif
  201862. png_size_t key_len;
  201863. char buf[1];
  201864. png_charp new_key;
  201865. compression_state comp;
  201866. png_debug(1, "in png_write_zTXt\n");
  201867. comp.num_output_ptr = 0;
  201868. comp.max_output_ptr = 0;
  201869. comp.output_ptr = NULL;
  201870. comp.input = NULL;
  201871. comp.input_len = 0;
  201872. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201873. {
  201874. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201875. return;
  201876. }
  201877. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201878. {
  201879. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201880. png_free(png_ptr, new_key);
  201881. return;
  201882. }
  201883. text_len = png_strlen(text);
  201884. /* compute the compressed data; do it now for the length */
  201885. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201886. &comp);
  201887. /* write start of chunk */
  201888. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201889. (key_len+text_len+2));
  201890. /* write key */
  201891. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201892. png_free(png_ptr, new_key);
  201893. buf[0] = (png_byte)compression;
  201894. /* write compression */
  201895. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201896. /* write the compressed data */
  201897. png_write_compressed_data_out(png_ptr, &comp);
  201898. /* close the chunk */
  201899. png_write_chunk_end(png_ptr);
  201900. }
  201901. #endif
  201902. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201903. /* write an iTXt chunk */
  201904. void /* PRIVATE */
  201905. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201906. png_charp lang, png_charp lang_key, png_charp text)
  201907. {
  201908. #ifdef PNG_USE_LOCAL_ARRAYS
  201909. PNG_iTXt;
  201910. #endif
  201911. png_size_t lang_len, key_len, lang_key_len, text_len;
  201912. png_charp new_lang, new_key;
  201913. png_byte cbuf[2];
  201914. compression_state comp;
  201915. png_debug(1, "in png_write_iTXt\n");
  201916. comp.num_output_ptr = 0;
  201917. comp.max_output_ptr = 0;
  201918. comp.output_ptr = NULL;
  201919. comp.input = NULL;
  201920. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201921. {
  201922. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201923. return;
  201924. }
  201925. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201926. {
  201927. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201928. new_lang = NULL;
  201929. lang_len = 0;
  201930. }
  201931. if (lang_key == NULL)
  201932. lang_key_len = 0;
  201933. else
  201934. lang_key_len = png_strlen(lang_key);
  201935. if (text == NULL)
  201936. text_len = 0;
  201937. else
  201938. text_len = png_strlen(text);
  201939. /* compute the compressed data; do it now for the length */
  201940. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201941. &comp);
  201942. /* make sure we include the compression flag, the compression byte,
  201943. * and the NULs after the key, lang, and lang_key parts */
  201944. png_write_chunk_start(png_ptr, png_iTXt,
  201945. (png_uint_32)(
  201946. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201947. + key_len
  201948. + lang_len
  201949. + lang_key_len
  201950. + text_len));
  201951. /*
  201952. * We leave it to the application to meet PNG-1.0 requirements on the
  201953. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201954. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201955. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201956. */
  201957. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201958. /* set the compression flag */
  201959. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201960. compression == PNG_TEXT_COMPRESSION_NONE)
  201961. cbuf[0] = 0;
  201962. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201963. cbuf[0] = 1;
  201964. /* set the compression method */
  201965. cbuf[1] = 0;
  201966. png_write_chunk_data(png_ptr, cbuf, 2);
  201967. cbuf[0] = 0;
  201968. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201969. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201970. png_write_compressed_data_out(png_ptr, &comp);
  201971. png_write_chunk_end(png_ptr);
  201972. png_free(png_ptr, new_key);
  201973. if (new_lang)
  201974. png_free(png_ptr, new_lang);
  201975. }
  201976. #endif
  201977. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201978. /* write the oFFs chunk */
  201979. void /* PRIVATE */
  201980. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201981. int unit_type)
  201982. {
  201983. #ifdef PNG_USE_LOCAL_ARRAYS
  201984. PNG_oFFs;
  201985. #endif
  201986. png_byte buf[9];
  201987. png_debug(1, "in png_write_oFFs\n");
  201988. if (unit_type >= PNG_OFFSET_LAST)
  201989. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201990. png_save_int_32(buf, x_offset);
  201991. png_save_int_32(buf + 4, y_offset);
  201992. buf[8] = (png_byte)unit_type;
  201993. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201994. }
  201995. #endif
  201996. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201997. /* write the pCAL chunk (described in the PNG extensions document) */
  201998. void /* PRIVATE */
  201999. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202000. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202001. {
  202002. #ifdef PNG_USE_LOCAL_ARRAYS
  202003. PNG_pCAL;
  202004. #endif
  202005. png_size_t purpose_len, units_len, total_len;
  202006. png_uint_32p params_len;
  202007. png_byte buf[10];
  202008. png_charp new_purpose;
  202009. int i;
  202010. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202011. if (type >= PNG_EQUATION_LAST)
  202012. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202013. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202014. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202015. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202016. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202017. total_len = purpose_len + units_len + 10;
  202018. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202019. *png_sizeof(png_uint_32)));
  202020. /* Find the length of each parameter, making sure we don't count the
  202021. null terminator for the last parameter. */
  202022. for (i = 0; i < nparams; i++)
  202023. {
  202024. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202025. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202026. total_len += (png_size_t)params_len[i];
  202027. }
  202028. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202029. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202030. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202031. png_save_int_32(buf, X0);
  202032. png_save_int_32(buf + 4, X1);
  202033. buf[8] = (png_byte)type;
  202034. buf[9] = (png_byte)nparams;
  202035. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202036. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202037. png_free(png_ptr, new_purpose);
  202038. for (i = 0; i < nparams; i++)
  202039. {
  202040. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202041. (png_size_t)params_len[i]);
  202042. }
  202043. png_free(png_ptr, params_len);
  202044. png_write_chunk_end(png_ptr);
  202045. }
  202046. #endif
  202047. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202048. /* write the sCAL chunk */
  202049. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202050. void /* PRIVATE */
  202051. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202052. {
  202053. #ifdef PNG_USE_LOCAL_ARRAYS
  202054. PNG_sCAL;
  202055. #endif
  202056. char buf[64];
  202057. png_size_t total_len;
  202058. png_debug(1, "in png_write_sCAL\n");
  202059. buf[0] = (char)unit;
  202060. #if defined(_WIN32_WCE)
  202061. /* sprintf() function is not supported on WindowsCE */
  202062. {
  202063. wchar_t wc_buf[32];
  202064. size_t wc_len;
  202065. swprintf(wc_buf, TEXT("%12.12e"), width);
  202066. wc_len = wcslen(wc_buf);
  202067. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202068. total_len = wc_len + 2;
  202069. swprintf(wc_buf, TEXT("%12.12e"), height);
  202070. wc_len = wcslen(wc_buf);
  202071. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202072. NULL, NULL);
  202073. total_len += wc_len;
  202074. }
  202075. #else
  202076. png_snprintf(buf + 1, 63, "%12.12e", width);
  202077. total_len = 1 + png_strlen(buf + 1) + 1;
  202078. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202079. total_len += png_strlen(buf + total_len);
  202080. #endif
  202081. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202082. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202083. }
  202084. #else
  202085. #ifdef PNG_FIXED_POINT_SUPPORTED
  202086. void /* PRIVATE */
  202087. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202088. png_charp height)
  202089. {
  202090. #ifdef PNG_USE_LOCAL_ARRAYS
  202091. PNG_sCAL;
  202092. #endif
  202093. png_byte buf[64];
  202094. png_size_t wlen, hlen, total_len;
  202095. png_debug(1, "in png_write_sCAL_s\n");
  202096. wlen = png_strlen(width);
  202097. hlen = png_strlen(height);
  202098. total_len = wlen + hlen + 2;
  202099. if (total_len > 64)
  202100. {
  202101. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202102. return;
  202103. }
  202104. buf[0] = (png_byte)unit;
  202105. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202106. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202107. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202108. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202109. }
  202110. #endif
  202111. #endif
  202112. #endif
  202113. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202114. /* write the pHYs chunk */
  202115. void /* PRIVATE */
  202116. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202117. png_uint_32 y_pixels_per_unit,
  202118. int unit_type)
  202119. {
  202120. #ifdef PNG_USE_LOCAL_ARRAYS
  202121. PNG_pHYs;
  202122. #endif
  202123. png_byte buf[9];
  202124. png_debug(1, "in png_write_pHYs\n");
  202125. if (unit_type >= PNG_RESOLUTION_LAST)
  202126. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202127. png_save_uint_32(buf, x_pixels_per_unit);
  202128. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202129. buf[8] = (png_byte)unit_type;
  202130. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202131. }
  202132. #endif
  202133. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202134. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202135. * or png_convert_from_time_t(), or fill in the structure yourself.
  202136. */
  202137. void /* PRIVATE */
  202138. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202139. {
  202140. #ifdef PNG_USE_LOCAL_ARRAYS
  202141. PNG_tIME;
  202142. #endif
  202143. png_byte buf[7];
  202144. png_debug(1, "in png_write_tIME\n");
  202145. if (mod_time->month > 12 || mod_time->month < 1 ||
  202146. mod_time->day > 31 || mod_time->day < 1 ||
  202147. mod_time->hour > 23 || mod_time->second > 60)
  202148. {
  202149. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202150. return;
  202151. }
  202152. png_save_uint_16(buf, mod_time->year);
  202153. buf[2] = mod_time->month;
  202154. buf[3] = mod_time->day;
  202155. buf[4] = mod_time->hour;
  202156. buf[5] = mod_time->minute;
  202157. buf[6] = mod_time->second;
  202158. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202159. }
  202160. #endif
  202161. /* initializes the row writing capability of libpng */
  202162. void /* PRIVATE */
  202163. png_write_start_row(png_structp png_ptr)
  202164. {
  202165. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202166. #ifdef PNG_USE_LOCAL_ARRAYS
  202167. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202168. /* start of interlace block */
  202169. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202170. /* offset to next interlace block */
  202171. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202172. /* start of interlace block in the y direction */
  202173. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202174. /* offset to next interlace block in the y direction */
  202175. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202176. #endif
  202177. #endif
  202178. png_size_t buf_size;
  202179. png_debug(1, "in png_write_start_row\n");
  202180. buf_size = (png_size_t)(PNG_ROWBYTES(
  202181. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202182. /* set up row buffer */
  202183. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202184. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202185. #ifndef PNG_NO_WRITE_FILTERING
  202186. /* set up filtering buffer, if using this filter */
  202187. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202188. {
  202189. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202190. (png_ptr->rowbytes + 1));
  202191. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202192. }
  202193. /* We only need to keep the previous row if we are using one of these. */
  202194. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202195. {
  202196. /* set up previous row buffer */
  202197. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202198. png_memset(png_ptr->prev_row, 0, buf_size);
  202199. if (png_ptr->do_filter & PNG_FILTER_UP)
  202200. {
  202201. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202202. (png_ptr->rowbytes + 1));
  202203. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202204. }
  202205. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202206. {
  202207. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202208. (png_ptr->rowbytes + 1));
  202209. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202210. }
  202211. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202212. {
  202213. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202214. (png_ptr->rowbytes + 1));
  202215. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202216. }
  202217. #endif /* PNG_NO_WRITE_FILTERING */
  202218. }
  202219. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202220. /* if interlaced, we need to set up width and height of pass */
  202221. if (png_ptr->interlaced)
  202222. {
  202223. if (!(png_ptr->transformations & PNG_INTERLACE))
  202224. {
  202225. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202226. png_pass_ystart[0]) / png_pass_yinc[0];
  202227. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202228. png_pass_start[0]) / png_pass_inc[0];
  202229. }
  202230. else
  202231. {
  202232. png_ptr->num_rows = png_ptr->height;
  202233. png_ptr->usr_width = png_ptr->width;
  202234. }
  202235. }
  202236. else
  202237. #endif
  202238. {
  202239. png_ptr->num_rows = png_ptr->height;
  202240. png_ptr->usr_width = png_ptr->width;
  202241. }
  202242. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202243. png_ptr->zstream.next_out = png_ptr->zbuf;
  202244. }
  202245. /* Internal use only. Called when finished processing a row of data. */
  202246. void /* PRIVATE */
  202247. png_write_finish_row(png_structp png_ptr)
  202248. {
  202249. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202250. #ifdef PNG_USE_LOCAL_ARRAYS
  202251. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202252. /* start of interlace block */
  202253. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202254. /* offset to next interlace block */
  202255. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202256. /* start of interlace block in the y direction */
  202257. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202258. /* offset to next interlace block in the y direction */
  202259. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202260. #endif
  202261. #endif
  202262. int ret;
  202263. png_debug(1, "in png_write_finish_row\n");
  202264. /* next row */
  202265. png_ptr->row_number++;
  202266. /* see if we are done */
  202267. if (png_ptr->row_number < png_ptr->num_rows)
  202268. return;
  202269. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202270. /* if interlaced, go to next pass */
  202271. if (png_ptr->interlaced)
  202272. {
  202273. png_ptr->row_number = 0;
  202274. if (png_ptr->transformations & PNG_INTERLACE)
  202275. {
  202276. png_ptr->pass++;
  202277. }
  202278. else
  202279. {
  202280. /* loop until we find a non-zero width or height pass */
  202281. do
  202282. {
  202283. png_ptr->pass++;
  202284. if (png_ptr->pass >= 7)
  202285. break;
  202286. png_ptr->usr_width = (png_ptr->width +
  202287. png_pass_inc[png_ptr->pass] - 1 -
  202288. png_pass_start[png_ptr->pass]) /
  202289. png_pass_inc[png_ptr->pass];
  202290. png_ptr->num_rows = (png_ptr->height +
  202291. png_pass_yinc[png_ptr->pass] - 1 -
  202292. png_pass_ystart[png_ptr->pass]) /
  202293. png_pass_yinc[png_ptr->pass];
  202294. if (png_ptr->transformations & PNG_INTERLACE)
  202295. break;
  202296. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202297. }
  202298. /* reset the row above the image for the next pass */
  202299. if (png_ptr->pass < 7)
  202300. {
  202301. if (png_ptr->prev_row != NULL)
  202302. png_memset(png_ptr->prev_row, 0,
  202303. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202304. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202305. return;
  202306. }
  202307. }
  202308. #endif
  202309. /* if we get here, we've just written the last row, so we need
  202310. to flush the compressor */
  202311. do
  202312. {
  202313. /* tell the compressor we are done */
  202314. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202315. /* check for an error */
  202316. if (ret == Z_OK)
  202317. {
  202318. /* check to see if we need more room */
  202319. if (!(png_ptr->zstream.avail_out))
  202320. {
  202321. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202322. png_ptr->zstream.next_out = png_ptr->zbuf;
  202323. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202324. }
  202325. }
  202326. else if (ret != Z_STREAM_END)
  202327. {
  202328. if (png_ptr->zstream.msg != NULL)
  202329. png_error(png_ptr, png_ptr->zstream.msg);
  202330. else
  202331. png_error(png_ptr, "zlib error");
  202332. }
  202333. } while (ret != Z_STREAM_END);
  202334. /* write any extra space */
  202335. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202336. {
  202337. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202338. png_ptr->zstream.avail_out);
  202339. }
  202340. deflateReset(&png_ptr->zstream);
  202341. png_ptr->zstream.data_type = Z_BINARY;
  202342. }
  202343. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202344. /* Pick out the correct pixels for the interlace pass.
  202345. * The basic idea here is to go through the row with a source
  202346. * pointer and a destination pointer (sp and dp), and copy the
  202347. * correct pixels for the pass. As the row gets compacted,
  202348. * sp will always be >= dp, so we should never overwrite anything.
  202349. * See the default: case for the easiest code to understand.
  202350. */
  202351. void /* PRIVATE */
  202352. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202353. {
  202354. #ifdef PNG_USE_LOCAL_ARRAYS
  202355. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202356. /* start of interlace block */
  202357. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202358. /* offset to next interlace block */
  202359. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202360. #endif
  202361. png_debug(1, "in png_do_write_interlace\n");
  202362. /* we don't have to do anything on the last pass (6) */
  202363. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202364. if (row != NULL && row_info != NULL && pass < 6)
  202365. #else
  202366. if (pass < 6)
  202367. #endif
  202368. {
  202369. /* each pixel depth is handled separately */
  202370. switch (row_info->pixel_depth)
  202371. {
  202372. case 1:
  202373. {
  202374. png_bytep sp;
  202375. png_bytep dp;
  202376. int shift;
  202377. int d;
  202378. int value;
  202379. png_uint_32 i;
  202380. png_uint_32 row_width = row_info->width;
  202381. dp = row;
  202382. d = 0;
  202383. shift = 7;
  202384. for (i = png_pass_start[pass]; i < row_width;
  202385. i += png_pass_inc[pass])
  202386. {
  202387. sp = row + (png_size_t)(i >> 3);
  202388. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202389. d |= (value << shift);
  202390. if (shift == 0)
  202391. {
  202392. shift = 7;
  202393. *dp++ = (png_byte)d;
  202394. d = 0;
  202395. }
  202396. else
  202397. shift--;
  202398. }
  202399. if (shift != 7)
  202400. *dp = (png_byte)d;
  202401. break;
  202402. }
  202403. case 2:
  202404. {
  202405. png_bytep sp;
  202406. png_bytep dp;
  202407. int shift;
  202408. int d;
  202409. int value;
  202410. png_uint_32 i;
  202411. png_uint_32 row_width = row_info->width;
  202412. dp = row;
  202413. shift = 6;
  202414. d = 0;
  202415. for (i = png_pass_start[pass]; i < row_width;
  202416. i += png_pass_inc[pass])
  202417. {
  202418. sp = row + (png_size_t)(i >> 2);
  202419. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202420. d |= (value << shift);
  202421. if (shift == 0)
  202422. {
  202423. shift = 6;
  202424. *dp++ = (png_byte)d;
  202425. d = 0;
  202426. }
  202427. else
  202428. shift -= 2;
  202429. }
  202430. if (shift != 6)
  202431. *dp = (png_byte)d;
  202432. break;
  202433. }
  202434. case 4:
  202435. {
  202436. png_bytep sp;
  202437. png_bytep dp;
  202438. int shift;
  202439. int d;
  202440. int value;
  202441. png_uint_32 i;
  202442. png_uint_32 row_width = row_info->width;
  202443. dp = row;
  202444. shift = 4;
  202445. d = 0;
  202446. for (i = png_pass_start[pass]; i < row_width;
  202447. i += png_pass_inc[pass])
  202448. {
  202449. sp = row + (png_size_t)(i >> 1);
  202450. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202451. d |= (value << shift);
  202452. if (shift == 0)
  202453. {
  202454. shift = 4;
  202455. *dp++ = (png_byte)d;
  202456. d = 0;
  202457. }
  202458. else
  202459. shift -= 4;
  202460. }
  202461. if (shift != 4)
  202462. *dp = (png_byte)d;
  202463. break;
  202464. }
  202465. default:
  202466. {
  202467. png_bytep sp;
  202468. png_bytep dp;
  202469. png_uint_32 i;
  202470. png_uint_32 row_width = row_info->width;
  202471. png_size_t pixel_bytes;
  202472. /* start at the beginning */
  202473. dp = row;
  202474. /* find out how many bytes each pixel takes up */
  202475. pixel_bytes = (row_info->pixel_depth >> 3);
  202476. /* loop through the row, only looking at the pixels that
  202477. matter */
  202478. for (i = png_pass_start[pass]; i < row_width;
  202479. i += png_pass_inc[pass])
  202480. {
  202481. /* find out where the original pixel is */
  202482. sp = row + (png_size_t)i * pixel_bytes;
  202483. /* move the pixel */
  202484. if (dp != sp)
  202485. png_memcpy(dp, sp, pixel_bytes);
  202486. /* next pixel */
  202487. dp += pixel_bytes;
  202488. }
  202489. break;
  202490. }
  202491. }
  202492. /* set new row width */
  202493. row_info->width = (row_info->width +
  202494. png_pass_inc[pass] - 1 -
  202495. png_pass_start[pass]) /
  202496. png_pass_inc[pass];
  202497. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202498. row_info->width);
  202499. }
  202500. }
  202501. #endif
  202502. /* This filters the row, chooses which filter to use, if it has not already
  202503. * been specified by the application, and then writes the row out with the
  202504. * chosen filter.
  202505. */
  202506. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202507. #define PNG_HISHIFT 10
  202508. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202509. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202510. void /* PRIVATE */
  202511. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202512. {
  202513. png_bytep best_row;
  202514. #ifndef PNG_NO_WRITE_FILTER
  202515. png_bytep prev_row, row_buf;
  202516. png_uint_32 mins, bpp;
  202517. png_byte filter_to_do = png_ptr->do_filter;
  202518. png_uint_32 row_bytes = row_info->rowbytes;
  202519. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202520. int num_p_filters = (int)png_ptr->num_prev_filters;
  202521. #endif
  202522. png_debug(1, "in png_write_find_filter\n");
  202523. /* find out how many bytes offset each pixel is */
  202524. bpp = (row_info->pixel_depth + 7) >> 3;
  202525. prev_row = png_ptr->prev_row;
  202526. #endif
  202527. best_row = png_ptr->row_buf;
  202528. #ifndef PNG_NO_WRITE_FILTER
  202529. row_buf = best_row;
  202530. mins = PNG_MAXSUM;
  202531. /* The prediction method we use is to find which method provides the
  202532. * smallest value when summing the absolute values of the distances
  202533. * from zero, using anything >= 128 as negative numbers. This is known
  202534. * as the "minimum sum of absolute differences" heuristic. Other
  202535. * heuristics are the "weighted minimum sum of absolute differences"
  202536. * (experimental and can in theory improve compression), and the "zlib
  202537. * predictive" method (not implemented yet), which does test compressions
  202538. * of lines using different filter methods, and then chooses the
  202539. * (series of) filter(s) that give minimum compressed data size (VERY
  202540. * computationally expensive).
  202541. *
  202542. * GRR 980525: consider also
  202543. * (1) minimum sum of absolute differences from running average (i.e.,
  202544. * keep running sum of non-absolute differences & count of bytes)
  202545. * [track dispersion, too? restart average if dispersion too large?]
  202546. * (1b) minimum sum of absolute differences from sliding average, probably
  202547. * with window size <= deflate window (usually 32K)
  202548. * (2) minimum sum of squared differences from zero or running average
  202549. * (i.e., ~ root-mean-square approach)
  202550. */
  202551. /* We don't need to test the 'no filter' case if this is the only filter
  202552. * that has been chosen, as it doesn't actually do anything to the data.
  202553. */
  202554. if ((filter_to_do & PNG_FILTER_NONE) &&
  202555. filter_to_do != PNG_FILTER_NONE)
  202556. {
  202557. png_bytep rp;
  202558. png_uint_32 sum = 0;
  202559. png_uint_32 i;
  202560. int v;
  202561. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202562. {
  202563. v = *rp;
  202564. sum += (v < 128) ? v : 256 - v;
  202565. }
  202566. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202567. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202568. {
  202569. png_uint_32 sumhi, sumlo;
  202570. int j;
  202571. sumlo = sum & PNG_LOMASK;
  202572. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202573. /* Reduce the sum if we match any of the previous rows */
  202574. for (j = 0; j < num_p_filters; j++)
  202575. {
  202576. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202577. {
  202578. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202579. PNG_WEIGHT_SHIFT;
  202580. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202581. PNG_WEIGHT_SHIFT;
  202582. }
  202583. }
  202584. /* Factor in the cost of this filter (this is here for completeness,
  202585. * but it makes no sense to have a "cost" for the NONE filter, as
  202586. * it has the minimum possible computational cost - none).
  202587. */
  202588. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202589. PNG_COST_SHIFT;
  202590. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202591. PNG_COST_SHIFT;
  202592. if (sumhi > PNG_HIMASK)
  202593. sum = PNG_MAXSUM;
  202594. else
  202595. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202596. }
  202597. #endif
  202598. mins = sum;
  202599. }
  202600. /* sub filter */
  202601. if (filter_to_do == PNG_FILTER_SUB)
  202602. /* it's the only filter so no testing is needed */
  202603. {
  202604. png_bytep rp, lp, dp;
  202605. png_uint_32 i;
  202606. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202607. i++, rp++, dp++)
  202608. {
  202609. *dp = *rp;
  202610. }
  202611. for (lp = row_buf + 1; i < row_bytes;
  202612. i++, rp++, lp++, dp++)
  202613. {
  202614. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202615. }
  202616. best_row = png_ptr->sub_row;
  202617. }
  202618. else if (filter_to_do & PNG_FILTER_SUB)
  202619. {
  202620. png_bytep rp, dp, lp;
  202621. png_uint_32 sum = 0, lmins = mins;
  202622. png_uint_32 i;
  202623. int v;
  202624. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202625. /* We temporarily increase the "minimum sum" by the factor we
  202626. * would reduce the sum of this filter, so that we can do the
  202627. * early exit comparison without scaling the sum each time.
  202628. */
  202629. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202630. {
  202631. int j;
  202632. png_uint_32 lmhi, lmlo;
  202633. lmlo = lmins & PNG_LOMASK;
  202634. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202635. for (j = 0; j < num_p_filters; j++)
  202636. {
  202637. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202638. {
  202639. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202640. PNG_WEIGHT_SHIFT;
  202641. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202642. PNG_WEIGHT_SHIFT;
  202643. }
  202644. }
  202645. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202646. PNG_COST_SHIFT;
  202647. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202648. PNG_COST_SHIFT;
  202649. if (lmhi > PNG_HIMASK)
  202650. lmins = PNG_MAXSUM;
  202651. else
  202652. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202653. }
  202654. #endif
  202655. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202656. i++, rp++, dp++)
  202657. {
  202658. v = *dp = *rp;
  202659. sum += (v < 128) ? v : 256 - v;
  202660. }
  202661. for (lp = row_buf + 1; i < row_bytes;
  202662. i++, rp++, lp++, dp++)
  202663. {
  202664. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202665. sum += (v < 128) ? v : 256 - v;
  202666. if (sum > lmins) /* We are already worse, don't continue. */
  202667. break;
  202668. }
  202669. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202670. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202671. {
  202672. int j;
  202673. png_uint_32 sumhi, sumlo;
  202674. sumlo = sum & PNG_LOMASK;
  202675. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202676. for (j = 0; j < num_p_filters; j++)
  202677. {
  202678. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202679. {
  202680. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202681. PNG_WEIGHT_SHIFT;
  202682. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202683. PNG_WEIGHT_SHIFT;
  202684. }
  202685. }
  202686. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202687. PNG_COST_SHIFT;
  202688. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202689. PNG_COST_SHIFT;
  202690. if (sumhi > PNG_HIMASK)
  202691. sum = PNG_MAXSUM;
  202692. else
  202693. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202694. }
  202695. #endif
  202696. if (sum < mins)
  202697. {
  202698. mins = sum;
  202699. best_row = png_ptr->sub_row;
  202700. }
  202701. }
  202702. /* up filter */
  202703. if (filter_to_do == PNG_FILTER_UP)
  202704. {
  202705. png_bytep rp, dp, pp;
  202706. png_uint_32 i;
  202707. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202708. pp = prev_row + 1; i < row_bytes;
  202709. i++, rp++, pp++, dp++)
  202710. {
  202711. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202712. }
  202713. best_row = png_ptr->up_row;
  202714. }
  202715. else if (filter_to_do & PNG_FILTER_UP)
  202716. {
  202717. png_bytep rp, dp, pp;
  202718. png_uint_32 sum = 0, lmins = mins;
  202719. png_uint_32 i;
  202720. int v;
  202721. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202722. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202723. {
  202724. int j;
  202725. png_uint_32 lmhi, lmlo;
  202726. lmlo = lmins & PNG_LOMASK;
  202727. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202728. for (j = 0; j < num_p_filters; j++)
  202729. {
  202730. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202731. {
  202732. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202733. PNG_WEIGHT_SHIFT;
  202734. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202735. PNG_WEIGHT_SHIFT;
  202736. }
  202737. }
  202738. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202739. PNG_COST_SHIFT;
  202740. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202741. PNG_COST_SHIFT;
  202742. if (lmhi > PNG_HIMASK)
  202743. lmins = PNG_MAXSUM;
  202744. else
  202745. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202746. }
  202747. #endif
  202748. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202749. pp = prev_row + 1; i < row_bytes; i++)
  202750. {
  202751. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202752. sum += (v < 128) ? v : 256 - v;
  202753. if (sum > lmins) /* We are already worse, don't continue. */
  202754. break;
  202755. }
  202756. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202757. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202758. {
  202759. int j;
  202760. png_uint_32 sumhi, sumlo;
  202761. sumlo = sum & PNG_LOMASK;
  202762. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202763. for (j = 0; j < num_p_filters; j++)
  202764. {
  202765. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202766. {
  202767. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202768. PNG_WEIGHT_SHIFT;
  202769. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202770. PNG_WEIGHT_SHIFT;
  202771. }
  202772. }
  202773. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202774. PNG_COST_SHIFT;
  202775. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202776. PNG_COST_SHIFT;
  202777. if (sumhi > PNG_HIMASK)
  202778. sum = PNG_MAXSUM;
  202779. else
  202780. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202781. }
  202782. #endif
  202783. if (sum < mins)
  202784. {
  202785. mins = sum;
  202786. best_row = png_ptr->up_row;
  202787. }
  202788. }
  202789. /* avg filter */
  202790. if (filter_to_do == PNG_FILTER_AVG)
  202791. {
  202792. png_bytep rp, dp, pp, lp;
  202793. png_uint_32 i;
  202794. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202795. pp = prev_row + 1; i < bpp; i++)
  202796. {
  202797. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202798. }
  202799. for (lp = row_buf + 1; i < row_bytes; i++)
  202800. {
  202801. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202802. & 0xff);
  202803. }
  202804. best_row = png_ptr->avg_row;
  202805. }
  202806. else if (filter_to_do & PNG_FILTER_AVG)
  202807. {
  202808. png_bytep rp, dp, pp, lp;
  202809. png_uint_32 sum = 0, lmins = mins;
  202810. png_uint_32 i;
  202811. int v;
  202812. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202813. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202814. {
  202815. int j;
  202816. png_uint_32 lmhi, lmlo;
  202817. lmlo = lmins & PNG_LOMASK;
  202818. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202819. for (j = 0; j < num_p_filters; j++)
  202820. {
  202821. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202822. {
  202823. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202824. PNG_WEIGHT_SHIFT;
  202825. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202826. PNG_WEIGHT_SHIFT;
  202827. }
  202828. }
  202829. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202830. PNG_COST_SHIFT;
  202831. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202832. PNG_COST_SHIFT;
  202833. if (lmhi > PNG_HIMASK)
  202834. lmins = PNG_MAXSUM;
  202835. else
  202836. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202837. }
  202838. #endif
  202839. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202840. pp = prev_row + 1; i < bpp; i++)
  202841. {
  202842. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202843. sum += (v < 128) ? v : 256 - v;
  202844. }
  202845. for (lp = row_buf + 1; i < row_bytes; i++)
  202846. {
  202847. v = *dp++ =
  202848. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202849. sum += (v < 128) ? v : 256 - v;
  202850. if (sum > lmins) /* We are already worse, don't continue. */
  202851. break;
  202852. }
  202853. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202854. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202855. {
  202856. int j;
  202857. png_uint_32 sumhi, sumlo;
  202858. sumlo = sum & PNG_LOMASK;
  202859. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202860. for (j = 0; j < num_p_filters; j++)
  202861. {
  202862. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202863. {
  202864. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202865. PNG_WEIGHT_SHIFT;
  202866. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202867. PNG_WEIGHT_SHIFT;
  202868. }
  202869. }
  202870. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202871. PNG_COST_SHIFT;
  202872. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202873. PNG_COST_SHIFT;
  202874. if (sumhi > PNG_HIMASK)
  202875. sum = PNG_MAXSUM;
  202876. else
  202877. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202878. }
  202879. #endif
  202880. if (sum < mins)
  202881. {
  202882. mins = sum;
  202883. best_row = png_ptr->avg_row;
  202884. }
  202885. }
  202886. /* Paeth filter */
  202887. if (filter_to_do == PNG_FILTER_PAETH)
  202888. {
  202889. png_bytep rp, dp, pp, cp, lp;
  202890. png_uint_32 i;
  202891. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202892. pp = prev_row + 1; i < bpp; i++)
  202893. {
  202894. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202895. }
  202896. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202897. {
  202898. int a, b, c, pa, pb, pc, p;
  202899. b = *pp++;
  202900. c = *cp++;
  202901. a = *lp++;
  202902. p = b - c;
  202903. pc = a - c;
  202904. #ifdef PNG_USE_ABS
  202905. pa = abs(p);
  202906. pb = abs(pc);
  202907. pc = abs(p + pc);
  202908. #else
  202909. pa = p < 0 ? -p : p;
  202910. pb = pc < 0 ? -pc : pc;
  202911. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202912. #endif
  202913. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202914. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202915. }
  202916. best_row = png_ptr->paeth_row;
  202917. }
  202918. else if (filter_to_do & PNG_FILTER_PAETH)
  202919. {
  202920. png_bytep rp, dp, pp, cp, lp;
  202921. png_uint_32 sum = 0, lmins = mins;
  202922. png_uint_32 i;
  202923. int v;
  202924. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202925. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202926. {
  202927. int j;
  202928. png_uint_32 lmhi, lmlo;
  202929. lmlo = lmins & PNG_LOMASK;
  202930. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202931. for (j = 0; j < num_p_filters; j++)
  202932. {
  202933. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202934. {
  202935. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202936. PNG_WEIGHT_SHIFT;
  202937. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202938. PNG_WEIGHT_SHIFT;
  202939. }
  202940. }
  202941. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202942. PNG_COST_SHIFT;
  202943. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202944. PNG_COST_SHIFT;
  202945. if (lmhi > PNG_HIMASK)
  202946. lmins = PNG_MAXSUM;
  202947. else
  202948. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202949. }
  202950. #endif
  202951. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202952. pp = prev_row + 1; i < bpp; i++)
  202953. {
  202954. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202955. sum += (v < 128) ? v : 256 - v;
  202956. }
  202957. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202958. {
  202959. int a, b, c, pa, pb, pc, p;
  202960. b = *pp++;
  202961. c = *cp++;
  202962. a = *lp++;
  202963. #ifndef PNG_SLOW_PAETH
  202964. p = b - c;
  202965. pc = a - c;
  202966. #ifdef PNG_USE_ABS
  202967. pa = abs(p);
  202968. pb = abs(pc);
  202969. pc = abs(p + pc);
  202970. #else
  202971. pa = p < 0 ? -p : p;
  202972. pb = pc < 0 ? -pc : pc;
  202973. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202974. #endif
  202975. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202976. #else /* PNG_SLOW_PAETH */
  202977. p = a + b - c;
  202978. pa = abs(p - a);
  202979. pb = abs(p - b);
  202980. pc = abs(p - c);
  202981. if (pa <= pb && pa <= pc)
  202982. p = a;
  202983. else if (pb <= pc)
  202984. p = b;
  202985. else
  202986. p = c;
  202987. #endif /* PNG_SLOW_PAETH */
  202988. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202989. sum += (v < 128) ? v : 256 - v;
  202990. if (sum > lmins) /* We are already worse, don't continue. */
  202991. break;
  202992. }
  202993. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202994. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202995. {
  202996. int j;
  202997. png_uint_32 sumhi, sumlo;
  202998. sumlo = sum & PNG_LOMASK;
  202999. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203000. for (j = 0; j < num_p_filters; j++)
  203001. {
  203002. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203003. {
  203004. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203005. PNG_WEIGHT_SHIFT;
  203006. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203007. PNG_WEIGHT_SHIFT;
  203008. }
  203009. }
  203010. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203011. PNG_COST_SHIFT;
  203012. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203013. PNG_COST_SHIFT;
  203014. if (sumhi > PNG_HIMASK)
  203015. sum = PNG_MAXSUM;
  203016. else
  203017. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203018. }
  203019. #endif
  203020. if (sum < mins)
  203021. {
  203022. best_row = png_ptr->paeth_row;
  203023. }
  203024. }
  203025. #endif /* PNG_NO_WRITE_FILTER */
  203026. /* Do the actual writing of the filtered row data from the chosen filter. */
  203027. png_write_filtered_row(png_ptr, best_row);
  203028. #ifndef PNG_NO_WRITE_FILTER
  203029. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203030. /* Save the type of filter we picked this time for future calculations */
  203031. if (png_ptr->num_prev_filters > 0)
  203032. {
  203033. int j;
  203034. for (j = 1; j < num_p_filters; j++)
  203035. {
  203036. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203037. }
  203038. png_ptr->prev_filters[j] = best_row[0];
  203039. }
  203040. #endif
  203041. #endif /* PNG_NO_WRITE_FILTER */
  203042. }
  203043. /* Do the actual writing of a previously filtered row. */
  203044. void /* PRIVATE */
  203045. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203046. {
  203047. png_debug(1, "in png_write_filtered_row\n");
  203048. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203049. /* set up the zlib input buffer */
  203050. png_ptr->zstream.next_in = filtered_row;
  203051. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203052. /* repeat until we have compressed all the data */
  203053. do
  203054. {
  203055. int ret; /* return of zlib */
  203056. /* compress the data */
  203057. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203058. /* check for compression errors */
  203059. if (ret != Z_OK)
  203060. {
  203061. if (png_ptr->zstream.msg != NULL)
  203062. png_error(png_ptr, png_ptr->zstream.msg);
  203063. else
  203064. png_error(png_ptr, "zlib error");
  203065. }
  203066. /* see if it is time to write another IDAT */
  203067. if (!(png_ptr->zstream.avail_out))
  203068. {
  203069. /* write the IDAT and reset the zlib output buffer */
  203070. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203071. png_ptr->zstream.next_out = png_ptr->zbuf;
  203072. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203073. }
  203074. /* repeat until all data has been compressed */
  203075. } while (png_ptr->zstream.avail_in);
  203076. /* swap the current and previous rows */
  203077. if (png_ptr->prev_row != NULL)
  203078. {
  203079. png_bytep tptr;
  203080. tptr = png_ptr->prev_row;
  203081. png_ptr->prev_row = png_ptr->row_buf;
  203082. png_ptr->row_buf = tptr;
  203083. }
  203084. /* finish row - updates counters and flushes zlib if last row */
  203085. png_write_finish_row(png_ptr);
  203086. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203087. png_ptr->flush_rows++;
  203088. if (png_ptr->flush_dist > 0 &&
  203089. png_ptr->flush_rows >= png_ptr->flush_dist)
  203090. {
  203091. png_write_flush(png_ptr);
  203092. }
  203093. #endif
  203094. }
  203095. #endif /* PNG_WRITE_SUPPORTED */
  203096. /*** End of inlined file: pngwutil.c ***/
  203097. #else
  203098. extern "C"
  203099. {
  203100. #include <png.h>
  203101. #include <pngconf.h>
  203102. }
  203103. #endif
  203104. }
  203105. #undef max
  203106. #undef min
  203107. #if JUCE_MSVC
  203108. #pragma warning (pop)
  203109. #endif
  203110. BEGIN_JUCE_NAMESPACE
  203111. using ::calloc;
  203112. using ::malloc;
  203113. using ::free;
  203114. namespace PNGHelpers
  203115. {
  203116. using namespace pnglibNamespace;
  203117. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203118. {
  203119. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203120. }
  203121. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203122. {
  203123. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203124. }
  203125. struct PNGErrorStruct {};
  203126. static void errorCallback (png_structp, png_const_charp)
  203127. {
  203128. throw PNGErrorStruct();
  203129. }
  203130. }
  203131. PNGImageFormat::PNGImageFormat() {}
  203132. PNGImageFormat::~PNGImageFormat() {}
  203133. const String PNGImageFormat::getFormatName()
  203134. {
  203135. return "PNG";
  203136. }
  203137. bool PNGImageFormat::canUnderstand (InputStream& in)
  203138. {
  203139. const int bytesNeeded = 4;
  203140. char header [bytesNeeded];
  203141. return in.read (header, bytesNeeded) == bytesNeeded
  203142. && header[1] == 'P'
  203143. && header[2] == 'N'
  203144. && header[3] == 'G';
  203145. }
  203146. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203147. const Image juce_loadWithCoreImage (InputStream& input);
  203148. #endif
  203149. const Image PNGImageFormat::decodeImage (InputStream& in)
  203150. {
  203151. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203152. return juce_loadWithCoreImage (in);
  203153. #else
  203154. using namespace pnglibNamespace;
  203155. Image image;
  203156. png_structp pngReadStruct;
  203157. png_infop pngInfoStruct;
  203158. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203159. if (pngReadStruct != 0)
  203160. {
  203161. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203162. if (pngInfoStruct == 0)
  203163. {
  203164. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203165. return Image::null;
  203166. }
  203167. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203168. // read the header..
  203169. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203170. png_uint_32 width, height;
  203171. int bitDepth, colorType, interlaceType;
  203172. png_read_info (pngReadStruct, pngInfoStruct);
  203173. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203174. &width, &height,
  203175. &bitDepth, &colorType,
  203176. &interlaceType, 0, 0);
  203177. if (bitDepth == 16)
  203178. png_set_strip_16 (pngReadStruct);
  203179. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203180. png_set_expand (pngReadStruct);
  203181. if (bitDepth < 8)
  203182. png_set_expand (pngReadStruct);
  203183. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203184. png_set_expand (pngReadStruct);
  203185. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203186. png_set_gray_to_rgb (pngReadStruct);
  203187. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203188. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203189. || pngInfoStruct->num_trans > 0;
  203190. // Load the image into a temp buffer in the pnglib format..
  203191. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203192. {
  203193. HeapBlock <png_bytep> rows (height);
  203194. for (int y = (int) height; --y >= 0;)
  203195. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203196. png_read_image (pngReadStruct, rows);
  203197. png_read_end (pngReadStruct, pngInfoStruct);
  203198. }
  203199. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203200. // now convert the data to a juce image format..
  203201. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203202. (int) width, (int) height, hasAlphaChan);
  203203. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203204. const Image::BitmapData destData (image, true);
  203205. uint8* srcRow = tempBuffer;
  203206. uint8* destRow = destData.data;
  203207. for (int y = 0; y < (int) height; ++y)
  203208. {
  203209. const uint8* src = srcRow;
  203210. srcRow += (width << 2);
  203211. uint8* dest = destRow;
  203212. destRow += destData.lineStride;
  203213. if (hasAlphaChan)
  203214. {
  203215. for (int i = (int) width; --i >= 0;)
  203216. {
  203217. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203218. ((PixelARGB*) dest)->premultiply();
  203219. dest += destData.pixelStride;
  203220. src += 4;
  203221. }
  203222. }
  203223. else
  203224. {
  203225. for (int i = (int) width; --i >= 0;)
  203226. {
  203227. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203228. dest += destData.pixelStride;
  203229. src += 4;
  203230. }
  203231. }
  203232. }
  203233. }
  203234. return image;
  203235. #endif
  203236. }
  203237. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203238. {
  203239. using namespace pnglibNamespace;
  203240. const int width = image.getWidth();
  203241. const int height = image.getHeight();
  203242. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203243. if (pngWriteStruct == 0)
  203244. return false;
  203245. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203246. if (pngInfoStruct == 0)
  203247. {
  203248. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203249. return false;
  203250. }
  203251. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203252. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203253. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203254. : PNG_COLOR_TYPE_RGB,
  203255. PNG_INTERLACE_NONE,
  203256. PNG_COMPRESSION_TYPE_BASE,
  203257. PNG_FILTER_TYPE_BASE);
  203258. HeapBlock <uint8> rowData (width * 4);
  203259. png_color_8 sig_bit;
  203260. sig_bit.red = 8;
  203261. sig_bit.green = 8;
  203262. sig_bit.blue = 8;
  203263. sig_bit.alpha = 8;
  203264. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203265. png_write_info (pngWriteStruct, pngInfoStruct);
  203266. png_set_shift (pngWriteStruct, &sig_bit);
  203267. png_set_packing (pngWriteStruct);
  203268. const Image::BitmapData srcData (image, false);
  203269. for (int y = 0; y < height; ++y)
  203270. {
  203271. uint8* dst = rowData;
  203272. const uint8* src = srcData.getLinePointer (y);
  203273. if (image.hasAlphaChannel())
  203274. {
  203275. for (int i = width; --i >= 0;)
  203276. {
  203277. PixelARGB p (*(const PixelARGB*) src);
  203278. p.unpremultiply();
  203279. *dst++ = p.getRed();
  203280. *dst++ = p.getGreen();
  203281. *dst++ = p.getBlue();
  203282. *dst++ = p.getAlpha();
  203283. src += srcData.pixelStride;
  203284. }
  203285. }
  203286. else
  203287. {
  203288. for (int i = width; --i >= 0;)
  203289. {
  203290. *dst++ = ((const PixelRGB*) src)->getRed();
  203291. *dst++ = ((const PixelRGB*) src)->getGreen();
  203292. *dst++ = ((const PixelRGB*) src)->getBlue();
  203293. src += srcData.pixelStride;
  203294. }
  203295. }
  203296. png_write_rows (pngWriteStruct, &rowData, 1);
  203297. }
  203298. png_write_end (pngWriteStruct, pngInfoStruct);
  203299. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203300. out.flush();
  203301. return true;
  203302. }
  203303. END_JUCE_NAMESPACE
  203304. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203305. #endif
  203306. //==============================================================================
  203307. #if JUCE_BUILD_NATIVE
  203308. #if JUCE_WINDOWS
  203309. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203310. /*
  203311. This file wraps together all the win32-specific code, so that
  203312. we can include all the native headers just once, and compile all our
  203313. platform-specific stuff in one big lump, keeping it out of the way of
  203314. the rest of the codebase.
  203315. */
  203316. #if JUCE_WINDOWS
  203317. BEGIN_JUCE_NAMESPACE
  203318. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203319. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203320. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203321. /**
  203322. Helper class that takes chunks of incoming midi bytes, packages them into
  203323. messages, and dispatches them to a midi callback.
  203324. */
  203325. class MidiDataConcatenator
  203326. {
  203327. public:
  203328. MidiDataConcatenator (const int initialBufferSize)
  203329. : pendingData (initialBufferSize),
  203330. pendingBytes (0), pendingDataTime (0)
  203331. {
  203332. }
  203333. void reset()
  203334. {
  203335. pendingBytes = 0;
  203336. pendingDataTime = 0;
  203337. }
  203338. void pushMidiData (const void* data, int numBytes, double time,
  203339. MidiInput* input, MidiInputCallback& callback)
  203340. {
  203341. const uint8* d = static_cast <const uint8*> (data);
  203342. while (numBytes > 0)
  203343. {
  203344. if (pendingBytes > 0 || d[0] == 0xf0)
  203345. {
  203346. processSysex (d, numBytes, time, input, callback);
  203347. }
  203348. else
  203349. {
  203350. int used = 0;
  203351. const MidiMessage m (d, numBytes, used, 0, time);
  203352. if (used <= 0)
  203353. {
  203354. jassertfalse; // malformed midi message
  203355. break;
  203356. }
  203357. callback.handleIncomingMidiMessage (input, m);
  203358. numBytes -= used;
  203359. d += used;
  203360. }
  203361. }
  203362. }
  203363. private:
  203364. void processSysex (const uint8*& d, int& numBytes, double time,
  203365. MidiInput* input, MidiInputCallback& callback)
  203366. {
  203367. if (*d == 0xf0)
  203368. {
  203369. pendingBytes = 0;
  203370. pendingDataTime = time;
  203371. }
  203372. pendingData.ensureSize (pendingBytes + numBytes, false);
  203373. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203374. uint8* dest = totalMessage + pendingBytes;
  203375. do
  203376. {
  203377. if (pendingBytes > 0 && *d >= 0x80)
  203378. {
  203379. if (*d >= 0xfa || *d == 0xf8)
  203380. {
  203381. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203382. ++d;
  203383. --numBytes;
  203384. }
  203385. else
  203386. {
  203387. if (*d == 0xf7)
  203388. {
  203389. *dest++ = *d++;
  203390. pendingBytes++;
  203391. --numBytes;
  203392. }
  203393. break;
  203394. }
  203395. }
  203396. else
  203397. {
  203398. *dest++ = *d++;
  203399. pendingBytes++;
  203400. --numBytes;
  203401. }
  203402. }
  203403. while (numBytes > 0);
  203404. if (pendingBytes > 0)
  203405. {
  203406. if (totalMessage [pendingBytes - 1] == 0xf7)
  203407. {
  203408. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203409. pendingBytes = 0;
  203410. }
  203411. else
  203412. {
  203413. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203414. }
  203415. }
  203416. }
  203417. MemoryBlock pendingData;
  203418. int pendingBytes;
  203419. double pendingDataTime;
  203420. MidiDataConcatenator (const MidiDataConcatenator&);
  203421. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203422. };
  203423. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203424. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203425. #define JUCE_INCLUDED_FILE 1
  203426. // Now include the actual code files..
  203427. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203428. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203429. // compiled on its own).
  203430. #if JUCE_INCLUDED_FILE
  203431. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203432. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203433. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203434. #ifndef DOXYGEN
  203435. // use with DynamicLibraryLoader to simplify importing functions
  203436. //
  203437. // functionName: function to import
  203438. // localFunctionName: name you want to use to actually call it (must be different)
  203439. // returnType: the return type
  203440. // object: the DynamicLibraryLoader to use
  203441. // params: list of params (bracketed)
  203442. //
  203443. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203444. typedef returnType (WINAPI *type##localFunctionName) params; \
  203445. type##localFunctionName localFunctionName \
  203446. = (type##localFunctionName)object.findProcAddress (#functionName);
  203447. // loads and unloads a DLL automatically
  203448. class JUCE_API DynamicLibraryLoader
  203449. {
  203450. public:
  203451. DynamicLibraryLoader (const String& name);
  203452. ~DynamicLibraryLoader();
  203453. void* findProcAddress (const String& functionName);
  203454. private:
  203455. void* libHandle;
  203456. };
  203457. #endif
  203458. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203459. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203460. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203461. {
  203462. libHandle = LoadLibrary (name);
  203463. }
  203464. DynamicLibraryLoader::~DynamicLibraryLoader()
  203465. {
  203466. FreeLibrary ((HMODULE) libHandle);
  203467. }
  203468. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203469. {
  203470. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203471. }
  203472. #endif
  203473. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203474. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203475. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203476. // compiled on its own).
  203477. #if JUCE_INCLUDED_FILE
  203478. extern void juce_initialiseThreadEvents();
  203479. void Logger::outputDebugString (const String& text)
  203480. {
  203481. OutputDebugString (text + "\n");
  203482. }
  203483. static int64 hiResTicksPerSecond;
  203484. static double hiResTicksScaleFactor;
  203485. #if JUCE_USE_INTRINSICS
  203486. // CPU info functions using intrinsics...
  203487. #pragma intrinsic (__cpuid)
  203488. #pragma intrinsic (__rdtsc)
  203489. const String SystemStats::getCpuVendor()
  203490. {
  203491. int info [4];
  203492. __cpuid (info, 0);
  203493. char v [12];
  203494. memcpy (v, info + 1, 4);
  203495. memcpy (v + 4, info + 3, 4);
  203496. memcpy (v + 8, info + 2, 4);
  203497. return String (v, 12);
  203498. }
  203499. #else
  203500. // CPU info functions using old fashioned inline asm...
  203501. static void juce_getCpuVendor (char* const v)
  203502. {
  203503. int vendor[4];
  203504. zeromem (vendor, 16);
  203505. #ifdef JUCE_64BIT
  203506. #else
  203507. #ifndef __MINGW32__
  203508. __try
  203509. #endif
  203510. {
  203511. #if JUCE_GCC
  203512. unsigned int dummy = 0;
  203513. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203514. #else
  203515. __asm
  203516. {
  203517. mov eax, 0
  203518. cpuid
  203519. mov [vendor], ebx
  203520. mov [vendor + 4], edx
  203521. mov [vendor + 8], ecx
  203522. }
  203523. #endif
  203524. }
  203525. #ifndef __MINGW32__
  203526. __except (EXCEPTION_EXECUTE_HANDLER)
  203527. {
  203528. *v = 0;
  203529. }
  203530. #endif
  203531. #endif
  203532. memcpy (v, vendor, 16);
  203533. }
  203534. const String SystemStats::getCpuVendor()
  203535. {
  203536. char v [16];
  203537. juce_getCpuVendor (v);
  203538. return String (v, 16);
  203539. }
  203540. #endif
  203541. void SystemStats::initialiseStats()
  203542. {
  203543. juce_initialiseThreadEvents();
  203544. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203545. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203546. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203547. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203548. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203549. #else
  203550. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203551. #endif
  203552. {
  203553. SYSTEM_INFO systemInfo;
  203554. GetSystemInfo (&systemInfo);
  203555. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203556. }
  203557. LARGE_INTEGER f;
  203558. QueryPerformanceFrequency (&f);
  203559. hiResTicksPerSecond = f.QuadPart;
  203560. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203561. String s (SystemStats::getJUCEVersion());
  203562. const MMRESULT res = timeBeginPeriod (1);
  203563. (void) res;
  203564. jassert (res == TIMERR_NOERROR);
  203565. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203566. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203567. #endif
  203568. }
  203569. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203570. {
  203571. OSVERSIONINFO info;
  203572. info.dwOSVersionInfoSize = sizeof (info);
  203573. GetVersionEx (&info);
  203574. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203575. {
  203576. switch (info.dwMajorVersion)
  203577. {
  203578. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203579. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203580. default: jassertfalse; break; // !! not a supported OS!
  203581. }
  203582. }
  203583. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203584. {
  203585. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203586. return Win98;
  203587. }
  203588. return UnknownOS;
  203589. }
  203590. const String SystemStats::getOperatingSystemName()
  203591. {
  203592. const char* name = "Unknown OS";
  203593. switch (getOperatingSystemType())
  203594. {
  203595. case Windows7: name = "Windows 7"; break;
  203596. case WinVista: name = "Windows Vista"; break;
  203597. case WinXP: name = "Windows XP"; break;
  203598. case Win2000: name = "Windows 2000"; break;
  203599. case Win98: name = "Windows 98"; break;
  203600. default: jassertfalse; break; // !! new type of OS?
  203601. }
  203602. return name;
  203603. }
  203604. bool SystemStats::isOperatingSystem64Bit()
  203605. {
  203606. #ifdef _WIN64
  203607. return true;
  203608. #else
  203609. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203610. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203611. BOOL isWow64 = FALSE;
  203612. return (fnIsWow64Process != 0)
  203613. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203614. && (isWow64 != FALSE);
  203615. #endif
  203616. }
  203617. int SystemStats::getMemorySizeInMegabytes()
  203618. {
  203619. MEMORYSTATUSEX mem;
  203620. mem.dwLength = sizeof (mem);
  203621. GlobalMemoryStatusEx (&mem);
  203622. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203623. }
  203624. uint32 juce_millisecondsSinceStartup() throw()
  203625. {
  203626. return (uint32) timeGetTime();
  203627. }
  203628. int64 Time::getHighResolutionTicks() throw()
  203629. {
  203630. LARGE_INTEGER ticks;
  203631. QueryPerformanceCounter (&ticks);
  203632. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203633. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203634. // fix for a very obscure PCI hardware bug that can make the counter
  203635. // sometimes jump forwards by a few seconds..
  203636. static int64 hiResTicksOffset = 0;
  203637. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203638. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203639. hiResTicksOffset = newOffset;
  203640. return ticks.QuadPart + hiResTicksOffset;
  203641. }
  203642. double Time::getMillisecondCounterHiRes() throw()
  203643. {
  203644. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203645. }
  203646. int64 Time::getHighResolutionTicksPerSecond() throw()
  203647. {
  203648. return hiResTicksPerSecond;
  203649. }
  203650. static int64 juce_getClockCycleCounter() throw()
  203651. {
  203652. #if JUCE_USE_INTRINSICS
  203653. // MS intrinsics version...
  203654. return __rdtsc();
  203655. #elif JUCE_GCC
  203656. // GNU inline asm version...
  203657. unsigned int hi = 0, lo = 0;
  203658. __asm__ __volatile__ (
  203659. "xor %%eax, %%eax \n\
  203660. xor %%edx, %%edx \n\
  203661. rdtsc \n\
  203662. movl %%eax, %[lo] \n\
  203663. movl %%edx, %[hi]"
  203664. :
  203665. : [hi] "m" (hi),
  203666. [lo] "m" (lo)
  203667. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203668. return (int64) ((((uint64) hi) << 32) | lo);
  203669. #else
  203670. // MSVC inline asm version...
  203671. unsigned int hi = 0, lo = 0;
  203672. __asm
  203673. {
  203674. xor eax, eax
  203675. xor edx, edx
  203676. rdtsc
  203677. mov lo, eax
  203678. mov hi, edx
  203679. }
  203680. return (int64) ((((uint64) hi) << 32) | lo);
  203681. #endif
  203682. }
  203683. int SystemStats::getCpuSpeedInMegaherz()
  203684. {
  203685. const int64 cycles = juce_getClockCycleCounter();
  203686. const uint32 millis = Time::getMillisecondCounter();
  203687. int lastResult = 0;
  203688. for (;;)
  203689. {
  203690. int n = 1000000;
  203691. while (--n > 0) {}
  203692. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203693. const int64 cyclesNow = juce_getClockCycleCounter();
  203694. if (millisElapsed > 80)
  203695. {
  203696. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203697. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203698. return newResult;
  203699. lastResult = newResult;
  203700. }
  203701. }
  203702. }
  203703. bool Time::setSystemTimeToThisTime() const
  203704. {
  203705. SYSTEMTIME st;
  203706. st.wDayOfWeek = 0;
  203707. st.wYear = (WORD) getYear();
  203708. st.wMonth = (WORD) (getMonth() + 1);
  203709. st.wDay = (WORD) getDayOfMonth();
  203710. st.wHour = (WORD) getHours();
  203711. st.wMinute = (WORD) getMinutes();
  203712. st.wSecond = (WORD) getSeconds();
  203713. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203714. // do this twice because of daylight saving conversion problems - the
  203715. // first one sets it up, the second one kicks it in.
  203716. return SetLocalTime (&st) != 0
  203717. && SetLocalTime (&st) != 0;
  203718. }
  203719. int SystemStats::getPageSize()
  203720. {
  203721. SYSTEM_INFO systemInfo;
  203722. GetSystemInfo (&systemInfo);
  203723. return systemInfo.dwPageSize;
  203724. }
  203725. const String SystemStats::getLogonName()
  203726. {
  203727. TCHAR text [256];
  203728. DWORD len = numElementsInArray (text) - 2;
  203729. zerostruct (text);
  203730. GetUserName (text, &len);
  203731. return String (text, len);
  203732. }
  203733. const String SystemStats::getFullUserName()
  203734. {
  203735. return getLogonName();
  203736. }
  203737. #endif
  203738. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203739. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203740. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203741. // compiled on its own).
  203742. #if JUCE_INCLUDED_FILE
  203743. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203744. extern HWND juce_messageWindowHandle;
  203745. #endif
  203746. #if ! JUCE_USE_INTRINSICS
  203747. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203748. // older ones we have to actually call the ops as win32 functions..
  203749. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203750. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203751. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203752. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203753. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203754. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203755. {
  203756. jassertfalse; // This operation isn't available in old MS compiler versions!
  203757. __int64 oldValue = *value;
  203758. if (oldValue == valueToCompare)
  203759. *value = newValue;
  203760. return oldValue;
  203761. }
  203762. #endif
  203763. CriticalSection::CriticalSection() throw()
  203764. {
  203765. // (just to check the MS haven't changed this structure and broken things...)
  203766. #if _MSC_VER >= 1400
  203767. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203768. #else
  203769. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203770. #endif
  203771. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203772. }
  203773. CriticalSection::~CriticalSection() throw()
  203774. {
  203775. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203776. }
  203777. void CriticalSection::enter() const throw()
  203778. {
  203779. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203780. }
  203781. bool CriticalSection::tryEnter() const throw()
  203782. {
  203783. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203784. }
  203785. void CriticalSection::exit() const throw()
  203786. {
  203787. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203788. }
  203789. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203790. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203791. {
  203792. }
  203793. WaitableEvent::~WaitableEvent() throw()
  203794. {
  203795. CloseHandle (internal);
  203796. }
  203797. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203798. {
  203799. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203800. }
  203801. void WaitableEvent::signal() const throw()
  203802. {
  203803. SetEvent (internal);
  203804. }
  203805. void WaitableEvent::reset() const throw()
  203806. {
  203807. ResetEvent (internal);
  203808. }
  203809. void JUCE_API juce_threadEntryPoint (void*);
  203810. static unsigned int __stdcall threadEntryProc (void* userData)
  203811. {
  203812. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203813. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203814. GetCurrentThreadId(), TRUE);
  203815. #endif
  203816. juce_threadEntryPoint (userData);
  203817. _endthreadex (0);
  203818. return 0;
  203819. }
  203820. void juce_CloseThreadHandle (void* handle)
  203821. {
  203822. CloseHandle ((HANDLE) handle);
  203823. }
  203824. void* juce_createThread (void* userData)
  203825. {
  203826. unsigned int threadId;
  203827. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203828. }
  203829. void juce_killThread (void* handle)
  203830. {
  203831. if (handle != 0)
  203832. {
  203833. #if JUCE_DEBUG
  203834. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203835. #endif
  203836. TerminateThread (handle, 0);
  203837. }
  203838. }
  203839. void juce_setCurrentThreadName (const String& name)
  203840. {
  203841. #if JUCE_DEBUG && JUCE_MSVC
  203842. struct
  203843. {
  203844. DWORD dwType;
  203845. LPCSTR szName;
  203846. DWORD dwThreadID;
  203847. DWORD dwFlags;
  203848. } info;
  203849. info.dwType = 0x1000;
  203850. info.szName = name.toCString();
  203851. info.dwThreadID = GetCurrentThreadId();
  203852. info.dwFlags = 0;
  203853. __try
  203854. {
  203855. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203856. }
  203857. __except (EXCEPTION_CONTINUE_EXECUTION)
  203858. {}
  203859. #else
  203860. (void) name;
  203861. #endif
  203862. }
  203863. Thread::ThreadID Thread::getCurrentThreadId()
  203864. {
  203865. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203866. }
  203867. // priority 1 to 10 where 5=normal, 1=low
  203868. bool juce_setThreadPriority (void* threadHandle, int priority)
  203869. {
  203870. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203871. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203872. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203873. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203874. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203875. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203876. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203877. if (threadHandle == 0)
  203878. threadHandle = GetCurrentThread();
  203879. return SetThreadPriority (threadHandle, pri) != FALSE;
  203880. }
  203881. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203882. {
  203883. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203884. }
  203885. static HANDLE sleepEvent = 0;
  203886. void juce_initialiseThreadEvents()
  203887. {
  203888. if (sleepEvent == 0)
  203889. #if JUCE_DEBUG
  203890. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203891. #else
  203892. sleepEvent = CreateEvent (0, 0, 0, 0);
  203893. #endif
  203894. }
  203895. void Thread::yield()
  203896. {
  203897. Sleep (0);
  203898. }
  203899. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203900. {
  203901. if (millisecs >= 10)
  203902. {
  203903. Sleep (millisecs);
  203904. }
  203905. else
  203906. {
  203907. jassert (sleepEvent != 0);
  203908. // unlike Sleep() this is guaranteed to return to the current thread after
  203909. // the time expires, so we'll use this for short waits, which are more likely
  203910. // to need to be accurate
  203911. WaitForSingleObject (sleepEvent, millisecs);
  203912. }
  203913. }
  203914. static int lastProcessPriority = -1;
  203915. // called by WindowDriver because Windows does wierd things to process priority
  203916. // when you swap apps, and this forces an update when the app is brought to the front.
  203917. void juce_repeatLastProcessPriority()
  203918. {
  203919. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203920. {
  203921. DWORD p;
  203922. switch (lastProcessPriority)
  203923. {
  203924. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203925. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203926. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203927. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203928. default: jassertfalse; return; // bad priority value
  203929. }
  203930. SetPriorityClass (GetCurrentProcess(), p);
  203931. }
  203932. }
  203933. void Process::setPriority (ProcessPriority prior)
  203934. {
  203935. if (lastProcessPriority != (int) prior)
  203936. {
  203937. lastProcessPriority = (int) prior;
  203938. juce_repeatLastProcessPriority();
  203939. }
  203940. }
  203941. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203942. {
  203943. return IsDebuggerPresent() != FALSE;
  203944. }
  203945. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203946. {
  203947. return juce_isRunningUnderDebugger();
  203948. }
  203949. void Process::raisePrivilege()
  203950. {
  203951. jassertfalse; // xxx not implemented
  203952. }
  203953. void Process::lowerPrivilege()
  203954. {
  203955. jassertfalse; // xxx not implemented
  203956. }
  203957. void Process::terminate()
  203958. {
  203959. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203960. _CrtDumpMemoryLeaks();
  203961. #endif
  203962. // bullet in the head in case there's a problem shutting down..
  203963. ExitProcess (0);
  203964. }
  203965. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203966. {
  203967. void* result = 0;
  203968. JUCE_TRY
  203969. {
  203970. result = LoadLibrary (name);
  203971. }
  203972. JUCE_CATCH_ALL
  203973. return result;
  203974. }
  203975. void PlatformUtilities::freeDynamicLibrary (void* h)
  203976. {
  203977. JUCE_TRY
  203978. {
  203979. if (h != 0)
  203980. FreeLibrary ((HMODULE) h);
  203981. }
  203982. JUCE_CATCH_ALL
  203983. }
  203984. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203985. {
  203986. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203987. }
  203988. class InterProcessLock::Pimpl
  203989. {
  203990. public:
  203991. Pimpl (const String& name, const int timeOutMillisecs)
  203992. : handle (0), refCount (1)
  203993. {
  203994. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203995. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203996. {
  203997. if (timeOutMillisecs == 0)
  203998. {
  203999. close();
  204000. return;
  204001. }
  204002. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204003. {
  204004. case WAIT_OBJECT_0:
  204005. case WAIT_ABANDONED:
  204006. break;
  204007. case WAIT_TIMEOUT:
  204008. default:
  204009. close();
  204010. break;
  204011. }
  204012. }
  204013. }
  204014. ~Pimpl()
  204015. {
  204016. close();
  204017. }
  204018. void close()
  204019. {
  204020. if (handle != 0)
  204021. {
  204022. ReleaseMutex (handle);
  204023. CloseHandle (handle);
  204024. handle = 0;
  204025. }
  204026. }
  204027. HANDLE handle;
  204028. int refCount;
  204029. };
  204030. InterProcessLock::InterProcessLock (const String& name_)
  204031. : name (name_)
  204032. {
  204033. }
  204034. InterProcessLock::~InterProcessLock()
  204035. {
  204036. }
  204037. bool InterProcessLock::enter (const int timeOutMillisecs)
  204038. {
  204039. const ScopedLock sl (lock);
  204040. if (pimpl == 0)
  204041. {
  204042. pimpl = new Pimpl (name, timeOutMillisecs);
  204043. if (pimpl->handle == 0)
  204044. pimpl = 0;
  204045. }
  204046. else
  204047. {
  204048. pimpl->refCount++;
  204049. }
  204050. return pimpl != 0;
  204051. }
  204052. void InterProcessLock::exit()
  204053. {
  204054. const ScopedLock sl (lock);
  204055. // Trying to release the lock too many times!
  204056. jassert (pimpl != 0);
  204057. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204058. pimpl = 0;
  204059. }
  204060. #endif
  204061. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204062. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204063. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204064. // compiled on its own).
  204065. #if JUCE_INCLUDED_FILE
  204066. #ifndef CSIDL_MYMUSIC
  204067. #define CSIDL_MYMUSIC 0x000d
  204068. #endif
  204069. #ifndef CSIDL_MYVIDEO
  204070. #define CSIDL_MYVIDEO 0x000e
  204071. #endif
  204072. #ifndef INVALID_FILE_ATTRIBUTES
  204073. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204074. #endif
  204075. const juce_wchar File::separator = '\\';
  204076. const String File::separatorString ("\\");
  204077. bool File::exists() const
  204078. {
  204079. return fullPath.isNotEmpty()
  204080. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204081. }
  204082. bool File::existsAsFile() const
  204083. {
  204084. return fullPath.isNotEmpty()
  204085. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204086. }
  204087. bool File::isDirectory() const
  204088. {
  204089. const DWORD attr = GetFileAttributes (fullPath);
  204090. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204091. }
  204092. bool File::hasWriteAccess() const
  204093. {
  204094. if (exists())
  204095. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204096. // on windows, it seems that even read-only directories can still be written into,
  204097. // so checking the parent directory's permissions would return the wrong result..
  204098. return true;
  204099. }
  204100. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204101. {
  204102. DWORD attr = GetFileAttributes (fullPath);
  204103. if (attr == INVALID_FILE_ATTRIBUTES)
  204104. return false;
  204105. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204106. return true;
  204107. if (shouldBeReadOnly)
  204108. attr |= FILE_ATTRIBUTE_READONLY;
  204109. else
  204110. attr &= ~FILE_ATTRIBUTE_READONLY;
  204111. return SetFileAttributes (fullPath, attr) != FALSE;
  204112. }
  204113. bool File::isHidden() const
  204114. {
  204115. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204116. }
  204117. bool File::deleteFile() const
  204118. {
  204119. if (! exists())
  204120. return true;
  204121. else if (isDirectory())
  204122. return RemoveDirectory (fullPath) != 0;
  204123. else
  204124. return DeleteFile (fullPath) != 0;
  204125. }
  204126. bool File::moveToTrash() const
  204127. {
  204128. if (! exists())
  204129. return true;
  204130. SHFILEOPSTRUCT fos;
  204131. zerostruct (fos);
  204132. // The string we pass in must be double null terminated..
  204133. String doubleNullTermPath (getFullPathName() + " ");
  204134. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204135. p [getFullPathName().length()] = 0;
  204136. fos.wFunc = FO_DELETE;
  204137. fos.pFrom = p;
  204138. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204139. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204140. return SHFileOperation (&fos) == 0;
  204141. }
  204142. bool File::copyInternal (const File& dest) const
  204143. {
  204144. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204145. }
  204146. bool File::moveInternal (const File& dest) const
  204147. {
  204148. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204149. }
  204150. void File::createDirectoryInternal (const String& fileName) const
  204151. {
  204152. CreateDirectory (fileName, 0);
  204153. }
  204154. int64 juce_fileSetPosition (void* handle, int64 pos)
  204155. {
  204156. LARGE_INTEGER li;
  204157. li.QuadPart = pos;
  204158. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204159. return li.QuadPart;
  204160. }
  204161. void FileInputStream::openHandle()
  204162. {
  204163. totalSize = file.getSize();
  204164. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204165. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204166. if (h != INVALID_HANDLE_VALUE)
  204167. fileHandle = (void*) h;
  204168. }
  204169. void FileInputStream::closeHandle()
  204170. {
  204171. CloseHandle ((HANDLE) fileHandle);
  204172. }
  204173. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204174. {
  204175. if (fileHandle != 0)
  204176. {
  204177. DWORD actualNum = 0;
  204178. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204179. return (size_t) actualNum;
  204180. }
  204181. return 0;
  204182. }
  204183. void FileOutputStream::openHandle()
  204184. {
  204185. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204186. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204187. if (h != INVALID_HANDLE_VALUE)
  204188. {
  204189. LARGE_INTEGER li;
  204190. li.QuadPart = 0;
  204191. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204192. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204193. {
  204194. fileHandle = (void*) h;
  204195. currentPosition = li.QuadPart;
  204196. }
  204197. }
  204198. }
  204199. void FileOutputStream::closeHandle()
  204200. {
  204201. CloseHandle ((HANDLE) fileHandle);
  204202. }
  204203. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204204. {
  204205. if (fileHandle != 0)
  204206. {
  204207. DWORD actualNum = 0;
  204208. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204209. return (int) actualNum;
  204210. }
  204211. return 0;
  204212. }
  204213. void FileOutputStream::flushInternal()
  204214. {
  204215. if (fileHandle != 0)
  204216. FlushFileBuffers ((HANDLE) fileHandle);
  204217. }
  204218. int64 File::getSize() const
  204219. {
  204220. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204221. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204222. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204223. return 0;
  204224. }
  204225. static int64 fileTimeToTime (const FILETIME* const ft)
  204226. {
  204227. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204228. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204229. }
  204230. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204231. {
  204232. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204233. }
  204234. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204235. {
  204236. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204237. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204238. {
  204239. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204240. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204241. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204242. }
  204243. else
  204244. {
  204245. creationTime = accessTime = modificationTime = 0;
  204246. }
  204247. }
  204248. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204249. {
  204250. bool ok = false;
  204251. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204252. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204253. if (h != INVALID_HANDLE_VALUE)
  204254. {
  204255. FILETIME m, a, c;
  204256. timeToFileTime (modificationTime, &m);
  204257. timeToFileTime (accessTime, &a);
  204258. timeToFileTime (creationTime, &c);
  204259. ok = SetFileTime (h,
  204260. creationTime > 0 ? &c : 0,
  204261. accessTime > 0 ? &a : 0,
  204262. modificationTime > 0 ? &m : 0) != 0;
  204263. CloseHandle (h);
  204264. }
  204265. return ok;
  204266. }
  204267. void File::findFileSystemRoots (Array<File>& destArray)
  204268. {
  204269. TCHAR buffer [2048];
  204270. buffer[0] = 0;
  204271. buffer[1] = 0;
  204272. GetLogicalDriveStrings (2048, buffer);
  204273. const TCHAR* n = buffer;
  204274. StringArray roots;
  204275. while (*n != 0)
  204276. {
  204277. roots.add (String (n));
  204278. while (*n++ != 0)
  204279. {}
  204280. }
  204281. roots.sort (true);
  204282. for (int i = 0; i < roots.size(); ++i)
  204283. destArray.add (roots [i]);
  204284. }
  204285. static const String getDriveFromPath (const String& path)
  204286. {
  204287. if (path.isNotEmpty() && path[1] == ':')
  204288. return path.substring (0, 2) + '\\';
  204289. return path;
  204290. }
  204291. const String File::getVolumeLabel() const
  204292. {
  204293. TCHAR dest[64];
  204294. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204295. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204296. dest[0] = 0;
  204297. return dest;
  204298. }
  204299. int File::getVolumeSerialNumber() const
  204300. {
  204301. TCHAR dest[64];
  204302. DWORD serialNum;
  204303. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204304. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204305. return 0;
  204306. return (int) serialNum;
  204307. }
  204308. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204309. {
  204310. ULARGE_INTEGER spc, tot, totFree;
  204311. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204312. return total ? (int64) tot.QuadPart
  204313. : (int64) spc.QuadPart;
  204314. return 0;
  204315. }
  204316. int64 File::getBytesFreeOnVolume() const
  204317. {
  204318. return getDiskSpaceInfo (getFullPathName(), false);
  204319. }
  204320. int64 File::getVolumeTotalSize() const
  204321. {
  204322. return getDiskSpaceInfo (getFullPathName(), true);
  204323. }
  204324. static unsigned int getWindowsDriveType (const String& path)
  204325. {
  204326. return GetDriveType (getDriveFromPath (path));
  204327. }
  204328. bool File::isOnCDRomDrive() const
  204329. {
  204330. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204331. }
  204332. bool File::isOnHardDisk() const
  204333. {
  204334. if (fullPath.isEmpty())
  204335. return false;
  204336. const unsigned int n = getWindowsDriveType (getFullPathName());
  204337. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204338. return n != DRIVE_REMOVABLE;
  204339. else
  204340. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204341. }
  204342. bool File::isOnRemovableDrive() const
  204343. {
  204344. if (fullPath.isEmpty())
  204345. return false;
  204346. const unsigned int n = getWindowsDriveType (getFullPathName());
  204347. return n == DRIVE_CDROM
  204348. || n == DRIVE_REMOTE
  204349. || n == DRIVE_REMOVABLE
  204350. || n == DRIVE_RAMDISK;
  204351. }
  204352. static const File juce_getSpecialFolderPath (int type)
  204353. {
  204354. WCHAR path [MAX_PATH + 256];
  204355. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204356. return File (String (path));
  204357. return File::nonexistent;
  204358. }
  204359. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204360. {
  204361. int csidlType = 0;
  204362. switch (type)
  204363. {
  204364. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204365. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204366. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204367. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204368. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204369. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204370. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204371. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204372. case tempDirectory:
  204373. {
  204374. WCHAR dest [2048];
  204375. dest[0] = 0;
  204376. GetTempPath (numElementsInArray (dest), dest);
  204377. return File (String (dest));
  204378. }
  204379. case invokedExecutableFile:
  204380. case currentExecutableFile:
  204381. case currentApplicationFile:
  204382. {
  204383. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204384. WCHAR dest [MAX_PATH + 256];
  204385. dest[0] = 0;
  204386. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204387. return File (String (dest));
  204388. }
  204389. case hostApplicationPath:
  204390. {
  204391. WCHAR dest [MAX_PATH + 256];
  204392. dest[0] = 0;
  204393. GetModuleFileName (0, dest, numElementsInArray (dest));
  204394. return File (String (dest));
  204395. }
  204396. default:
  204397. jassertfalse; // unknown type?
  204398. return File::nonexistent;
  204399. }
  204400. return juce_getSpecialFolderPath (csidlType);
  204401. }
  204402. const File File::getCurrentWorkingDirectory()
  204403. {
  204404. WCHAR dest [MAX_PATH + 256];
  204405. dest[0] = 0;
  204406. GetCurrentDirectory (numElementsInArray (dest), dest);
  204407. return File (String (dest));
  204408. }
  204409. bool File::setAsCurrentWorkingDirectory() const
  204410. {
  204411. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204412. }
  204413. const String File::getVersion() const
  204414. {
  204415. String result;
  204416. DWORD handle = 0;
  204417. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204418. HeapBlock<char> buffer;
  204419. buffer.calloc (bufferSize);
  204420. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204421. {
  204422. VS_FIXEDFILEINFO* vffi;
  204423. UINT len = 0;
  204424. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204425. {
  204426. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204427. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204428. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204429. << (int) LOWORD (vffi->dwFileVersionLS);
  204430. }
  204431. }
  204432. return result;
  204433. }
  204434. const File File::getLinkedTarget() const
  204435. {
  204436. File result (*this);
  204437. String p (getFullPathName());
  204438. if (! exists())
  204439. p += ".lnk";
  204440. else if (getFileExtension() != ".lnk")
  204441. return result;
  204442. ComSmartPtr <IShellLink> shellLink;
  204443. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204444. {
  204445. ComSmartPtr <IPersistFile> persistFile;
  204446. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  204447. {
  204448. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204449. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204450. {
  204451. WIN32_FIND_DATA winFindData;
  204452. WCHAR resolvedPath [MAX_PATH];
  204453. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204454. result = File (resolvedPath);
  204455. }
  204456. }
  204457. }
  204458. return result;
  204459. }
  204460. class DirectoryIterator::NativeIterator::Pimpl
  204461. {
  204462. public:
  204463. Pimpl (const File& directory, const String& wildCard)
  204464. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204465. handle (INVALID_HANDLE_VALUE)
  204466. {
  204467. }
  204468. ~Pimpl()
  204469. {
  204470. if (handle != INVALID_HANDLE_VALUE)
  204471. FindClose (handle);
  204472. }
  204473. bool next (String& filenameFound,
  204474. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204475. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204476. {
  204477. WIN32_FIND_DATA findData;
  204478. if (handle == INVALID_HANDLE_VALUE)
  204479. {
  204480. handle = FindFirstFile (directoryWithWildCard, &findData);
  204481. if (handle == INVALID_HANDLE_VALUE)
  204482. return false;
  204483. }
  204484. else
  204485. {
  204486. if (FindNextFile (handle, &findData) == 0)
  204487. return false;
  204488. }
  204489. filenameFound = findData.cFileName;
  204490. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204491. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204492. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204493. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204494. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204495. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204496. return true;
  204497. }
  204498. juce_UseDebuggingNewOperator
  204499. private:
  204500. const String directoryWithWildCard;
  204501. HANDLE handle;
  204502. Pimpl (const Pimpl&);
  204503. Pimpl& operator= (const Pimpl&);
  204504. };
  204505. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204506. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204507. {
  204508. }
  204509. DirectoryIterator::NativeIterator::~NativeIterator()
  204510. {
  204511. }
  204512. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204513. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204514. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204515. {
  204516. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204517. }
  204518. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204519. {
  204520. HINSTANCE hInstance = 0;
  204521. JUCE_TRY
  204522. {
  204523. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204524. }
  204525. JUCE_CATCH_ALL
  204526. return hInstance > (HINSTANCE) 32;
  204527. }
  204528. void File::revealToUser() const
  204529. {
  204530. if (isDirectory())
  204531. startAsProcess();
  204532. else if (getParentDirectory().exists())
  204533. getParentDirectory().startAsProcess();
  204534. }
  204535. class NamedPipeInternal
  204536. {
  204537. public:
  204538. NamedPipeInternal (const String& file, const bool isPipe_)
  204539. : pipeH (0),
  204540. cancelEvent (0),
  204541. connected (false),
  204542. isPipe (isPipe_)
  204543. {
  204544. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204545. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204546. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204547. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204548. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204549. }
  204550. ~NamedPipeInternal()
  204551. {
  204552. disconnectPipe();
  204553. if (pipeH != 0)
  204554. CloseHandle (pipeH);
  204555. CloseHandle (cancelEvent);
  204556. }
  204557. bool connect (const int timeOutMs)
  204558. {
  204559. if (! isPipe)
  204560. return true;
  204561. if (! connected)
  204562. {
  204563. OVERLAPPED over;
  204564. zerostruct (over);
  204565. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204566. if (ConnectNamedPipe (pipeH, &over))
  204567. {
  204568. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204569. }
  204570. else
  204571. {
  204572. const int err = GetLastError();
  204573. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204574. {
  204575. HANDLE handles[] = { over.hEvent, cancelEvent };
  204576. if (WaitForMultipleObjects (2, handles, FALSE,
  204577. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204578. connected = true;
  204579. }
  204580. else if (err == ERROR_PIPE_CONNECTED)
  204581. {
  204582. connected = true;
  204583. }
  204584. }
  204585. CloseHandle (over.hEvent);
  204586. }
  204587. return connected;
  204588. }
  204589. void disconnectPipe()
  204590. {
  204591. if (connected)
  204592. {
  204593. DisconnectNamedPipe (pipeH);
  204594. connected = false;
  204595. }
  204596. }
  204597. HANDLE pipeH;
  204598. HANDLE cancelEvent;
  204599. bool connected, isPipe;
  204600. };
  204601. void NamedPipe::close()
  204602. {
  204603. cancelPendingReads();
  204604. const ScopedLock sl (lock);
  204605. delete static_cast<NamedPipeInternal*> (internal);
  204606. internal = 0;
  204607. }
  204608. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204609. {
  204610. close();
  204611. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204612. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204613. {
  204614. internal = intern.release();
  204615. return true;
  204616. }
  204617. return false;
  204618. }
  204619. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204620. {
  204621. const ScopedLock sl (lock);
  204622. int bytesRead = -1;
  204623. bool waitAgain = true;
  204624. while (waitAgain && internal != 0)
  204625. {
  204626. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204627. waitAgain = false;
  204628. if (! intern->connect (timeOutMilliseconds))
  204629. break;
  204630. if (maxBytesToRead <= 0)
  204631. return 0;
  204632. OVERLAPPED over;
  204633. zerostruct (over);
  204634. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204635. unsigned long numRead;
  204636. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204637. {
  204638. bytesRead = (int) numRead;
  204639. }
  204640. else if (GetLastError() == ERROR_IO_PENDING)
  204641. {
  204642. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204643. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204644. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204645. : INFINITE);
  204646. if (waitResult != WAIT_OBJECT_0)
  204647. {
  204648. // if the operation timed out, let's cancel it...
  204649. CancelIo (intern->pipeH);
  204650. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204651. }
  204652. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204653. {
  204654. bytesRead = (int) numRead;
  204655. }
  204656. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204657. {
  204658. intern->disconnectPipe();
  204659. waitAgain = true;
  204660. }
  204661. }
  204662. else
  204663. {
  204664. waitAgain = internal != 0;
  204665. Sleep (5);
  204666. }
  204667. CloseHandle (over.hEvent);
  204668. }
  204669. return bytesRead;
  204670. }
  204671. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204672. {
  204673. int bytesWritten = -1;
  204674. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204675. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204676. {
  204677. if (numBytesToWrite <= 0)
  204678. return 0;
  204679. OVERLAPPED over;
  204680. zerostruct (over);
  204681. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204682. unsigned long numWritten;
  204683. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204684. {
  204685. bytesWritten = (int) numWritten;
  204686. }
  204687. else if (GetLastError() == ERROR_IO_PENDING)
  204688. {
  204689. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204690. DWORD waitResult;
  204691. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204692. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204693. : INFINITE);
  204694. if (waitResult != WAIT_OBJECT_0)
  204695. {
  204696. CancelIo (intern->pipeH);
  204697. WaitForSingleObject (over.hEvent, INFINITE);
  204698. }
  204699. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204700. {
  204701. bytesWritten = (int) numWritten;
  204702. }
  204703. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204704. {
  204705. intern->disconnectPipe();
  204706. }
  204707. }
  204708. CloseHandle (over.hEvent);
  204709. }
  204710. return bytesWritten;
  204711. }
  204712. void NamedPipe::cancelPendingReads()
  204713. {
  204714. if (internal != 0)
  204715. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204716. }
  204717. #endif
  204718. /*** End of inlined file: juce_win32_Files.cpp ***/
  204719. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204720. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204721. // compiled on its own).
  204722. #if JUCE_INCLUDED_FILE
  204723. #ifndef INTERNET_FLAG_NEED_FILE
  204724. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204725. #endif
  204726. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204727. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204728. #endif
  204729. struct ConnectionAndRequestStruct
  204730. {
  204731. HINTERNET connection, request;
  204732. };
  204733. static HINTERNET sessionHandle = 0;
  204734. #ifndef WORKAROUND_TIMEOUT_BUG
  204735. //#define WORKAROUND_TIMEOUT_BUG 1
  204736. #endif
  204737. #if WORKAROUND_TIMEOUT_BUG
  204738. // Required because of a Microsoft bug in setting a timeout
  204739. class InternetConnectThread : public Thread
  204740. {
  204741. public:
  204742. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204743. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204744. {
  204745. startThread();
  204746. }
  204747. ~InternetConnectThread()
  204748. {
  204749. stopThread (60000);
  204750. }
  204751. void run()
  204752. {
  204753. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204754. uc.nPort, _T(""), _T(""),
  204755. isFtp ? INTERNET_SERVICE_FTP
  204756. : INTERNET_SERVICE_HTTP,
  204757. 0, 0);
  204758. notify();
  204759. }
  204760. juce_UseDebuggingNewOperator
  204761. private:
  204762. URL_COMPONENTS& uc;
  204763. HINTERNET& connection;
  204764. const bool isFtp;
  204765. InternetConnectThread (const InternetConnectThread&);
  204766. InternetConnectThread& operator= (const InternetConnectThread&);
  204767. };
  204768. #endif
  204769. void* juce_openInternetFile (const String& url,
  204770. const String& headers,
  204771. const MemoryBlock& postData,
  204772. const bool isPost,
  204773. URL::OpenStreamProgressCallback* callback,
  204774. void* callbackContext,
  204775. int timeOutMs)
  204776. {
  204777. if (sessionHandle == 0)
  204778. sessionHandle = InternetOpen (_T("juce"),
  204779. INTERNET_OPEN_TYPE_PRECONFIG,
  204780. 0, 0, 0);
  204781. if (sessionHandle != 0)
  204782. {
  204783. // break up the url..
  204784. TCHAR file[1024], server[1024];
  204785. URL_COMPONENTS uc;
  204786. zerostruct (uc);
  204787. uc.dwStructSize = sizeof (uc);
  204788. uc.dwUrlPathLength = sizeof (file);
  204789. uc.dwHostNameLength = sizeof (server);
  204790. uc.lpszUrlPath = file;
  204791. uc.lpszHostName = server;
  204792. if (InternetCrackUrl (url, 0, 0, &uc))
  204793. {
  204794. int disable = 1;
  204795. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204796. if (timeOutMs == 0)
  204797. timeOutMs = 30000;
  204798. else if (timeOutMs < 0)
  204799. timeOutMs = -1;
  204800. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204801. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204802. #if WORKAROUND_TIMEOUT_BUG
  204803. HINTERNET connection = 0;
  204804. {
  204805. InternetConnectThread connectThread (uc, connection, isFtp);
  204806. connectThread.wait (timeOutMs);
  204807. if (connection == 0)
  204808. {
  204809. InternetCloseHandle (sessionHandle);
  204810. sessionHandle = 0;
  204811. }
  204812. }
  204813. #else
  204814. HINTERNET connection = InternetConnect (sessionHandle,
  204815. uc.lpszHostName,
  204816. uc.nPort,
  204817. _T(""), _T(""),
  204818. isFtp ? INTERNET_SERVICE_FTP
  204819. : INTERNET_SERVICE_HTTP,
  204820. 0, 0);
  204821. #endif
  204822. if (connection != 0)
  204823. {
  204824. if (isFtp)
  204825. {
  204826. HINTERNET request = FtpOpenFile (connection,
  204827. uc.lpszUrlPath,
  204828. GENERIC_READ,
  204829. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204830. 0);
  204831. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204832. result->connection = connection;
  204833. result->request = request;
  204834. return result;
  204835. }
  204836. else
  204837. {
  204838. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204839. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204840. if (url.startsWithIgnoreCase ("https:"))
  204841. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204842. // IE7 seems to automatically work out when it's https)
  204843. HINTERNET request = HttpOpenRequest (connection,
  204844. isPost ? _T("POST")
  204845. : _T("GET"),
  204846. uc.lpszUrlPath,
  204847. 0, 0, mimeTypes, flags, 0);
  204848. if (request != 0)
  204849. {
  204850. INTERNET_BUFFERS buffers;
  204851. zerostruct (buffers);
  204852. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204853. buffers.lpcszHeader = (LPCTSTR) headers;
  204854. buffers.dwHeadersLength = headers.length();
  204855. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204856. ConnectionAndRequestStruct* result = 0;
  204857. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204858. {
  204859. int bytesSent = 0;
  204860. for (;;)
  204861. {
  204862. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204863. DWORD bytesDone = 0;
  204864. if (bytesToDo > 0
  204865. && ! InternetWriteFile (request,
  204866. static_cast <const char*> (postData.getData()) + bytesSent,
  204867. bytesToDo, &bytesDone))
  204868. {
  204869. break;
  204870. }
  204871. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204872. {
  204873. result = new ConnectionAndRequestStruct();
  204874. result->connection = connection;
  204875. result->request = request;
  204876. if (! HttpEndRequest (request, 0, 0, 0))
  204877. break;
  204878. return result;
  204879. }
  204880. bytesSent += bytesDone;
  204881. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204882. break;
  204883. }
  204884. }
  204885. InternetCloseHandle (request);
  204886. }
  204887. InternetCloseHandle (connection);
  204888. }
  204889. }
  204890. }
  204891. }
  204892. return 0;
  204893. }
  204894. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204895. {
  204896. DWORD bytesRead = 0;
  204897. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204898. if (crs != 0)
  204899. InternetReadFile (crs->request,
  204900. buffer, bytesToRead,
  204901. &bytesRead);
  204902. return bytesRead;
  204903. }
  204904. int juce_seekInInternetFile (void* handle, int newPosition)
  204905. {
  204906. if (handle != 0)
  204907. {
  204908. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204909. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204910. }
  204911. return -1;
  204912. }
  204913. int64 juce_getInternetFileContentLength (void* handle)
  204914. {
  204915. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204916. if (crs != 0)
  204917. {
  204918. DWORD index = 0, result = 0, size = sizeof (result);
  204919. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204920. return (int64) result;
  204921. }
  204922. return -1;
  204923. }
  204924. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204925. {
  204926. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204927. if (crs != 0)
  204928. {
  204929. DWORD bufferSizeBytes = 4096;
  204930. for (;;)
  204931. {
  204932. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204933. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204934. {
  204935. StringArray headersArray;
  204936. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204937. for (int i = 0; i < headersArray.size(); ++i)
  204938. {
  204939. const String& header = headersArray[i];
  204940. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204941. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204942. const String previousValue (headers [key]);
  204943. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204944. }
  204945. break;
  204946. }
  204947. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204948. break;
  204949. }
  204950. }
  204951. }
  204952. void juce_closeInternetFile (void* handle)
  204953. {
  204954. if (handle != 0)
  204955. {
  204956. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204957. InternetCloseHandle (crs->request);
  204958. InternetCloseHandle (crs->connection);
  204959. }
  204960. }
  204961. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204962. {
  204963. int numFound = 0;
  204964. DynamicLibraryLoader dll ("iphlpapi.dll");
  204965. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204966. if (getAdaptersInfo != 0)
  204967. {
  204968. ULONG len = sizeof (IP_ADAPTER_INFO);
  204969. MemoryBlock mb;
  204970. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204971. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204972. {
  204973. mb.setSize (len);
  204974. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204975. }
  204976. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204977. {
  204978. PIP_ADAPTER_INFO adapter = adapterInfo;
  204979. while (adapter != 0)
  204980. {
  204981. int64 mac = 0;
  204982. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204983. mac = (mac << 8) | adapter->Address[i];
  204984. if (littleEndian)
  204985. mac = (int64) ByteOrder::swap ((uint64) mac);
  204986. if (numFound < maxNum && mac != 0)
  204987. addresses [numFound++] = mac;
  204988. adapter = adapter->Next;
  204989. }
  204990. }
  204991. }
  204992. return numFound;
  204993. }
  204994. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204995. {
  204996. int numFound = 0;
  204997. DynamicLibraryLoader dll ("netapi32.dll");
  204998. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204999. if (NetbiosCall != 0)
  205000. {
  205001. NCB ncb;
  205002. zerostruct (ncb);
  205003. struct ASTAT
  205004. {
  205005. ADAPTER_STATUS adapt;
  205006. NAME_BUFFER NameBuff [30];
  205007. };
  205008. ASTAT astat;
  205009. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205010. LANA_ENUM enums;
  205011. zerostruct (enums);
  205012. ncb.ncb_command = NCBENUM;
  205013. ncb.ncb_buffer = (unsigned char*) &enums;
  205014. ncb.ncb_length = sizeof (LANA_ENUM);
  205015. NetbiosCall (&ncb);
  205016. for (int i = 0; i < enums.length; ++i)
  205017. {
  205018. zerostruct (ncb);
  205019. ncb.ncb_command = NCBRESET;
  205020. ncb.ncb_lana_num = enums.lana[i];
  205021. if (NetbiosCall (&ncb) == 0)
  205022. {
  205023. zerostruct (ncb);
  205024. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205025. ncb.ncb_command = NCBASTAT;
  205026. ncb.ncb_lana_num = enums.lana[i];
  205027. ncb.ncb_buffer = (unsigned char*) &astat;
  205028. ncb.ncb_length = sizeof (ASTAT);
  205029. if (NetbiosCall (&ncb) == 0)
  205030. {
  205031. if (astat.adapt.adapter_type == 0xfe)
  205032. {
  205033. uint64 mac = 0;
  205034. for (int i = 6; --i >= 0;)
  205035. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205036. if (numFound < maxNum && mac != 0)
  205037. addresses [numFound++] = mac;
  205038. }
  205039. }
  205040. }
  205041. }
  205042. }
  205043. return numFound;
  205044. }
  205045. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205046. {
  205047. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205048. if (numFound == 0)
  205049. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205050. return numFound;
  205051. }
  205052. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205053. const String& emailSubject,
  205054. const String& bodyText,
  205055. const StringArray& filesToAttach)
  205056. {
  205057. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205058. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205059. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205060. bool ok = false;
  205061. if (mapiSendMail != 0)
  205062. {
  205063. MapiMessage message;
  205064. zerostruct (message);
  205065. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205066. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205067. MapiRecipDesc recip;
  205068. zerostruct (recip);
  205069. recip.ulRecipClass = MAPI_TO;
  205070. String targetEmailAddress_ (targetEmailAddress);
  205071. if (targetEmailAddress_.isEmpty())
  205072. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205073. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205074. message.nRecipCount = 1;
  205075. message.lpRecips = &recip;
  205076. HeapBlock <MapiFileDesc> files;
  205077. files.calloc (filesToAttach.size());
  205078. message.nFileCount = filesToAttach.size();
  205079. message.lpFiles = files;
  205080. for (int i = 0; i < filesToAttach.size(); ++i)
  205081. {
  205082. files[i].nPosition = (ULONG) -1;
  205083. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205084. }
  205085. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205086. }
  205087. FreeLibrary (h);
  205088. return ok;
  205089. }
  205090. #endif
  205091. /*** End of inlined file: juce_win32_Network.cpp ***/
  205092. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205093. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205094. // compiled on its own).
  205095. #if JUCE_INCLUDED_FILE
  205096. static HKEY findKeyForPath (String name,
  205097. const bool createForWriting,
  205098. String& valueName)
  205099. {
  205100. HKEY rootKey = 0;
  205101. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205102. rootKey = HKEY_CURRENT_USER;
  205103. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205104. rootKey = HKEY_LOCAL_MACHINE;
  205105. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205106. rootKey = HKEY_CLASSES_ROOT;
  205107. if (rootKey != 0)
  205108. {
  205109. name = name.substring (name.indexOfChar ('\\') + 1);
  205110. const int lastSlash = name.lastIndexOfChar ('\\');
  205111. valueName = name.substring (lastSlash + 1);
  205112. name = name.substring (0, lastSlash);
  205113. HKEY key;
  205114. DWORD result;
  205115. if (createForWriting)
  205116. {
  205117. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205118. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205119. return key;
  205120. }
  205121. else
  205122. {
  205123. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205124. return key;
  205125. }
  205126. }
  205127. return 0;
  205128. }
  205129. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205130. const String& defaultValue)
  205131. {
  205132. String valueName, result (defaultValue);
  205133. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205134. if (k != 0)
  205135. {
  205136. WCHAR buffer [2048];
  205137. unsigned long bufferSize = sizeof (buffer);
  205138. DWORD type = REG_SZ;
  205139. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205140. {
  205141. if (type == REG_SZ)
  205142. result = buffer;
  205143. else if (type == REG_DWORD)
  205144. result = String ((int) *(DWORD*) buffer);
  205145. }
  205146. RegCloseKey (k);
  205147. }
  205148. return result;
  205149. }
  205150. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205151. const String& value)
  205152. {
  205153. String valueName;
  205154. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205155. if (k != 0)
  205156. {
  205157. RegSetValueEx (k, valueName, 0, REG_SZ,
  205158. (const BYTE*) (const WCHAR*) value,
  205159. sizeof (WCHAR) * (value.length() + 1));
  205160. RegCloseKey (k);
  205161. }
  205162. }
  205163. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205164. {
  205165. bool exists = false;
  205166. String valueName;
  205167. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205168. if (k != 0)
  205169. {
  205170. unsigned char buffer [2048];
  205171. unsigned long bufferSize = sizeof (buffer);
  205172. DWORD type = 0;
  205173. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205174. exists = true;
  205175. RegCloseKey (k);
  205176. }
  205177. return exists;
  205178. }
  205179. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205180. {
  205181. String valueName;
  205182. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205183. if (k != 0)
  205184. {
  205185. RegDeleteValue (k, valueName);
  205186. RegCloseKey (k);
  205187. }
  205188. }
  205189. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205190. {
  205191. String valueName;
  205192. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205193. if (k != 0)
  205194. {
  205195. RegDeleteKey (k, valueName);
  205196. RegCloseKey (k);
  205197. }
  205198. }
  205199. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205200. const String& symbolicDescription,
  205201. const String& fullDescription,
  205202. const File& targetExecutable,
  205203. int iconResourceNumber)
  205204. {
  205205. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205206. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205207. if (iconResourceNumber != 0)
  205208. setRegistryValue (key + "\\DefaultIcon\\",
  205209. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205210. setRegistryValue (key + "\\", fullDescription);
  205211. setRegistryValue (key + "\\shell\\open\\command\\",
  205212. targetExecutable.getFullPathName() + " %1");
  205213. }
  205214. bool juce_IsRunningInWine()
  205215. {
  205216. HKEY key;
  205217. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205218. {
  205219. RegCloseKey (key);
  205220. return true;
  205221. }
  205222. return false;
  205223. }
  205224. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205225. {
  205226. String s (::GetCommandLineW());
  205227. StringArray tokens;
  205228. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205229. return tokens.joinIntoString (" ", 1);
  205230. }
  205231. static void* currentModuleHandle = 0;
  205232. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205233. {
  205234. if (currentModuleHandle == 0)
  205235. currentModuleHandle = GetModuleHandle (0);
  205236. return currentModuleHandle;
  205237. }
  205238. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205239. {
  205240. currentModuleHandle = newHandle;
  205241. }
  205242. void PlatformUtilities::fpuReset()
  205243. {
  205244. #if JUCE_MSVC
  205245. _clearfp();
  205246. #endif
  205247. }
  205248. void PlatformUtilities::beep()
  205249. {
  205250. MessageBeep (MB_OK);
  205251. }
  205252. #endif
  205253. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205254. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205255. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205256. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205257. // compiled on its own).
  205258. #if JUCE_INCLUDED_FILE
  205259. static const unsigned int specialId = WM_APP + 0x4400;
  205260. static const unsigned int broadcastId = WM_APP + 0x4403;
  205261. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205262. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205263. HWND juce_messageWindowHandle = 0;
  205264. extern long improbableWindowNumber; // defined in windowing.cpp
  205265. #ifndef WM_APPCOMMAND
  205266. #define WM_APPCOMMAND 0x0319
  205267. #endif
  205268. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205269. const UINT message,
  205270. const WPARAM wParam,
  205271. const LPARAM lParam) throw()
  205272. {
  205273. JUCE_TRY
  205274. {
  205275. if (h == juce_messageWindowHandle)
  205276. {
  205277. if (message == specialCallbackId)
  205278. {
  205279. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205280. return (LRESULT) (*func) ((void*) lParam);
  205281. }
  205282. else if (message == specialId)
  205283. {
  205284. // these are trapped early in the dispatch call, but must also be checked
  205285. // here in case there are windows modal dialog boxes doing their own
  205286. // dispatch loop and not calling our version
  205287. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205288. return 0;
  205289. }
  205290. else if (message == broadcastId)
  205291. {
  205292. const ScopedPointer <String> messageString ((String*) lParam);
  205293. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205294. return 0;
  205295. }
  205296. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205297. {
  205298. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205299. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205300. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205301. return 0;
  205302. }
  205303. }
  205304. }
  205305. JUCE_CATCH_EXCEPTION
  205306. return DefWindowProc (h, message, wParam, lParam);
  205307. }
  205308. static bool isEventBlockedByModalComps (MSG& m)
  205309. {
  205310. if (Component::getNumCurrentlyModalComponents() == 0
  205311. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205312. return false;
  205313. switch (m.message)
  205314. {
  205315. case WM_MOUSEMOVE:
  205316. case WM_NCMOUSEMOVE:
  205317. case 0x020A: /* WM_MOUSEWHEEL */
  205318. case 0x020E: /* WM_MOUSEHWHEEL */
  205319. case WM_KEYUP:
  205320. case WM_SYSKEYUP:
  205321. case WM_CHAR:
  205322. case WM_APPCOMMAND:
  205323. case WM_LBUTTONUP:
  205324. case WM_MBUTTONUP:
  205325. case WM_RBUTTONUP:
  205326. case WM_MOUSEACTIVATE:
  205327. case WM_NCMOUSEHOVER:
  205328. case WM_MOUSEHOVER:
  205329. return true;
  205330. case WM_NCLBUTTONDOWN:
  205331. case WM_NCLBUTTONDBLCLK:
  205332. case WM_NCRBUTTONDOWN:
  205333. case WM_NCRBUTTONDBLCLK:
  205334. case WM_NCMBUTTONDOWN:
  205335. case WM_NCMBUTTONDBLCLK:
  205336. case WM_LBUTTONDOWN:
  205337. case WM_LBUTTONDBLCLK:
  205338. case WM_MBUTTONDOWN:
  205339. case WM_MBUTTONDBLCLK:
  205340. case WM_RBUTTONDOWN:
  205341. case WM_RBUTTONDBLCLK:
  205342. case WM_KEYDOWN:
  205343. case WM_SYSKEYDOWN:
  205344. {
  205345. Component* const modal = Component::getCurrentlyModalComponent (0);
  205346. if (modal != 0)
  205347. modal->inputAttemptWhenModal();
  205348. return true;
  205349. }
  205350. default:
  205351. break;
  205352. }
  205353. return false;
  205354. }
  205355. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205356. {
  205357. MSG m;
  205358. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205359. return false;
  205360. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205361. {
  205362. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205363. {
  205364. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205365. }
  205366. else if (m.message == WM_QUIT)
  205367. {
  205368. if (JUCEApplication::getInstance() != 0)
  205369. JUCEApplication::getInstance()->systemRequestedQuit();
  205370. }
  205371. else if (! isEventBlockedByModalComps (m))
  205372. {
  205373. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205374. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205375. {
  205376. // if it's someone else's window being clicked on, and the focus is
  205377. // currently on a juce window, pass the kb focus over..
  205378. HWND currentFocus = GetFocus();
  205379. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205380. SetFocus (m.hwnd);
  205381. }
  205382. TranslateMessage (&m);
  205383. DispatchMessage (&m);
  205384. }
  205385. }
  205386. return true;
  205387. }
  205388. bool juce_postMessageToSystemQueue (Message* message)
  205389. {
  205390. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205391. }
  205392. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205393. void* userData)
  205394. {
  205395. if (MessageManager::getInstance()->isThisTheMessageThread())
  205396. {
  205397. return (*callback) (userData);
  205398. }
  205399. else
  205400. {
  205401. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205402. // deadlock because the message manager is blocked from running, and can't
  205403. // call your function..
  205404. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205405. return (void*) SendMessage (juce_messageWindowHandle,
  205406. specialCallbackId,
  205407. (WPARAM) callback,
  205408. (LPARAM) userData);
  205409. }
  205410. }
  205411. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205412. {
  205413. if (hwnd != juce_messageWindowHandle)
  205414. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205415. return TRUE;
  205416. }
  205417. void MessageManager::broadcastMessage (const String& value)
  205418. {
  205419. Array<void*> windows;
  205420. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205421. const String localCopy (value);
  205422. COPYDATASTRUCT data;
  205423. data.dwData = broadcastId;
  205424. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205425. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205426. for (int i = windows.size(); --i >= 0;)
  205427. {
  205428. HWND hwnd = (HWND) windows.getUnchecked(i);
  205429. TCHAR windowName [64]; // no need to read longer strings than this
  205430. GetWindowText (hwnd, windowName, 64);
  205431. windowName [63] = 0;
  205432. if (String (windowName) == messageWindowName)
  205433. {
  205434. DWORD_PTR result;
  205435. SendMessageTimeout (hwnd, WM_COPYDATA,
  205436. (WPARAM) juce_messageWindowHandle,
  205437. (LPARAM) &data,
  205438. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205439. 8000,
  205440. &result);
  205441. }
  205442. }
  205443. }
  205444. static const String getMessageWindowClassName()
  205445. {
  205446. // this name has to be different for each app/dll instance because otherwise
  205447. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205448. // window class).
  205449. static int number = 0;
  205450. if (number == 0)
  205451. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205452. return "JUCEcs_" + String (number);
  205453. }
  205454. void MessageManager::doPlatformSpecificInitialisation()
  205455. {
  205456. OleInitialize (0);
  205457. const String className (getMessageWindowClassName());
  205458. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205459. WNDCLASSEX wc;
  205460. zerostruct (wc);
  205461. wc.cbSize = sizeof (wc);
  205462. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205463. wc.cbWndExtra = 4;
  205464. wc.hInstance = hmod;
  205465. wc.lpszClassName = className;
  205466. RegisterClassEx (&wc);
  205467. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205468. messageWindowName,
  205469. 0, 0, 0, 0, 0, 0, 0,
  205470. hmod, 0);
  205471. }
  205472. void MessageManager::doPlatformSpecificShutdown()
  205473. {
  205474. DestroyWindow (juce_messageWindowHandle);
  205475. UnregisterClass (getMessageWindowClassName(), 0);
  205476. OleUninitialize();
  205477. }
  205478. #endif
  205479. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205480. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205481. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205482. // compiled on its own).
  205483. #if JUCE_INCLUDED_FILE
  205484. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205485. NEWTEXTMETRICEXW*,
  205486. int type,
  205487. LPARAM lParam)
  205488. {
  205489. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205490. {
  205491. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205492. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205493. }
  205494. return 1;
  205495. }
  205496. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205497. NEWTEXTMETRICEXW*,
  205498. int type,
  205499. LPARAM lParam)
  205500. {
  205501. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205502. {
  205503. LOGFONTW lf;
  205504. zerostruct (lf);
  205505. lf.lfWeight = FW_DONTCARE;
  205506. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205507. lf.lfQuality = DEFAULT_QUALITY;
  205508. lf.lfCharSet = DEFAULT_CHARSET;
  205509. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205510. lf.lfPitchAndFamily = FF_DONTCARE;
  205511. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205512. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205513. HDC dc = CreateCompatibleDC (0);
  205514. EnumFontFamiliesEx (dc, &lf,
  205515. (FONTENUMPROCW) &wfontEnum2,
  205516. lParam, 0);
  205517. DeleteDC (dc);
  205518. }
  205519. return 1;
  205520. }
  205521. const StringArray Font::findAllTypefaceNames()
  205522. {
  205523. StringArray results;
  205524. HDC dc = CreateCompatibleDC (0);
  205525. {
  205526. LOGFONTW lf;
  205527. zerostruct (lf);
  205528. lf.lfWeight = FW_DONTCARE;
  205529. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205530. lf.lfQuality = DEFAULT_QUALITY;
  205531. lf.lfCharSet = DEFAULT_CHARSET;
  205532. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205533. lf.lfPitchAndFamily = FF_DONTCARE;
  205534. lf.lfFaceName[0] = 0;
  205535. EnumFontFamiliesEx (dc, &lf,
  205536. (FONTENUMPROCW) &wfontEnum1,
  205537. (LPARAM) &results, 0);
  205538. }
  205539. DeleteDC (dc);
  205540. results.sort (true);
  205541. return results;
  205542. }
  205543. extern bool juce_IsRunningInWine();
  205544. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205545. {
  205546. if (juce_IsRunningInWine())
  205547. {
  205548. // If we're running in Wine, then use fonts that might be available on Linux..
  205549. defaultSans = "Bitstream Vera Sans";
  205550. defaultSerif = "Bitstream Vera Serif";
  205551. defaultFixed = "Bitstream Vera Sans Mono";
  205552. }
  205553. else
  205554. {
  205555. defaultSans = "Verdana";
  205556. defaultSerif = "Times";
  205557. defaultFixed = "Lucida Console";
  205558. }
  205559. }
  205560. class FontDCHolder : private DeletedAtShutdown
  205561. {
  205562. public:
  205563. FontDCHolder()
  205564. : dc (0), numKPs (0), size (0),
  205565. bold (false), italic (false)
  205566. {
  205567. }
  205568. ~FontDCHolder()
  205569. {
  205570. if (dc != 0)
  205571. {
  205572. DeleteDC (dc);
  205573. DeleteObject (fontH);
  205574. }
  205575. clearSingletonInstance();
  205576. }
  205577. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205578. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205579. {
  205580. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205581. {
  205582. fontName = fontName_;
  205583. bold = bold_;
  205584. italic = italic_;
  205585. size = size_;
  205586. if (dc != 0)
  205587. {
  205588. DeleteDC (dc);
  205589. DeleteObject (fontH);
  205590. kps.free();
  205591. }
  205592. fontH = 0;
  205593. dc = CreateCompatibleDC (0);
  205594. SetMapperFlags (dc, 0);
  205595. SetMapMode (dc, MM_TEXT);
  205596. LOGFONTW lfw;
  205597. zerostruct (lfw);
  205598. lfw.lfCharSet = DEFAULT_CHARSET;
  205599. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205600. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205601. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205602. lfw.lfQuality = PROOF_QUALITY;
  205603. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205604. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205605. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205606. lfw.lfHeight = size > 0 ? size : -256;
  205607. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205608. if (standardSizedFont != 0)
  205609. {
  205610. if (SelectObject (dc, standardSizedFont) != 0)
  205611. {
  205612. fontH = standardSizedFont;
  205613. if (size == 0)
  205614. {
  205615. OUTLINETEXTMETRIC otm;
  205616. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205617. {
  205618. lfw.lfHeight = -(int) otm.otmEMSquare;
  205619. fontH = CreateFontIndirect (&lfw);
  205620. SelectObject (dc, fontH);
  205621. DeleteObject (standardSizedFont);
  205622. }
  205623. }
  205624. }
  205625. else
  205626. {
  205627. jassertfalse;
  205628. }
  205629. }
  205630. else
  205631. {
  205632. jassertfalse;
  205633. }
  205634. }
  205635. return dc;
  205636. }
  205637. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205638. {
  205639. if (kps == 0)
  205640. {
  205641. numKPs = GetKerningPairs (dc, 0, 0);
  205642. kps.calloc (numKPs);
  205643. GetKerningPairs (dc, numKPs, kps);
  205644. }
  205645. numKPs_ = numKPs;
  205646. return kps;
  205647. }
  205648. private:
  205649. HFONT fontH;
  205650. HDC dc;
  205651. String fontName;
  205652. HeapBlock <KERNINGPAIR> kps;
  205653. int numKPs, size;
  205654. bool bold, italic;
  205655. FontDCHolder (const FontDCHolder&);
  205656. FontDCHolder& operator= (const FontDCHolder&);
  205657. };
  205658. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205659. class WindowsTypeface : public CustomTypeface
  205660. {
  205661. public:
  205662. WindowsTypeface (const Font& font)
  205663. {
  205664. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205665. font.isBold(), font.isItalic(), 0);
  205666. TEXTMETRIC tm;
  205667. tm.tmAscent = tm.tmHeight = 1;
  205668. tm.tmDefaultChar = 0;
  205669. GetTextMetrics (dc, &tm);
  205670. setCharacteristics (font.getTypefaceName(),
  205671. tm.tmAscent / (float) tm.tmHeight,
  205672. font.isBold(), font.isItalic(),
  205673. tm.tmDefaultChar);
  205674. }
  205675. bool loadGlyphIfPossible (juce_wchar character)
  205676. {
  205677. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205678. GLYPHMETRICS gm;
  205679. {
  205680. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205681. WORD index = 0;
  205682. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205683. && index == 0xffff)
  205684. {
  205685. return false;
  205686. }
  205687. }
  205688. Path glyphPath;
  205689. TEXTMETRIC tm;
  205690. if (! GetTextMetrics (dc, &tm))
  205691. {
  205692. addGlyph (character, glyphPath, 0);
  205693. return true;
  205694. }
  205695. const float height = (float) tm.tmHeight;
  205696. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205697. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205698. &gm, 0, 0, &identityMatrix);
  205699. if (bufSize > 0)
  205700. {
  205701. HeapBlock<char> data (bufSize);
  205702. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205703. bufSize, data, &identityMatrix);
  205704. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205705. const float scaleX = 1.0f / height;
  205706. const float scaleY = -1.0f / height;
  205707. while ((char*) pheader < data + bufSize)
  205708. {
  205709. float x = scaleX * pheader->pfxStart.x.value;
  205710. float y = scaleY * pheader->pfxStart.y.value;
  205711. glyphPath.startNewSubPath (x, y);
  205712. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205713. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205714. while ((const char*) curve < curveEnd)
  205715. {
  205716. if (curve->wType == TT_PRIM_LINE)
  205717. {
  205718. for (int i = 0; i < curve->cpfx; ++i)
  205719. {
  205720. x = scaleX * curve->apfx[i].x.value;
  205721. y = scaleY * curve->apfx[i].y.value;
  205722. glyphPath.lineTo (x, y);
  205723. }
  205724. }
  205725. else if (curve->wType == TT_PRIM_QSPLINE)
  205726. {
  205727. for (int i = 0; i < curve->cpfx - 1; ++i)
  205728. {
  205729. const float x2 = scaleX * curve->apfx[i].x.value;
  205730. const float y2 = scaleY * curve->apfx[i].y.value;
  205731. float x3, y3;
  205732. if (i < curve->cpfx - 2)
  205733. {
  205734. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205735. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205736. }
  205737. else
  205738. {
  205739. x3 = scaleX * curve->apfx[i + 1].x.value;
  205740. y3 = scaleY * curve->apfx[i + 1].y.value;
  205741. }
  205742. glyphPath.quadraticTo (x2, y2, x3, y3);
  205743. x = x3;
  205744. y = y3;
  205745. }
  205746. }
  205747. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205748. }
  205749. pheader = (const TTPOLYGONHEADER*) curve;
  205750. glyphPath.closeSubPath();
  205751. }
  205752. }
  205753. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205754. int numKPs;
  205755. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205756. for (int i = 0; i < numKPs; ++i)
  205757. {
  205758. if (kps[i].wFirst == character)
  205759. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205760. kps[i].iKernAmount / height);
  205761. }
  205762. return true;
  205763. }
  205764. juce_UseDebuggingNewOperator
  205765. };
  205766. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205767. {
  205768. return new WindowsTypeface (font);
  205769. }
  205770. #endif
  205771. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205772. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205773. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205774. // compiled on its own).
  205775. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205776. class SharedD2DFactory : public DeletedAtShutdown
  205777. {
  205778. public:
  205779. SharedD2DFactory()
  205780. {
  205781. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205782. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205783. if (directWriteFactory != 0)
  205784. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205785. }
  205786. ~SharedD2DFactory()
  205787. {
  205788. clearSingletonInstance();
  205789. }
  205790. juce_DeclareSingleton (SharedD2DFactory, false);
  205791. ComSmartPtr <ID2D1Factory> d2dFactory;
  205792. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205793. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205794. };
  205795. juce_ImplementSingleton (SharedD2DFactory)
  205796. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205797. {
  205798. public:
  205799. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205800. : hwnd (hwnd_),
  205801. currentState (0)
  205802. {
  205803. RECT windowRect;
  205804. GetClientRect (hwnd, &windowRect);
  205805. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205806. bounds.setSize (size.width, size.height);
  205807. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205808. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205809. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205810. // xxx check for error
  205811. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205812. }
  205813. ~Direct2DLowLevelGraphicsContext()
  205814. {
  205815. states.clear();
  205816. }
  205817. void resized()
  205818. {
  205819. RECT windowRect;
  205820. GetClientRect (hwnd, &windowRect);
  205821. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205822. renderingTarget->Resize (size);
  205823. bounds.setSize (size.width, size.height);
  205824. }
  205825. void clear()
  205826. {
  205827. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205828. }
  205829. void start()
  205830. {
  205831. renderingTarget->BeginDraw();
  205832. saveState();
  205833. }
  205834. void end()
  205835. {
  205836. states.clear();
  205837. currentState = 0;
  205838. renderingTarget->EndDraw();
  205839. renderingTarget->CheckWindowState();
  205840. }
  205841. bool isVectorDevice() const { return false; }
  205842. void setOrigin (int x, int y)
  205843. {
  205844. currentState->origin.addXY (x, y);
  205845. }
  205846. bool clipToRectangle (const Rectangle<int>& r)
  205847. {
  205848. currentState->clipToRectangle (r);
  205849. return ! isClipEmpty();
  205850. }
  205851. bool clipToRectangleList (const RectangleList& clipRegion)
  205852. {
  205853. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205854. return ! isClipEmpty();
  205855. }
  205856. void excludeClipRectangle (const Rectangle<int>&)
  205857. {
  205858. //xxx
  205859. }
  205860. void clipToPath (const Path& path, const AffineTransform& transform)
  205861. {
  205862. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205863. }
  205864. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205865. {
  205866. currentState->clipToImage (sourceImage,transform);
  205867. }
  205868. bool clipRegionIntersects (const Rectangle<int>& r)
  205869. {
  205870. const Rectangle<int> r2 (r + currentState->origin);
  205871. return currentState->clipRect.intersects (r2);
  205872. }
  205873. const Rectangle<int> getClipBounds() const
  205874. {
  205875. // xxx could this take into account complex clip regions?
  205876. return currentState->clipRect - currentState->origin;
  205877. }
  205878. bool isClipEmpty() const
  205879. {
  205880. return currentState->clipRect.isEmpty();
  205881. }
  205882. void saveState()
  205883. {
  205884. states.add (new SavedState (*this));
  205885. currentState = states.getLast();
  205886. }
  205887. void restoreState()
  205888. {
  205889. jassert (states.size() > 1) //you should never pop the last state!
  205890. states.removeLast (1);
  205891. currentState = states.getLast();
  205892. }
  205893. void setFill (const FillType& fillType)
  205894. {
  205895. currentState->setFill (fillType);
  205896. }
  205897. void setOpacity (float newOpacity)
  205898. {
  205899. currentState->setOpacity (newOpacity);
  205900. }
  205901. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205902. {
  205903. }
  205904. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205905. {
  205906. currentState->createBrush();
  205907. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205908. }
  205909. void fillPath (const Path& p, const AffineTransform& transform)
  205910. {
  205911. currentState->createBrush();
  205912. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205913. if (renderingTarget != 0)
  205914. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205915. }
  205916. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205917. {
  205918. const int x = currentState->origin.getX();
  205919. const int y = currentState->origin.getY();
  205920. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205921. D2D1_SIZE_U size;
  205922. size.width = image.getWidth();
  205923. size.height = image.getHeight();
  205924. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205925. Image img (image.convertedToFormat (Image::ARGB));
  205926. Image::BitmapData bd (img, false);
  205927. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205928. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205929. {
  205930. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205931. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205932. if (tempBitmap != 0)
  205933. renderingTarget->DrawBitmap (tempBitmap);
  205934. }
  205935. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205936. }
  205937. void drawLine (const Line <float>& line)
  205938. {
  205939. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205940. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205941. line.getEnd() + currentState->origin.toFloat());
  205942. currentState->createBrush();
  205943. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205944. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205945. currentState->currentBrush);
  205946. }
  205947. void drawVerticalLine (int x, float top, float bottom)
  205948. {
  205949. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205950. currentState->createBrush();
  205951. x += currentState->origin.getX();
  205952. const int y = currentState->origin.getY();
  205953. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205954. D2D1::Point2F (x, y + bottom),
  205955. currentState->currentBrush);
  205956. }
  205957. void drawHorizontalLine (int y, float left, float right)
  205958. {
  205959. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205960. currentState->createBrush();
  205961. y += currentState->origin.getY();
  205962. const int x = currentState->origin.getX();
  205963. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205964. D2D1::Point2F (x + right, y),
  205965. currentState->currentBrush);
  205966. }
  205967. void setFont (const Font& newFont)
  205968. {
  205969. currentState->setFont (newFont);
  205970. }
  205971. const Font getFont()
  205972. {
  205973. return currentState->font;
  205974. }
  205975. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205976. {
  205977. const float x = currentState->origin.getX();
  205978. const float y = currentState->origin.getY();
  205979. currentState->createBrush();
  205980. currentState->createFont();
  205981. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205982. float hScale = currentState->font.getHorizontalScale();
  205983. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205984. float dpiX = 0, dpiY = 0;
  205985. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205986. UINT32 glyphNum = glyphNumber;
  205987. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205988. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205989. DWRITE_GLYPH_OFFSET offset;
  205990. offset.advanceOffset = 0;
  205991. offset.ascenderOffset = 0;
  205992. float glyphAdvances = 0;
  205993. DWRITE_GLYPH_RUN glyph;
  205994. glyph.fontFace = currentState->currentFontFace;
  205995. glyph.glyphCount = 1;
  205996. glyph.glyphIndices = &glyphNum1;
  205997. glyph.isSideways = FALSE;
  205998. glyph.glyphAdvances = &glyphAdvances;
  205999. glyph.glyphOffsets = &offset;
  206000. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206001. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206002. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206003. }
  206004. class SavedState
  206005. {
  206006. public:
  206007. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206008. : owner (owner_), currentBrush (0),
  206009. fontScaling (1.0f), currentFontFace (0),
  206010. clipsRect (false), shouldClipRect (false),
  206011. clipsRectList (false), shouldClipRectList (false),
  206012. clipsComplex (false), shouldClipComplex (false),
  206013. clipsBitmap (false), shouldClipBitmap (false)
  206014. {
  206015. if (owner.currentState != 0)
  206016. {
  206017. // xxx seems like a very slow way to create one of these, and this is a performance
  206018. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206019. setFill (owner.currentState->fillType);
  206020. currentBrush = owner.currentState->currentBrush;
  206021. origin = owner.currentState->origin;
  206022. clipRect = owner.currentState->clipRect;
  206023. font = owner.currentState->font;
  206024. currentFontFace = owner.currentState->currentFontFace;
  206025. }
  206026. else
  206027. {
  206028. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206029. clipRect.setSize (size.width, size.height);
  206030. setFill (FillType (Colours::black));
  206031. }
  206032. }
  206033. ~SavedState()
  206034. {
  206035. clearClip();
  206036. clearFont();
  206037. clearFill();
  206038. clearPathClip();
  206039. clearImageClip();
  206040. complexClipLayer = 0;
  206041. bitmapMaskLayer = 0;
  206042. }
  206043. void clearClip()
  206044. {
  206045. popClips();
  206046. shouldClipRect = false;
  206047. }
  206048. void clipToRectangle (const Rectangle<int>& r)
  206049. {
  206050. clearClip();
  206051. clipRect = r + origin;
  206052. shouldClipRect = true;
  206053. pushClips();
  206054. }
  206055. void clearPathClip()
  206056. {
  206057. popClips();
  206058. if (shouldClipComplex)
  206059. {
  206060. complexClipGeometry = 0;
  206061. shouldClipComplex = false;
  206062. }
  206063. }
  206064. void clipToPath (ID2D1Geometry* geometry)
  206065. {
  206066. clearPathClip();
  206067. if (complexClipLayer == 0)
  206068. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206069. complexClipGeometry = geometry;
  206070. shouldClipComplex = true;
  206071. pushClips();
  206072. }
  206073. void clearRectListClip()
  206074. {
  206075. popClips();
  206076. if (shouldClipRectList)
  206077. {
  206078. rectListGeometry = 0;
  206079. shouldClipRectList = false;
  206080. }
  206081. }
  206082. void clipToRectList (ID2D1Geometry* geometry)
  206083. {
  206084. clearRectListClip();
  206085. if (rectListLayer == 0)
  206086. owner.renderingTarget->CreateLayer (&rectListLayer);
  206087. rectListGeometry = geometry;
  206088. shouldClipRectList = true;
  206089. pushClips();
  206090. }
  206091. void clearImageClip()
  206092. {
  206093. popClips();
  206094. if (shouldClipBitmap)
  206095. {
  206096. maskBitmap = 0;
  206097. bitmapMaskBrush = 0;
  206098. shouldClipBitmap = false;
  206099. }
  206100. }
  206101. void clipToImage (const Image& image, const AffineTransform& transform)
  206102. {
  206103. clearImageClip();
  206104. if (bitmapMaskLayer == 0)
  206105. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206106. D2D1_BRUSH_PROPERTIES brushProps;
  206107. brushProps.opacity = 1;
  206108. brushProps.transform = transfromToMatrix (transform);
  206109. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206110. D2D1_SIZE_U size;
  206111. size.width = image.getWidth();
  206112. size.height = image.getHeight();
  206113. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206114. maskImage = image.convertedToFormat (Image::ARGB);
  206115. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206116. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206117. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206118. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206119. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206120. imageMaskLayerParams = D2D1::LayerParameters();
  206121. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206122. shouldClipBitmap = true;
  206123. pushClips();
  206124. }
  206125. void popClips()
  206126. {
  206127. if (clipsBitmap)
  206128. {
  206129. owner.renderingTarget->PopLayer();
  206130. clipsBitmap = false;
  206131. }
  206132. if (clipsComplex)
  206133. {
  206134. owner.renderingTarget->PopLayer();
  206135. clipsComplex = false;
  206136. }
  206137. if (clipsRectList)
  206138. {
  206139. owner.renderingTarget->PopLayer();
  206140. clipsRectList = false;
  206141. }
  206142. if (clipsRect)
  206143. {
  206144. owner.renderingTarget->PopAxisAlignedClip();
  206145. clipsRect = false;
  206146. }
  206147. }
  206148. void pushClips()
  206149. {
  206150. if (shouldClipRect && ! clipsRect)
  206151. {
  206152. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206153. clipsRect = true;
  206154. }
  206155. if (shouldClipRectList && ! clipsRectList)
  206156. {
  206157. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206158. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206159. layerParams.geometricMask = rectListGeometry;
  206160. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206161. clipsRectList = true;
  206162. }
  206163. if (shouldClipComplex && ! clipsComplex)
  206164. {
  206165. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206166. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206167. layerParams.geometricMask = complexClipGeometry;
  206168. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206169. clipsComplex = true;
  206170. }
  206171. if (shouldClipBitmap && ! clipsBitmap)
  206172. {
  206173. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206174. clipsBitmap = true;
  206175. }
  206176. }
  206177. void setFill (const FillType& newFillType)
  206178. {
  206179. if (fillType != newFillType)
  206180. {
  206181. fillType = newFillType;
  206182. clearFill();
  206183. }
  206184. }
  206185. void clearFont()
  206186. {
  206187. currentFontFace = localFontFace = 0;
  206188. }
  206189. void setFont (const Font& newFont)
  206190. {
  206191. if (font != newFont)
  206192. {
  206193. font = newFont;
  206194. clearFont();
  206195. }
  206196. }
  206197. void createFont()
  206198. {
  206199. // xxx The font shouldn't be managed by the graphics context.
  206200. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206201. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206202. // WindowsTypeface class.
  206203. if (currentFontFace == 0)
  206204. {
  206205. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206206. fontScaling = systemType->getAscent();
  206207. BOOL fontFound;
  206208. uint32 fontIndex;
  206209. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206210. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206211. if (! fontFound)
  206212. fontIndex = 0;
  206213. ComSmartPtr <IDWriteFontFamily> fontFam;
  206214. fonts->GetFontFamily (fontIndex, &fontFam);
  206215. ComSmartPtr <IDWriteFont> font;
  206216. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206217. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206218. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206219. font->CreateFontFace (&localFontFace);
  206220. currentFontFace = localFontFace;
  206221. }
  206222. }
  206223. void setOpacity (float newOpacity)
  206224. {
  206225. fillType.setOpacity (newOpacity);
  206226. if (currentBrush != 0)
  206227. currentBrush->SetOpacity (newOpacity);
  206228. }
  206229. void clearFill()
  206230. {
  206231. gradientStops = 0;
  206232. linearGradient = 0;
  206233. radialGradient = 0;
  206234. bitmap = 0;
  206235. bitmapBrush = 0;
  206236. currentBrush = 0;
  206237. }
  206238. void createBrush()
  206239. {
  206240. if (currentBrush == 0)
  206241. {
  206242. const int x = origin.getX();
  206243. const int y = origin.getY();
  206244. if (fillType.isColour())
  206245. {
  206246. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206247. owner.colourBrush->SetColor (colour);
  206248. currentBrush = owner.colourBrush;
  206249. }
  206250. else if (fillType.isTiledImage())
  206251. {
  206252. D2D1_BRUSH_PROPERTIES brushProps;
  206253. brushProps.opacity = fillType.getOpacity();
  206254. brushProps.transform = transfromToMatrix (fillType.transform);
  206255. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206256. image = fillType.image;
  206257. D2D1_SIZE_U size;
  206258. size.width = image.getWidth();
  206259. size.height = image.getHeight();
  206260. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206261. this->image = image.convertedToFormat (Image::ARGB);
  206262. Image::BitmapData bd (this->image, false);
  206263. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206264. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206265. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206266. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206267. currentBrush = bitmapBrush;
  206268. }
  206269. else if (fillType.isGradient())
  206270. {
  206271. gradientStops = 0;
  206272. D2D1_BRUSH_PROPERTIES brushProps;
  206273. brushProps.opacity = fillType.getOpacity();
  206274. brushProps.transform = transfromToMatrix (fillType.transform);
  206275. const int numColors = fillType.gradient->getNumColours();
  206276. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206277. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206278. {
  206279. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206280. stops[i].position = fillType.gradient->getColourPosition(i);
  206281. }
  206282. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206283. if (fillType.gradient->isRadial)
  206284. {
  206285. radialGradient = 0;
  206286. const Point<float>& p1 = fillType.gradient->point1;
  206287. const Point<float>& p2 = fillType.gradient->point2;
  206288. float r = p1.getDistanceFrom (p2);
  206289. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206290. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206291. D2D1::Point2F (0, 0),
  206292. r, r);
  206293. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206294. currentBrush = radialGradient;
  206295. }
  206296. else
  206297. {
  206298. linearGradient = 0;
  206299. const Point<float>& p1 = fillType.gradient->point1;
  206300. const Point<float>& p2 = fillType.gradient->point2;
  206301. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206302. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206303. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206304. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206305. currentBrush = linearGradient;
  206306. }
  206307. }
  206308. }
  206309. }
  206310. juce_UseDebuggingNewOperator
  206311. //xxx most of these members should probably be private...
  206312. Direct2DLowLevelGraphicsContext& owner;
  206313. Point<int> origin;
  206314. Font font;
  206315. float fontScaling;
  206316. IDWriteFontFace* currentFontFace;
  206317. ComSmartPtr <IDWriteFontFace> localFontFace;
  206318. FillType fillType;
  206319. Image image;
  206320. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206321. Rectangle<int> clipRect;
  206322. bool clipsRect, shouldClipRect;
  206323. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206324. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206325. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206326. bool clipsComplex, shouldClipComplex;
  206327. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206328. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206329. ComSmartPtr <ID2D1Layer> rectListLayer;
  206330. bool clipsRectList, shouldClipRectList;
  206331. Image maskImage;
  206332. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206333. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206334. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206335. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206336. bool clipsBitmap, shouldClipBitmap;
  206337. ID2D1Brush* currentBrush;
  206338. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206339. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206340. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206341. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206342. private:
  206343. SavedState (const SavedState&);
  206344. SavedState& operator= (const SavedState& other);
  206345. };
  206346. juce_UseDebuggingNewOperator
  206347. private:
  206348. HWND hwnd;
  206349. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206350. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206351. Rectangle<int> bounds;
  206352. SavedState* currentState;
  206353. OwnedArray<SavedState> states;
  206354. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206355. {
  206356. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206357. }
  206358. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206359. {
  206360. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206361. }
  206362. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206363. {
  206364. transform.transformPoint (x, y);
  206365. return D2D1::Point2F (x, y);
  206366. }
  206367. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206368. {
  206369. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206370. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206371. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206372. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206373. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206374. }
  206375. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206376. {
  206377. ID2D1PathGeometry* p = 0;
  206378. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206379. ComSmartPtr <ID2D1GeometrySink> sink;
  206380. HRESULT hr = p->Open (&sink); // xxx handle error
  206381. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206382. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206383. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206384. hr = sink->Close();
  206385. return p;
  206386. }
  206387. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206388. {
  206389. Path::Iterator it (path);
  206390. while (it.next())
  206391. {
  206392. switch (it.elementType)
  206393. {
  206394. case Path::Iterator::cubicTo:
  206395. {
  206396. D2D1_BEZIER_SEGMENT seg;
  206397. transform.transformPoint (it.x1, it.y1);
  206398. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206399. transform.transformPoint (it.x2, it.y2);
  206400. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206401. transform.transformPoint(it.x3, it.y3);
  206402. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206403. sink->AddBezier (seg);
  206404. break;
  206405. }
  206406. case Path::Iterator::lineTo:
  206407. {
  206408. transform.transformPoint (it.x1, it.y1);
  206409. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206410. break;
  206411. }
  206412. case Path::Iterator::quadraticTo:
  206413. {
  206414. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206415. transform.transformPoint (it.x1, it.y1);
  206416. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206417. transform.transformPoint (it.x2, it.y2);
  206418. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206419. sink->AddQuadraticBezier (seg);
  206420. break;
  206421. }
  206422. case Path::Iterator::closePath:
  206423. {
  206424. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206425. break;
  206426. }
  206427. case Path::Iterator::startNewSubPath:
  206428. {
  206429. transform.transformPoint (it.x1, it.y1);
  206430. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206431. break;
  206432. }
  206433. }
  206434. }
  206435. }
  206436. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206437. {
  206438. ID2D1PathGeometry* p = 0;
  206439. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206440. ComSmartPtr <ID2D1GeometrySink> sink;
  206441. HRESULT hr = p->Open (&sink);
  206442. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206443. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206444. hr = sink->Close();
  206445. return p;
  206446. }
  206447. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206448. {
  206449. D2D1::Matrix3x2F matrix;
  206450. matrix._11 = transform.mat00;
  206451. matrix._12 = transform.mat10;
  206452. matrix._21 = transform.mat01;
  206453. matrix._22 = transform.mat11;
  206454. matrix._31 = transform.mat02;
  206455. matrix._32 = transform.mat12;
  206456. return matrix;
  206457. }
  206458. };
  206459. #endif
  206460. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206461. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206462. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206463. // compiled on its own).
  206464. #if JUCE_INCLUDED_FILE
  206465. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206466. // these are in the windows SDK, but need to be repeated here for GCC..
  206467. #ifndef GET_APPCOMMAND_LPARAM
  206468. #define FAPPCOMMAND_MASK 0xF000
  206469. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206470. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206471. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206472. #define APPCOMMAND_MEDIA_STOP 13
  206473. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206474. #define WM_APPCOMMAND 0x0319
  206475. #endif
  206476. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206477. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206478. extern bool juce_IsRunningInWine();
  206479. #ifndef ULW_ALPHA
  206480. #define ULW_ALPHA 0x00000002
  206481. #endif
  206482. #ifndef AC_SRC_ALPHA
  206483. #define AC_SRC_ALPHA 0x01
  206484. #endif
  206485. static HPALETTE palette = 0;
  206486. static bool createPaletteIfNeeded = true;
  206487. static bool shouldDeactivateTitleBar = true;
  206488. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206489. #define WM_TRAYNOTIFY WM_USER + 100
  206490. using ::abs;
  206491. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206492. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206493. bool Desktop::canUseSemiTransparentWindows() throw()
  206494. {
  206495. if (updateLayeredWindow == 0)
  206496. {
  206497. if (! juce_IsRunningInWine())
  206498. {
  206499. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206500. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206501. }
  206502. }
  206503. return updateLayeredWindow != 0;
  206504. }
  206505. const int extendedKeyModifier = 0x10000;
  206506. const int KeyPress::spaceKey = VK_SPACE;
  206507. const int KeyPress::returnKey = VK_RETURN;
  206508. const int KeyPress::escapeKey = VK_ESCAPE;
  206509. const int KeyPress::backspaceKey = VK_BACK;
  206510. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206511. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206512. const int KeyPress::tabKey = VK_TAB;
  206513. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206514. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206515. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206516. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206517. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206518. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206519. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206520. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206521. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206522. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206523. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206524. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206525. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206526. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206527. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206528. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206529. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206530. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206531. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206532. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206533. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206534. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206535. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206536. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206537. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206538. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206539. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206540. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206541. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206542. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206543. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206544. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206545. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206546. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206547. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206548. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206549. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206550. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206551. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206552. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206553. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206554. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206555. const int KeyPress::playKey = 0x30000;
  206556. const int KeyPress::stopKey = 0x30001;
  206557. const int KeyPress::fastForwardKey = 0x30002;
  206558. const int KeyPress::rewindKey = 0x30003;
  206559. class WindowsBitmapImage : public Image::SharedImage
  206560. {
  206561. public:
  206562. HBITMAP hBitmap;
  206563. BITMAPV4HEADER bitmapInfo;
  206564. HDC hdc;
  206565. unsigned char* bitmapData;
  206566. WindowsBitmapImage (const Image::PixelFormat format_,
  206567. const int w, const int h, const bool clearImage)
  206568. : Image::SharedImage (format_, w, h)
  206569. {
  206570. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206571. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206572. zerostruct (bitmapInfo);
  206573. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206574. bitmapInfo.bV4Width = w;
  206575. bitmapInfo.bV4Height = h;
  206576. bitmapInfo.bV4Planes = 1;
  206577. bitmapInfo.bV4CSType = 1;
  206578. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206579. if (format_ == Image::ARGB)
  206580. {
  206581. bitmapInfo.bV4AlphaMask = 0xff000000;
  206582. bitmapInfo.bV4RedMask = 0xff0000;
  206583. bitmapInfo.bV4GreenMask = 0xff00;
  206584. bitmapInfo.bV4BlueMask = 0xff;
  206585. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206586. }
  206587. else
  206588. {
  206589. bitmapInfo.bV4V4Compression = BI_RGB;
  206590. }
  206591. lineStride = -((w * pixelStride + 3) & ~3);
  206592. HDC dc = GetDC (0);
  206593. hdc = CreateCompatibleDC (dc);
  206594. ReleaseDC (0, dc);
  206595. SetMapMode (hdc, MM_TEXT);
  206596. hBitmap = CreateDIBSection (hdc,
  206597. (BITMAPINFO*) &(bitmapInfo),
  206598. DIB_RGB_COLORS,
  206599. (void**) &bitmapData,
  206600. 0, 0);
  206601. SelectObject (hdc, hBitmap);
  206602. if (format_ == Image::ARGB && clearImage)
  206603. zeromem (bitmapData, abs (h * lineStride));
  206604. imageData = bitmapData - (lineStride * (h - 1));
  206605. }
  206606. ~WindowsBitmapImage()
  206607. {
  206608. DeleteDC (hdc);
  206609. DeleteObject (hBitmap);
  206610. }
  206611. Image::ImageType getType() const { return Image::NativeImage; }
  206612. LowLevelGraphicsContext* createLowLevelContext()
  206613. {
  206614. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206615. }
  206616. SharedImage* clone()
  206617. {
  206618. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206619. for (int i = 0; i < height; ++i)
  206620. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206621. return im;
  206622. }
  206623. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206624. const int x, const int y,
  206625. const RectangleList& maskedRegion) throw()
  206626. {
  206627. static HDRAWDIB hdd = 0;
  206628. static bool needToCreateDrawDib = true;
  206629. if (needToCreateDrawDib)
  206630. {
  206631. needToCreateDrawDib = false;
  206632. HDC dc = GetDC (0);
  206633. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206634. ReleaseDC (0, dc);
  206635. // only open if we're not palettised
  206636. if (n > 8)
  206637. hdd = DrawDibOpen();
  206638. }
  206639. if (createPaletteIfNeeded)
  206640. {
  206641. HDC dc = GetDC (0);
  206642. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206643. ReleaseDC (0, dc);
  206644. if (n <= 8)
  206645. palette = CreateHalftonePalette (dc);
  206646. createPaletteIfNeeded = false;
  206647. }
  206648. if (palette != 0)
  206649. {
  206650. SelectPalette (dc, palette, FALSE);
  206651. RealizePalette (dc);
  206652. SetStretchBltMode (dc, HALFTONE);
  206653. }
  206654. SetMapMode (dc, MM_TEXT);
  206655. if (transparent)
  206656. {
  206657. POINT p, pos;
  206658. SIZE size;
  206659. RECT windowBounds;
  206660. GetWindowRect (hwnd, &windowBounds);
  206661. p.x = -x;
  206662. p.y = -y;
  206663. pos.x = windowBounds.left;
  206664. pos.y = windowBounds.top;
  206665. size.cx = windowBounds.right - windowBounds.left;
  206666. size.cy = windowBounds.bottom - windowBounds.top;
  206667. BLENDFUNCTION bf;
  206668. bf.AlphaFormat = AC_SRC_ALPHA;
  206669. bf.BlendFlags = 0;
  206670. bf.BlendOp = AC_SRC_OVER;
  206671. bf.SourceConstantAlpha = 0xff;
  206672. if (! maskedRegion.isEmpty())
  206673. {
  206674. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206675. {
  206676. const Rectangle<int>& r = *i.getRectangle();
  206677. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206678. }
  206679. }
  206680. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206681. }
  206682. else
  206683. {
  206684. int savedDC = 0;
  206685. if (! maskedRegion.isEmpty())
  206686. {
  206687. savedDC = SaveDC (dc);
  206688. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206689. {
  206690. const Rectangle<int>& r = *i.getRectangle();
  206691. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206692. }
  206693. }
  206694. if (hdd == 0)
  206695. {
  206696. StretchDIBits (dc,
  206697. x, y, width, height,
  206698. 0, 0, width, height,
  206699. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206700. DIB_RGB_COLORS, SRCCOPY);
  206701. }
  206702. else
  206703. {
  206704. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206705. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206706. 0, 0, width, height, 0);
  206707. }
  206708. if (! maskedRegion.isEmpty())
  206709. RestoreDC (dc, savedDC);
  206710. }
  206711. }
  206712. juce_UseDebuggingNewOperator
  206713. private:
  206714. WindowsBitmapImage (const WindowsBitmapImage&);
  206715. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206716. };
  206717. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206718. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206719. {
  206720. SHORT k = (SHORT) keyCode;
  206721. if ((keyCode & extendedKeyModifier) == 0
  206722. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206723. k += (SHORT) 'A' - (SHORT) 'a';
  206724. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206725. (SHORT) '+', VK_OEM_PLUS,
  206726. (SHORT) '-', VK_OEM_MINUS,
  206727. (SHORT) '.', VK_OEM_PERIOD,
  206728. (SHORT) ';', VK_OEM_1,
  206729. (SHORT) ':', VK_OEM_1,
  206730. (SHORT) '/', VK_OEM_2,
  206731. (SHORT) '?', VK_OEM_2,
  206732. (SHORT) '[', VK_OEM_4,
  206733. (SHORT) ']', VK_OEM_6 };
  206734. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206735. if (k == translatedValues [i])
  206736. k = translatedValues [i + 1];
  206737. return (GetKeyState (k) & 0x8000) != 0;
  206738. }
  206739. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206740. {
  206741. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206742. return callback (userData);
  206743. else
  206744. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206745. }
  206746. class Win32ComponentPeer : public ComponentPeer
  206747. {
  206748. public:
  206749. enum RenderingEngineType
  206750. {
  206751. softwareRenderingEngine = 0,
  206752. direct2DRenderingEngine
  206753. };
  206754. Win32ComponentPeer (Component* const component,
  206755. const int windowStyleFlags,
  206756. HWND parentToAddTo_)
  206757. : ComponentPeer (component, windowStyleFlags),
  206758. dontRepaint (false),
  206759. #if JUCE_DIRECT2D
  206760. currentRenderingEngine (direct2DRenderingEngine),
  206761. #else
  206762. currentRenderingEngine (softwareRenderingEngine),
  206763. #endif
  206764. fullScreen (false),
  206765. isDragging (false),
  206766. isMouseOver (false),
  206767. hasCreatedCaret (false),
  206768. currentWindowIcon (0),
  206769. dropTarget (0),
  206770. parentToAddTo (parentToAddTo_)
  206771. {
  206772. callFunctionIfNotLocked (&createWindowCallback, this);
  206773. setTitle (component->getName());
  206774. if ((windowStyleFlags & windowHasDropShadow) != 0
  206775. && Desktop::canUseSemiTransparentWindows())
  206776. {
  206777. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206778. if (shadower != 0)
  206779. shadower->setOwner (component);
  206780. }
  206781. }
  206782. ~Win32ComponentPeer()
  206783. {
  206784. setTaskBarIcon (Image());
  206785. shadower = 0;
  206786. // do this before the next bit to avoid messages arriving for this window
  206787. // before it's destroyed
  206788. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206789. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206790. if (currentWindowIcon != 0)
  206791. DestroyIcon (currentWindowIcon);
  206792. if (dropTarget != 0)
  206793. {
  206794. dropTarget->Release();
  206795. dropTarget = 0;
  206796. }
  206797. #if JUCE_DIRECT2D
  206798. direct2DContext = 0;
  206799. #endif
  206800. }
  206801. void* getNativeHandle() const
  206802. {
  206803. return hwnd;
  206804. }
  206805. void setVisible (bool shouldBeVisible)
  206806. {
  206807. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206808. if (shouldBeVisible)
  206809. InvalidateRect (hwnd, 0, 0);
  206810. else
  206811. lastPaintTime = 0;
  206812. }
  206813. void setTitle (const String& title)
  206814. {
  206815. SetWindowText (hwnd, title);
  206816. }
  206817. void setPosition (int x, int y)
  206818. {
  206819. offsetWithinParent (x, y);
  206820. SetWindowPos (hwnd, 0,
  206821. x - windowBorder.getLeft(),
  206822. y - windowBorder.getTop(),
  206823. 0, 0,
  206824. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206825. }
  206826. void repaintNowIfTransparent()
  206827. {
  206828. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206829. handlePaintMessage();
  206830. }
  206831. void updateBorderSize()
  206832. {
  206833. WINDOWINFO info;
  206834. info.cbSize = sizeof (info);
  206835. if (GetWindowInfo (hwnd, &info))
  206836. {
  206837. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206838. info.rcClient.left - info.rcWindow.left,
  206839. info.rcWindow.bottom - info.rcClient.bottom,
  206840. info.rcWindow.right - info.rcClient.right);
  206841. }
  206842. #if JUCE_DIRECT2D
  206843. if (direct2DContext != 0)
  206844. direct2DContext->resized();
  206845. #endif
  206846. }
  206847. void setSize (int w, int h)
  206848. {
  206849. SetWindowPos (hwnd, 0, 0, 0,
  206850. w + windowBorder.getLeftAndRight(),
  206851. h + windowBorder.getTopAndBottom(),
  206852. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206853. updateBorderSize();
  206854. repaintNowIfTransparent();
  206855. }
  206856. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206857. {
  206858. fullScreen = isNowFullScreen;
  206859. offsetWithinParent (x, y);
  206860. SetWindowPos (hwnd, 0,
  206861. x - windowBorder.getLeft(),
  206862. y - windowBorder.getTop(),
  206863. w + windowBorder.getLeftAndRight(),
  206864. h + windowBorder.getTopAndBottom(),
  206865. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206866. updateBorderSize();
  206867. repaintNowIfTransparent();
  206868. }
  206869. const Rectangle<int> getBounds() const
  206870. {
  206871. RECT r;
  206872. GetWindowRect (hwnd, &r);
  206873. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206874. HWND parentH = GetParent (hwnd);
  206875. if (parentH != 0)
  206876. {
  206877. GetWindowRect (parentH, &r);
  206878. bounds.translate (-r.left, -r.top);
  206879. }
  206880. return windowBorder.subtractedFrom (bounds);
  206881. }
  206882. const Point<int> getScreenPosition() const
  206883. {
  206884. RECT r;
  206885. GetWindowRect (hwnd, &r);
  206886. return Point<int> (r.left + windowBorder.getLeft(),
  206887. r.top + windowBorder.getTop());
  206888. }
  206889. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206890. {
  206891. return relativePosition + getScreenPosition();
  206892. }
  206893. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206894. {
  206895. return screenPosition - getScreenPosition();
  206896. }
  206897. void setMinimised (bool shouldBeMinimised)
  206898. {
  206899. if (shouldBeMinimised != isMinimised())
  206900. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206901. }
  206902. bool isMinimised() const
  206903. {
  206904. WINDOWPLACEMENT wp;
  206905. wp.length = sizeof (WINDOWPLACEMENT);
  206906. GetWindowPlacement (hwnd, &wp);
  206907. return wp.showCmd == SW_SHOWMINIMIZED;
  206908. }
  206909. void setFullScreen (bool shouldBeFullScreen)
  206910. {
  206911. setMinimised (false);
  206912. if (fullScreen != shouldBeFullScreen)
  206913. {
  206914. fullScreen = shouldBeFullScreen;
  206915. const Component::SafePointer<Component> deletionChecker (component);
  206916. if (! fullScreen)
  206917. {
  206918. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206919. if (hasTitleBar())
  206920. ShowWindow (hwnd, SW_SHOWNORMAL);
  206921. if (! boundsCopy.isEmpty())
  206922. {
  206923. setBounds (boundsCopy.getX(),
  206924. boundsCopy.getY(),
  206925. boundsCopy.getWidth(),
  206926. boundsCopy.getHeight(),
  206927. false);
  206928. }
  206929. }
  206930. else
  206931. {
  206932. if (hasTitleBar())
  206933. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206934. else
  206935. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206936. }
  206937. if (deletionChecker != 0)
  206938. handleMovedOrResized();
  206939. }
  206940. }
  206941. bool isFullScreen() const
  206942. {
  206943. if (! hasTitleBar())
  206944. return fullScreen;
  206945. WINDOWPLACEMENT wp;
  206946. wp.length = sizeof (wp);
  206947. GetWindowPlacement (hwnd, &wp);
  206948. return wp.showCmd == SW_SHOWMAXIMIZED;
  206949. }
  206950. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206951. {
  206952. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206953. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206954. return false;
  206955. RECT r;
  206956. GetWindowRect (hwnd, &r);
  206957. POINT p;
  206958. p.x = position.getX() + r.left + windowBorder.getLeft();
  206959. p.y = position.getY() + r.top + windowBorder.getTop();
  206960. HWND w = WindowFromPoint (p);
  206961. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206962. }
  206963. const BorderSize getFrameSize() const
  206964. {
  206965. return windowBorder;
  206966. }
  206967. bool setAlwaysOnTop (bool alwaysOnTop)
  206968. {
  206969. const bool oldDeactivate = shouldDeactivateTitleBar;
  206970. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206971. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206972. 0, 0, 0, 0,
  206973. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206974. shouldDeactivateTitleBar = oldDeactivate;
  206975. if (shadower != 0)
  206976. shadower->componentBroughtToFront (*component);
  206977. return true;
  206978. }
  206979. void toFront (bool makeActive)
  206980. {
  206981. setMinimised (false);
  206982. const bool oldDeactivate = shouldDeactivateTitleBar;
  206983. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206984. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206985. shouldDeactivateTitleBar = oldDeactivate;
  206986. if (! makeActive)
  206987. {
  206988. // in this case a broughttofront call won't have occured, so do it now..
  206989. handleBroughtToFront();
  206990. }
  206991. }
  206992. void toBehind (ComponentPeer* other)
  206993. {
  206994. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206995. jassert (otherPeer != 0); // wrong type of window?
  206996. if (otherPeer != 0)
  206997. {
  206998. setMinimised (false);
  206999. // must be careful not to try to put a topmost window behind a normal one, or win32
  207000. // promotes the normal one to be topmost!
  207001. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207002. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207003. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207004. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207005. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207006. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207007. }
  207008. }
  207009. bool isFocused() const
  207010. {
  207011. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207012. }
  207013. void grabFocus()
  207014. {
  207015. const bool oldDeactivate = shouldDeactivateTitleBar;
  207016. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207017. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207018. shouldDeactivateTitleBar = oldDeactivate;
  207019. }
  207020. void textInputRequired (const Point<int>&)
  207021. {
  207022. if (! hasCreatedCaret)
  207023. {
  207024. hasCreatedCaret = true;
  207025. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207026. }
  207027. ShowCaret (hwnd);
  207028. SetCaretPos (0, 0);
  207029. }
  207030. void repaint (const Rectangle<int>& area)
  207031. {
  207032. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207033. InvalidateRect (hwnd, &r, FALSE);
  207034. }
  207035. void performAnyPendingRepaintsNow()
  207036. {
  207037. MSG m;
  207038. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207039. DispatchMessage (&m);
  207040. }
  207041. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207042. {
  207043. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207044. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207045. return 0;
  207046. }
  207047. void setTaskBarIcon (const Image& image)
  207048. {
  207049. if (image.isValid())
  207050. {
  207051. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207052. if (taskBarIcon == 0)
  207053. {
  207054. taskBarIcon = new NOTIFYICONDATA();
  207055. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207056. taskBarIcon->hWnd = (HWND) hwnd;
  207057. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207058. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207059. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207060. taskBarIcon->hIcon = hicon;
  207061. taskBarIcon->szTip[0] = 0;
  207062. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207063. }
  207064. else
  207065. {
  207066. HICON oldIcon = taskBarIcon->hIcon;
  207067. taskBarIcon->hIcon = hicon;
  207068. taskBarIcon->uFlags = NIF_ICON;
  207069. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207070. DestroyIcon (oldIcon);
  207071. }
  207072. DestroyIcon (hicon);
  207073. }
  207074. else if (taskBarIcon != 0)
  207075. {
  207076. taskBarIcon->uFlags = 0;
  207077. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207078. DestroyIcon (taskBarIcon->hIcon);
  207079. taskBarIcon = 0;
  207080. }
  207081. }
  207082. void setTaskBarIconToolTip (const String& toolTip) const
  207083. {
  207084. if (taskBarIcon != 0)
  207085. {
  207086. taskBarIcon->uFlags = NIF_TIP;
  207087. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207088. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207089. }
  207090. }
  207091. bool isInside (HWND h) const
  207092. {
  207093. return GetAncestor (hwnd, GA_ROOT) == h;
  207094. }
  207095. static void updateKeyModifiers() throw()
  207096. {
  207097. int keyMods = 0;
  207098. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207099. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207100. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207101. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207102. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207103. }
  207104. static void updateModifiersFromWParam (const WPARAM wParam)
  207105. {
  207106. int mouseMods = 0;
  207107. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207108. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207109. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207110. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207111. updateKeyModifiers();
  207112. }
  207113. static int64 getMouseEventTime()
  207114. {
  207115. static int64 eventTimeOffset = 0;
  207116. static DWORD lastMessageTime = 0;
  207117. const DWORD thisMessageTime = GetMessageTime();
  207118. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207119. {
  207120. lastMessageTime = thisMessageTime;
  207121. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207122. }
  207123. return eventTimeOffset + thisMessageTime;
  207124. }
  207125. juce_UseDebuggingNewOperator
  207126. bool dontRepaint;
  207127. static ModifierKeys currentModifiers;
  207128. static ModifierKeys modifiersAtLastCallback;
  207129. private:
  207130. HWND hwnd, parentToAddTo;
  207131. ScopedPointer<DropShadower> shadower;
  207132. RenderingEngineType currentRenderingEngine;
  207133. #if JUCE_DIRECT2D
  207134. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207135. #endif
  207136. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207137. BorderSize windowBorder;
  207138. HICON currentWindowIcon;
  207139. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207140. IDropTarget* dropTarget;
  207141. class TemporaryImage : public Timer
  207142. {
  207143. public:
  207144. TemporaryImage() {}
  207145. ~TemporaryImage() {}
  207146. const Image& getImage (const bool transparent, const int w, const int h)
  207147. {
  207148. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207149. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207150. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207151. startTimer (3000);
  207152. return image;
  207153. }
  207154. void timerCallback()
  207155. {
  207156. stopTimer();
  207157. image = Image::null;
  207158. }
  207159. private:
  207160. Image image;
  207161. TemporaryImage (const TemporaryImage&);
  207162. TemporaryImage& operator= (const TemporaryImage&);
  207163. };
  207164. TemporaryImage offscreenImageGenerator;
  207165. class WindowClassHolder : public DeletedAtShutdown
  207166. {
  207167. public:
  207168. WindowClassHolder()
  207169. : windowClassName ("JUCE_")
  207170. {
  207171. // this name has to be different for each app/dll instance because otherwise
  207172. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207173. // window class).
  207174. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207175. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207176. TCHAR moduleFile [1024];
  207177. moduleFile[0] = 0;
  207178. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207179. WORD iconNum = 0;
  207180. WNDCLASSEX wcex;
  207181. wcex.cbSize = sizeof (wcex);
  207182. wcex.style = CS_OWNDC;
  207183. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207184. wcex.lpszClassName = windowClassName;
  207185. wcex.cbClsExtra = 0;
  207186. wcex.cbWndExtra = 32;
  207187. wcex.hInstance = moduleHandle;
  207188. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207189. iconNum = 1;
  207190. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207191. wcex.hCursor = 0;
  207192. wcex.hbrBackground = 0;
  207193. wcex.lpszMenuName = 0;
  207194. RegisterClassEx (&wcex);
  207195. }
  207196. ~WindowClassHolder()
  207197. {
  207198. if (ComponentPeer::getNumPeers() == 0)
  207199. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207200. clearSingletonInstance();
  207201. }
  207202. String windowClassName;
  207203. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207204. };
  207205. static void* createWindowCallback (void* userData)
  207206. {
  207207. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207208. return 0;
  207209. }
  207210. void createWindow()
  207211. {
  207212. DWORD exstyle = WS_EX_ACCEPTFILES;
  207213. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207214. if (hasTitleBar())
  207215. {
  207216. type |= WS_OVERLAPPED;
  207217. if ((styleFlags & windowHasCloseButton) != 0)
  207218. {
  207219. type |= WS_SYSMENU;
  207220. }
  207221. else
  207222. {
  207223. // annoyingly, windows won't let you have a min/max button without a close button
  207224. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207225. }
  207226. if ((styleFlags & windowIsResizable) != 0)
  207227. type |= WS_THICKFRAME;
  207228. }
  207229. else if (parentToAddTo != 0)
  207230. {
  207231. type |= WS_CHILD;
  207232. }
  207233. else
  207234. {
  207235. type |= WS_POPUP | WS_SYSMENU;
  207236. }
  207237. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207238. exstyle |= WS_EX_TOOLWINDOW;
  207239. else
  207240. exstyle |= WS_EX_APPWINDOW;
  207241. if ((styleFlags & windowHasMinimiseButton) != 0)
  207242. type |= WS_MINIMIZEBOX;
  207243. if ((styleFlags & windowHasMaximiseButton) != 0)
  207244. type |= WS_MAXIMIZEBOX;
  207245. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207246. exstyle |= WS_EX_TRANSPARENT;
  207247. if ((styleFlags & windowIsSemiTransparent) != 0
  207248. && Desktop::canUseSemiTransparentWindows())
  207249. exstyle |= WS_EX_LAYERED;
  207250. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207251. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207252. #if JUCE_DIRECT2D
  207253. updateDirect2DContext();
  207254. #endif
  207255. if (hwnd != 0)
  207256. {
  207257. SetWindowLongPtr (hwnd, 0, 0);
  207258. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207259. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207260. if (dropTarget == 0)
  207261. dropTarget = new JuceDropTarget (this);
  207262. RegisterDragDrop (hwnd, dropTarget);
  207263. updateBorderSize();
  207264. // Calling this function here is (for some reason) necessary to make Windows
  207265. // correctly enable the menu items that we specify in the wm_initmenu message.
  207266. GetSystemMenu (hwnd, false);
  207267. }
  207268. else
  207269. {
  207270. jassertfalse;
  207271. }
  207272. }
  207273. static void* destroyWindowCallback (void* handle)
  207274. {
  207275. RevokeDragDrop ((HWND) handle);
  207276. DestroyWindow ((HWND) handle);
  207277. return 0;
  207278. }
  207279. static void* toFrontCallback1 (void* h)
  207280. {
  207281. SetForegroundWindow ((HWND) h);
  207282. return 0;
  207283. }
  207284. static void* toFrontCallback2 (void* h)
  207285. {
  207286. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207287. return 0;
  207288. }
  207289. static void* setFocusCallback (void* h)
  207290. {
  207291. SetFocus ((HWND) h);
  207292. return 0;
  207293. }
  207294. static void* getFocusCallback (void*)
  207295. {
  207296. return GetFocus();
  207297. }
  207298. void offsetWithinParent (int& x, int& y) const
  207299. {
  207300. if (isTransparent())
  207301. {
  207302. HWND parentHwnd = GetParent (hwnd);
  207303. if (parentHwnd != 0)
  207304. {
  207305. RECT parentRect;
  207306. GetWindowRect (parentHwnd, &parentRect);
  207307. x += parentRect.left;
  207308. y += parentRect.top;
  207309. }
  207310. }
  207311. }
  207312. bool isTransparent() const
  207313. {
  207314. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207315. }
  207316. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207317. void setIcon (const Image& newIcon)
  207318. {
  207319. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207320. if (hicon != 0)
  207321. {
  207322. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207323. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207324. if (currentWindowIcon != 0)
  207325. DestroyIcon (currentWindowIcon);
  207326. currentWindowIcon = hicon;
  207327. }
  207328. }
  207329. void handlePaintMessage()
  207330. {
  207331. #if JUCE_DIRECT2D
  207332. if (direct2DContext != 0)
  207333. {
  207334. RECT r;
  207335. if (GetUpdateRect (hwnd, &r, false))
  207336. {
  207337. direct2DContext->start();
  207338. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207339. handlePaint (*direct2DContext);
  207340. direct2DContext->end();
  207341. }
  207342. }
  207343. else
  207344. #endif
  207345. {
  207346. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207347. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207348. PAINTSTRUCT paintStruct;
  207349. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207350. // message and become re-entrant, but that's OK
  207351. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207352. // corrupt the image it's using to paint into, so do a check here.
  207353. static bool reentrant = false;
  207354. if (reentrant)
  207355. {
  207356. DeleteObject (rgn);
  207357. EndPaint (hwnd, &paintStruct);
  207358. return;
  207359. }
  207360. reentrant = true;
  207361. // this is the rectangle to update..
  207362. int x = paintStruct.rcPaint.left;
  207363. int y = paintStruct.rcPaint.top;
  207364. int w = paintStruct.rcPaint.right - x;
  207365. int h = paintStruct.rcPaint.bottom - y;
  207366. const bool transparent = isTransparent();
  207367. if (transparent)
  207368. {
  207369. // it's not possible to have a transparent window with a title bar at the moment!
  207370. jassert (! hasTitleBar());
  207371. RECT r;
  207372. GetWindowRect (hwnd, &r);
  207373. x = y = 0;
  207374. w = r.right - r.left;
  207375. h = r.bottom - r.top;
  207376. }
  207377. if (w > 0 && h > 0)
  207378. {
  207379. clearMaskedRegion();
  207380. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207381. RectangleList contextClip;
  207382. const Rectangle<int> clipBounds (0, 0, w, h);
  207383. bool needToPaintAll = true;
  207384. if (regionType == COMPLEXREGION && ! transparent)
  207385. {
  207386. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207387. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207388. DeleteObject (clipRgn);
  207389. char rgnData [8192];
  207390. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207391. if (res > 0 && res <= sizeof (rgnData))
  207392. {
  207393. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207394. if (hdr->iType == RDH_RECTANGLES
  207395. && hdr->rcBound.right - hdr->rcBound.left >= w
  207396. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207397. {
  207398. needToPaintAll = false;
  207399. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207400. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207401. while (--num >= 0)
  207402. {
  207403. if (rects->right <= x + w && rects->bottom <= y + h)
  207404. {
  207405. const int cx = jmax (x, (int) rects->left);
  207406. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207407. .getIntersection (clipBounds));
  207408. }
  207409. else
  207410. {
  207411. needToPaintAll = true;
  207412. break;
  207413. }
  207414. ++rects;
  207415. }
  207416. }
  207417. }
  207418. }
  207419. if (needToPaintAll)
  207420. {
  207421. contextClip.clear();
  207422. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207423. }
  207424. if (transparent)
  207425. {
  207426. RectangleList::Iterator i (contextClip);
  207427. while (i.next())
  207428. offscreenImage.clear (*i.getRectangle());
  207429. }
  207430. // if the component's not opaque, this won't draw properly unless the platform can support this
  207431. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207432. updateCurrentModifiers();
  207433. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207434. handlePaint (context);
  207435. if (! dontRepaint)
  207436. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207437. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207438. }
  207439. DeleteObject (rgn);
  207440. EndPaint (hwnd, &paintStruct);
  207441. reentrant = false;
  207442. }
  207443. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207444. _fpreset(); // because some graphics cards can unmask FP exceptions
  207445. #endif
  207446. lastPaintTime = Time::getMillisecondCounter();
  207447. }
  207448. void doMouseEvent (const Point<int>& position)
  207449. {
  207450. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207451. }
  207452. const StringArray getAvailableRenderingEngines()
  207453. {
  207454. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207455. #if JUCE_DIRECT2D
  207456. // xxx is this correct? Seems to enable it on Vista too??
  207457. OSVERSIONINFO info;
  207458. zerostruct (info);
  207459. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207460. GetVersionEx (&info);
  207461. if (info.dwMajorVersion >= 6)
  207462. s.add ("Direct2D");
  207463. #endif
  207464. return s;
  207465. }
  207466. int getCurrentRenderingEngine() throw()
  207467. {
  207468. return currentRenderingEngine;
  207469. }
  207470. #if JUCE_DIRECT2D
  207471. void updateDirect2DContext()
  207472. {
  207473. if (currentRenderingEngine != direct2DRenderingEngine)
  207474. direct2DContext = 0;
  207475. else if (direct2DContext == 0)
  207476. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207477. }
  207478. #endif
  207479. void setCurrentRenderingEngine (int index)
  207480. {
  207481. (void) index;
  207482. #if JUCE_DIRECT2D
  207483. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207484. updateDirect2DContext();
  207485. repaint (component->getLocalBounds());
  207486. #endif
  207487. }
  207488. void doMouseMove (const Point<int>& position)
  207489. {
  207490. if (! isMouseOver)
  207491. {
  207492. isMouseOver = true;
  207493. updateKeyModifiers();
  207494. TRACKMOUSEEVENT tme;
  207495. tme.cbSize = sizeof (tme);
  207496. tme.dwFlags = TME_LEAVE;
  207497. tme.hwndTrack = hwnd;
  207498. tme.dwHoverTime = 0;
  207499. if (! TrackMouseEvent (&tme))
  207500. jassertfalse;
  207501. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207502. }
  207503. else if (! isDragging)
  207504. {
  207505. if (! contains (position, false))
  207506. return;
  207507. }
  207508. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207509. static uint32 lastMouseTime = 0;
  207510. const uint32 now = Time::getMillisecondCounter();
  207511. const int maxMouseMovesPerSecond = 60;
  207512. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207513. {
  207514. lastMouseTime = now;
  207515. doMouseEvent (position);
  207516. }
  207517. }
  207518. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207519. {
  207520. if (GetCapture() != hwnd)
  207521. SetCapture (hwnd);
  207522. doMouseMove (position);
  207523. updateModifiersFromWParam (wParam);
  207524. isDragging = true;
  207525. doMouseEvent (position);
  207526. }
  207527. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207528. {
  207529. updateModifiersFromWParam (wParam);
  207530. isDragging = false;
  207531. // release the mouse capture if the user has released all buttons
  207532. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207533. ReleaseCapture();
  207534. doMouseEvent (position);
  207535. }
  207536. void doCaptureChanged()
  207537. {
  207538. if (isDragging)
  207539. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207540. }
  207541. void doMouseExit()
  207542. {
  207543. isMouseOver = false;
  207544. doMouseEvent (getCurrentMousePos());
  207545. }
  207546. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207547. {
  207548. updateKeyModifiers();
  207549. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207550. handleMouseWheel (0, position, getMouseEventTime(),
  207551. isVertical ? 0.0f : amount,
  207552. isVertical ? amount : 0.0f);
  207553. }
  207554. void sendModifierKeyChangeIfNeeded()
  207555. {
  207556. if (modifiersAtLastCallback != currentModifiers)
  207557. {
  207558. modifiersAtLastCallback = currentModifiers;
  207559. handleModifierKeysChange();
  207560. }
  207561. }
  207562. bool doKeyUp (const WPARAM key)
  207563. {
  207564. updateKeyModifiers();
  207565. switch (key)
  207566. {
  207567. case VK_SHIFT:
  207568. case VK_CONTROL:
  207569. case VK_MENU:
  207570. case VK_CAPITAL:
  207571. case VK_LWIN:
  207572. case VK_RWIN:
  207573. case VK_APPS:
  207574. case VK_NUMLOCK:
  207575. case VK_SCROLL:
  207576. case VK_LSHIFT:
  207577. case VK_RSHIFT:
  207578. case VK_LCONTROL:
  207579. case VK_LMENU:
  207580. case VK_RCONTROL:
  207581. case VK_RMENU:
  207582. sendModifierKeyChangeIfNeeded();
  207583. }
  207584. return handleKeyUpOrDown (false)
  207585. || Component::getCurrentlyModalComponent() != 0;
  207586. }
  207587. bool doKeyDown (const WPARAM key)
  207588. {
  207589. updateKeyModifiers();
  207590. bool used = false;
  207591. switch (key)
  207592. {
  207593. case VK_SHIFT:
  207594. case VK_LSHIFT:
  207595. case VK_RSHIFT:
  207596. case VK_CONTROL:
  207597. case VK_LCONTROL:
  207598. case VK_RCONTROL:
  207599. case VK_MENU:
  207600. case VK_LMENU:
  207601. case VK_RMENU:
  207602. case VK_LWIN:
  207603. case VK_RWIN:
  207604. case VK_CAPITAL:
  207605. case VK_NUMLOCK:
  207606. case VK_SCROLL:
  207607. case VK_APPS:
  207608. sendModifierKeyChangeIfNeeded();
  207609. break;
  207610. case VK_LEFT:
  207611. case VK_RIGHT:
  207612. case VK_UP:
  207613. case VK_DOWN:
  207614. case VK_PRIOR:
  207615. case VK_NEXT:
  207616. case VK_HOME:
  207617. case VK_END:
  207618. case VK_DELETE:
  207619. case VK_INSERT:
  207620. case VK_F1:
  207621. case VK_F2:
  207622. case VK_F3:
  207623. case VK_F4:
  207624. case VK_F5:
  207625. case VK_F6:
  207626. case VK_F7:
  207627. case VK_F8:
  207628. case VK_F9:
  207629. case VK_F10:
  207630. case VK_F11:
  207631. case VK_F12:
  207632. case VK_F13:
  207633. case VK_F14:
  207634. case VK_F15:
  207635. case VK_F16:
  207636. used = handleKeyUpOrDown (true);
  207637. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207638. break;
  207639. case VK_ADD:
  207640. case VK_SUBTRACT:
  207641. case VK_MULTIPLY:
  207642. case VK_DIVIDE:
  207643. case VK_SEPARATOR:
  207644. case VK_DECIMAL:
  207645. used = handleKeyUpOrDown (true);
  207646. break;
  207647. default:
  207648. used = handleKeyUpOrDown (true);
  207649. {
  207650. MSG msg;
  207651. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207652. {
  207653. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207654. // manually generate the key-press event that matches this key-down.
  207655. const UINT keyChar = MapVirtualKey (key, 2);
  207656. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207657. }
  207658. }
  207659. break;
  207660. }
  207661. if (Component::getCurrentlyModalComponent() != 0)
  207662. used = true;
  207663. return used;
  207664. }
  207665. bool doKeyChar (int key, const LPARAM flags)
  207666. {
  207667. updateKeyModifiers();
  207668. juce_wchar textChar = (juce_wchar) key;
  207669. const int virtualScanCode = (flags >> 16) & 0xff;
  207670. if (key >= '0' && key <= '9')
  207671. {
  207672. switch (virtualScanCode) // check for a numeric keypad scan-code
  207673. {
  207674. case 0x52:
  207675. case 0x4f:
  207676. case 0x50:
  207677. case 0x51:
  207678. case 0x4b:
  207679. case 0x4c:
  207680. case 0x4d:
  207681. case 0x47:
  207682. case 0x48:
  207683. case 0x49:
  207684. key = (key - '0') + KeyPress::numberPad0;
  207685. break;
  207686. default:
  207687. break;
  207688. }
  207689. }
  207690. else
  207691. {
  207692. // convert the scan code to an unmodified character code..
  207693. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207694. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207695. keyChar = LOWORD (keyChar);
  207696. if (keyChar != 0)
  207697. key = (int) keyChar;
  207698. // avoid sending junk text characters for some control-key combinations
  207699. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207700. textChar = 0;
  207701. }
  207702. return handleKeyPress (key, textChar);
  207703. }
  207704. bool doAppCommand (const LPARAM lParam)
  207705. {
  207706. int key = 0;
  207707. switch (GET_APPCOMMAND_LPARAM (lParam))
  207708. {
  207709. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207710. key = KeyPress::playKey;
  207711. break;
  207712. case APPCOMMAND_MEDIA_STOP:
  207713. key = KeyPress::stopKey;
  207714. break;
  207715. case APPCOMMAND_MEDIA_NEXTTRACK:
  207716. key = KeyPress::fastForwardKey;
  207717. break;
  207718. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207719. key = KeyPress::rewindKey;
  207720. break;
  207721. }
  207722. if (key != 0)
  207723. {
  207724. updateKeyModifiers();
  207725. if (hwnd == GetActiveWindow())
  207726. {
  207727. handleKeyPress (key, 0);
  207728. return true;
  207729. }
  207730. }
  207731. return false;
  207732. }
  207733. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207734. {
  207735. public:
  207736. JuceDropTarget (Win32ComponentPeer* const owner_)
  207737. : owner (owner_)
  207738. {
  207739. }
  207740. ~JuceDropTarget() {}
  207741. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207742. {
  207743. updateFileList (pDataObject);
  207744. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207745. *pdwEffect = DROPEFFECT_COPY;
  207746. return S_OK;
  207747. }
  207748. HRESULT __stdcall DragLeave()
  207749. {
  207750. owner->handleFileDragExit (files);
  207751. return S_OK;
  207752. }
  207753. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207754. {
  207755. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207756. *pdwEffect = DROPEFFECT_COPY;
  207757. return S_OK;
  207758. }
  207759. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207760. {
  207761. updateFileList (pDataObject);
  207762. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207763. *pdwEffect = DROPEFFECT_COPY;
  207764. return S_OK;
  207765. }
  207766. private:
  207767. Win32ComponentPeer* const owner;
  207768. StringArray files;
  207769. void updateFileList (IDataObject* const pDataObject)
  207770. {
  207771. files.clear();
  207772. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207773. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207774. if (pDataObject->GetData (&format, &medium) == S_OK)
  207775. {
  207776. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207777. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207778. unsigned int i = 0;
  207779. if (pDropFiles->fWide)
  207780. {
  207781. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207782. for (;;)
  207783. {
  207784. unsigned int len = 0;
  207785. while (i + len < totalLen && fname [i + len] != 0)
  207786. ++len;
  207787. if (len == 0)
  207788. break;
  207789. files.add (String (fname + i, len));
  207790. i += len + 1;
  207791. }
  207792. }
  207793. else
  207794. {
  207795. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207796. for (;;)
  207797. {
  207798. unsigned int len = 0;
  207799. while (i + len < totalLen && fname [i + len] != 0)
  207800. ++len;
  207801. if (len == 0)
  207802. break;
  207803. files.add (String (fname + i, len));
  207804. i += len + 1;
  207805. }
  207806. }
  207807. GlobalUnlock (medium.hGlobal);
  207808. }
  207809. }
  207810. JuceDropTarget (const JuceDropTarget&);
  207811. JuceDropTarget& operator= (const JuceDropTarget&);
  207812. };
  207813. void doSettingChange()
  207814. {
  207815. Desktop::getInstance().refreshMonitorSizes();
  207816. if (fullScreen && ! isMinimised())
  207817. {
  207818. const Rectangle<int> r (component->getParentMonitorArea());
  207819. SetWindowPos (hwnd, 0,
  207820. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207821. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207822. }
  207823. }
  207824. public:
  207825. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207826. {
  207827. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207828. if (peer != 0)
  207829. return peer->peerWindowProc (h, message, wParam, lParam);
  207830. return DefWindowProcW (h, message, wParam, lParam);
  207831. }
  207832. private:
  207833. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207834. {
  207835. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207836. }
  207837. const Point<int> getCurrentMousePos() throw()
  207838. {
  207839. RECT wr;
  207840. GetWindowRect (hwnd, &wr);
  207841. const DWORD mp = GetMessagePos();
  207842. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207843. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207844. }
  207845. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207846. {
  207847. if (isValidPeer (this))
  207848. {
  207849. switch (message)
  207850. {
  207851. case WM_NCHITTEST:
  207852. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207853. return HTTRANSPARENT;
  207854. if (hasTitleBar())
  207855. break;
  207856. return HTCLIENT;
  207857. case WM_PAINT:
  207858. handlePaintMessage();
  207859. return 0;
  207860. case WM_NCPAINT:
  207861. if (wParam != 1)
  207862. handlePaintMessage();
  207863. if (hasTitleBar())
  207864. break;
  207865. return 0;
  207866. case WM_ERASEBKGND:
  207867. case WM_NCCALCSIZE:
  207868. if (hasTitleBar())
  207869. break;
  207870. return 1;
  207871. case WM_MOUSEMOVE:
  207872. doMouseMove (getPointFromLParam (lParam));
  207873. return 0;
  207874. case WM_MOUSELEAVE:
  207875. doMouseExit();
  207876. return 0;
  207877. case WM_LBUTTONDOWN:
  207878. case WM_MBUTTONDOWN:
  207879. case WM_RBUTTONDOWN:
  207880. doMouseDown (getPointFromLParam (lParam), wParam);
  207881. return 0;
  207882. case WM_LBUTTONUP:
  207883. case WM_MBUTTONUP:
  207884. case WM_RBUTTONUP:
  207885. doMouseUp (getPointFromLParam (lParam), wParam);
  207886. return 0;
  207887. case WM_CAPTURECHANGED:
  207888. doCaptureChanged();
  207889. return 0;
  207890. case WM_NCMOUSEMOVE:
  207891. if (hasTitleBar())
  207892. break;
  207893. return 0;
  207894. case 0x020A: /* WM_MOUSEWHEEL */
  207895. doMouseWheel (getCurrentMousePos(), wParam, true);
  207896. return 0;
  207897. case 0x020E: /* WM_MOUSEHWHEEL */
  207898. doMouseWheel (getCurrentMousePos(), wParam, false);
  207899. return 0;
  207900. case WM_WINDOWPOSCHANGING:
  207901. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207902. {
  207903. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207904. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207905. {
  207906. if (constrainer != 0)
  207907. {
  207908. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207909. component->getY() - windowBorder.getTop(),
  207910. component->getWidth() + windowBorder.getLeftAndRight(),
  207911. component->getHeight() + windowBorder.getTopAndBottom());
  207912. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207913. constrainer->checkBounds (pos, current,
  207914. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207915. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207916. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207917. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207918. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207919. wp->x = pos.getX();
  207920. wp->y = pos.getY();
  207921. wp->cx = pos.getWidth();
  207922. wp->cy = pos.getHeight();
  207923. }
  207924. }
  207925. }
  207926. return 0;
  207927. case WM_WINDOWPOSCHANGED:
  207928. doMouseEvent (getCurrentMousePos());
  207929. handleMovedOrResized();
  207930. if (dontRepaint)
  207931. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207932. return 0;
  207933. case WM_KEYDOWN:
  207934. case WM_SYSKEYDOWN:
  207935. if (doKeyDown (wParam))
  207936. return 0;
  207937. break;
  207938. case WM_KEYUP:
  207939. case WM_SYSKEYUP:
  207940. if (doKeyUp (wParam))
  207941. return 0;
  207942. break;
  207943. case WM_CHAR:
  207944. if (doKeyChar ((int) wParam, lParam))
  207945. return 0;
  207946. break;
  207947. case WM_APPCOMMAND:
  207948. if (doAppCommand (lParam))
  207949. return TRUE;
  207950. break;
  207951. case WM_SETFOCUS:
  207952. updateKeyModifiers();
  207953. handleFocusGain();
  207954. break;
  207955. case WM_KILLFOCUS:
  207956. if (hasCreatedCaret)
  207957. {
  207958. hasCreatedCaret = false;
  207959. DestroyCaret();
  207960. }
  207961. handleFocusLoss();
  207962. break;
  207963. case WM_ACTIVATEAPP:
  207964. // Windows does weird things to process priority when you swap apps,
  207965. // so this forces an update when the app is brought to the front
  207966. if (wParam != FALSE)
  207967. juce_repeatLastProcessPriority();
  207968. else
  207969. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207970. juce_CheckCurrentlyFocusedTopLevelWindow();
  207971. modifiersAtLastCallback = -1;
  207972. return 0;
  207973. case WM_ACTIVATE:
  207974. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207975. {
  207976. modifiersAtLastCallback = -1;
  207977. updateKeyModifiers();
  207978. if (isMinimised())
  207979. {
  207980. component->repaint();
  207981. handleMovedOrResized();
  207982. if (! ComponentPeer::isValidPeer (this))
  207983. return 0;
  207984. }
  207985. if (LOWORD (wParam) == WA_CLICKACTIVE
  207986. && component->isCurrentlyBlockedByAnotherModalComponent())
  207987. {
  207988. const Point<int> mousePos (component->getMouseXYRelative());
  207989. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  207990. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207991. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207992. return 0;
  207993. }
  207994. handleBroughtToFront();
  207995. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207996. Component::getCurrentlyModalComponent()->toFront (true);
  207997. return 0;
  207998. }
  207999. break;
  208000. case WM_NCACTIVATE:
  208001. // while a temporary window is being shown, prevent Windows from deactivating the
  208002. // title bars of our main windows.
  208003. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208004. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208005. break;
  208006. case WM_MOUSEACTIVATE:
  208007. if (! component->getMouseClickGrabsKeyboardFocus())
  208008. return MA_NOACTIVATE;
  208009. break;
  208010. case WM_SHOWWINDOW:
  208011. if (wParam != 0)
  208012. handleBroughtToFront();
  208013. break;
  208014. case WM_CLOSE:
  208015. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208016. handleUserClosingWindow();
  208017. return 0;
  208018. case WM_QUERYENDSESSION:
  208019. if (JUCEApplication::getInstance() != 0)
  208020. {
  208021. JUCEApplication::getInstance()->systemRequestedQuit();
  208022. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208023. }
  208024. return TRUE;
  208025. case WM_TRAYNOTIFY:
  208026. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208027. {
  208028. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208029. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208030. {
  208031. Component* const current = Component::getCurrentlyModalComponent();
  208032. if (current != 0)
  208033. current->inputAttemptWhenModal();
  208034. }
  208035. }
  208036. else
  208037. {
  208038. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208039. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208040. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208041. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208042. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208043. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208044. eventMods = eventMods.withoutMouseButtons();
  208045. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208046. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208047. Point<int>(), getMouseEventTime(), 1, false);
  208048. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208049. {
  208050. SetFocus (hwnd);
  208051. SetForegroundWindow (hwnd);
  208052. component->mouseDown (e);
  208053. }
  208054. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208055. {
  208056. component->mouseUp (e);
  208057. }
  208058. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208059. {
  208060. component->mouseDoubleClick (e);
  208061. }
  208062. else if (lParam == WM_MOUSEMOVE)
  208063. {
  208064. component->mouseMove (e);
  208065. }
  208066. }
  208067. break;
  208068. case WM_SYNCPAINT:
  208069. return 0;
  208070. case WM_PALETTECHANGED:
  208071. InvalidateRect (h, 0, 0);
  208072. break;
  208073. case WM_DISPLAYCHANGE:
  208074. InvalidateRect (h, 0, 0);
  208075. createPaletteIfNeeded = true;
  208076. // intentional fall-through...
  208077. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208078. doSettingChange();
  208079. break;
  208080. case WM_INITMENU:
  208081. if (! hasTitleBar())
  208082. {
  208083. if (isFullScreen())
  208084. {
  208085. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208086. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208087. }
  208088. else if (! isMinimised())
  208089. {
  208090. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208091. }
  208092. }
  208093. break;
  208094. case WM_SYSCOMMAND:
  208095. switch (wParam & 0xfff0)
  208096. {
  208097. case SC_CLOSE:
  208098. if (sendInputAttemptWhenModalMessage())
  208099. return 0;
  208100. if (hasTitleBar())
  208101. {
  208102. PostMessage (h, WM_CLOSE, 0, 0);
  208103. return 0;
  208104. }
  208105. break;
  208106. case SC_KEYMENU:
  208107. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208108. // obscure situations that can arise if a modal loop is started from an alt-key
  208109. // keypress).
  208110. if (hasTitleBar() && h == GetCapture())
  208111. ReleaseCapture();
  208112. break;
  208113. case SC_MAXIMIZE:
  208114. if (sendInputAttemptWhenModalMessage())
  208115. return 0;
  208116. setFullScreen (true);
  208117. return 0;
  208118. case SC_MINIMIZE:
  208119. if (sendInputAttemptWhenModalMessage())
  208120. return 0;
  208121. if (! hasTitleBar())
  208122. {
  208123. setMinimised (true);
  208124. return 0;
  208125. }
  208126. break;
  208127. case SC_RESTORE:
  208128. if (sendInputAttemptWhenModalMessage())
  208129. return 0;
  208130. if (hasTitleBar())
  208131. {
  208132. if (isFullScreen())
  208133. {
  208134. setFullScreen (false);
  208135. return 0;
  208136. }
  208137. }
  208138. else
  208139. {
  208140. if (isMinimised())
  208141. setMinimised (false);
  208142. else if (isFullScreen())
  208143. setFullScreen (false);
  208144. return 0;
  208145. }
  208146. break;
  208147. }
  208148. break;
  208149. case WM_NCLBUTTONDOWN:
  208150. case WM_NCRBUTTONDOWN:
  208151. case WM_NCMBUTTONDOWN:
  208152. sendInputAttemptWhenModalMessage();
  208153. break;
  208154. //case WM_IME_STARTCOMPOSITION;
  208155. // return 0;
  208156. case WM_GETDLGCODE:
  208157. return DLGC_WANTALLKEYS;
  208158. default:
  208159. break;
  208160. }
  208161. }
  208162. return DefWindowProcW (h, message, wParam, lParam);
  208163. }
  208164. bool sendInputAttemptWhenModalMessage()
  208165. {
  208166. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208167. {
  208168. Component* const current = Component::getCurrentlyModalComponent();
  208169. if (current != 0)
  208170. current->inputAttemptWhenModal();
  208171. return true;
  208172. }
  208173. return false;
  208174. }
  208175. Win32ComponentPeer (const Win32ComponentPeer&);
  208176. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208177. };
  208178. ModifierKeys Win32ComponentPeer::currentModifiers;
  208179. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208180. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208181. {
  208182. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208183. }
  208184. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208185. void ModifierKeys::updateCurrentModifiers() throw()
  208186. {
  208187. currentModifiers = Win32ComponentPeer::currentModifiers;
  208188. }
  208189. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208190. {
  208191. Win32ComponentPeer::updateKeyModifiers();
  208192. int keyMods = 0;
  208193. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208194. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208195. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208196. Win32ComponentPeer::currentModifiers
  208197. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208198. return Win32ComponentPeer::currentModifiers;
  208199. }
  208200. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208201. {
  208202. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208203. if (wp != 0)
  208204. wp->setTaskBarIcon (newImage);
  208205. }
  208206. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208207. {
  208208. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208209. if (wp != 0)
  208210. wp->setTaskBarIconToolTip (tooltip);
  208211. }
  208212. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208213. {
  208214. DWORD val = GetWindowLong (h, styleType);
  208215. if (bitIsSet)
  208216. val |= feature;
  208217. else
  208218. val &= ~feature;
  208219. SetWindowLongPtr (h, styleType, val);
  208220. SetWindowPos (h, 0, 0, 0, 0, 0,
  208221. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208222. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208223. }
  208224. bool Process::isForegroundProcess()
  208225. {
  208226. HWND fg = GetForegroundWindow();
  208227. if (fg == 0)
  208228. return true;
  208229. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208230. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208231. // have to see if any of our windows are children of the foreground window
  208232. fg = GetAncestor (fg, GA_ROOT);
  208233. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208234. {
  208235. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208236. if (wp != 0 && wp->isInside (fg))
  208237. return true;
  208238. }
  208239. return false;
  208240. }
  208241. bool AlertWindow::showNativeDialogBox (const String& title,
  208242. const String& bodyText,
  208243. bool isOkCancel)
  208244. {
  208245. return MessageBox (0, bodyText, title,
  208246. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208247. : MB_OK)) == IDOK;
  208248. }
  208249. void Desktop::createMouseInputSources()
  208250. {
  208251. mouseSources.add (new MouseInputSource (0, true));
  208252. }
  208253. const Point<int> Desktop::getMousePosition()
  208254. {
  208255. POINT mousePos;
  208256. GetCursorPos (&mousePos);
  208257. return Point<int> (mousePos.x, mousePos.y);
  208258. }
  208259. void Desktop::setMousePosition (const Point<int>& newPosition)
  208260. {
  208261. SetCursorPos (newPosition.getX(), newPosition.getY());
  208262. }
  208263. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208264. {
  208265. return createSoftwareImage (format, width, height, clearImage);
  208266. }
  208267. class ScreenSaverDefeater : public Timer,
  208268. public DeletedAtShutdown
  208269. {
  208270. public:
  208271. ScreenSaverDefeater()
  208272. {
  208273. startTimer (10000);
  208274. timerCallback();
  208275. }
  208276. ~ScreenSaverDefeater() {}
  208277. void timerCallback()
  208278. {
  208279. if (Process::isForegroundProcess())
  208280. {
  208281. // simulate a shift key getting pressed..
  208282. INPUT input[2];
  208283. input[0].type = INPUT_KEYBOARD;
  208284. input[0].ki.wVk = VK_SHIFT;
  208285. input[0].ki.dwFlags = 0;
  208286. input[0].ki.dwExtraInfo = 0;
  208287. input[1].type = INPUT_KEYBOARD;
  208288. input[1].ki.wVk = VK_SHIFT;
  208289. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208290. input[1].ki.dwExtraInfo = 0;
  208291. SendInput (2, input, sizeof (INPUT));
  208292. }
  208293. }
  208294. };
  208295. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208296. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208297. {
  208298. if (isEnabled)
  208299. deleteAndZero (screenSaverDefeater);
  208300. else if (screenSaverDefeater == 0)
  208301. screenSaverDefeater = new ScreenSaverDefeater();
  208302. }
  208303. bool Desktop::isScreenSaverEnabled()
  208304. {
  208305. return screenSaverDefeater == 0;
  208306. }
  208307. /* (The code below is the "correct" way to disable the screen saver, but it
  208308. completely fails on winXP when the saver is password-protected...)
  208309. static bool juce_screenSaverEnabled = true;
  208310. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208311. {
  208312. juce_screenSaverEnabled = isEnabled;
  208313. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208314. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208315. }
  208316. bool Desktop::isScreenSaverEnabled() throw()
  208317. {
  208318. return juce_screenSaverEnabled;
  208319. }
  208320. */
  208321. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208322. {
  208323. if (enableOrDisable)
  208324. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208325. }
  208326. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208327. {
  208328. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208329. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208330. return TRUE;
  208331. }
  208332. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208333. {
  208334. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208335. // make sure the first in the list is the main monitor
  208336. for (int i = 1; i < monitorCoords.size(); ++i)
  208337. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208338. monitorCoords.swap (i, 0);
  208339. if (monitorCoords.size() == 0)
  208340. {
  208341. RECT r;
  208342. GetWindowRect (GetDesktopWindow(), &r);
  208343. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208344. }
  208345. if (clipToWorkArea)
  208346. {
  208347. // clip the main monitor to the active non-taskbar area
  208348. RECT r;
  208349. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208350. Rectangle<int>& screen = monitorCoords.getReference (0);
  208351. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208352. jmax (screen.getY(), (int) r.top));
  208353. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208354. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208355. }
  208356. }
  208357. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208358. {
  208359. Image im;
  208360. if (bitmap != 0)
  208361. {
  208362. BITMAP bm;
  208363. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208364. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208365. {
  208366. HDC tempDC = GetDC (0);
  208367. HDC dc = CreateCompatibleDC (tempDC);
  208368. ReleaseDC (0, tempDC);
  208369. SelectObject (dc, bitmap);
  208370. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208371. Image::BitmapData imageData (im, true);
  208372. for (int y = bm.bmHeight; --y >= 0;)
  208373. {
  208374. for (int x = bm.bmWidth; --x >= 0;)
  208375. {
  208376. COLORREF col = GetPixel (dc, x, y);
  208377. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208378. (uint8) GetGValue (col),
  208379. (uint8) GetBValue (col)));
  208380. }
  208381. }
  208382. DeleteDC (dc);
  208383. }
  208384. }
  208385. return im;
  208386. }
  208387. static const Image createImageFromHICON (HICON icon)
  208388. {
  208389. ICONINFO info;
  208390. if (GetIconInfo (icon, &info))
  208391. {
  208392. Image mask (createImageFromHBITMAP (info.hbmMask));
  208393. Image image (createImageFromHBITMAP (info.hbmColor));
  208394. if (mask.isValid() && image.isValid())
  208395. {
  208396. for (int y = image.getHeight(); --y >= 0;)
  208397. {
  208398. for (int x = image.getWidth(); --x >= 0;)
  208399. {
  208400. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208401. if (brightness > 0.0f)
  208402. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208403. }
  208404. }
  208405. return image;
  208406. }
  208407. }
  208408. return Image::null;
  208409. }
  208410. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208411. {
  208412. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208413. Image bitmap (nativeBitmap);
  208414. {
  208415. Graphics g (bitmap);
  208416. g.drawImageAt (image, 0, 0);
  208417. }
  208418. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208419. ICONINFO info;
  208420. info.fIcon = isIcon;
  208421. info.xHotspot = hotspotX;
  208422. info.yHotspot = hotspotY;
  208423. info.hbmMask = mask;
  208424. info.hbmColor = nativeBitmap->hBitmap;
  208425. HICON hi = CreateIconIndirect (&info);
  208426. DeleteObject (mask);
  208427. return hi;
  208428. }
  208429. const Image juce_createIconForFile (const File& file)
  208430. {
  208431. Image image;
  208432. WCHAR filename [1024];
  208433. file.getFullPathName().copyToUnicode (filename, 1023);
  208434. WORD iconNum = 0;
  208435. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208436. filename, &iconNum);
  208437. if (icon != 0)
  208438. {
  208439. image = createImageFromHICON (icon);
  208440. DestroyIcon (icon);
  208441. }
  208442. return image;
  208443. }
  208444. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208445. {
  208446. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208447. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208448. Image im (image);
  208449. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208450. {
  208451. im = im.rescaled (maxW, maxH);
  208452. hotspotX = (hotspotX * maxW) / image.getWidth();
  208453. hotspotY = (hotspotY * maxH) / image.getHeight();
  208454. }
  208455. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208456. }
  208457. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208458. {
  208459. if (cursorHandle != 0 && ! isStandard)
  208460. DestroyCursor ((HCURSOR) cursorHandle);
  208461. }
  208462. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208463. {
  208464. LPCTSTR cursorName = IDC_ARROW;
  208465. switch (type)
  208466. {
  208467. case NormalCursor: break;
  208468. case NoCursor: return 0;
  208469. case WaitCursor: cursorName = IDC_WAIT; break;
  208470. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208471. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208472. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208473. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208474. case LeftRightResizeCursor:
  208475. case LeftEdgeResizeCursor:
  208476. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208477. case UpDownResizeCursor:
  208478. case TopEdgeResizeCursor:
  208479. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208480. case TopLeftCornerResizeCursor:
  208481. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208482. case TopRightCornerResizeCursor:
  208483. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208484. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208485. case DraggingHandCursor:
  208486. {
  208487. static void* dragHandCursor = 0;
  208488. if (dragHandCursor == 0)
  208489. {
  208490. static const unsigned char dragHandData[] =
  208491. { 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,
  208492. 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,
  208493. 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 };
  208494. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208495. }
  208496. return dragHandCursor;
  208497. }
  208498. default:
  208499. jassertfalse; break;
  208500. }
  208501. HCURSOR cursorH = LoadCursor (0, cursorName);
  208502. if (cursorH == 0)
  208503. cursorH = LoadCursor (0, IDC_ARROW);
  208504. return cursorH;
  208505. }
  208506. void MouseCursor::showInWindow (ComponentPeer*) const
  208507. {
  208508. SetCursor ((HCURSOR) getHandle());
  208509. }
  208510. void MouseCursor::showInAllWindows() const
  208511. {
  208512. showInWindow (0);
  208513. }
  208514. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208515. {
  208516. public:
  208517. JuceDropSource() {}
  208518. ~JuceDropSource() {}
  208519. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208520. {
  208521. if (escapePressed)
  208522. return DRAGDROP_S_CANCEL;
  208523. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208524. return DRAGDROP_S_DROP;
  208525. return S_OK;
  208526. }
  208527. HRESULT __stdcall GiveFeedback (DWORD)
  208528. {
  208529. return DRAGDROP_S_USEDEFAULTCURSORS;
  208530. }
  208531. };
  208532. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208533. {
  208534. public:
  208535. JuceEnumFormatEtc (const FORMATETC* const format_)
  208536. : format (format_),
  208537. index (0)
  208538. {
  208539. }
  208540. ~JuceEnumFormatEtc() {}
  208541. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208542. {
  208543. if (result == 0)
  208544. return E_POINTER;
  208545. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208546. newOne->index = index;
  208547. *result = newOne;
  208548. return S_OK;
  208549. }
  208550. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208551. {
  208552. if (pceltFetched != 0)
  208553. *pceltFetched = 0;
  208554. else if (celt != 1)
  208555. return S_FALSE;
  208556. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208557. {
  208558. copyFormatEtc (lpFormatEtc [0], *format);
  208559. ++index;
  208560. if (pceltFetched != 0)
  208561. *pceltFetched = 1;
  208562. return S_OK;
  208563. }
  208564. return S_FALSE;
  208565. }
  208566. HRESULT __stdcall Skip (ULONG celt)
  208567. {
  208568. if (index + (int) celt >= 1)
  208569. return S_FALSE;
  208570. index += celt;
  208571. return S_OK;
  208572. }
  208573. HRESULT __stdcall Reset()
  208574. {
  208575. index = 0;
  208576. return S_OK;
  208577. }
  208578. private:
  208579. const FORMATETC* const format;
  208580. int index;
  208581. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208582. {
  208583. dest = source;
  208584. if (source.ptd != 0)
  208585. {
  208586. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208587. *(dest.ptd) = *(source.ptd);
  208588. }
  208589. }
  208590. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208591. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208592. };
  208593. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208594. {
  208595. public:
  208596. JuceDataObject (JuceDropSource* const dropSource_,
  208597. const FORMATETC* const format_,
  208598. const STGMEDIUM* const medium_)
  208599. : dropSource (dropSource_),
  208600. format (format_),
  208601. medium (medium_)
  208602. {
  208603. }
  208604. virtual ~JuceDataObject()
  208605. {
  208606. jassert (refCount == 0);
  208607. }
  208608. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208609. {
  208610. if ((pFormatEtc->tymed & format->tymed) != 0
  208611. && pFormatEtc->cfFormat == format->cfFormat
  208612. && pFormatEtc->dwAspect == format->dwAspect)
  208613. {
  208614. pMedium->tymed = format->tymed;
  208615. pMedium->pUnkForRelease = 0;
  208616. if (format->tymed == TYMED_HGLOBAL)
  208617. {
  208618. const SIZE_T len = GlobalSize (medium->hGlobal);
  208619. void* const src = GlobalLock (medium->hGlobal);
  208620. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208621. memcpy (dst, src, len);
  208622. GlobalUnlock (medium->hGlobal);
  208623. pMedium->hGlobal = dst;
  208624. return S_OK;
  208625. }
  208626. }
  208627. return DV_E_FORMATETC;
  208628. }
  208629. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208630. {
  208631. if (f == 0)
  208632. return E_INVALIDARG;
  208633. if (f->tymed == format->tymed
  208634. && f->cfFormat == format->cfFormat
  208635. && f->dwAspect == format->dwAspect)
  208636. return S_OK;
  208637. return DV_E_FORMATETC;
  208638. }
  208639. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208640. {
  208641. pFormatEtcOut->ptd = 0;
  208642. return E_NOTIMPL;
  208643. }
  208644. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208645. {
  208646. if (result == 0)
  208647. return E_POINTER;
  208648. if (direction == DATADIR_GET)
  208649. {
  208650. *result = new JuceEnumFormatEtc (format);
  208651. return S_OK;
  208652. }
  208653. *result = 0;
  208654. return E_NOTIMPL;
  208655. }
  208656. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208657. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208658. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208659. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208660. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208661. private:
  208662. JuceDropSource* const dropSource;
  208663. const FORMATETC* const format;
  208664. const STGMEDIUM* const medium;
  208665. JuceDataObject (const JuceDataObject&);
  208666. JuceDataObject& operator= (const JuceDataObject&);
  208667. };
  208668. static HDROP createHDrop (const StringArray& fileNames)
  208669. {
  208670. int totalChars = 0;
  208671. for (int i = fileNames.size(); --i >= 0;)
  208672. totalChars += fileNames[i].length() + 1;
  208673. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208674. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208675. if (hDrop != 0)
  208676. {
  208677. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208678. pDropFiles->pFiles = sizeof (DROPFILES);
  208679. pDropFiles->fWide = true;
  208680. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208681. for (int i = 0; i < fileNames.size(); ++i)
  208682. {
  208683. fileNames[i].copyToUnicode (fname, 2048);
  208684. fname += fileNames[i].length() + 1;
  208685. }
  208686. *fname = 0;
  208687. GlobalUnlock (hDrop);
  208688. }
  208689. return hDrop;
  208690. }
  208691. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208692. {
  208693. JuceDropSource* const source = new JuceDropSource();
  208694. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208695. DWORD effect;
  208696. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208697. data->Release();
  208698. source->Release();
  208699. return res == DRAGDROP_S_DROP;
  208700. }
  208701. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208702. {
  208703. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208704. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208705. medium.hGlobal = createHDrop (files);
  208706. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208707. : DROPEFFECT_COPY);
  208708. }
  208709. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208710. {
  208711. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208712. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208713. const int numChars = text.length();
  208714. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208715. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208716. text.copyToUnicode (data, numChars + 1);
  208717. format.cfFormat = CF_UNICODETEXT;
  208718. GlobalUnlock (medium.hGlobal);
  208719. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208720. }
  208721. #endif
  208722. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208723. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208724. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208725. // compiled on its own).
  208726. #if JUCE_INCLUDED_FILE
  208727. namespace FileChooserHelpers
  208728. {
  208729. static bool areThereAnyAlwaysOnTopWindows()
  208730. {
  208731. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208732. {
  208733. Component* c = Desktop::getInstance().getComponent (i);
  208734. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208735. return true;
  208736. }
  208737. return false;
  208738. }
  208739. struct FileChooserCallbackInfo
  208740. {
  208741. String initialPath;
  208742. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208743. ScopedPointer<Component> customComponent;
  208744. };
  208745. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208746. {
  208747. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208748. if (msg == BFFM_INITIALIZED)
  208749. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208750. else if (msg == BFFM_VALIDATEFAILEDW)
  208751. info->returnedString = (LPCWSTR) lParam;
  208752. else if (msg == BFFM_VALIDATEFAILEDA)
  208753. info->returnedString = (const char*) lParam;
  208754. return 0;
  208755. }
  208756. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208757. {
  208758. if (uiMsg == WM_INITDIALOG)
  208759. {
  208760. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208761. HWND dialogH = GetParent (hdlg);
  208762. jassert (dialogH != 0);
  208763. if (dialogH == 0)
  208764. dialogH = hdlg;
  208765. RECT r, cr;
  208766. GetWindowRect (dialogH, &r);
  208767. GetClientRect (dialogH, &cr);
  208768. SetWindowPos (dialogH, 0,
  208769. r.left, r.top,
  208770. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208771. jmax (150, (int) (r.bottom - r.top)),
  208772. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208773. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208774. customComp->addToDesktop (0, dialogH);
  208775. }
  208776. else if (uiMsg == WM_NOTIFY)
  208777. {
  208778. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208779. if (ofn->hdr.code == CDN_SELCHANGE)
  208780. {
  208781. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208782. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208783. if (comp != 0)
  208784. {
  208785. WCHAR path [MAX_PATH * 2];
  208786. zerostruct (path);
  208787. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208788. comp->selectedFileChanged (File (path));
  208789. }
  208790. }
  208791. }
  208792. return 0;
  208793. }
  208794. class CustomComponentHolder : public Component
  208795. {
  208796. public:
  208797. CustomComponentHolder (Component* customComp)
  208798. {
  208799. setVisible (true);
  208800. setOpaque (true);
  208801. addAndMakeVisible (customComp);
  208802. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208803. }
  208804. void paint (Graphics& g)
  208805. {
  208806. g.fillAll (Colours::lightgrey);
  208807. }
  208808. void resized()
  208809. {
  208810. if (getNumChildComponents() > 0)
  208811. getChildComponent(0)->setBounds (getLocalBounds());
  208812. }
  208813. juce_UseDebuggingNewOperator
  208814. private:
  208815. CustomComponentHolder (const CustomComponentHolder&);
  208816. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208817. };
  208818. }
  208819. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208820. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208821. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208822. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208823. {
  208824. using namespace FileChooserHelpers;
  208825. HeapBlock<WCHAR> files;
  208826. const int charsAvailableForResult = 32768;
  208827. files.calloc (charsAvailableForResult + 1);
  208828. int filenameOffset = 0;
  208829. FileChooserCallbackInfo info;
  208830. // use a modal window as the parent for this dialog box
  208831. // to block input from other app windows
  208832. Component parentWindow (String::empty);
  208833. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208834. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208835. mainMon.getY() + mainMon.getHeight() / 4,
  208836. 0, 0);
  208837. parentWindow.setOpaque (true);
  208838. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208839. parentWindow.addToDesktop (0);
  208840. if (extraInfoComponent == 0)
  208841. parentWindow.enterModalState();
  208842. if (currentFileOrDirectory.isDirectory())
  208843. {
  208844. info.initialPath = currentFileOrDirectory.getFullPathName();
  208845. }
  208846. else
  208847. {
  208848. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208849. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208850. }
  208851. if (selectsDirectory)
  208852. {
  208853. BROWSEINFO bi;
  208854. zerostruct (bi);
  208855. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208856. bi.pszDisplayName = files;
  208857. bi.lpszTitle = title;
  208858. bi.lParam = (LPARAM) &info;
  208859. bi.lpfn = browseCallbackProc;
  208860. #ifdef BIF_USENEWUI
  208861. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208862. #else
  208863. bi.ulFlags = 0x50;
  208864. #endif
  208865. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208866. if (! SHGetPathFromIDListW (list, files))
  208867. {
  208868. files[0] = 0;
  208869. info.returnedString = String::empty;
  208870. }
  208871. LPMALLOC al;
  208872. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208873. al->Free (list);
  208874. if (info.returnedString.isNotEmpty())
  208875. {
  208876. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208877. return;
  208878. }
  208879. }
  208880. else
  208881. {
  208882. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208883. if (warnAboutOverwritingExistingFiles)
  208884. flags |= OFN_OVERWRITEPROMPT;
  208885. if (selectMultipleFiles)
  208886. flags |= OFN_ALLOWMULTISELECT;
  208887. if (extraInfoComponent != 0)
  208888. {
  208889. flags |= OFN_ENABLEHOOK;
  208890. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208891. info.customComponent->enterModalState();
  208892. }
  208893. WCHAR filters [1024];
  208894. zerostruct (filters);
  208895. filter.copyToUnicode (filters, 1024);
  208896. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208897. OPENFILENAMEW of;
  208898. zerostruct (of);
  208899. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208900. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208901. #else
  208902. of.lStructSize = sizeof (of);
  208903. #endif
  208904. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208905. of.lpstrFilter = filters;
  208906. of.nFilterIndex = 1;
  208907. of.lpstrFile = files;
  208908. of.nMaxFile = charsAvailableForResult;
  208909. of.lpstrInitialDir = info.initialPath;
  208910. of.lpstrTitle = title;
  208911. of.Flags = flags;
  208912. of.lCustData = (LPARAM) &info;
  208913. if (extraInfoComponent != 0)
  208914. of.lpfnHook = &openCallback;
  208915. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208916. : GetOpenFileName (&of)))
  208917. return;
  208918. filenameOffset = of.nFileOffset;
  208919. }
  208920. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208921. {
  208922. const WCHAR* filename = files + filenameOffset;
  208923. while (*filename != 0)
  208924. {
  208925. results.add (File (String (files) + "\\" + String (filename)));
  208926. filename += CharacterFunctions::length (filename) + 1;
  208927. }
  208928. }
  208929. else if (files[0] != 0)
  208930. {
  208931. results.add (File (String (files)));
  208932. }
  208933. }
  208934. #endif
  208935. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208936. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208937. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208938. // compiled on its own).
  208939. #if JUCE_INCLUDED_FILE
  208940. void SystemClipboard::copyTextToClipboard (const String& text)
  208941. {
  208942. if (OpenClipboard (0) != 0)
  208943. {
  208944. if (EmptyClipboard() != 0)
  208945. {
  208946. const int len = text.length();
  208947. if (len > 0)
  208948. {
  208949. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208950. (len + 1) * sizeof (wchar_t));
  208951. if (bufH != 0)
  208952. {
  208953. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208954. text.copyToUnicode (data, len);
  208955. GlobalUnlock (bufH);
  208956. SetClipboardData (CF_UNICODETEXT, bufH);
  208957. }
  208958. }
  208959. }
  208960. CloseClipboard();
  208961. }
  208962. }
  208963. const String SystemClipboard::getTextFromClipboard()
  208964. {
  208965. String result;
  208966. if (OpenClipboard (0) != 0)
  208967. {
  208968. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208969. if (bufH != 0)
  208970. {
  208971. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208972. if (data != 0)
  208973. {
  208974. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208975. GlobalUnlock (bufH);
  208976. }
  208977. }
  208978. CloseClipboard();
  208979. }
  208980. return result;
  208981. }
  208982. #endif
  208983. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208984. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208985. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208986. // compiled on its own).
  208987. #if JUCE_INCLUDED_FILE
  208988. namespace ActiveXHelpers
  208989. {
  208990. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208991. {
  208992. public:
  208993. JuceIStorage() {}
  208994. ~JuceIStorage() {}
  208995. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208996. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208997. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208998. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208999. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209000. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209001. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209002. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209003. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209004. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209005. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209006. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209007. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209008. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209009. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209010. juce_UseDebuggingNewOperator
  209011. };
  209012. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209013. {
  209014. HWND window;
  209015. public:
  209016. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209017. ~JuceOleInPlaceFrame() {}
  209018. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209019. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209020. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209021. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209022. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209023. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209024. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209025. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209026. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209027. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209028. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209029. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209030. juce_UseDebuggingNewOperator
  209031. };
  209032. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209033. {
  209034. HWND window;
  209035. JuceOleInPlaceFrame* frame;
  209036. public:
  209037. JuceIOleInPlaceSite (HWND window_)
  209038. : window (window_),
  209039. frame (new JuceOleInPlaceFrame (window))
  209040. {}
  209041. ~JuceIOleInPlaceSite()
  209042. {
  209043. frame->Release();
  209044. }
  209045. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209046. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209047. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209048. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209049. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209050. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209051. {
  209052. *lplpFrame = frame;
  209053. *lplpDoc = 0;
  209054. lpFrameInfo->fMDIApp = FALSE;
  209055. lpFrameInfo->hwndFrame = window;
  209056. lpFrameInfo->haccel = 0;
  209057. lpFrameInfo->cAccelEntries = 0;
  209058. return S_OK;
  209059. }
  209060. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209061. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209062. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209063. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209064. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209065. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209066. juce_UseDebuggingNewOperator
  209067. };
  209068. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209069. {
  209070. JuceIOleInPlaceSite* inplaceSite;
  209071. public:
  209072. JuceIOleClientSite (HWND window)
  209073. : inplaceSite (new JuceIOleInPlaceSite (window))
  209074. {}
  209075. ~JuceIOleClientSite()
  209076. {
  209077. inplaceSite->Release();
  209078. }
  209079. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209080. {
  209081. if (type == IID_IOleInPlaceSite)
  209082. {
  209083. inplaceSite->AddRef();
  209084. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209085. return S_OK;
  209086. }
  209087. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209088. }
  209089. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209090. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209091. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209092. HRESULT __stdcall ShowObject() { return S_OK; }
  209093. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209094. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209095. juce_UseDebuggingNewOperator
  209096. };
  209097. static Array<ActiveXControlComponent*> activeXComps;
  209098. static HWND getHWND (const ActiveXControlComponent* const component)
  209099. {
  209100. HWND hwnd = 0;
  209101. const IID iid = IID_IOleWindow;
  209102. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209103. if (window != 0)
  209104. {
  209105. window->GetWindow (&hwnd);
  209106. window->Release();
  209107. }
  209108. return hwnd;
  209109. }
  209110. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209111. {
  209112. RECT activeXRect, peerRect;
  209113. GetWindowRect (hwnd, &activeXRect);
  209114. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209115. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209116. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209117. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209118. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209119. switch (message)
  209120. {
  209121. case WM_MOUSEMOVE:
  209122. case WM_LBUTTONDOWN:
  209123. case WM_MBUTTONDOWN:
  209124. case WM_RBUTTONDOWN:
  209125. case WM_LBUTTONUP:
  209126. case WM_MBUTTONUP:
  209127. case WM_RBUTTONUP:
  209128. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209129. break;
  209130. default:
  209131. break;
  209132. }
  209133. }
  209134. }
  209135. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209136. {
  209137. ActiveXControlComponent* const owner;
  209138. bool wasShowing;
  209139. public:
  209140. HWND controlHWND;
  209141. IStorage* storage;
  209142. IOleClientSite* clientSite;
  209143. IOleObject* control;
  209144. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  209145. : ComponentMovementWatcher (owner_),
  209146. owner (owner_),
  209147. wasShowing (owner_ != 0 && owner_->isShowing()),
  209148. controlHWND (0),
  209149. storage (new ActiveXHelpers::JuceIStorage()),
  209150. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209151. control (0)
  209152. {
  209153. }
  209154. ~Pimpl()
  209155. {
  209156. if (control != 0)
  209157. {
  209158. control->Close (OLECLOSE_NOSAVE);
  209159. control->Release();
  209160. }
  209161. clientSite->Release();
  209162. storage->Release();
  209163. }
  209164. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209165. {
  209166. Component* const topComp = owner->getTopLevelComponent();
  209167. if (topComp->getPeer() != 0)
  209168. {
  209169. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  209170. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  209171. }
  209172. }
  209173. void componentPeerChanged()
  209174. {
  209175. const bool isShowingNow = owner->isShowing();
  209176. if (wasShowing != isShowingNow)
  209177. {
  209178. wasShowing = isShowingNow;
  209179. owner->setControlVisible (isShowingNow);
  209180. }
  209181. componentMovedOrResized (true, true);
  209182. }
  209183. void componentVisibilityChanged (Component&)
  209184. {
  209185. componentPeerChanged();
  209186. }
  209187. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209188. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209189. {
  209190. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209191. {
  209192. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209193. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209194. {
  209195. switch (message)
  209196. {
  209197. case WM_MOUSEMOVE:
  209198. case WM_LBUTTONDOWN:
  209199. case WM_MBUTTONDOWN:
  209200. case WM_RBUTTONDOWN:
  209201. case WM_LBUTTONUP:
  209202. case WM_MBUTTONUP:
  209203. case WM_RBUTTONUP:
  209204. case WM_LBUTTONDBLCLK:
  209205. case WM_MBUTTONDBLCLK:
  209206. case WM_RBUTTONDBLCLK:
  209207. if (ax->isShowing())
  209208. {
  209209. ComponentPeer* const peer = ax->getPeer();
  209210. if (peer != 0)
  209211. {
  209212. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209213. if (! ax->areMouseEventsAllowed())
  209214. return 0;
  209215. }
  209216. }
  209217. break;
  209218. default:
  209219. break;
  209220. }
  209221. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209222. }
  209223. }
  209224. return DefWindowProc (hwnd, message, wParam, lParam);
  209225. }
  209226. };
  209227. ActiveXControlComponent::ActiveXControlComponent()
  209228. : originalWndProc (0),
  209229. mouseEventsAllowed (true)
  209230. {
  209231. ActiveXHelpers::activeXComps.add (this);
  209232. }
  209233. ActiveXControlComponent::~ActiveXControlComponent()
  209234. {
  209235. deleteControl();
  209236. ActiveXHelpers::activeXComps.removeValue (this);
  209237. }
  209238. void ActiveXControlComponent::paint (Graphics& g)
  209239. {
  209240. if (control == 0)
  209241. g.fillAll (Colours::lightgrey);
  209242. }
  209243. bool ActiveXControlComponent::createControl (const void* controlIID)
  209244. {
  209245. deleteControl();
  209246. ComponentPeer* const peer = getPeer();
  209247. // the component must have already been added to a real window when you call this!
  209248. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209249. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209250. {
  209251. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209252. HWND hwnd = (HWND) peer->getNativeHandle();
  209253. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  209254. HRESULT hr;
  209255. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209256. newControl->clientSite, newControl->storage,
  209257. (void**) &(newControl->control))) == S_OK)
  209258. {
  209259. newControl->control->SetHostNames (L"Juce", 0);
  209260. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209261. {
  209262. RECT rect;
  209263. rect.left = pos.getX();
  209264. rect.top = pos.getY();
  209265. rect.right = pos.getX() + getWidth();
  209266. rect.bottom = pos.getY() + getHeight();
  209267. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209268. {
  209269. control = newControl;
  209270. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209271. control->controlHWND = ActiveXHelpers::getHWND (this);
  209272. if (control->controlHWND != 0)
  209273. {
  209274. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209275. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209276. }
  209277. return true;
  209278. }
  209279. }
  209280. }
  209281. }
  209282. return false;
  209283. }
  209284. void ActiveXControlComponent::deleteControl()
  209285. {
  209286. control = 0;
  209287. originalWndProc = 0;
  209288. }
  209289. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209290. {
  209291. void* result = 0;
  209292. if (control != 0 && control->control != 0
  209293. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209294. return result;
  209295. return 0;
  209296. }
  209297. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209298. {
  209299. if (control->controlHWND != 0)
  209300. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209301. }
  209302. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209303. {
  209304. if (control->controlHWND != 0)
  209305. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209306. }
  209307. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209308. {
  209309. mouseEventsAllowed = eventsCanReachControl;
  209310. }
  209311. #endif
  209312. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209313. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209314. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209315. // compiled on its own).
  209316. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209317. using namespace QTOLibrary;
  209318. using namespace QTOControlLib;
  209319. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209320. static bool isQTAvailable = false;
  209321. class QuickTimeMovieComponent::Pimpl
  209322. {
  209323. public:
  209324. Pimpl() : dataHandle (0)
  209325. {
  209326. }
  209327. ~Pimpl()
  209328. {
  209329. clearHandle();
  209330. }
  209331. void clearHandle()
  209332. {
  209333. if (dataHandle != 0)
  209334. {
  209335. DisposeHandle (dataHandle);
  209336. dataHandle = 0;
  209337. }
  209338. }
  209339. IQTControlPtr qtControl;
  209340. IQTMoviePtr qtMovie;
  209341. Handle dataHandle;
  209342. };
  209343. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209344. : movieLoaded (false),
  209345. controllerVisible (true)
  209346. {
  209347. pimpl = new Pimpl();
  209348. setMouseEventsAllowed (false);
  209349. }
  209350. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209351. {
  209352. closeMovie();
  209353. pimpl->qtControl = 0;
  209354. deleteControl();
  209355. pimpl = 0;
  209356. }
  209357. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209358. {
  209359. if (! isQTAvailable)
  209360. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209361. return isQTAvailable;
  209362. }
  209363. void QuickTimeMovieComponent::createControlIfNeeded()
  209364. {
  209365. if (isShowing() && ! isControlCreated())
  209366. {
  209367. const IID qtIID = __uuidof (QTControl);
  209368. if (createControl (&qtIID))
  209369. {
  209370. const IID qtInterfaceIID = __uuidof (IQTControl);
  209371. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209372. if (pimpl->qtControl != 0)
  209373. {
  209374. pimpl->qtControl->Release(); // it has one ref too many at this point
  209375. pimpl->qtControl->QuickTimeInitialize();
  209376. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209377. if (movieFile != File::nonexistent)
  209378. loadMovie (movieFile, controllerVisible);
  209379. }
  209380. }
  209381. }
  209382. }
  209383. bool QuickTimeMovieComponent::isControlCreated() const
  209384. {
  209385. return isControlOpen();
  209386. }
  209387. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209388. const bool isControllerVisible)
  209389. {
  209390. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209391. movieFile = File::nonexistent;
  209392. movieLoaded = false;
  209393. pimpl->qtMovie = 0;
  209394. controllerVisible = isControllerVisible;
  209395. createControlIfNeeded();
  209396. if (isControlCreated())
  209397. {
  209398. if (pimpl->qtControl != 0)
  209399. {
  209400. pimpl->qtControl->Put_MovieHandle (0);
  209401. pimpl->clearHandle();
  209402. Movie movie;
  209403. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209404. {
  209405. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209406. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209407. if (pimpl->qtMovie != 0)
  209408. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209409. : qtMovieControllerTypeNone);
  209410. }
  209411. if (movie == 0)
  209412. pimpl->clearHandle();
  209413. }
  209414. movieLoaded = (pimpl->qtMovie != 0);
  209415. }
  209416. else
  209417. {
  209418. // You're trying to open a movie when the control hasn't yet been created, probably because
  209419. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209420. jassertfalse;
  209421. }
  209422. return movieLoaded;
  209423. }
  209424. void QuickTimeMovieComponent::closeMovie()
  209425. {
  209426. stop();
  209427. movieFile = File::nonexistent;
  209428. movieLoaded = false;
  209429. pimpl->qtMovie = 0;
  209430. if (pimpl->qtControl != 0)
  209431. pimpl->qtControl->Put_MovieHandle (0);
  209432. pimpl->clearHandle();
  209433. }
  209434. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209435. {
  209436. return movieFile;
  209437. }
  209438. bool QuickTimeMovieComponent::isMovieOpen() const
  209439. {
  209440. return movieLoaded;
  209441. }
  209442. double QuickTimeMovieComponent::getMovieDuration() const
  209443. {
  209444. if (pimpl->qtMovie != 0)
  209445. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209446. return 0.0;
  209447. }
  209448. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209449. {
  209450. if (pimpl->qtMovie != 0)
  209451. {
  209452. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209453. width = r.right - r.left;
  209454. height = r.bottom - r.top;
  209455. }
  209456. else
  209457. {
  209458. width = height = 0;
  209459. }
  209460. }
  209461. void QuickTimeMovieComponent::play()
  209462. {
  209463. if (pimpl->qtMovie != 0)
  209464. pimpl->qtMovie->Play();
  209465. }
  209466. void QuickTimeMovieComponent::stop()
  209467. {
  209468. if (pimpl->qtMovie != 0)
  209469. pimpl->qtMovie->Stop();
  209470. }
  209471. bool QuickTimeMovieComponent::isPlaying() const
  209472. {
  209473. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209474. }
  209475. void QuickTimeMovieComponent::setPosition (const double seconds)
  209476. {
  209477. if (pimpl->qtMovie != 0)
  209478. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209479. }
  209480. double QuickTimeMovieComponent::getPosition() const
  209481. {
  209482. if (pimpl->qtMovie != 0)
  209483. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209484. return 0.0;
  209485. }
  209486. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209487. {
  209488. if (pimpl->qtMovie != 0)
  209489. pimpl->qtMovie->PutRate (newSpeed);
  209490. }
  209491. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209492. {
  209493. if (pimpl->qtMovie != 0)
  209494. {
  209495. pimpl->qtMovie->PutAudioVolume (newVolume);
  209496. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209497. }
  209498. }
  209499. float QuickTimeMovieComponent::getMovieVolume() const
  209500. {
  209501. if (pimpl->qtMovie != 0)
  209502. return pimpl->qtMovie->GetAudioVolume();
  209503. return 0.0f;
  209504. }
  209505. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209506. {
  209507. if (pimpl->qtMovie != 0)
  209508. pimpl->qtMovie->PutLoop (shouldLoop);
  209509. }
  209510. bool QuickTimeMovieComponent::isLooping() const
  209511. {
  209512. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209513. }
  209514. bool QuickTimeMovieComponent::isControllerVisible() const
  209515. {
  209516. return controllerVisible;
  209517. }
  209518. void QuickTimeMovieComponent::parentHierarchyChanged()
  209519. {
  209520. createControlIfNeeded();
  209521. QTCompBaseClass::parentHierarchyChanged();
  209522. }
  209523. void QuickTimeMovieComponent::visibilityChanged()
  209524. {
  209525. createControlIfNeeded();
  209526. QTCompBaseClass::visibilityChanged();
  209527. }
  209528. void QuickTimeMovieComponent::paint (Graphics& g)
  209529. {
  209530. if (! isControlCreated())
  209531. g.fillAll (Colours::black);
  209532. }
  209533. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209534. {
  209535. Handle dataRef = 0;
  209536. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209537. if (err == noErr)
  209538. {
  209539. Str255 suffix;
  209540. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209541. StringPtr name = suffix;
  209542. err = PtrAndHand (name, dataRef, name[0] + 1);
  209543. if (err == noErr)
  209544. {
  209545. long atoms[3];
  209546. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209547. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209548. atoms[2] = EndianU32_NtoB (MovieFileType);
  209549. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209550. if (err == noErr)
  209551. return dataRef;
  209552. }
  209553. DisposeHandle (dataRef);
  209554. }
  209555. return 0;
  209556. }
  209557. static CFStringRef juceStringToCFString (const String& s)
  209558. {
  209559. const int len = s.length();
  209560. const juce_wchar* const t = s;
  209561. HeapBlock <UniChar> temp (len + 2);
  209562. for (int i = 0; i <= len; ++i)
  209563. temp[i] = t[i];
  209564. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209565. }
  209566. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209567. {
  209568. Boolean trueBool = true;
  209569. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209570. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209571. props[prop].propValueSize = sizeof (trueBool);
  209572. props[prop].propValueAddress = &trueBool;
  209573. ++prop;
  209574. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209575. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209576. props[prop].propValueSize = sizeof (trueBool);
  209577. props[prop].propValueAddress = &trueBool;
  209578. ++prop;
  209579. Boolean isActive = true;
  209580. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209581. props[prop].propID = kQTNewMoviePropertyID_Active;
  209582. props[prop].propValueSize = sizeof (isActive);
  209583. props[prop].propValueAddress = &isActive;
  209584. ++prop;
  209585. MacSetPort (0);
  209586. jassert (prop <= 5);
  209587. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209588. return err == noErr;
  209589. }
  209590. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209591. {
  209592. if (input == 0)
  209593. return false;
  209594. dataHandle = 0;
  209595. bool ok = false;
  209596. QTNewMoviePropertyElement props[5];
  209597. zeromem (props, sizeof (props));
  209598. int prop = 0;
  209599. DataReferenceRecord dr;
  209600. props[prop].propClass = kQTPropertyClass_DataLocation;
  209601. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209602. props[prop].propValueSize = sizeof (dr);
  209603. props[prop].propValueAddress = &dr;
  209604. ++prop;
  209605. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209606. if (fin != 0)
  209607. {
  209608. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209609. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209610. &dr.dataRef, &dr.dataRefType);
  209611. ok = openMovie (props, prop, movie);
  209612. DisposeHandle (dr.dataRef);
  209613. CFRelease (filePath);
  209614. }
  209615. else
  209616. {
  209617. // sanity-check because this currently needs to load the whole stream into memory..
  209618. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209619. dataHandle = NewHandle ((Size) input->getTotalLength());
  209620. HLock (dataHandle);
  209621. // read the entire stream into memory - this is a pain, but can't get it to work
  209622. // properly using a custom callback to supply the data.
  209623. input->read (*dataHandle, (int) input->getTotalLength());
  209624. HUnlock (dataHandle);
  209625. // different types to get QT to try. (We should really be a bit smarter here by
  209626. // working out in advance which one the stream contains, rather than just trying
  209627. // each one)
  209628. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209629. "\04.avi", "\04.m4a" };
  209630. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209631. {
  209632. /* // this fails for some bizarre reason - it can be bodged to work with
  209633. // movies, but can't seem to do it for other file types..
  209634. QTNewMovieUserProcRecord procInfo;
  209635. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209636. procInfo.getMovieUserProcRefcon = this;
  209637. procInfo.defaultDataRef.dataRef = dataRef;
  209638. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209639. props[prop].propClass = kQTPropertyClass_DataLocation;
  209640. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209641. props[prop].propValueSize = sizeof (procInfo);
  209642. props[prop].propValueAddress = (void*) &procInfo;
  209643. ++prop; */
  209644. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209645. dr.dataRefType = HandleDataHandlerSubType;
  209646. ok = openMovie (props, prop, movie);
  209647. DisposeHandle (dr.dataRef);
  209648. }
  209649. }
  209650. return ok;
  209651. }
  209652. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209653. const bool isControllerVisible)
  209654. {
  209655. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209656. movieFile = movieFile_;
  209657. return ok;
  209658. }
  209659. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209660. const bool isControllerVisible)
  209661. {
  209662. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209663. }
  209664. void QuickTimeMovieComponent::goToStart()
  209665. {
  209666. setPosition (0.0);
  209667. }
  209668. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209669. const RectanglePlacement& placement)
  209670. {
  209671. int normalWidth, normalHeight;
  209672. getMovieNormalSize (normalWidth, normalHeight);
  209673. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209674. {
  209675. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209676. placement.applyTo (x, y, w, h,
  209677. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209678. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209679. if (w > 0 && h > 0)
  209680. {
  209681. setBounds (roundToInt (x), roundToInt (y),
  209682. roundToInt (w), roundToInt (h));
  209683. }
  209684. }
  209685. else
  209686. {
  209687. setBounds (spaceToFitWithin);
  209688. }
  209689. }
  209690. #endif
  209691. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209692. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209693. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209694. // compiled on its own).
  209695. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209696. class WebBrowserComponentInternal : public ActiveXControlComponent
  209697. {
  209698. public:
  209699. WebBrowserComponentInternal()
  209700. : browser (0),
  209701. connectionPoint (0),
  209702. adviseCookie (0)
  209703. {
  209704. }
  209705. ~WebBrowserComponentInternal()
  209706. {
  209707. if (connectionPoint != 0)
  209708. connectionPoint->Unadvise (adviseCookie);
  209709. if (browser != 0)
  209710. browser->Release();
  209711. }
  209712. void createBrowser()
  209713. {
  209714. createControl (&CLSID_WebBrowser);
  209715. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209716. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209717. if (connectionPointContainer != 0)
  209718. {
  209719. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209720. &connectionPoint);
  209721. if (connectionPoint != 0)
  209722. {
  209723. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209724. jassert (owner != 0);
  209725. EventHandler* handler = new EventHandler (owner);
  209726. connectionPoint->Advise (handler, &adviseCookie);
  209727. handler->Release();
  209728. }
  209729. }
  209730. }
  209731. void goToURL (const String& url,
  209732. const StringArray* headers,
  209733. const MemoryBlock* postData)
  209734. {
  209735. if (browser != 0)
  209736. {
  209737. LPSAFEARRAY sa = 0;
  209738. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209739. VariantInit (&flags);
  209740. VariantInit (&frame);
  209741. VariantInit (&postDataVar);
  209742. VariantInit (&headersVar);
  209743. if (headers != 0)
  209744. {
  209745. V_VT (&headersVar) = VT_BSTR;
  209746. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209747. }
  209748. if (postData != 0 && postData->getSize() > 0)
  209749. {
  209750. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209751. if (sa != 0)
  209752. {
  209753. void* data = 0;
  209754. SafeArrayAccessData (sa, &data);
  209755. jassert (data != 0);
  209756. if (data != 0)
  209757. {
  209758. postData->copyTo (data, 0, postData->getSize());
  209759. SafeArrayUnaccessData (sa);
  209760. VARIANT postDataVar2;
  209761. VariantInit (&postDataVar2);
  209762. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209763. V_ARRAY (&postDataVar2) = sa;
  209764. postDataVar = postDataVar2;
  209765. }
  209766. }
  209767. }
  209768. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209769. &flags, &frame,
  209770. &postDataVar, &headersVar);
  209771. if (sa != 0)
  209772. SafeArrayDestroy (sa);
  209773. VariantClear (&flags);
  209774. VariantClear (&frame);
  209775. VariantClear (&postDataVar);
  209776. VariantClear (&headersVar);
  209777. }
  209778. }
  209779. IWebBrowser2* browser;
  209780. juce_UseDebuggingNewOperator
  209781. private:
  209782. IConnectionPoint* connectionPoint;
  209783. DWORD adviseCookie;
  209784. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209785. public ComponentMovementWatcher
  209786. {
  209787. public:
  209788. EventHandler (WebBrowserComponent* owner_)
  209789. : ComponentMovementWatcher (owner_),
  209790. owner (owner_)
  209791. {
  209792. }
  209793. ~EventHandler()
  209794. {
  209795. }
  209796. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209797. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209798. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209799. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209800. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209801. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209802. UINT __RPC_FAR* /*puArgErr*/)
  209803. {
  209804. switch (dispIdMember)
  209805. {
  209806. case DISPID_BEFORENAVIGATE2:
  209807. {
  209808. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209809. String url;
  209810. if ((vurl->vt & VT_BYREF) != 0)
  209811. url = *vurl->pbstrVal;
  209812. else
  209813. url = vurl->bstrVal;
  209814. *pDispParams->rgvarg->pboolVal
  209815. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209816. : VARIANT_TRUE;
  209817. return S_OK;
  209818. }
  209819. default:
  209820. break;
  209821. }
  209822. return E_NOTIMPL;
  209823. }
  209824. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209825. void componentPeerChanged() {}
  209826. void componentVisibilityChanged (Component&)
  209827. {
  209828. owner->visibilityChanged();
  209829. }
  209830. juce_UseDebuggingNewOperator
  209831. private:
  209832. WebBrowserComponent* const owner;
  209833. EventHandler (const EventHandler&);
  209834. EventHandler& operator= (const EventHandler&);
  209835. };
  209836. };
  209837. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209838. : browser (0),
  209839. blankPageShown (false),
  209840. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209841. {
  209842. setOpaque (true);
  209843. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209844. }
  209845. WebBrowserComponent::~WebBrowserComponent()
  209846. {
  209847. delete browser;
  209848. }
  209849. void WebBrowserComponent::goToURL (const String& url,
  209850. const StringArray* headers,
  209851. const MemoryBlock* postData)
  209852. {
  209853. lastURL = url;
  209854. lastHeaders.clear();
  209855. if (headers != 0)
  209856. lastHeaders = *headers;
  209857. lastPostData.setSize (0);
  209858. if (postData != 0)
  209859. lastPostData = *postData;
  209860. blankPageShown = false;
  209861. browser->goToURL (url, headers, postData);
  209862. }
  209863. void WebBrowserComponent::stop()
  209864. {
  209865. if (browser->browser != 0)
  209866. browser->browser->Stop();
  209867. }
  209868. void WebBrowserComponent::goBack()
  209869. {
  209870. lastURL = String::empty;
  209871. blankPageShown = false;
  209872. if (browser->browser != 0)
  209873. browser->browser->GoBack();
  209874. }
  209875. void WebBrowserComponent::goForward()
  209876. {
  209877. lastURL = String::empty;
  209878. if (browser->browser != 0)
  209879. browser->browser->GoForward();
  209880. }
  209881. void WebBrowserComponent::refresh()
  209882. {
  209883. if (browser->browser != 0)
  209884. browser->browser->Refresh();
  209885. }
  209886. void WebBrowserComponent::paint (Graphics& g)
  209887. {
  209888. if (browser->browser == 0)
  209889. g.fillAll (Colours::white);
  209890. }
  209891. void WebBrowserComponent::checkWindowAssociation()
  209892. {
  209893. if (isShowing())
  209894. {
  209895. if (browser->browser == 0 && getPeer() != 0)
  209896. {
  209897. browser->createBrowser();
  209898. reloadLastURL();
  209899. }
  209900. else
  209901. {
  209902. if (blankPageShown)
  209903. goBack();
  209904. }
  209905. }
  209906. else
  209907. {
  209908. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209909. {
  209910. // when the component becomes invisible, some stuff like flash
  209911. // carries on playing audio, so we need to force it onto a blank
  209912. // page to avoid this..
  209913. blankPageShown = true;
  209914. browser->goToURL ("about:blank", 0, 0);
  209915. }
  209916. }
  209917. }
  209918. void WebBrowserComponent::reloadLastURL()
  209919. {
  209920. if (lastURL.isNotEmpty())
  209921. {
  209922. goToURL (lastURL, &lastHeaders, &lastPostData);
  209923. lastURL = String::empty;
  209924. }
  209925. }
  209926. void WebBrowserComponent::parentHierarchyChanged()
  209927. {
  209928. checkWindowAssociation();
  209929. }
  209930. void WebBrowserComponent::resized()
  209931. {
  209932. browser->setSize (getWidth(), getHeight());
  209933. }
  209934. void WebBrowserComponent::visibilityChanged()
  209935. {
  209936. checkWindowAssociation();
  209937. }
  209938. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209939. {
  209940. return true;
  209941. }
  209942. #endif
  209943. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209944. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209945. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209946. // compiled on its own).
  209947. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209948. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209949. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209950. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209951. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209952. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209953. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209954. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209955. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209956. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209957. #define WGL_ACCELERATION_ARB 0x2003
  209958. #define WGL_SWAP_METHOD_ARB 0x2007
  209959. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209960. #define WGL_PIXEL_TYPE_ARB 0x2013
  209961. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209962. #define WGL_COLOR_BITS_ARB 0x2014
  209963. #define WGL_RED_BITS_ARB 0x2015
  209964. #define WGL_GREEN_BITS_ARB 0x2017
  209965. #define WGL_BLUE_BITS_ARB 0x2019
  209966. #define WGL_ALPHA_BITS_ARB 0x201B
  209967. #define WGL_DEPTH_BITS_ARB 0x2022
  209968. #define WGL_STENCIL_BITS_ARB 0x2023
  209969. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209970. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209971. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209972. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209973. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209974. #define WGL_STEREO_ARB 0x2012
  209975. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209976. #define WGL_SAMPLES_ARB 0x2042
  209977. #define WGL_TYPE_RGBA_ARB 0x202B
  209978. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209979. {
  209980. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209981. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209982. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209983. else
  209984. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209985. }
  209986. class WindowedGLContext : public OpenGLContext
  209987. {
  209988. public:
  209989. WindowedGLContext (Component* const component_,
  209990. HGLRC contextToShareWith,
  209991. const OpenGLPixelFormat& pixelFormat)
  209992. : renderContext (0),
  209993. dc (0),
  209994. component (component_)
  209995. {
  209996. jassert (component != 0);
  209997. createNativeWindow();
  209998. // Use a default pixel format that should be supported everywhere
  209999. PIXELFORMATDESCRIPTOR pfd;
  210000. zerostruct (pfd);
  210001. pfd.nSize = sizeof (pfd);
  210002. pfd.nVersion = 1;
  210003. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210004. pfd.iPixelType = PFD_TYPE_RGBA;
  210005. pfd.cColorBits = 24;
  210006. pfd.cDepthBits = 16;
  210007. const int format = ChoosePixelFormat (dc, &pfd);
  210008. if (format != 0)
  210009. SetPixelFormat (dc, format, &pfd);
  210010. renderContext = wglCreateContext (dc);
  210011. makeActive();
  210012. setPixelFormat (pixelFormat);
  210013. if (contextToShareWith != 0 && renderContext != 0)
  210014. wglShareLists (contextToShareWith, renderContext);
  210015. }
  210016. ~WindowedGLContext()
  210017. {
  210018. deleteContext();
  210019. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210020. nativeWindow = 0;
  210021. }
  210022. void deleteContext()
  210023. {
  210024. makeInactive();
  210025. if (renderContext != 0)
  210026. {
  210027. wglDeleteContext (renderContext);
  210028. renderContext = 0;
  210029. }
  210030. }
  210031. bool makeActive() const throw()
  210032. {
  210033. jassert (renderContext != 0);
  210034. return wglMakeCurrent (dc, renderContext) != 0;
  210035. }
  210036. bool makeInactive() const throw()
  210037. {
  210038. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210039. }
  210040. bool isActive() const throw()
  210041. {
  210042. return wglGetCurrentContext() == renderContext;
  210043. }
  210044. const OpenGLPixelFormat getPixelFormat() const
  210045. {
  210046. OpenGLPixelFormat pf;
  210047. makeActive();
  210048. StringArray availableExtensions;
  210049. getWglExtensions (dc, availableExtensions);
  210050. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210051. return pf;
  210052. }
  210053. void* getRawContext() const throw()
  210054. {
  210055. return renderContext;
  210056. }
  210057. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210058. {
  210059. makeActive();
  210060. PIXELFORMATDESCRIPTOR pfd;
  210061. zerostruct (pfd);
  210062. pfd.nSize = sizeof (pfd);
  210063. pfd.nVersion = 1;
  210064. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210065. pfd.iPixelType = PFD_TYPE_RGBA;
  210066. pfd.iLayerType = PFD_MAIN_PLANE;
  210067. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210068. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210069. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210070. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210071. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210072. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210073. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210074. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210075. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210076. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210077. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210078. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210079. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210080. int format = 0;
  210081. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210082. StringArray availableExtensions;
  210083. getWglExtensions (dc, availableExtensions);
  210084. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210085. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210086. {
  210087. int attributes[64];
  210088. int n = 0;
  210089. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210090. attributes[n++] = GL_TRUE;
  210091. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210092. attributes[n++] = GL_TRUE;
  210093. attributes[n++] = WGL_ACCELERATION_ARB;
  210094. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210095. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210096. attributes[n++] = GL_TRUE;
  210097. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210098. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210099. attributes[n++] = WGL_COLOR_BITS_ARB;
  210100. attributes[n++] = pfd.cColorBits;
  210101. attributes[n++] = WGL_RED_BITS_ARB;
  210102. attributes[n++] = pixelFormat.redBits;
  210103. attributes[n++] = WGL_GREEN_BITS_ARB;
  210104. attributes[n++] = pixelFormat.greenBits;
  210105. attributes[n++] = WGL_BLUE_BITS_ARB;
  210106. attributes[n++] = pixelFormat.blueBits;
  210107. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210108. attributes[n++] = pixelFormat.alphaBits;
  210109. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210110. attributes[n++] = pixelFormat.depthBufferBits;
  210111. if (pixelFormat.stencilBufferBits > 0)
  210112. {
  210113. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210114. attributes[n++] = pixelFormat.stencilBufferBits;
  210115. }
  210116. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210117. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210118. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210119. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210120. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210121. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210122. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210123. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210124. if (availableExtensions.contains ("WGL_ARB_multisample")
  210125. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210126. {
  210127. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210128. attributes[n++] = 1;
  210129. attributes[n++] = WGL_SAMPLES_ARB;
  210130. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210131. }
  210132. attributes[n++] = 0;
  210133. UINT formatsCount;
  210134. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210135. (void) ok;
  210136. jassert (ok);
  210137. }
  210138. else
  210139. {
  210140. format = ChoosePixelFormat (dc, &pfd);
  210141. }
  210142. if (format != 0)
  210143. {
  210144. makeInactive();
  210145. // win32 can't change the pixel format of a window, so need to delete the
  210146. // old one and create a new one..
  210147. jassert (nativeWindow != 0);
  210148. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210149. nativeWindow = 0;
  210150. createNativeWindow();
  210151. if (SetPixelFormat (dc, format, &pfd))
  210152. {
  210153. wglDeleteContext (renderContext);
  210154. renderContext = wglCreateContext (dc);
  210155. jassert (renderContext != 0);
  210156. return renderContext != 0;
  210157. }
  210158. }
  210159. return false;
  210160. }
  210161. void updateWindowPosition (int x, int y, int w, int h, int)
  210162. {
  210163. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210164. x, y, w, h,
  210165. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210166. }
  210167. void repaint()
  210168. {
  210169. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210170. }
  210171. void swapBuffers()
  210172. {
  210173. SwapBuffers (dc);
  210174. }
  210175. bool setSwapInterval (int numFramesPerSwap)
  210176. {
  210177. makeActive();
  210178. StringArray availableExtensions;
  210179. getWglExtensions (dc, availableExtensions);
  210180. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210181. return availableExtensions.contains ("WGL_EXT_swap_control")
  210182. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210183. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210184. }
  210185. int getSwapInterval() const
  210186. {
  210187. makeActive();
  210188. StringArray availableExtensions;
  210189. getWglExtensions (dc, availableExtensions);
  210190. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210191. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210192. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210193. return wglGetSwapIntervalEXT();
  210194. return 0;
  210195. }
  210196. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210197. {
  210198. jassert (isActive());
  210199. StringArray availableExtensions;
  210200. getWglExtensions (dc, availableExtensions);
  210201. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210202. int numTypes = 0;
  210203. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210204. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210205. {
  210206. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210207. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210208. jassertfalse;
  210209. }
  210210. else
  210211. {
  210212. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210213. }
  210214. OpenGLPixelFormat pf;
  210215. for (int i = 0; i < numTypes; ++i)
  210216. {
  210217. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210218. {
  210219. bool alreadyListed = false;
  210220. for (int j = results.size(); --j >= 0;)
  210221. if (pf == *results.getUnchecked(j))
  210222. alreadyListed = true;
  210223. if (! alreadyListed)
  210224. results.add (new OpenGLPixelFormat (pf));
  210225. }
  210226. }
  210227. }
  210228. void* getNativeWindowHandle() const
  210229. {
  210230. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210231. }
  210232. juce_UseDebuggingNewOperator
  210233. HGLRC renderContext;
  210234. private:
  210235. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210236. Component* const component;
  210237. HDC dc;
  210238. void createNativeWindow()
  210239. {
  210240. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210241. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210242. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210243. nativeWindow->dontRepaint = true;
  210244. nativeWindow->setVisible (true);
  210245. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210246. }
  210247. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210248. OpenGLPixelFormat& result,
  210249. const StringArray& availableExtensions) const throw()
  210250. {
  210251. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210252. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210253. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210254. {
  210255. int attributes[32];
  210256. int numAttributes = 0;
  210257. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210258. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210259. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210260. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210261. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210262. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210263. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210264. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210265. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210266. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210267. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210268. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210269. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210270. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210271. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210272. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210273. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210274. int values[32];
  210275. zeromem (values, sizeof (values));
  210276. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210277. {
  210278. int n = 0;
  210279. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210280. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210281. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210282. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210283. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210284. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210285. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210286. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210287. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210288. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210289. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210290. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210291. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210292. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210293. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210294. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210295. return isValidFormat;
  210296. }
  210297. else
  210298. {
  210299. jassertfalse;
  210300. }
  210301. }
  210302. else
  210303. {
  210304. PIXELFORMATDESCRIPTOR pfd;
  210305. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210306. {
  210307. result.redBits = pfd.cRedBits;
  210308. result.greenBits = pfd.cGreenBits;
  210309. result.blueBits = pfd.cBlueBits;
  210310. result.alphaBits = pfd.cAlphaBits;
  210311. result.depthBufferBits = pfd.cDepthBits;
  210312. result.stencilBufferBits = pfd.cStencilBits;
  210313. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210314. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210315. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210316. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210317. result.fullSceneAntiAliasingNumSamples = 0;
  210318. return true;
  210319. }
  210320. else
  210321. {
  210322. jassertfalse;
  210323. }
  210324. }
  210325. return false;
  210326. }
  210327. WindowedGLContext (const WindowedGLContext&);
  210328. WindowedGLContext& operator= (const WindowedGLContext&);
  210329. };
  210330. OpenGLContext* OpenGLComponent::createContext()
  210331. {
  210332. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210333. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210334. preferredPixelFormat));
  210335. return (c->renderContext != 0) ? c.release() : 0;
  210336. }
  210337. void* OpenGLComponent::getNativeWindowHandle() const
  210338. {
  210339. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210340. }
  210341. void juce_glViewport (const int w, const int h)
  210342. {
  210343. glViewport (0, 0, w, h);
  210344. }
  210345. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210346. OwnedArray <OpenGLPixelFormat>& results)
  210347. {
  210348. Component tempComp;
  210349. {
  210350. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210351. wc.makeActive();
  210352. wc.findAlternativeOpenGLPixelFormats (results);
  210353. }
  210354. }
  210355. #endif
  210356. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210357. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210358. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210359. // compiled on its own).
  210360. #if JUCE_INCLUDED_FILE
  210361. #if JUCE_USE_CDREADER
  210362. namespace CDReaderHelpers
  210363. {
  210364. //***************************************************************************
  210365. // %%% TARGET STATUS VALUES %%%
  210366. //***************************************************************************
  210367. #define STATUS_GOOD 0x00 // Status Good
  210368. #define STATUS_CHKCOND 0x02 // Check Condition
  210369. #define STATUS_CONDMET 0x04 // Condition Met
  210370. #define STATUS_BUSY 0x08 // Busy
  210371. #define STATUS_INTERM 0x10 // Intermediate
  210372. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210373. #define STATUS_RESCONF 0x18 // Reservation conflict
  210374. #define STATUS_COMTERM 0x22 // Command Terminated
  210375. #define STATUS_QFULL 0x28 // Queue full
  210376. //***************************************************************************
  210377. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210378. //***************************************************************************
  210379. #define MAXLUN 7 // Maximum Logical Unit Id
  210380. #define MAXTARG 7 // Maximum Target Id
  210381. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210382. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210383. //***************************************************************************
  210384. // %%% Commands for all Device Types %%%
  210385. //***************************************************************************
  210386. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210387. #define SCSI_COMPARE 0x39 // Compare (O)
  210388. #define SCSI_COPY 0x18 // Copy (O)
  210389. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210390. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210391. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210392. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210393. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210394. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210395. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210396. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210397. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210398. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210399. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210400. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210401. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210402. //***************************************************************************
  210403. // %%% Commands Unique to Direct Access Devices %%%
  210404. //***************************************************************************
  210405. #define SCSI_COMPARE 0x39 // Compare (O)
  210406. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210407. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210408. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210409. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210410. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210411. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210412. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210413. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210414. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210415. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210416. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210417. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210418. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210419. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210420. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210421. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210422. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210423. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210424. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210425. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210426. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210427. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210428. #define SCSI_VERIFY 0x2F // Verify (O)
  210429. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210430. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210431. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210432. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210433. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210434. //***************************************************************************
  210435. // %%% Commands Unique to Sequential Access Devices %%%
  210436. //***************************************************************************
  210437. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210438. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210439. #define SCSI_LOCATE 0x2B // Locate (O)
  210440. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210441. #define SCSI_READ_POS 0x34 // Read Position (O)
  210442. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210443. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210444. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210445. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210446. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210447. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210448. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210449. //***************************************************************************
  210450. // %%% Commands Unique to Printer Devices %%%
  210451. //***************************************************************************
  210452. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210453. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210454. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210455. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210456. //***************************************************************************
  210457. // %%% Commands Unique to Processor Devices %%%
  210458. //***************************************************************************
  210459. #define SCSI_RECEIVE 0x08 // Receive (O)
  210460. #define SCSI_SEND 0x0A // Send (O)
  210461. //***************************************************************************
  210462. // %%% Commands Unique to Write-Once Devices %%%
  210463. //***************************************************************************
  210464. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210465. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210466. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210467. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210468. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210469. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210470. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210471. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210472. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210473. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210474. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210475. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210476. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210477. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210478. //***************************************************************************
  210479. // %%% Commands Unique to CD-ROM Devices %%%
  210480. //***************************************************************************
  210481. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210482. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210483. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210484. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210485. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210486. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210487. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210488. #define SCSI_READHEADER 0x44 // Read Header (O)
  210489. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210490. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210491. //***************************************************************************
  210492. // %%% Commands Unique to Scanner Devices %%%
  210493. //***************************************************************************
  210494. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210495. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210496. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210497. #define SCSI_SCAN 0x1B // Scan (O)
  210498. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210499. //***************************************************************************
  210500. // %%% Commands Unique to Optical Memory Devices %%%
  210501. //***************************************************************************
  210502. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210503. //***************************************************************************
  210504. // %%% Commands Unique to Medium Changer Devices %%%
  210505. //***************************************************************************
  210506. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210507. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210508. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210509. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210510. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210511. //***************************************************************************
  210512. // %%% Commands Unique to Communication Devices %%%
  210513. //***************************************************************************
  210514. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210515. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210516. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210517. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210518. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210519. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210520. //***************************************************************************
  210521. // %%% Request Sense Data Format %%%
  210522. //***************************************************************************
  210523. typedef struct {
  210524. BYTE ErrorCode; // Error Code (70H or 71H)
  210525. BYTE SegmentNum; // Number of current segment descriptor
  210526. BYTE SenseKey; // Sense Key(See bit definitions too)
  210527. BYTE InfoByte0; // Information MSB
  210528. BYTE InfoByte1; // Information MID
  210529. BYTE InfoByte2; // Information MID
  210530. BYTE InfoByte3; // Information LSB
  210531. BYTE AddSenLen; // Additional Sense Length
  210532. BYTE ComSpecInf0; // Command Specific Information MSB
  210533. BYTE ComSpecInf1; // Command Specific Information MID
  210534. BYTE ComSpecInf2; // Command Specific Information MID
  210535. BYTE ComSpecInf3; // Command Specific Information LSB
  210536. BYTE AddSenseCode; // Additional Sense Code
  210537. BYTE AddSenQual; // Additional Sense Code Qualifier
  210538. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210539. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210540. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210541. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210542. BYTE AddSenseBytes; // Additional Sense Bytes
  210543. } SENSE_DATA_FMT;
  210544. //***************************************************************************
  210545. // %%% REQUEST SENSE ERROR CODE %%%
  210546. //***************************************************************************
  210547. #define SERROR_CURRENT 0x70 // Current Errors
  210548. #define SERROR_DEFERED 0x71 // Deferred Errors
  210549. //***************************************************************************
  210550. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210551. //***************************************************************************
  210552. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210553. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210554. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210555. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210556. //***************************************************************************
  210557. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210558. //***************************************************************************
  210559. #define KEY_NOSENSE 0x00 // No Sense
  210560. #define KEY_RECERROR 0x01 // Recovered Error
  210561. #define KEY_NOTREADY 0x02 // Not Ready
  210562. #define KEY_MEDIUMERR 0x03 // Medium Error
  210563. #define KEY_HARDERROR 0x04 // Hardware Error
  210564. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210565. #define KEY_UNITATT 0x06 // Unit Attention
  210566. #define KEY_DATAPROT 0x07 // Data Protect
  210567. #define KEY_BLANKCHK 0x08 // Blank Check
  210568. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210569. #define KEY_COPYABORT 0x0A // Copy Abort
  210570. #define KEY_EQUAL 0x0C // Equal (Search)
  210571. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210572. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210573. #define KEY_RESERVED 0x0F // Reserved
  210574. //***************************************************************************
  210575. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210576. //***************************************************************************
  210577. #define DTYPE_DASD 0x00 // Disk Device
  210578. #define DTYPE_SEQD 0x01 // Tape Device
  210579. #define DTYPE_PRNT 0x02 // Printer
  210580. #define DTYPE_PROC 0x03 // Processor
  210581. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210582. #define DTYPE_CROM 0x05 // CD-ROM device
  210583. #define DTYPE_SCAN 0x06 // Scanner device
  210584. #define DTYPE_OPTI 0x07 // Optical memory device
  210585. #define DTYPE_JUKE 0x08 // Medium Changer device
  210586. #define DTYPE_COMM 0x09 // Communications device
  210587. #define DTYPE_RESL 0x0A // Reserved (low)
  210588. #define DTYPE_RESH 0x1E // Reserved (high)
  210589. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210590. //***************************************************************************
  210591. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210592. //***************************************************************************
  210593. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210594. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210595. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210596. #define ANSI_RESLO 0x3 // Reserved (low)
  210597. #define ANSI_RESHI 0x7 // Reserved (high)
  210598. typedef struct
  210599. {
  210600. USHORT Length;
  210601. UCHAR ScsiStatus;
  210602. UCHAR PathId;
  210603. UCHAR TargetId;
  210604. UCHAR Lun;
  210605. UCHAR CdbLength;
  210606. UCHAR SenseInfoLength;
  210607. UCHAR DataIn;
  210608. ULONG DataTransferLength;
  210609. ULONG TimeOutValue;
  210610. ULONG DataBufferOffset;
  210611. ULONG SenseInfoOffset;
  210612. UCHAR Cdb[16];
  210613. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210614. typedef struct
  210615. {
  210616. USHORT Length;
  210617. UCHAR ScsiStatus;
  210618. UCHAR PathId;
  210619. UCHAR TargetId;
  210620. UCHAR Lun;
  210621. UCHAR CdbLength;
  210622. UCHAR SenseInfoLength;
  210623. UCHAR DataIn;
  210624. ULONG DataTransferLength;
  210625. ULONG TimeOutValue;
  210626. PVOID DataBuffer;
  210627. ULONG SenseInfoOffset;
  210628. UCHAR Cdb[16];
  210629. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210630. typedef struct
  210631. {
  210632. SCSI_PASS_THROUGH_DIRECT spt;
  210633. ULONG Filler;
  210634. UCHAR ucSenseBuf[32];
  210635. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210636. typedef struct
  210637. {
  210638. ULONG Length;
  210639. UCHAR PortNumber;
  210640. UCHAR PathId;
  210641. UCHAR TargetId;
  210642. UCHAR Lun;
  210643. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210644. #define METHOD_BUFFERED 0
  210645. #define METHOD_IN_DIRECT 1
  210646. #define METHOD_OUT_DIRECT 2
  210647. #define METHOD_NEITHER 3
  210648. #define FILE_ANY_ACCESS 0
  210649. #ifndef FILE_READ_ACCESS
  210650. #define FILE_READ_ACCESS (0x0001)
  210651. #endif
  210652. #ifndef FILE_WRITE_ACCESS
  210653. #define FILE_WRITE_ACCESS (0x0002)
  210654. #endif
  210655. #define IOCTL_SCSI_BASE 0x00000004
  210656. #define SCSI_IOCTL_DATA_OUT 0
  210657. #define SCSI_IOCTL_DATA_IN 1
  210658. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210659. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210660. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210661. )
  210662. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210663. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210664. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210665. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210666. #define SENSE_LEN 14
  210667. #define SRB_DIR_SCSI 0x00
  210668. #define SRB_POSTING 0x01
  210669. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210670. #define SRB_DIR_IN 0x08
  210671. #define SRB_DIR_OUT 0x10
  210672. #define SRB_EVENT_NOTIFY 0x40
  210673. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210674. #define MAX_SRB_TIMEOUT 1080001u
  210675. #define DEFAULT_SRB_TIMEOUT 1080001u
  210676. #define SC_HA_INQUIRY 0x00
  210677. #define SC_GET_DEV_TYPE 0x01
  210678. #define SC_EXEC_SCSI_CMD 0x02
  210679. #define SC_ABORT_SRB 0x03
  210680. #define SC_RESET_DEV 0x04
  210681. #define SC_SET_HA_PARMS 0x05
  210682. #define SC_GET_DISK_INFO 0x06
  210683. #define SC_RESCAN_SCSI_BUS 0x07
  210684. #define SC_GETSET_TIMEOUTS 0x08
  210685. #define SS_PENDING 0x00
  210686. #define SS_COMP 0x01
  210687. #define SS_ABORTED 0x02
  210688. #define SS_ABORT_FAIL 0x03
  210689. #define SS_ERR 0x04
  210690. #define SS_INVALID_CMD 0x80
  210691. #define SS_INVALID_HA 0x81
  210692. #define SS_NO_DEVICE 0x82
  210693. #define SS_INVALID_SRB 0xE0
  210694. #define SS_OLD_MANAGER 0xE1
  210695. #define SS_BUFFER_ALIGN 0xE1
  210696. #define SS_ILLEGAL_MODE 0xE2
  210697. #define SS_NO_ASPI 0xE3
  210698. #define SS_FAILED_INIT 0xE4
  210699. #define SS_ASPI_IS_BUSY 0xE5
  210700. #define SS_BUFFER_TO_BIG 0xE6
  210701. #define SS_BUFFER_TOO_BIG 0xE6
  210702. #define SS_MISMATCHED_COMPONENTS 0xE7
  210703. #define SS_NO_ADAPTERS 0xE8
  210704. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210705. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210706. #define SS_BAD_INSTALL 0xEB
  210707. #define HASTAT_OK 0x00
  210708. #define HASTAT_SEL_TO 0x11
  210709. #define HASTAT_DO_DU 0x12
  210710. #define HASTAT_BUS_FREE 0x13
  210711. #define HASTAT_PHASE_ERR 0x14
  210712. #define HASTAT_TIMEOUT 0x09
  210713. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210714. #define HASTAT_MESSAGE_REJECT 0x0D
  210715. #define HASTAT_BUS_RESET 0x0E
  210716. #define HASTAT_PARITY_ERROR 0x0F
  210717. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210718. #define PACKED
  210719. #pragma pack(1)
  210720. typedef struct
  210721. {
  210722. BYTE SRB_Cmd;
  210723. BYTE SRB_Status;
  210724. BYTE SRB_HaID;
  210725. BYTE SRB_Flags;
  210726. DWORD SRB_Hdr_Rsvd;
  210727. BYTE HA_Count;
  210728. BYTE HA_SCSI_ID;
  210729. BYTE HA_ManagerId[16];
  210730. BYTE HA_Identifier[16];
  210731. BYTE HA_Unique[16];
  210732. WORD HA_Rsvd1;
  210733. BYTE pad[20];
  210734. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210735. typedef struct
  210736. {
  210737. BYTE SRB_Cmd;
  210738. BYTE SRB_Status;
  210739. BYTE SRB_HaID;
  210740. BYTE SRB_Flags;
  210741. DWORD SRB_Hdr_Rsvd;
  210742. BYTE SRB_Target;
  210743. BYTE SRB_Lun;
  210744. BYTE SRB_DeviceType;
  210745. BYTE SRB_Rsvd1;
  210746. BYTE pad[68];
  210747. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210748. typedef struct
  210749. {
  210750. BYTE SRB_Cmd;
  210751. BYTE SRB_Status;
  210752. BYTE SRB_HaID;
  210753. BYTE SRB_Flags;
  210754. DWORD SRB_Hdr_Rsvd;
  210755. BYTE SRB_Target;
  210756. BYTE SRB_Lun;
  210757. WORD SRB_Rsvd1;
  210758. DWORD SRB_BufLen;
  210759. BYTE FAR *SRB_BufPointer;
  210760. BYTE SRB_SenseLen;
  210761. BYTE SRB_CDBLen;
  210762. BYTE SRB_HaStat;
  210763. BYTE SRB_TargStat;
  210764. VOID FAR *SRB_PostProc;
  210765. BYTE SRB_Rsvd2[20];
  210766. BYTE CDBByte[16];
  210767. BYTE SenseArea[SENSE_LEN+2];
  210768. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210769. typedef struct
  210770. {
  210771. BYTE SRB_Cmd;
  210772. BYTE SRB_Status;
  210773. BYTE SRB_HaId;
  210774. BYTE SRB_Flags;
  210775. DWORD SRB_Hdr_Rsvd;
  210776. } PACKED SRB, *PSRB, FAR *LPSRB;
  210777. #pragma pack()
  210778. struct CDDeviceInfo
  210779. {
  210780. char vendor[9];
  210781. char productId[17];
  210782. char rev[5];
  210783. char vendorSpec[21];
  210784. BYTE ha;
  210785. BYTE tgt;
  210786. BYTE lun;
  210787. char scsiDriveLetter; // will be 0 if not using scsi
  210788. };
  210789. class CDReadBuffer
  210790. {
  210791. public:
  210792. int startFrame;
  210793. int numFrames;
  210794. int dataStartOffset;
  210795. int dataLength;
  210796. int bufferSize;
  210797. HeapBlock<BYTE> buffer;
  210798. int index;
  210799. bool wantsIndex;
  210800. CDReadBuffer (const int numberOfFrames)
  210801. : startFrame (0),
  210802. numFrames (0),
  210803. dataStartOffset (0),
  210804. dataLength (0),
  210805. bufferSize (2352 * numberOfFrames),
  210806. buffer (bufferSize),
  210807. index (0),
  210808. wantsIndex (false)
  210809. {
  210810. }
  210811. bool isZero() const throw()
  210812. {
  210813. BYTE* p = buffer + dataStartOffset;
  210814. for (int i = dataLength; --i >= 0;)
  210815. if (*p++ != 0)
  210816. return false;
  210817. return true;
  210818. }
  210819. };
  210820. class CDDeviceHandle;
  210821. class CDController
  210822. {
  210823. public:
  210824. CDController();
  210825. virtual ~CDController();
  210826. virtual bool read (CDReadBuffer* t) = 0;
  210827. virtual void shutDown();
  210828. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210829. int getLastIndex();
  210830. public:
  210831. bool initialised;
  210832. CDDeviceHandle* deviceInfo;
  210833. int framesToCheck, framesOverlap;
  210834. void prepare (SRB_ExecSCSICmd& s);
  210835. void perform (SRB_ExecSCSICmd& s);
  210836. void setPaused (bool paused);
  210837. };
  210838. #pragma pack(1)
  210839. struct TOCTRACK
  210840. {
  210841. BYTE rsvd;
  210842. BYTE ADR;
  210843. BYTE trackNumber;
  210844. BYTE rsvd2;
  210845. BYTE addr[4];
  210846. };
  210847. struct TOC
  210848. {
  210849. WORD tocLen;
  210850. BYTE firstTrack;
  210851. BYTE lastTrack;
  210852. TOCTRACK tracks[100];
  210853. };
  210854. #pragma pack()
  210855. enum
  210856. {
  210857. READTYPE_ANY = 0,
  210858. READTYPE_ATAPI1 = 1,
  210859. READTYPE_ATAPI2 = 2,
  210860. READTYPE_READ6 = 3,
  210861. READTYPE_READ10 = 4,
  210862. READTYPE_READ_D8 = 5,
  210863. READTYPE_READ_D4 = 6,
  210864. READTYPE_READ_D4_1 = 7,
  210865. READTYPE_READ10_2 = 8
  210866. };
  210867. class CDDeviceHandle
  210868. {
  210869. public:
  210870. CDDeviceHandle (const CDDeviceInfo* const device)
  210871. : scsiHandle (0),
  210872. readType (READTYPE_ANY),
  210873. controller (0)
  210874. {
  210875. memcpy (&info, device, sizeof (info));
  210876. }
  210877. ~CDDeviceHandle()
  210878. {
  210879. if (controller != 0)
  210880. {
  210881. controller->shutDown();
  210882. controller = 0;
  210883. }
  210884. if (scsiHandle != 0)
  210885. CloseHandle (scsiHandle);
  210886. }
  210887. bool readTOC (TOC* lpToc);
  210888. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210889. void openDrawer (bool shouldBeOpen);
  210890. CDDeviceInfo info;
  210891. HANDLE scsiHandle;
  210892. BYTE readType;
  210893. private:
  210894. ScopedPointer<CDController> controller;
  210895. bool testController (const int readType,
  210896. CDController* const newController,
  210897. CDReadBuffer* const bufferToUse);
  210898. };
  210899. DWORD (*fGetASPI32SupportInfo)(void);
  210900. DWORD (*fSendASPI32Command)(LPSRB);
  210901. static HINSTANCE winAspiLib = 0;
  210902. static bool usingScsi = false;
  210903. static bool initialised = false;
  210904. static bool InitialiseCDRipper()
  210905. {
  210906. if (! initialised)
  210907. {
  210908. initialised = true;
  210909. OSVERSIONINFO info;
  210910. info.dwOSVersionInfoSize = sizeof (info);
  210911. GetVersionEx (&info);
  210912. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210913. if (! usingScsi)
  210914. {
  210915. fGetASPI32SupportInfo = 0;
  210916. fSendASPI32Command = 0;
  210917. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210918. if (winAspiLib != 0)
  210919. {
  210920. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210921. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210922. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210923. return false;
  210924. }
  210925. else
  210926. {
  210927. usingScsi = true;
  210928. }
  210929. }
  210930. }
  210931. return true;
  210932. }
  210933. static void DeinitialiseCDRipper()
  210934. {
  210935. if (winAspiLib != 0)
  210936. {
  210937. fGetASPI32SupportInfo = 0;
  210938. fSendASPI32Command = 0;
  210939. FreeLibrary (winAspiLib);
  210940. winAspiLib = 0;
  210941. }
  210942. initialised = false;
  210943. }
  210944. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210945. {
  210946. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210947. OSVERSIONINFO info;
  210948. info.dwOSVersionInfoSize = sizeof (info);
  210949. GetVersionEx (&info);
  210950. DWORD flags = GENERIC_READ;
  210951. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210952. flags = GENERIC_READ | GENERIC_WRITE;
  210953. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210954. if (h == INVALID_HANDLE_VALUE)
  210955. {
  210956. flags ^= GENERIC_WRITE;
  210957. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210958. }
  210959. return h;
  210960. }
  210961. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  210962. const char driveLetter,
  210963. HANDLE& deviceHandle,
  210964. const bool retryOnFailure = true)
  210965. {
  210966. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210967. zerostruct (s);
  210968. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210969. s.spt.CdbLength = srb->SRB_CDBLen;
  210970. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210971. ? SCSI_IOCTL_DATA_IN
  210972. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210973. ? SCSI_IOCTL_DATA_OUT
  210974. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210975. s.spt.DataTransferLength = srb->SRB_BufLen;
  210976. s.spt.TimeOutValue = 5;
  210977. s.spt.DataBuffer = srb->SRB_BufPointer;
  210978. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210979. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210980. srb->SRB_Status = SS_ERR;
  210981. srb->SRB_TargStat = 0x0004;
  210982. DWORD bytesReturned = 0;
  210983. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210984. &s, sizeof (s),
  210985. &s, sizeof (s),
  210986. &bytesReturned, 0) != 0)
  210987. {
  210988. srb->SRB_Status = SS_COMP;
  210989. }
  210990. else if (retryOnFailure)
  210991. {
  210992. const DWORD error = GetLastError();
  210993. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210994. {
  210995. if (error != ERROR_INVALID_HANDLE)
  210996. CloseHandle (deviceHandle);
  210997. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  210998. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210999. }
  211000. }
  211001. return srb->SRB_Status;
  211002. }
  211003. // Controller types..
  211004. class ControllerType1 : public CDController
  211005. {
  211006. public:
  211007. ControllerType1() {}
  211008. ~ControllerType1() {}
  211009. bool read (CDReadBuffer* rb)
  211010. {
  211011. if (rb->numFrames * 2352 > rb->bufferSize)
  211012. return false;
  211013. SRB_ExecSCSICmd s;
  211014. prepare (s);
  211015. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211016. s.SRB_BufLen = rb->bufferSize;
  211017. s.SRB_BufPointer = rb->buffer;
  211018. s.SRB_CDBLen = 12;
  211019. s.CDBByte[0] = 0xBE;
  211020. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211021. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211022. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211023. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211024. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211025. perform (s);
  211026. if (s.SRB_Status != SS_COMP)
  211027. return false;
  211028. rb->dataLength = rb->numFrames * 2352;
  211029. rb->dataStartOffset = 0;
  211030. return true;
  211031. }
  211032. };
  211033. class ControllerType2 : public CDController
  211034. {
  211035. public:
  211036. ControllerType2() {}
  211037. ~ControllerType2() {}
  211038. void shutDown()
  211039. {
  211040. if (initialised)
  211041. {
  211042. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211043. SRB_ExecSCSICmd s;
  211044. prepare (s);
  211045. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211046. s.SRB_BufLen = 0x0C;
  211047. s.SRB_BufPointer = bufPointer;
  211048. s.SRB_CDBLen = 6;
  211049. s.CDBByte[0] = 0x15;
  211050. s.CDBByte[4] = 0x0C;
  211051. perform (s);
  211052. }
  211053. }
  211054. bool init()
  211055. {
  211056. SRB_ExecSCSICmd s;
  211057. s.SRB_Status = SS_ERR;
  211058. if (deviceInfo->readType == READTYPE_READ10_2)
  211059. {
  211060. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211061. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211062. for (int i = 0; i < 2; ++i)
  211063. {
  211064. prepare (s);
  211065. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211066. s.SRB_BufLen = 0x14;
  211067. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211068. s.SRB_CDBLen = 6;
  211069. s.CDBByte[0] = 0x15;
  211070. s.CDBByte[1] = 0x10;
  211071. s.CDBByte[4] = 0x14;
  211072. perform (s);
  211073. if (s.SRB_Status != SS_COMP)
  211074. return false;
  211075. }
  211076. }
  211077. else
  211078. {
  211079. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211080. prepare (s);
  211081. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211082. s.SRB_BufLen = 0x0C;
  211083. s.SRB_BufPointer = bufPointer;
  211084. s.SRB_CDBLen = 6;
  211085. s.CDBByte[0] = 0x15;
  211086. s.CDBByte[4] = 0x0C;
  211087. perform (s);
  211088. }
  211089. return s.SRB_Status == SS_COMP;
  211090. }
  211091. bool read (CDReadBuffer* rb)
  211092. {
  211093. if (rb->numFrames * 2352 > rb->bufferSize)
  211094. return false;
  211095. if (!initialised)
  211096. {
  211097. initialised = init();
  211098. if (!initialised)
  211099. return false;
  211100. }
  211101. SRB_ExecSCSICmd s;
  211102. prepare (s);
  211103. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211104. s.SRB_BufLen = rb->bufferSize;
  211105. s.SRB_BufPointer = rb->buffer;
  211106. s.SRB_CDBLen = 10;
  211107. s.CDBByte[0] = 0x28;
  211108. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211109. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211110. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211111. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211112. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211113. perform (s);
  211114. if (s.SRB_Status != SS_COMP)
  211115. return false;
  211116. rb->dataLength = rb->numFrames * 2352;
  211117. rb->dataStartOffset = 0;
  211118. return true;
  211119. }
  211120. };
  211121. class ControllerType3 : public CDController
  211122. {
  211123. public:
  211124. ControllerType3() {}
  211125. ~ControllerType3() {}
  211126. bool read (CDReadBuffer* rb)
  211127. {
  211128. if (rb->numFrames * 2352 > rb->bufferSize)
  211129. return false;
  211130. if (!initialised)
  211131. {
  211132. setPaused (false);
  211133. initialised = true;
  211134. }
  211135. SRB_ExecSCSICmd s;
  211136. prepare (s);
  211137. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211138. s.SRB_BufLen = rb->numFrames * 2352;
  211139. s.SRB_BufPointer = rb->buffer;
  211140. s.SRB_CDBLen = 12;
  211141. s.CDBByte[0] = 0xD8;
  211142. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211143. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211144. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211145. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211146. perform (s);
  211147. if (s.SRB_Status != SS_COMP)
  211148. return false;
  211149. rb->dataLength = rb->numFrames * 2352;
  211150. rb->dataStartOffset = 0;
  211151. return true;
  211152. }
  211153. };
  211154. class ControllerType4 : public CDController
  211155. {
  211156. public:
  211157. ControllerType4() {}
  211158. ~ControllerType4() {}
  211159. bool selectD4Mode()
  211160. {
  211161. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211162. SRB_ExecSCSICmd s;
  211163. prepare (s);
  211164. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211165. s.SRB_CDBLen = 6;
  211166. s.SRB_BufLen = 12;
  211167. s.SRB_BufPointer = bufPointer;
  211168. s.CDBByte[0] = 0x15;
  211169. s.CDBByte[1] = 0x10;
  211170. s.CDBByte[4] = 0x08;
  211171. perform (s);
  211172. return s.SRB_Status == SS_COMP;
  211173. }
  211174. bool read (CDReadBuffer* rb)
  211175. {
  211176. if (rb->numFrames * 2352 > rb->bufferSize)
  211177. return false;
  211178. if (!initialised)
  211179. {
  211180. setPaused (true);
  211181. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211182. selectD4Mode();
  211183. initialised = true;
  211184. }
  211185. SRB_ExecSCSICmd s;
  211186. prepare (s);
  211187. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211188. s.SRB_BufLen = rb->bufferSize;
  211189. s.SRB_BufPointer = rb->buffer;
  211190. s.SRB_CDBLen = 10;
  211191. s.CDBByte[0] = 0xD4;
  211192. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211193. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211194. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211195. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211196. perform (s);
  211197. if (s.SRB_Status != SS_COMP)
  211198. return false;
  211199. rb->dataLength = rb->numFrames * 2352;
  211200. rb->dataStartOffset = 0;
  211201. return true;
  211202. }
  211203. };
  211204. CDController::CDController() : initialised (false)
  211205. {
  211206. }
  211207. CDController::~CDController()
  211208. {
  211209. }
  211210. void CDController::prepare (SRB_ExecSCSICmd& s)
  211211. {
  211212. zerostruct (s);
  211213. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211214. s.SRB_HaID = deviceInfo->info.ha;
  211215. s.SRB_Target = deviceInfo->info.tgt;
  211216. s.SRB_Lun = deviceInfo->info.lun;
  211217. s.SRB_SenseLen = SENSE_LEN;
  211218. }
  211219. void CDController::perform (SRB_ExecSCSICmd& s)
  211220. {
  211221. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211222. s.SRB_PostProc = event;
  211223. ResetEvent (event);
  211224. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211225. deviceInfo->info.scsiDriveLetter,
  211226. deviceInfo->scsiHandle)
  211227. : fSendASPI32Command ((LPSRB)&s);
  211228. if (status == SS_PENDING)
  211229. WaitForSingleObject (event, 4000);
  211230. CloseHandle (event);
  211231. }
  211232. void CDController::setPaused (bool paused)
  211233. {
  211234. SRB_ExecSCSICmd s;
  211235. prepare (s);
  211236. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211237. s.SRB_CDBLen = 10;
  211238. s.CDBByte[0] = 0x4B;
  211239. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211240. perform (s);
  211241. }
  211242. void CDController::shutDown()
  211243. {
  211244. }
  211245. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211246. {
  211247. if (overlapBuffer != 0)
  211248. {
  211249. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211250. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211251. if (doJitter
  211252. && overlapBuffer->startFrame > 0
  211253. && overlapBuffer->numFrames > 0
  211254. && overlapBuffer->dataLength > 0)
  211255. {
  211256. const int numFrames = rb->numFrames;
  211257. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211258. {
  211259. rb->startFrame -= framesOverlap;
  211260. if (framesToCheck < framesOverlap
  211261. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211262. rb->numFrames += framesOverlap;
  211263. }
  211264. else
  211265. {
  211266. overlapBuffer->dataLength = 0;
  211267. overlapBuffer->startFrame = 0;
  211268. overlapBuffer->numFrames = 0;
  211269. }
  211270. }
  211271. if (! read (rb))
  211272. return false;
  211273. if (doJitter)
  211274. {
  211275. const int checkLen = framesToCheck * 2352;
  211276. const int maxToCheck = rb->dataLength - checkLen;
  211277. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211278. return true;
  211279. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211280. bool found = false;
  211281. for (int i = 0; i < maxToCheck; ++i)
  211282. {
  211283. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211284. {
  211285. i += checkLen;
  211286. rb->dataStartOffset = i;
  211287. rb->dataLength -= i;
  211288. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211289. found = true;
  211290. break;
  211291. }
  211292. }
  211293. rb->numFrames = rb->dataLength / 2352;
  211294. rb->dataLength = 2352 * rb->numFrames;
  211295. if (!found)
  211296. return false;
  211297. }
  211298. if (canDoJitter)
  211299. {
  211300. memcpy (overlapBuffer->buffer,
  211301. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211302. 2352 * framesToCheck);
  211303. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211304. overlapBuffer->numFrames = framesToCheck;
  211305. overlapBuffer->dataLength = 2352 * framesToCheck;
  211306. overlapBuffer->dataStartOffset = 0;
  211307. }
  211308. else
  211309. {
  211310. overlapBuffer->startFrame = 0;
  211311. overlapBuffer->numFrames = 0;
  211312. overlapBuffer->dataLength = 0;
  211313. }
  211314. return true;
  211315. }
  211316. else
  211317. {
  211318. return read (rb);
  211319. }
  211320. }
  211321. int CDController::getLastIndex()
  211322. {
  211323. char qdata[100];
  211324. SRB_ExecSCSICmd s;
  211325. prepare (s);
  211326. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211327. s.SRB_BufLen = sizeof (qdata);
  211328. s.SRB_BufPointer = (BYTE*)qdata;
  211329. s.SRB_CDBLen = 12;
  211330. s.CDBByte[0] = 0x42;
  211331. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211332. s.CDBByte[2] = 64;
  211333. s.CDBByte[3] = 1; // get current position
  211334. s.CDBByte[7] = 0;
  211335. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211336. perform (s);
  211337. if (s.SRB_Status == SS_COMP)
  211338. return qdata[7];
  211339. return 0;
  211340. }
  211341. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211342. {
  211343. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211344. SRB_ExecSCSICmd s;
  211345. zerostruct (s);
  211346. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211347. s.SRB_HaID = info.ha;
  211348. s.SRB_Target = info.tgt;
  211349. s.SRB_Lun = info.lun;
  211350. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211351. s.SRB_BufLen = 0x324;
  211352. s.SRB_BufPointer = (BYTE*)lpToc;
  211353. s.SRB_SenseLen = 0x0E;
  211354. s.SRB_CDBLen = 0x0A;
  211355. s.SRB_PostProc = event;
  211356. s.CDBByte[0] = 0x43;
  211357. s.CDBByte[1] = 0x00;
  211358. s.CDBByte[7] = 0x03;
  211359. s.CDBByte[8] = 0x24;
  211360. ResetEvent (event);
  211361. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211362. : fSendASPI32Command ((LPSRB)&s);
  211363. if (status == SS_PENDING)
  211364. WaitForSingleObject (event, 4000);
  211365. CloseHandle (event);
  211366. return (s.SRB_Status == SS_COMP);
  211367. }
  211368. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211369. CDReadBuffer* const overlapBuffer)
  211370. {
  211371. if (controller == 0)
  211372. {
  211373. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211374. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211375. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211376. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211377. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211378. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211379. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211380. }
  211381. buffer->index = 0;
  211382. if ((controller != 0)
  211383. && controller->readAudio (buffer, overlapBuffer))
  211384. {
  211385. if (buffer->wantsIndex)
  211386. buffer->index = controller->getLastIndex();
  211387. return true;
  211388. }
  211389. return false;
  211390. }
  211391. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211392. {
  211393. if (shouldBeOpen)
  211394. {
  211395. if (controller != 0)
  211396. {
  211397. controller->shutDown();
  211398. controller = 0;
  211399. }
  211400. if (scsiHandle != 0)
  211401. {
  211402. CloseHandle (scsiHandle);
  211403. scsiHandle = 0;
  211404. }
  211405. }
  211406. SRB_ExecSCSICmd s;
  211407. zerostruct (s);
  211408. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211409. s.SRB_HaID = info.ha;
  211410. s.SRB_Target = info.tgt;
  211411. s.SRB_Lun = info.lun;
  211412. s.SRB_SenseLen = SENSE_LEN;
  211413. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211414. s.SRB_BufLen = 0;
  211415. s.SRB_BufPointer = 0;
  211416. s.SRB_CDBLen = 12;
  211417. s.CDBByte[0] = 0x1b;
  211418. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211419. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211420. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211421. s.SRB_PostProc = event;
  211422. ResetEvent (event);
  211423. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211424. : fSendASPI32Command ((LPSRB)&s);
  211425. if (status == SS_PENDING)
  211426. WaitForSingleObject (event, 4000);
  211427. CloseHandle (event);
  211428. }
  211429. bool CDDeviceHandle::testController (const int type,
  211430. CDController* const newController,
  211431. CDReadBuffer* const rb)
  211432. {
  211433. controller = newController;
  211434. readType = (BYTE)type;
  211435. controller->deviceInfo = this;
  211436. controller->framesToCheck = 1;
  211437. controller->framesOverlap = 3;
  211438. bool passed = false;
  211439. memset (rb->buffer, 0xcd, rb->bufferSize);
  211440. if (controller->read (rb))
  211441. {
  211442. passed = true;
  211443. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211444. int wrong = 0;
  211445. for (int i = rb->dataLength / 4; --i >= 0;)
  211446. {
  211447. if (*p++ == (int) 0xcdcdcdcd)
  211448. {
  211449. if (++wrong == 4)
  211450. {
  211451. passed = false;
  211452. break;
  211453. }
  211454. }
  211455. else
  211456. {
  211457. wrong = 0;
  211458. }
  211459. }
  211460. }
  211461. if (! passed)
  211462. {
  211463. controller->shutDown();
  211464. controller = 0;
  211465. }
  211466. return passed;
  211467. }
  211468. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211469. {
  211470. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211471. const int bufSize = 128;
  211472. BYTE buffer[bufSize];
  211473. zeromem (buffer, bufSize);
  211474. SRB_ExecSCSICmd s;
  211475. zerostruct (s);
  211476. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211477. s.SRB_HaID = ha;
  211478. s.SRB_Target = tgt;
  211479. s.SRB_Lun = lun;
  211480. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211481. s.SRB_BufLen = bufSize;
  211482. s.SRB_BufPointer = buffer;
  211483. s.SRB_SenseLen = SENSE_LEN;
  211484. s.SRB_CDBLen = 6;
  211485. s.SRB_PostProc = event;
  211486. s.CDBByte[0] = SCSI_INQUIRY;
  211487. s.CDBByte[4] = 100;
  211488. ResetEvent (event);
  211489. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211490. WaitForSingleObject (event, 4000);
  211491. CloseHandle (event);
  211492. if (s.SRB_Status == SS_COMP)
  211493. {
  211494. memcpy (dev->vendor, &buffer[8], 8);
  211495. memcpy (dev->productId, &buffer[16], 16);
  211496. memcpy (dev->rev, &buffer[32], 4);
  211497. memcpy (dev->vendorSpec, &buffer[36], 20);
  211498. }
  211499. }
  211500. static int FindCDDevices (CDDeviceInfo* const list,
  211501. int maxItems)
  211502. {
  211503. int count = 0;
  211504. if (usingScsi)
  211505. {
  211506. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211507. {
  211508. TCHAR drivePath[8];
  211509. drivePath[0] = driveLetter;
  211510. drivePath[1] = ':';
  211511. drivePath[2] = '\\';
  211512. drivePath[3] = 0;
  211513. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211514. {
  211515. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211516. if (h != INVALID_HANDLE_VALUE)
  211517. {
  211518. BYTE buffer[100], passThroughStruct[1024];
  211519. zeromem (buffer, sizeof (buffer));
  211520. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211521. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211522. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211523. p->spt.CdbLength = 6;
  211524. p->spt.SenseInfoLength = 24;
  211525. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211526. p->spt.DataTransferLength = 100;
  211527. p->spt.TimeOutValue = 2;
  211528. p->spt.DataBuffer = buffer;
  211529. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211530. p->spt.Cdb[0] = 0x12;
  211531. p->spt.Cdb[4] = 100;
  211532. DWORD bytesReturned = 0;
  211533. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211534. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211535. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211536. &bytesReturned, 0) != 0)
  211537. {
  211538. zeromem (&list[count], sizeof (CDDeviceInfo));
  211539. list[count].scsiDriveLetter = driveLetter;
  211540. memcpy (list[count].vendor, &buffer[8], 8);
  211541. memcpy (list[count].productId, &buffer[16], 16);
  211542. memcpy (list[count].rev, &buffer[32], 4);
  211543. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211544. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211545. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211546. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211547. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211548. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211549. &bytesReturned, 0) != 0)
  211550. {
  211551. list[count].ha = scsiAddr->PortNumber;
  211552. list[count].tgt = scsiAddr->TargetId;
  211553. list[count].lun = scsiAddr->Lun;
  211554. ++count;
  211555. }
  211556. }
  211557. CloseHandle (h);
  211558. }
  211559. }
  211560. }
  211561. }
  211562. else
  211563. {
  211564. const DWORD d = fGetASPI32SupportInfo();
  211565. BYTE status = HIBYTE (LOWORD (d));
  211566. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211567. return 0;
  211568. const int numAdapters = LOBYTE (LOWORD (d));
  211569. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211570. {
  211571. SRB_HAInquiry s;
  211572. zerostruct (s);
  211573. s.SRB_Cmd = SC_HA_INQUIRY;
  211574. s.SRB_HaID = ha;
  211575. fSendASPI32Command ((LPSRB)&s);
  211576. if (s.SRB_Status == SS_COMP)
  211577. {
  211578. maxItems = (int)s.HA_Unique[3];
  211579. if (maxItems == 0)
  211580. maxItems = 8;
  211581. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211582. {
  211583. for (BYTE lun = 0; lun < 8; ++lun)
  211584. {
  211585. SRB_GDEVBlock sb;
  211586. zerostruct (sb);
  211587. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211588. sb.SRB_HaID = ha;
  211589. sb.SRB_Target = tgt;
  211590. sb.SRB_Lun = lun;
  211591. fSendASPI32Command ((LPSRB) &sb);
  211592. if (sb.SRB_Status == SS_COMP
  211593. && sb.SRB_DeviceType == DTYPE_CROM)
  211594. {
  211595. zeromem (&list[count], sizeof (CDDeviceInfo));
  211596. list[count].ha = ha;
  211597. list[count].tgt = tgt;
  211598. list[count].lun = lun;
  211599. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211600. ++count;
  211601. }
  211602. }
  211603. }
  211604. }
  211605. }
  211606. }
  211607. return count;
  211608. }
  211609. static int ripperUsers = 0;
  211610. static bool initialisedOk = false;
  211611. class DeinitialiseTimer : private Timer,
  211612. private DeletedAtShutdown
  211613. {
  211614. DeinitialiseTimer (const DeinitialiseTimer&);
  211615. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211616. public:
  211617. DeinitialiseTimer()
  211618. {
  211619. startTimer (4000);
  211620. }
  211621. ~DeinitialiseTimer()
  211622. {
  211623. if (--ripperUsers == 0)
  211624. DeinitialiseCDRipper();
  211625. }
  211626. void timerCallback()
  211627. {
  211628. delete this;
  211629. }
  211630. juce_UseDebuggingNewOperator
  211631. };
  211632. static void incUserCount()
  211633. {
  211634. if (ripperUsers++ == 0)
  211635. initialisedOk = InitialiseCDRipper();
  211636. }
  211637. static void decUserCount()
  211638. {
  211639. new DeinitialiseTimer();
  211640. }
  211641. struct CDDeviceWrapper
  211642. {
  211643. ScopedPointer<CDDeviceHandle> cdH;
  211644. ScopedPointer<CDReadBuffer> overlapBuffer;
  211645. bool jitter;
  211646. };
  211647. static int getAddressOf (const TOCTRACK* const t)
  211648. {
  211649. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211650. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211651. }
  211652. static const int samplesPerFrame = 44100 / 75;
  211653. static const int bytesPerFrame = samplesPerFrame * 4;
  211654. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211655. {
  211656. SRB_GDEVBlock s;
  211657. zerostruct (s);
  211658. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211659. s.SRB_HaID = device->ha;
  211660. s.SRB_Target = device->tgt;
  211661. s.SRB_Lun = device->lun;
  211662. if (usingScsi)
  211663. {
  211664. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211665. if (h != INVALID_HANDLE_VALUE)
  211666. {
  211667. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211668. cdh->scsiHandle = h;
  211669. return cdh;
  211670. }
  211671. }
  211672. else
  211673. {
  211674. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211675. && s.SRB_DeviceType == DTYPE_CROM)
  211676. {
  211677. return new CDDeviceHandle (device);
  211678. }
  211679. }
  211680. return 0;
  211681. }
  211682. }
  211683. const StringArray AudioCDReader::getAvailableCDNames()
  211684. {
  211685. using namespace CDReaderHelpers;
  211686. StringArray results;
  211687. incUserCount();
  211688. if (initialisedOk)
  211689. {
  211690. CDDeviceInfo list[8];
  211691. const int num = FindCDDevices (list, 8);
  211692. decUserCount();
  211693. for (int i = 0; i < num; ++i)
  211694. {
  211695. String s;
  211696. if (list[i].scsiDriveLetter > 0)
  211697. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211698. s << String (list[i].vendor).trim()
  211699. << ' ' << String (list[i].productId).trim()
  211700. << ' ' << String (list[i].rev).trim();
  211701. results.add (s);
  211702. }
  211703. }
  211704. return results;
  211705. }
  211706. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211707. {
  211708. using namespace CDReaderHelpers;
  211709. incUserCount();
  211710. if (initialisedOk)
  211711. {
  211712. CDDeviceInfo list[8];
  211713. const int num = FindCDDevices (list, 8);
  211714. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211715. {
  211716. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211717. if (handle != 0)
  211718. {
  211719. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211720. d->cdH = handle;
  211721. d->overlapBuffer = new CDReadBuffer(3);
  211722. return new AudioCDReader (d);
  211723. }
  211724. }
  211725. }
  211726. decUserCount();
  211727. return 0;
  211728. }
  211729. AudioCDReader::AudioCDReader (void* handle_)
  211730. : AudioFormatReader (0, "CD Audio"),
  211731. handle (handle_),
  211732. indexingEnabled (false),
  211733. lastIndex (0),
  211734. firstFrameInBuffer (0),
  211735. samplesInBuffer (0)
  211736. {
  211737. using namespace CDReaderHelpers;
  211738. jassert (handle_ != 0);
  211739. refreshTrackLengths();
  211740. sampleRate = 44100.0;
  211741. bitsPerSample = 16;
  211742. numChannels = 2;
  211743. usesFloatingPointData = false;
  211744. buffer.setSize (4 * bytesPerFrame, true);
  211745. }
  211746. AudioCDReader::~AudioCDReader()
  211747. {
  211748. using namespace CDReaderHelpers;
  211749. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211750. delete device;
  211751. decUserCount();
  211752. }
  211753. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211754. int64 startSampleInFile, int numSamples)
  211755. {
  211756. using namespace CDReaderHelpers;
  211757. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211758. bool ok = true;
  211759. while (numSamples > 0)
  211760. {
  211761. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211762. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211763. if (startSampleInFile >= bufferStartSample
  211764. && startSampleInFile < bufferEndSample)
  211765. {
  211766. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211767. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211768. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211769. const short* src = (const short*) buffer.getData();
  211770. src += 2 * (startSampleInFile - bufferStartSample);
  211771. for (int i = 0; i < toDo; ++i)
  211772. {
  211773. l[i] = src [i << 1] << 16;
  211774. if (r != 0)
  211775. r[i] = src [(i << 1) + 1] << 16;
  211776. }
  211777. startOffsetInDestBuffer += toDo;
  211778. startSampleInFile += toDo;
  211779. numSamples -= toDo;
  211780. }
  211781. else
  211782. {
  211783. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211784. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211785. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211786. {
  211787. device->overlapBuffer->dataLength = 0;
  211788. device->overlapBuffer->startFrame = 0;
  211789. device->overlapBuffer->numFrames = 0;
  211790. device->jitter = false;
  211791. }
  211792. firstFrameInBuffer = frameNeeded;
  211793. lastIndex = 0;
  211794. CDReadBuffer readBuffer (framesInBuffer + 4);
  211795. readBuffer.wantsIndex = indexingEnabled;
  211796. int i;
  211797. for (i = 5; --i >= 0;)
  211798. {
  211799. readBuffer.startFrame = frameNeeded;
  211800. readBuffer.numFrames = framesInBuffer;
  211801. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211802. break;
  211803. else
  211804. device->overlapBuffer->dataLength = 0;
  211805. }
  211806. if (i >= 0)
  211807. {
  211808. memcpy ((char*) buffer.getData(),
  211809. readBuffer.buffer + readBuffer.dataStartOffset,
  211810. readBuffer.dataLength);
  211811. samplesInBuffer = readBuffer.dataLength >> 2;
  211812. lastIndex = readBuffer.index;
  211813. }
  211814. else
  211815. {
  211816. int* l = destSamples[0] + startOffsetInDestBuffer;
  211817. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211818. while (--numSamples >= 0)
  211819. {
  211820. *l++ = 0;
  211821. if (r != 0)
  211822. *r++ = 0;
  211823. }
  211824. // sometimes the read fails for just the very last couple of blocks, so
  211825. // we'll ignore and errors in the last half-second of the disk..
  211826. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211827. break;
  211828. }
  211829. }
  211830. }
  211831. return ok;
  211832. }
  211833. bool AudioCDReader::isCDStillPresent() const
  211834. {
  211835. using namespace CDReaderHelpers;
  211836. TOC toc;
  211837. zerostruct (toc);
  211838. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211839. }
  211840. void AudioCDReader::refreshTrackLengths()
  211841. {
  211842. using namespace CDReaderHelpers;
  211843. trackStartSamples.clear();
  211844. zeromem (audioTracks, sizeof (audioTracks));
  211845. TOC toc;
  211846. zerostruct (toc);
  211847. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211848. {
  211849. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211850. for (int i = 0; i <= numTracks; ++i)
  211851. {
  211852. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211853. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211854. }
  211855. }
  211856. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211857. }
  211858. bool AudioCDReader::isTrackAudio (int trackNum) const
  211859. {
  211860. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211861. }
  211862. void AudioCDReader::enableIndexScanning (bool b)
  211863. {
  211864. indexingEnabled = b;
  211865. }
  211866. int AudioCDReader::getLastIndex() const
  211867. {
  211868. return lastIndex;
  211869. }
  211870. const int framesPerIndexRead = 4;
  211871. int AudioCDReader::getIndexAt (int samplePos)
  211872. {
  211873. using namespace CDReaderHelpers;
  211874. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211875. const int frameNeeded = samplePos / samplesPerFrame;
  211876. device->overlapBuffer->dataLength = 0;
  211877. device->overlapBuffer->startFrame = 0;
  211878. device->overlapBuffer->numFrames = 0;
  211879. device->jitter = false;
  211880. firstFrameInBuffer = 0;
  211881. lastIndex = 0;
  211882. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211883. readBuffer.wantsIndex = true;
  211884. int i;
  211885. for (i = 5; --i >= 0;)
  211886. {
  211887. readBuffer.startFrame = frameNeeded;
  211888. readBuffer.numFrames = framesPerIndexRead;
  211889. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211890. break;
  211891. }
  211892. if (i >= 0)
  211893. return readBuffer.index;
  211894. return -1;
  211895. }
  211896. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211897. {
  211898. using namespace CDReaderHelpers;
  211899. Array <int> indexes;
  211900. const int trackStart = getPositionOfTrackStart (trackNumber);
  211901. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211902. bool needToScan = true;
  211903. if (trackEnd - trackStart > 20 * 44100)
  211904. {
  211905. // check the end of the track for indexes before scanning the whole thing
  211906. needToScan = false;
  211907. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211908. bool seenAnIndex = false;
  211909. while (pos <= trackEnd - samplesPerFrame)
  211910. {
  211911. const int index = getIndexAt (pos);
  211912. if (index == 0)
  211913. {
  211914. // lead-out, so skip back a bit if we've not found any indexes yet..
  211915. if (seenAnIndex)
  211916. break;
  211917. pos -= 44100 * 5;
  211918. if (pos < trackStart)
  211919. break;
  211920. }
  211921. else
  211922. {
  211923. if (index > 0)
  211924. seenAnIndex = true;
  211925. if (index > 1)
  211926. {
  211927. needToScan = true;
  211928. break;
  211929. }
  211930. pos += samplesPerFrame * framesPerIndexRead;
  211931. }
  211932. }
  211933. }
  211934. if (needToScan)
  211935. {
  211936. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211937. int pos = trackStart;
  211938. int last = -1;
  211939. while (pos < trackEnd - samplesPerFrame * 10)
  211940. {
  211941. const int frameNeeded = pos / samplesPerFrame;
  211942. device->overlapBuffer->dataLength = 0;
  211943. device->overlapBuffer->startFrame = 0;
  211944. device->overlapBuffer->numFrames = 0;
  211945. device->jitter = false;
  211946. firstFrameInBuffer = 0;
  211947. CDReadBuffer readBuffer (4);
  211948. readBuffer.wantsIndex = true;
  211949. int i;
  211950. for (i = 5; --i >= 0;)
  211951. {
  211952. readBuffer.startFrame = frameNeeded;
  211953. readBuffer.numFrames = framesPerIndexRead;
  211954. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211955. break;
  211956. }
  211957. if (i < 0)
  211958. break;
  211959. if (readBuffer.index > last && readBuffer.index > 1)
  211960. {
  211961. last = readBuffer.index;
  211962. indexes.add (pos);
  211963. }
  211964. pos += samplesPerFrame * framesPerIndexRead;
  211965. }
  211966. indexes.removeValue (trackStart);
  211967. }
  211968. return indexes;
  211969. }
  211970. void AudioCDReader::ejectDisk()
  211971. {
  211972. using namespace CDReaderHelpers;
  211973. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211974. }
  211975. #endif
  211976. #if JUCE_USE_CDBURNER
  211977. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211978. {
  211979. CoInitialize (0);
  211980. IDiscMaster* dm;
  211981. IDiscRecorder* result = 0;
  211982. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211983. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211984. IID_IDiscMaster,
  211985. (void**) &dm)))
  211986. {
  211987. if (SUCCEEDED (dm->Open()))
  211988. {
  211989. IEnumDiscRecorders* drEnum = 0;
  211990. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211991. {
  211992. IDiscRecorder* dr = 0;
  211993. DWORD dummy;
  211994. int index = 0;
  211995. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211996. {
  211997. if (indexToOpen == index)
  211998. {
  211999. result = dr;
  212000. break;
  212001. }
  212002. else if (list != 0)
  212003. {
  212004. BSTR path;
  212005. if (SUCCEEDED (dr->GetPath (&path)))
  212006. list->add ((const WCHAR*) path);
  212007. }
  212008. ++index;
  212009. dr->Release();
  212010. }
  212011. drEnum->Release();
  212012. }
  212013. if (master == 0)
  212014. dm->Close();
  212015. }
  212016. if (master != 0)
  212017. *master = dm;
  212018. else
  212019. dm->Release();
  212020. }
  212021. return result;
  212022. }
  212023. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212024. public Timer
  212025. {
  212026. public:
  212027. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212028. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212029. listener (0), progress (0), shouldCancel (false)
  212030. {
  212031. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212032. jassert (SUCCEEDED (hr));
  212033. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212034. //jassert (SUCCEEDED (hr));
  212035. lastState = getDiskState();
  212036. startTimer (2000);
  212037. }
  212038. ~Pimpl() {}
  212039. void releaseObjects()
  212040. {
  212041. discRecorder->Close();
  212042. if (redbook != 0)
  212043. redbook->Release();
  212044. discRecorder->Release();
  212045. discMaster->Release();
  212046. Release();
  212047. }
  212048. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212049. {
  212050. if (listener != 0 && ! shouldCancel)
  212051. shouldCancel = listener->audioCDBurnProgress (progress);
  212052. *pbCancel = shouldCancel;
  212053. return S_OK;
  212054. }
  212055. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212056. {
  212057. progress = nCompleted / (float) nTotal;
  212058. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212059. return E_NOTIMPL;
  212060. }
  212061. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212062. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212063. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212064. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212065. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212066. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212067. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212068. class ScopedDiscOpener
  212069. {
  212070. public:
  212071. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212072. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212073. private:
  212074. Pimpl& pimpl;
  212075. ScopedDiscOpener (const ScopedDiscOpener&);
  212076. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212077. };
  212078. DiskState getDiskState()
  212079. {
  212080. const ScopedDiscOpener opener (*this);
  212081. long type, flags;
  212082. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212083. if (FAILED (hr))
  212084. return unknown;
  212085. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212086. return writableDiskPresent;
  212087. if (type == 0)
  212088. return noDisc;
  212089. else
  212090. return readOnlyDiskPresent;
  212091. }
  212092. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212093. {
  212094. ComSmartPtr<IPropertyStorage> prop;
  212095. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212096. return defaultReturn;
  212097. PROPSPEC iPropSpec;
  212098. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212099. iPropSpec.lpwstr = name;
  212100. PROPVARIANT iPropVariant;
  212101. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212102. ? defaultReturn : (int) iPropVariant.lVal;
  212103. }
  212104. bool setIntProperty (const LPOLESTR name, const int value) const
  212105. {
  212106. ComSmartPtr<IPropertyStorage> prop;
  212107. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212108. return false;
  212109. PROPSPEC iPropSpec;
  212110. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212111. iPropSpec.lpwstr = name;
  212112. PROPVARIANT iPropVariant;
  212113. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212114. return false;
  212115. iPropVariant.lVal = (long) value;
  212116. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212117. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212118. }
  212119. void timerCallback()
  212120. {
  212121. const DiskState state = getDiskState();
  212122. if (state != lastState)
  212123. {
  212124. lastState = state;
  212125. owner.sendChangeMessage (&owner);
  212126. }
  212127. }
  212128. AudioCDBurner& owner;
  212129. DiskState lastState;
  212130. IDiscMaster* discMaster;
  212131. IDiscRecorder* discRecorder;
  212132. IRedbookDiscMaster* redbook;
  212133. AudioCDBurner::BurnProgressListener* listener;
  212134. float progress;
  212135. bool shouldCancel;
  212136. };
  212137. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212138. {
  212139. IDiscMaster* discMaster = 0;
  212140. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212141. if (discRecorder != 0)
  212142. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212143. }
  212144. AudioCDBurner::~AudioCDBurner()
  212145. {
  212146. if (pimpl != 0)
  212147. pimpl.release()->releaseObjects();
  212148. }
  212149. const StringArray AudioCDBurner::findAvailableDevices()
  212150. {
  212151. StringArray devs;
  212152. enumCDBurners (&devs, -1, 0);
  212153. return devs;
  212154. }
  212155. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212156. {
  212157. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212158. if (b->pimpl == 0)
  212159. b = 0;
  212160. return b.release();
  212161. }
  212162. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212163. {
  212164. return pimpl->getDiskState();
  212165. }
  212166. bool AudioCDBurner::isDiskPresent() const
  212167. {
  212168. return getDiskState() == writableDiskPresent;
  212169. }
  212170. bool AudioCDBurner::openTray()
  212171. {
  212172. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212173. return SUCCEEDED (pimpl->discRecorder->Eject());
  212174. }
  212175. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212176. {
  212177. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212178. DiskState oldState = getDiskState();
  212179. DiskState newState = oldState;
  212180. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212181. {
  212182. newState = getDiskState();
  212183. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212184. }
  212185. return newState;
  212186. }
  212187. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212188. {
  212189. Array<int> results;
  212190. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212191. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212192. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212193. if (speeds[i] <= maxSpeed)
  212194. results.add (speeds[i]);
  212195. results.addIfNotAlreadyThere (maxSpeed);
  212196. return results;
  212197. }
  212198. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212199. {
  212200. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212201. return false;
  212202. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212203. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212204. }
  212205. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212206. {
  212207. long blocksFree = 0;
  212208. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212209. return blocksFree;
  212210. }
  212211. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212212. bool performFakeBurnForTesting, int writeSpeed)
  212213. {
  212214. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212215. pimpl->listener = listener;
  212216. pimpl->progress = 0;
  212217. pimpl->shouldCancel = false;
  212218. UINT_PTR cookie;
  212219. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212220. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212221. ejectDiscAfterwards);
  212222. String error;
  212223. if (hr != S_OK)
  212224. {
  212225. const char* e = "Couldn't open or write to the CD device";
  212226. if (hr == IMAPI_E_USERABORT)
  212227. e = "User cancelled the write operation";
  212228. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212229. e = "No Disk present";
  212230. error = e;
  212231. }
  212232. pimpl->discMaster->ProgressUnadvise (cookie);
  212233. pimpl->listener = 0;
  212234. return error;
  212235. }
  212236. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212237. {
  212238. if (audioSource == 0)
  212239. return false;
  212240. ScopedPointer<AudioSource> source (audioSource);
  212241. long bytesPerBlock;
  212242. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212243. const int samplesPerBlock = bytesPerBlock / 4;
  212244. bool ok = true;
  212245. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212246. HeapBlock <byte> buffer (bytesPerBlock);
  212247. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212248. int samplesDone = 0;
  212249. source->prepareToPlay (samplesPerBlock, 44100.0);
  212250. while (ok)
  212251. {
  212252. {
  212253. AudioSourceChannelInfo info;
  212254. info.buffer = &sourceBuffer;
  212255. info.numSamples = samplesPerBlock;
  212256. info.startSample = 0;
  212257. sourceBuffer.clear();
  212258. source->getNextAudioBlock (info);
  212259. }
  212260. zeromem (buffer, bytesPerBlock);
  212261. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212262. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212263. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212264. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212265. CDSampleFormat left (buffer, 2);
  212266. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212267. CDSampleFormat right (buffer + 2, 2);
  212268. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212269. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212270. if (FAILED (hr))
  212271. ok = false;
  212272. samplesDone += samplesPerBlock;
  212273. if (samplesDone >= numSamples)
  212274. break;
  212275. }
  212276. hr = pimpl->redbook->CloseAudioTrack();
  212277. return ok && hr == S_OK;
  212278. }
  212279. #endif
  212280. #endif
  212281. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212282. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212283. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212284. // compiled on its own).
  212285. #if JUCE_INCLUDED_FILE
  212286. class MidiInCollector
  212287. {
  212288. public:
  212289. MidiInCollector (MidiInput* const input_,
  212290. MidiInputCallback& callback_)
  212291. : deviceHandle (0),
  212292. input (input_),
  212293. callback (callback_),
  212294. concatenator (4096),
  212295. isStarted (false),
  212296. startTime (0)
  212297. {
  212298. }
  212299. ~MidiInCollector()
  212300. {
  212301. stop();
  212302. if (deviceHandle != 0)
  212303. {
  212304. int count = 5;
  212305. while (--count >= 0)
  212306. {
  212307. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212308. break;
  212309. Sleep (20);
  212310. }
  212311. }
  212312. }
  212313. void handleMessage (const uint32 message, const uint32 timeStamp)
  212314. {
  212315. if ((message & 0xff) >= 0x80 && isStarted)
  212316. {
  212317. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212318. writeFinishedBlocks();
  212319. }
  212320. }
  212321. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212322. {
  212323. if (isStarted)
  212324. {
  212325. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212326. writeFinishedBlocks();
  212327. }
  212328. }
  212329. void start()
  212330. {
  212331. jassert (deviceHandle != 0);
  212332. if (deviceHandle != 0 && ! isStarted)
  212333. {
  212334. activeMidiCollectors.addIfNotAlreadyThere (this);
  212335. for (int i = 0; i < (int) numHeaders; ++i)
  212336. headers[i].write (deviceHandle);
  212337. startTime = Time::getMillisecondCounter();
  212338. MMRESULT res = midiInStart (deviceHandle);
  212339. if (res == MMSYSERR_NOERROR)
  212340. {
  212341. concatenator.reset();
  212342. isStarted = true;
  212343. }
  212344. else
  212345. {
  212346. unprepareAllHeaders();
  212347. }
  212348. }
  212349. }
  212350. void stop()
  212351. {
  212352. if (isStarted)
  212353. {
  212354. isStarted = false;
  212355. midiInReset (deviceHandle);
  212356. midiInStop (deviceHandle);
  212357. activeMidiCollectors.removeValue (this);
  212358. unprepareAllHeaders();
  212359. concatenator.reset();
  212360. }
  212361. }
  212362. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212363. {
  212364. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212365. if (activeMidiCollectors.contains (collector))
  212366. {
  212367. if (uMsg == MIM_DATA)
  212368. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212369. else if (uMsg == MIM_LONGDATA)
  212370. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212371. }
  212372. }
  212373. juce_UseDebuggingNewOperator
  212374. HMIDIIN deviceHandle;
  212375. private:
  212376. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212377. MidiInput* input;
  212378. MidiInputCallback& callback;
  212379. MidiDataConcatenator concatenator;
  212380. bool volatile isStarted;
  212381. uint32 startTime;
  212382. class MidiHeader
  212383. {
  212384. public:
  212385. MidiHeader()
  212386. {
  212387. zerostruct (hdr);
  212388. hdr.lpData = data;
  212389. hdr.dwBufferLength = numElementsInArray (data);
  212390. }
  212391. void write (HMIDIIN deviceHandle)
  212392. {
  212393. hdr.dwBytesRecorded = 0;
  212394. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212395. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212396. }
  212397. void writeIfFinished (HMIDIIN deviceHandle)
  212398. {
  212399. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212400. {
  212401. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212402. (void) res;
  212403. write (deviceHandle);
  212404. }
  212405. }
  212406. void unprepare (HMIDIIN deviceHandle)
  212407. {
  212408. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212409. {
  212410. int c = 10;
  212411. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212412. Thread::sleep (20);
  212413. jassert (c >= 0);
  212414. }
  212415. }
  212416. private:
  212417. MIDIHDR hdr;
  212418. char data [256];
  212419. MidiHeader (const MidiHeader&);
  212420. MidiHeader& operator= (const MidiHeader&);
  212421. };
  212422. enum { numHeaders = 32 };
  212423. MidiHeader headers [numHeaders];
  212424. void writeFinishedBlocks()
  212425. {
  212426. for (int i = 0; i < (int) numHeaders; ++i)
  212427. headers[i].writeIfFinished (deviceHandle);
  212428. }
  212429. void unprepareAllHeaders()
  212430. {
  212431. for (int i = 0; i < (int) numHeaders; ++i)
  212432. headers[i].unprepare (deviceHandle);
  212433. }
  212434. double convertTimeStamp (uint32 timeStamp)
  212435. {
  212436. timeStamp += startTime;
  212437. const uint32 now = Time::getMillisecondCounter();
  212438. if (timeStamp > now)
  212439. {
  212440. if (timeStamp > now + 2)
  212441. --startTime;
  212442. timeStamp = now;
  212443. }
  212444. return timeStamp * 0.001;
  212445. }
  212446. MidiInCollector (const MidiInCollector&);
  212447. MidiInCollector& operator= (const MidiInCollector&);
  212448. };
  212449. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212450. const StringArray MidiInput::getDevices()
  212451. {
  212452. StringArray s;
  212453. const int num = midiInGetNumDevs();
  212454. for (int i = 0; i < num; ++i)
  212455. {
  212456. MIDIINCAPS mc;
  212457. zerostruct (mc);
  212458. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212459. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212460. }
  212461. return s;
  212462. }
  212463. int MidiInput::getDefaultDeviceIndex()
  212464. {
  212465. return 0;
  212466. }
  212467. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212468. {
  212469. if (callback == 0)
  212470. return 0;
  212471. UINT deviceId = MIDI_MAPPER;
  212472. int n = 0;
  212473. String name;
  212474. const int num = midiInGetNumDevs();
  212475. for (int i = 0; i < num; ++i)
  212476. {
  212477. MIDIINCAPS mc;
  212478. zerostruct (mc);
  212479. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212480. {
  212481. if (index == n)
  212482. {
  212483. deviceId = i;
  212484. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212485. break;
  212486. }
  212487. ++n;
  212488. }
  212489. }
  212490. ScopedPointer <MidiInput> in (new MidiInput (name));
  212491. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212492. HMIDIIN h;
  212493. HRESULT err = midiInOpen (&h, deviceId,
  212494. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212495. (DWORD_PTR) (MidiInCollector*) collector,
  212496. CALLBACK_FUNCTION);
  212497. if (err == MMSYSERR_NOERROR)
  212498. {
  212499. collector->deviceHandle = h;
  212500. in->internal = collector.release();
  212501. return in.release();
  212502. }
  212503. return 0;
  212504. }
  212505. MidiInput::MidiInput (const String& name_)
  212506. : name (name_),
  212507. internal (0)
  212508. {
  212509. }
  212510. MidiInput::~MidiInput()
  212511. {
  212512. delete static_cast <MidiInCollector*> (internal);
  212513. }
  212514. void MidiInput::start()
  212515. {
  212516. static_cast <MidiInCollector*> (internal)->start();
  212517. }
  212518. void MidiInput::stop()
  212519. {
  212520. static_cast <MidiInCollector*> (internal)->stop();
  212521. }
  212522. struct MidiOutHandle
  212523. {
  212524. int refCount;
  212525. UINT deviceId;
  212526. HMIDIOUT handle;
  212527. static Array<MidiOutHandle*> activeHandles;
  212528. juce_UseDebuggingNewOperator
  212529. };
  212530. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212531. const StringArray MidiOutput::getDevices()
  212532. {
  212533. StringArray s;
  212534. const int num = midiOutGetNumDevs();
  212535. for (int i = 0; i < num; ++i)
  212536. {
  212537. MIDIOUTCAPS mc;
  212538. zerostruct (mc);
  212539. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212540. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212541. }
  212542. return s;
  212543. }
  212544. int MidiOutput::getDefaultDeviceIndex()
  212545. {
  212546. const int num = midiOutGetNumDevs();
  212547. int n = 0;
  212548. for (int i = 0; i < num; ++i)
  212549. {
  212550. MIDIOUTCAPS mc;
  212551. zerostruct (mc);
  212552. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212553. {
  212554. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212555. return n;
  212556. ++n;
  212557. }
  212558. }
  212559. return 0;
  212560. }
  212561. MidiOutput* MidiOutput::openDevice (int index)
  212562. {
  212563. UINT deviceId = MIDI_MAPPER;
  212564. const int num = midiOutGetNumDevs();
  212565. int i, n = 0;
  212566. for (i = 0; i < num; ++i)
  212567. {
  212568. MIDIOUTCAPS mc;
  212569. zerostruct (mc);
  212570. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212571. {
  212572. // use the microsoft sw synth as a default - best not to allow deviceId
  212573. // to be MIDI_MAPPER, or else device sharing breaks
  212574. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212575. deviceId = i;
  212576. if (index == n)
  212577. {
  212578. deviceId = i;
  212579. break;
  212580. }
  212581. ++n;
  212582. }
  212583. }
  212584. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212585. {
  212586. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212587. if (han != 0 && han->deviceId == deviceId)
  212588. {
  212589. han->refCount++;
  212590. MidiOutput* const out = new MidiOutput();
  212591. out->internal = han;
  212592. return out;
  212593. }
  212594. }
  212595. for (i = 4; --i >= 0;)
  212596. {
  212597. HMIDIOUT h = 0;
  212598. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212599. if (res == MMSYSERR_NOERROR)
  212600. {
  212601. MidiOutHandle* const han = new MidiOutHandle();
  212602. han->deviceId = deviceId;
  212603. han->refCount = 1;
  212604. han->handle = h;
  212605. MidiOutHandle::activeHandles.add (han);
  212606. MidiOutput* const out = new MidiOutput();
  212607. out->internal = han;
  212608. return out;
  212609. }
  212610. else if (res == MMSYSERR_ALLOCATED)
  212611. {
  212612. Sleep (100);
  212613. }
  212614. else
  212615. {
  212616. break;
  212617. }
  212618. }
  212619. return 0;
  212620. }
  212621. MidiOutput::~MidiOutput()
  212622. {
  212623. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212624. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212625. {
  212626. midiOutClose (h->handle);
  212627. MidiOutHandle::activeHandles.removeValue (h);
  212628. delete h;
  212629. }
  212630. }
  212631. void MidiOutput::reset()
  212632. {
  212633. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212634. midiOutReset (h->handle);
  212635. }
  212636. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212637. {
  212638. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212639. DWORD n;
  212640. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212641. {
  212642. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212643. rightVol = nn[0] / (float) 0xffff;
  212644. leftVol = nn[1] / (float) 0xffff;
  212645. return true;
  212646. }
  212647. else
  212648. {
  212649. rightVol = leftVol = 1.0f;
  212650. return false;
  212651. }
  212652. }
  212653. void MidiOutput::setVolume (float leftVol, float rightVol)
  212654. {
  212655. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212656. DWORD n;
  212657. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212658. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212659. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212660. midiOutSetVolume (handle->handle, n);
  212661. }
  212662. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212663. {
  212664. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212665. if (message.getRawDataSize() > 3
  212666. || message.isSysEx())
  212667. {
  212668. MIDIHDR h;
  212669. zerostruct (h);
  212670. h.lpData = (char*) message.getRawData();
  212671. h.dwBufferLength = message.getRawDataSize();
  212672. h.dwBytesRecorded = message.getRawDataSize();
  212673. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212674. {
  212675. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212676. if (res == MMSYSERR_NOERROR)
  212677. {
  212678. while ((h.dwFlags & MHDR_DONE) == 0)
  212679. Sleep (1);
  212680. int count = 500; // 1 sec timeout
  212681. while (--count >= 0)
  212682. {
  212683. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212684. if (res == MIDIERR_STILLPLAYING)
  212685. Sleep (2);
  212686. else
  212687. break;
  212688. }
  212689. }
  212690. }
  212691. }
  212692. else
  212693. {
  212694. midiOutShortMsg (handle->handle,
  212695. *(unsigned int*) message.getRawData());
  212696. }
  212697. }
  212698. #endif
  212699. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212700. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212701. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212702. // compiled on its own).
  212703. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212704. #undef WINDOWS
  212705. // #define ASIO_DEBUGGING 1
  212706. #if ASIO_DEBUGGING
  212707. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212708. #else
  212709. #define log(a) {}
  212710. #endif
  212711. #if ASIO_DEBUGGING
  212712. static void logError (const String& context, long error)
  212713. {
  212714. String err ("unknown error");
  212715. if (error == ASE_NotPresent) err = "Not Present";
  212716. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212717. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212718. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212719. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212720. else if (error == ASE_NoClock) err = "No Clock";
  212721. else if (error == ASE_NoMemory) err = "Out of memory";
  212722. log ("!!error: " + context + " - " + err);
  212723. }
  212724. #else
  212725. #define logError(a, b) {}
  212726. #endif
  212727. class ASIOAudioIODevice;
  212728. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212729. static const int maxASIOChannels = 160;
  212730. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212731. private Timer
  212732. {
  212733. public:
  212734. Component ourWindow;
  212735. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212736. const String& optionalDllForDirectLoading_)
  212737. : AudioIODevice (name_, "ASIO"),
  212738. asioObject (0),
  212739. classId (classId_),
  212740. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212741. currentBitDepth (16),
  212742. currentSampleRate (0),
  212743. isOpen_ (false),
  212744. isStarted (false),
  212745. postOutput (true),
  212746. insideControlPanelModalLoop (false),
  212747. shouldUsePreferredSize (false)
  212748. {
  212749. name = name_;
  212750. ourWindow.addToDesktop (0);
  212751. windowHandle = ourWindow.getWindowHandle();
  212752. jassert (currentASIODev [slotNumber] == 0);
  212753. currentASIODev [slotNumber] = this;
  212754. openDevice();
  212755. }
  212756. ~ASIOAudioIODevice()
  212757. {
  212758. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212759. if (currentASIODev[i] == this)
  212760. currentASIODev[i] = 0;
  212761. close();
  212762. log ("ASIO - exiting");
  212763. removeCurrentDriver();
  212764. }
  212765. void updateSampleRates()
  212766. {
  212767. // find a list of sample rates..
  212768. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212769. sampleRates.clear();
  212770. if (asioObject != 0)
  212771. {
  212772. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212773. {
  212774. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212775. if (err == 0)
  212776. {
  212777. sampleRates.add ((int) possibleSampleRates[index]);
  212778. log ("rate: " + String ((int) possibleSampleRates[index]));
  212779. }
  212780. else if (err != ASE_NoClock)
  212781. {
  212782. logError ("CanSampleRate", err);
  212783. }
  212784. }
  212785. if (sampleRates.size() == 0)
  212786. {
  212787. double cr = 0;
  212788. const long err = asioObject->getSampleRate (&cr);
  212789. log ("No sample rates supported - current rate: " + String ((int) cr));
  212790. if (err == 0)
  212791. sampleRates.add ((int) cr);
  212792. }
  212793. }
  212794. }
  212795. const StringArray getOutputChannelNames()
  212796. {
  212797. return outputChannelNames;
  212798. }
  212799. const StringArray getInputChannelNames()
  212800. {
  212801. return inputChannelNames;
  212802. }
  212803. int getNumSampleRates()
  212804. {
  212805. return sampleRates.size();
  212806. }
  212807. double getSampleRate (int index)
  212808. {
  212809. return sampleRates [index];
  212810. }
  212811. int getNumBufferSizesAvailable()
  212812. {
  212813. return bufferSizes.size();
  212814. }
  212815. int getBufferSizeSamples (int index)
  212816. {
  212817. return bufferSizes [index];
  212818. }
  212819. int getDefaultBufferSize()
  212820. {
  212821. return preferredSize;
  212822. }
  212823. const String open (const BigInteger& inputChannels,
  212824. const BigInteger& outputChannels,
  212825. double sr,
  212826. int bufferSizeSamples)
  212827. {
  212828. close();
  212829. currentCallback = 0;
  212830. if (bufferSizeSamples <= 0)
  212831. shouldUsePreferredSize = true;
  212832. if (asioObject == 0 || ! isASIOOpen)
  212833. {
  212834. log ("Warning: device not open");
  212835. const String err (openDevice());
  212836. if (asioObject == 0 || ! isASIOOpen)
  212837. return err;
  212838. }
  212839. isStarted = false;
  212840. bufferIndex = -1;
  212841. long err = 0;
  212842. long newPreferredSize = 0;
  212843. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212844. minSize = 0;
  212845. maxSize = 0;
  212846. newPreferredSize = 0;
  212847. granularity = 0;
  212848. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212849. {
  212850. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212851. shouldUsePreferredSize = true;
  212852. preferredSize = newPreferredSize;
  212853. }
  212854. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212855. // dynamic changes to the buffer size...
  212856. shouldUsePreferredSize = shouldUsePreferredSize
  212857. || getName().containsIgnoreCase ("Digidesign");
  212858. if (shouldUsePreferredSize)
  212859. {
  212860. log ("Using preferred size for buffer..");
  212861. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212862. {
  212863. bufferSizeSamples = preferredSize;
  212864. }
  212865. else
  212866. {
  212867. bufferSizeSamples = 1024;
  212868. logError ("GetBufferSize1", err);
  212869. }
  212870. shouldUsePreferredSize = false;
  212871. }
  212872. int sampleRate = roundDoubleToInt (sr);
  212873. currentSampleRate = sampleRate;
  212874. currentBlockSizeSamples = bufferSizeSamples;
  212875. currentChansOut.clear();
  212876. currentChansIn.clear();
  212877. zeromem (inBuffers, sizeof (inBuffers));
  212878. zeromem (outBuffers, sizeof (outBuffers));
  212879. updateSampleRates();
  212880. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212881. sampleRate = sampleRates[0];
  212882. jassert (sampleRate != 0);
  212883. if (sampleRate == 0)
  212884. sampleRate = 44100;
  212885. long numSources = 32;
  212886. ASIOClockSource clocks[32];
  212887. zeromem (clocks, sizeof (clocks));
  212888. asioObject->getClockSources (clocks, &numSources);
  212889. bool isSourceSet = false;
  212890. // careful not to remove this loop because it does more than just logging!
  212891. int i;
  212892. for (i = 0; i < numSources; ++i)
  212893. {
  212894. String s ("clock: ");
  212895. s += clocks[i].name;
  212896. if (clocks[i].isCurrentSource)
  212897. {
  212898. isSourceSet = true;
  212899. s << " (cur)";
  212900. }
  212901. log (s);
  212902. }
  212903. if (numSources > 1 && ! isSourceSet)
  212904. {
  212905. log ("setting clock source");
  212906. asioObject->setClockSource (clocks[0].index);
  212907. Thread::sleep (20);
  212908. }
  212909. else
  212910. {
  212911. if (numSources == 0)
  212912. {
  212913. log ("ASIO - no clock sources!");
  212914. }
  212915. }
  212916. double cr = 0;
  212917. err = asioObject->getSampleRate (&cr);
  212918. if (err == 0)
  212919. {
  212920. currentSampleRate = cr;
  212921. }
  212922. else
  212923. {
  212924. logError ("GetSampleRate", err);
  212925. currentSampleRate = 0;
  212926. }
  212927. error = String::empty;
  212928. needToReset = false;
  212929. isReSync = false;
  212930. err = 0;
  212931. bool buffersCreated = false;
  212932. if (currentSampleRate != sampleRate)
  212933. {
  212934. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212935. err = asioObject->setSampleRate (sampleRate);
  212936. if (err == ASE_NoClock && numSources > 0)
  212937. {
  212938. log ("trying to set a clock source..");
  212939. Thread::sleep (10);
  212940. err = asioObject->setClockSource (clocks[0].index);
  212941. if (err != 0)
  212942. {
  212943. logError ("SetClock", err);
  212944. }
  212945. Thread::sleep (10);
  212946. err = asioObject->setSampleRate (sampleRate);
  212947. }
  212948. }
  212949. if (err == 0)
  212950. {
  212951. currentSampleRate = sampleRate;
  212952. if (needToReset)
  212953. {
  212954. if (isReSync)
  212955. {
  212956. log ("Resync request");
  212957. }
  212958. log ("! Resetting ASIO after sample rate change");
  212959. removeCurrentDriver();
  212960. loadDriver();
  212961. const String error (initDriver());
  212962. if (error.isNotEmpty())
  212963. {
  212964. log ("ASIOInit: " + error);
  212965. }
  212966. needToReset = false;
  212967. isReSync = false;
  212968. }
  212969. numActiveInputChans = 0;
  212970. numActiveOutputChans = 0;
  212971. ASIOBufferInfo* info = bufferInfos;
  212972. int i;
  212973. for (i = 0; i < totalNumInputChans; ++i)
  212974. {
  212975. if (inputChannels[i])
  212976. {
  212977. currentChansIn.setBit (i);
  212978. info->isInput = 1;
  212979. info->channelNum = i;
  212980. info->buffers[0] = info->buffers[1] = 0;
  212981. ++info;
  212982. ++numActiveInputChans;
  212983. }
  212984. }
  212985. for (i = 0; i < totalNumOutputChans; ++i)
  212986. {
  212987. if (outputChannels[i])
  212988. {
  212989. currentChansOut.setBit (i);
  212990. info->isInput = 0;
  212991. info->channelNum = i;
  212992. info->buffers[0] = info->buffers[1] = 0;
  212993. ++info;
  212994. ++numActiveOutputChans;
  212995. }
  212996. }
  212997. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212998. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212999. if (currentASIODev[0] == this)
  213000. {
  213001. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213002. callbacks.asioMessage = &asioMessagesCallback0;
  213003. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213004. }
  213005. else if (currentASIODev[1] == this)
  213006. {
  213007. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213008. callbacks.asioMessage = &asioMessagesCallback1;
  213009. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213010. }
  213011. else if (currentASIODev[2] == this)
  213012. {
  213013. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213014. callbacks.asioMessage = &asioMessagesCallback2;
  213015. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213016. }
  213017. else
  213018. {
  213019. jassertfalse;
  213020. }
  213021. log ("disposing buffers");
  213022. err = asioObject->disposeBuffers();
  213023. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213024. err = asioObject->createBuffers (bufferInfos,
  213025. totalBuffers,
  213026. currentBlockSizeSamples,
  213027. &callbacks);
  213028. if (err != 0)
  213029. {
  213030. currentBlockSizeSamples = preferredSize;
  213031. logError ("create buffers 2", err);
  213032. asioObject->disposeBuffers();
  213033. err = asioObject->createBuffers (bufferInfos,
  213034. totalBuffers,
  213035. currentBlockSizeSamples,
  213036. &callbacks);
  213037. }
  213038. if (err == 0)
  213039. {
  213040. buffersCreated = true;
  213041. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213042. int n = 0;
  213043. Array <int> types;
  213044. currentBitDepth = 16;
  213045. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213046. {
  213047. if (inputChannels[i])
  213048. {
  213049. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213050. ASIOChannelInfo channelInfo;
  213051. zerostruct (channelInfo);
  213052. channelInfo.channel = i;
  213053. channelInfo.isInput = 1;
  213054. asioObject->getChannelInfo (&channelInfo);
  213055. types.addIfNotAlreadyThere (channelInfo.type);
  213056. typeToFormatParameters (channelInfo.type,
  213057. inputChannelBitDepths[n],
  213058. inputChannelBytesPerSample[n],
  213059. inputChannelIsFloat[n],
  213060. inputChannelLittleEndian[n]);
  213061. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213062. ++n;
  213063. }
  213064. }
  213065. jassert (numActiveInputChans == n);
  213066. n = 0;
  213067. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213068. {
  213069. if (outputChannels[i])
  213070. {
  213071. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213072. ASIOChannelInfo channelInfo;
  213073. zerostruct (channelInfo);
  213074. channelInfo.channel = i;
  213075. channelInfo.isInput = 0;
  213076. asioObject->getChannelInfo (&channelInfo);
  213077. types.addIfNotAlreadyThere (channelInfo.type);
  213078. typeToFormatParameters (channelInfo.type,
  213079. outputChannelBitDepths[n],
  213080. outputChannelBytesPerSample[n],
  213081. outputChannelIsFloat[n],
  213082. outputChannelLittleEndian[n]);
  213083. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213084. ++n;
  213085. }
  213086. }
  213087. jassert (numActiveOutputChans == n);
  213088. for (i = types.size(); --i >= 0;)
  213089. {
  213090. log ("channel format: " + String (types[i]));
  213091. }
  213092. jassert (n <= totalBuffers);
  213093. for (i = 0; i < numActiveOutputChans; ++i)
  213094. {
  213095. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213096. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213097. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213098. {
  213099. log ("!! Null buffers");
  213100. }
  213101. else
  213102. {
  213103. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213104. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213105. }
  213106. }
  213107. inputLatency = outputLatency = 0;
  213108. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213109. {
  213110. log ("ASIO - no latencies");
  213111. }
  213112. else
  213113. {
  213114. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213115. }
  213116. isOpen_ = true;
  213117. log ("starting ASIO");
  213118. calledback = false;
  213119. err = asioObject->start();
  213120. if (err != 0)
  213121. {
  213122. isOpen_ = false;
  213123. log ("ASIO - stop on failure");
  213124. Thread::sleep (10);
  213125. asioObject->stop();
  213126. error = "Can't start device";
  213127. Thread::sleep (10);
  213128. }
  213129. else
  213130. {
  213131. int count = 300;
  213132. while (--count > 0 && ! calledback)
  213133. Thread::sleep (10);
  213134. isStarted = true;
  213135. if (! calledback)
  213136. {
  213137. error = "Device didn't start correctly";
  213138. log ("ASIO didn't callback - stopping..");
  213139. asioObject->stop();
  213140. }
  213141. }
  213142. }
  213143. else
  213144. {
  213145. error = "Can't create i/o buffers";
  213146. }
  213147. }
  213148. else
  213149. {
  213150. error = "Can't set sample rate: ";
  213151. error << sampleRate;
  213152. }
  213153. if (error.isNotEmpty())
  213154. {
  213155. logError (error, err);
  213156. if (asioObject != 0 && buffersCreated)
  213157. asioObject->disposeBuffers();
  213158. Thread::sleep (20);
  213159. isStarted = false;
  213160. isOpen_ = false;
  213161. const String errorCopy (error);
  213162. close(); // (this resets the error string)
  213163. error = errorCopy;
  213164. }
  213165. needToReset = false;
  213166. isReSync = false;
  213167. return error;
  213168. }
  213169. void close()
  213170. {
  213171. error = String::empty;
  213172. stopTimer();
  213173. stop();
  213174. if (isASIOOpen && isOpen_)
  213175. {
  213176. const ScopedLock sl (callbackLock);
  213177. isOpen_ = false;
  213178. isStarted = false;
  213179. needToReset = false;
  213180. isReSync = false;
  213181. log ("ASIO - stopping");
  213182. if (asioObject != 0)
  213183. {
  213184. Thread::sleep (20);
  213185. asioObject->stop();
  213186. Thread::sleep (10);
  213187. asioObject->disposeBuffers();
  213188. }
  213189. Thread::sleep (10);
  213190. }
  213191. }
  213192. bool isOpen()
  213193. {
  213194. return isOpen_ || insideControlPanelModalLoop;
  213195. }
  213196. int getCurrentBufferSizeSamples()
  213197. {
  213198. return currentBlockSizeSamples;
  213199. }
  213200. double getCurrentSampleRate()
  213201. {
  213202. return currentSampleRate;
  213203. }
  213204. const BigInteger getActiveOutputChannels() const
  213205. {
  213206. return currentChansOut;
  213207. }
  213208. const BigInteger getActiveInputChannels() const
  213209. {
  213210. return currentChansIn;
  213211. }
  213212. int getCurrentBitDepth()
  213213. {
  213214. return currentBitDepth;
  213215. }
  213216. int getOutputLatencyInSamples()
  213217. {
  213218. return outputLatency + currentBlockSizeSamples / 4;
  213219. }
  213220. int getInputLatencyInSamples()
  213221. {
  213222. return inputLatency + currentBlockSizeSamples / 4;
  213223. }
  213224. void start (AudioIODeviceCallback* callback)
  213225. {
  213226. if (callback != 0)
  213227. {
  213228. callback->audioDeviceAboutToStart (this);
  213229. const ScopedLock sl (callbackLock);
  213230. currentCallback = callback;
  213231. }
  213232. }
  213233. void stop()
  213234. {
  213235. AudioIODeviceCallback* const lastCallback = currentCallback;
  213236. {
  213237. const ScopedLock sl (callbackLock);
  213238. currentCallback = 0;
  213239. }
  213240. if (lastCallback != 0)
  213241. lastCallback->audioDeviceStopped();
  213242. }
  213243. bool isPlaying()
  213244. {
  213245. return isASIOOpen && (currentCallback != 0);
  213246. }
  213247. const String getLastError()
  213248. {
  213249. return error;
  213250. }
  213251. bool hasControlPanel() const
  213252. {
  213253. return true;
  213254. }
  213255. bool showControlPanel()
  213256. {
  213257. log ("ASIO - showing control panel");
  213258. Component modalWindow (String::empty);
  213259. modalWindow.setOpaque (true);
  213260. modalWindow.addToDesktop (0);
  213261. modalWindow.enterModalState();
  213262. bool done = false;
  213263. JUCE_TRY
  213264. {
  213265. // are there are devices that need to be closed before showing their control panel?
  213266. // close();
  213267. insideControlPanelModalLoop = true;
  213268. const uint32 started = Time::getMillisecondCounter();
  213269. if (asioObject != 0)
  213270. {
  213271. asioObject->controlPanel();
  213272. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213273. log ("spent: " + String (spent));
  213274. if (spent > 300)
  213275. {
  213276. shouldUsePreferredSize = true;
  213277. done = true;
  213278. }
  213279. }
  213280. }
  213281. JUCE_CATCH_ALL
  213282. insideControlPanelModalLoop = false;
  213283. return done;
  213284. }
  213285. void resetRequest() throw()
  213286. {
  213287. needToReset = true;
  213288. }
  213289. void resyncRequest() throw()
  213290. {
  213291. needToReset = true;
  213292. isReSync = true;
  213293. }
  213294. void timerCallback()
  213295. {
  213296. if (! insideControlPanelModalLoop)
  213297. {
  213298. stopTimer();
  213299. // used to cause a reset
  213300. log ("! ASIO restart request!");
  213301. if (isOpen_)
  213302. {
  213303. AudioIODeviceCallback* const oldCallback = currentCallback;
  213304. close();
  213305. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213306. currentSampleRate, currentBlockSizeSamples);
  213307. if (oldCallback != 0)
  213308. start (oldCallback);
  213309. }
  213310. }
  213311. else
  213312. {
  213313. startTimer (100);
  213314. }
  213315. }
  213316. juce_UseDebuggingNewOperator
  213317. private:
  213318. IASIO* volatile asioObject;
  213319. ASIOCallbacks callbacks;
  213320. void* windowHandle;
  213321. CLSID classId;
  213322. const String optionalDllForDirectLoading;
  213323. String error;
  213324. long totalNumInputChans, totalNumOutputChans;
  213325. StringArray inputChannelNames, outputChannelNames;
  213326. Array<int> sampleRates, bufferSizes;
  213327. long inputLatency, outputLatency;
  213328. long minSize, maxSize, preferredSize, granularity;
  213329. int volatile currentBlockSizeSamples;
  213330. int volatile currentBitDepth;
  213331. double volatile currentSampleRate;
  213332. BigInteger currentChansOut, currentChansIn;
  213333. AudioIODeviceCallback* volatile currentCallback;
  213334. CriticalSection callbackLock;
  213335. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213336. float* inBuffers [maxASIOChannels];
  213337. float* outBuffers [maxASIOChannels];
  213338. int inputChannelBitDepths [maxASIOChannels];
  213339. int outputChannelBitDepths [maxASIOChannels];
  213340. int inputChannelBytesPerSample [maxASIOChannels];
  213341. int outputChannelBytesPerSample [maxASIOChannels];
  213342. bool inputChannelIsFloat [maxASIOChannels];
  213343. bool outputChannelIsFloat [maxASIOChannels];
  213344. bool inputChannelLittleEndian [maxASIOChannels];
  213345. bool outputChannelLittleEndian [maxASIOChannels];
  213346. WaitableEvent event1;
  213347. HeapBlock <float> tempBuffer;
  213348. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213349. bool isOpen_, isStarted;
  213350. bool volatile isASIOOpen;
  213351. bool volatile calledback;
  213352. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213353. bool volatile insideControlPanelModalLoop;
  213354. bool volatile shouldUsePreferredSize;
  213355. void removeCurrentDriver()
  213356. {
  213357. if (asioObject != 0)
  213358. {
  213359. asioObject->Release();
  213360. asioObject = 0;
  213361. }
  213362. }
  213363. bool loadDriver()
  213364. {
  213365. removeCurrentDriver();
  213366. JUCE_TRY
  213367. {
  213368. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213369. classId, (void**) &asioObject) == S_OK)
  213370. {
  213371. return true;
  213372. }
  213373. // If a class isn't registered but we have a path for it, we can fallback to
  213374. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213375. if (optionalDllForDirectLoading.isNotEmpty())
  213376. {
  213377. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213378. if (h != 0)
  213379. {
  213380. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213381. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213382. if (dllGetClassObject != 0)
  213383. {
  213384. IClassFactory* classFactory = 0;
  213385. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213386. if (classFactory != 0)
  213387. {
  213388. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213389. classFactory->Release();
  213390. }
  213391. return asioObject != 0;
  213392. }
  213393. }
  213394. }
  213395. }
  213396. JUCE_CATCH_ALL
  213397. asioObject = 0;
  213398. return false;
  213399. }
  213400. const String initDriver()
  213401. {
  213402. if (asioObject != 0)
  213403. {
  213404. char buffer [256];
  213405. zeromem (buffer, sizeof (buffer));
  213406. if (! asioObject->init (windowHandle))
  213407. {
  213408. asioObject->getErrorMessage (buffer);
  213409. return String (buffer, sizeof (buffer) - 1);
  213410. }
  213411. // just in case any daft drivers expect this to be called..
  213412. asioObject->getDriverName (buffer);
  213413. return String::empty;
  213414. }
  213415. return "No Driver";
  213416. }
  213417. const String openDevice()
  213418. {
  213419. // use this in case the driver starts opening dialog boxes..
  213420. Component modalWindow (String::empty);
  213421. modalWindow.setOpaque (true);
  213422. modalWindow.addToDesktop (0);
  213423. modalWindow.enterModalState();
  213424. // open the device and get its info..
  213425. log ("opening ASIO device: " + getName());
  213426. needToReset = false;
  213427. isReSync = false;
  213428. outputChannelNames.clear();
  213429. inputChannelNames.clear();
  213430. bufferSizes.clear();
  213431. sampleRates.clear();
  213432. isASIOOpen = false;
  213433. isOpen_ = false;
  213434. totalNumInputChans = 0;
  213435. totalNumOutputChans = 0;
  213436. numActiveInputChans = 0;
  213437. numActiveOutputChans = 0;
  213438. currentCallback = 0;
  213439. error = String::empty;
  213440. if (getName().isEmpty())
  213441. return error;
  213442. long err = 0;
  213443. if (loadDriver())
  213444. {
  213445. if ((error = initDriver()).isEmpty())
  213446. {
  213447. numActiveInputChans = 0;
  213448. numActiveOutputChans = 0;
  213449. totalNumInputChans = 0;
  213450. totalNumOutputChans = 0;
  213451. if (asioObject != 0
  213452. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213453. {
  213454. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213455. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213456. {
  213457. // find a list of buffer sizes..
  213458. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213459. if (granularity >= 0)
  213460. {
  213461. granularity = jmax (1, (int) granularity);
  213462. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213463. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213464. }
  213465. else if (granularity < 0)
  213466. {
  213467. for (int i = 0; i < 18; ++i)
  213468. {
  213469. const int s = (1 << i);
  213470. if (s >= minSize && s <= maxSize)
  213471. bufferSizes.add (s);
  213472. }
  213473. }
  213474. if (! bufferSizes.contains (preferredSize))
  213475. bufferSizes.insert (0, preferredSize);
  213476. double currentRate = 0;
  213477. asioObject->getSampleRate (&currentRate);
  213478. if (currentRate <= 0.0 || currentRate > 192001.0)
  213479. {
  213480. log ("setting sample rate");
  213481. err = asioObject->setSampleRate (44100.0);
  213482. if (err != 0)
  213483. {
  213484. logError ("setting sample rate", err);
  213485. }
  213486. asioObject->getSampleRate (&currentRate);
  213487. }
  213488. currentSampleRate = currentRate;
  213489. postOutput = (asioObject->outputReady() == 0);
  213490. if (postOutput)
  213491. {
  213492. log ("ASIO outputReady = ok");
  213493. }
  213494. updateSampleRates();
  213495. // ..because cubase does it at this point
  213496. inputLatency = outputLatency = 0;
  213497. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213498. {
  213499. log ("ASIO - no latencies");
  213500. }
  213501. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213502. // create some dummy buffers now.. because cubase does..
  213503. numActiveInputChans = 0;
  213504. numActiveOutputChans = 0;
  213505. ASIOBufferInfo* info = bufferInfos;
  213506. int i, numChans = 0;
  213507. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213508. {
  213509. info->isInput = 1;
  213510. info->channelNum = i;
  213511. info->buffers[0] = info->buffers[1] = 0;
  213512. ++info;
  213513. ++numChans;
  213514. }
  213515. const int outputBufferIndex = numChans;
  213516. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213517. {
  213518. info->isInput = 0;
  213519. info->channelNum = i;
  213520. info->buffers[0] = info->buffers[1] = 0;
  213521. ++info;
  213522. ++numChans;
  213523. }
  213524. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213525. if (currentASIODev[0] == this)
  213526. {
  213527. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213528. callbacks.asioMessage = &asioMessagesCallback0;
  213529. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213530. }
  213531. else if (currentASIODev[1] == this)
  213532. {
  213533. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213534. callbacks.asioMessage = &asioMessagesCallback1;
  213535. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213536. }
  213537. else if (currentASIODev[2] == this)
  213538. {
  213539. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213540. callbacks.asioMessage = &asioMessagesCallback2;
  213541. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213542. }
  213543. else
  213544. {
  213545. jassertfalse;
  213546. }
  213547. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213548. if (preferredSize > 0)
  213549. {
  213550. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213551. if (err != 0)
  213552. {
  213553. logError ("dummy buffers", err);
  213554. }
  213555. }
  213556. long newInps = 0, newOuts = 0;
  213557. asioObject->getChannels (&newInps, &newOuts);
  213558. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213559. {
  213560. totalNumInputChans = newInps;
  213561. totalNumOutputChans = newOuts;
  213562. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213563. }
  213564. updateSampleRates();
  213565. ASIOChannelInfo channelInfo;
  213566. channelInfo.type = 0;
  213567. for (i = 0; i < totalNumInputChans; ++i)
  213568. {
  213569. zerostruct (channelInfo);
  213570. channelInfo.channel = i;
  213571. channelInfo.isInput = 1;
  213572. asioObject->getChannelInfo (&channelInfo);
  213573. inputChannelNames.add (String (channelInfo.name));
  213574. }
  213575. for (i = 0; i < totalNumOutputChans; ++i)
  213576. {
  213577. zerostruct (channelInfo);
  213578. channelInfo.channel = i;
  213579. channelInfo.isInput = 0;
  213580. asioObject->getChannelInfo (&channelInfo);
  213581. outputChannelNames.add (String (channelInfo.name));
  213582. typeToFormatParameters (channelInfo.type,
  213583. outputChannelBitDepths[i],
  213584. outputChannelBytesPerSample[i],
  213585. outputChannelIsFloat[i],
  213586. outputChannelLittleEndian[i]);
  213587. if (i < 2)
  213588. {
  213589. // clear the channels that are used with the dummy stuff
  213590. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213591. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213592. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213593. }
  213594. }
  213595. outputChannelNames.trim();
  213596. inputChannelNames.trim();
  213597. outputChannelNames.appendNumbersToDuplicates (false, true);
  213598. inputChannelNames.appendNumbersToDuplicates (false, true);
  213599. // start and stop because cubase does it..
  213600. asioObject->getLatencies (&inputLatency, &outputLatency);
  213601. if ((err = asioObject->start()) != 0)
  213602. {
  213603. // ignore an error here, as it might start later after setting other stuff up
  213604. logError ("ASIO start", err);
  213605. }
  213606. Thread::sleep (100);
  213607. asioObject->stop();
  213608. }
  213609. else
  213610. {
  213611. error = "Can't detect buffer sizes";
  213612. }
  213613. }
  213614. else
  213615. {
  213616. error = "Can't detect asio channels";
  213617. }
  213618. }
  213619. }
  213620. else
  213621. {
  213622. error = "No such device";
  213623. }
  213624. if (error.isNotEmpty())
  213625. {
  213626. logError (error, err);
  213627. if (asioObject != 0)
  213628. asioObject->disposeBuffers();
  213629. removeCurrentDriver();
  213630. isASIOOpen = false;
  213631. }
  213632. else
  213633. {
  213634. isASIOOpen = true;
  213635. log ("ASIO device open");
  213636. }
  213637. isOpen_ = false;
  213638. needToReset = false;
  213639. isReSync = false;
  213640. return error;
  213641. }
  213642. void callback (const long index)
  213643. {
  213644. if (isStarted)
  213645. {
  213646. bufferIndex = index;
  213647. processBuffer();
  213648. }
  213649. else
  213650. {
  213651. if (postOutput && (asioObject != 0))
  213652. asioObject->outputReady();
  213653. }
  213654. calledback = true;
  213655. }
  213656. void processBuffer()
  213657. {
  213658. const ASIOBufferInfo* const infos = bufferInfos;
  213659. const int bi = bufferIndex;
  213660. const ScopedLock sl (callbackLock);
  213661. if (needToReset)
  213662. {
  213663. needToReset = false;
  213664. if (isReSync)
  213665. {
  213666. log ("! ASIO resync");
  213667. isReSync = false;
  213668. }
  213669. else
  213670. {
  213671. startTimer (20);
  213672. }
  213673. }
  213674. if (bi >= 0)
  213675. {
  213676. const int samps = currentBlockSizeSamples;
  213677. if (currentCallback != 0)
  213678. {
  213679. int i;
  213680. for (i = 0; i < numActiveInputChans; ++i)
  213681. {
  213682. float* const dst = inBuffers[i];
  213683. jassert (dst != 0);
  213684. const char* const src = (const char*) (infos[i].buffers[bi]);
  213685. if (inputChannelIsFloat[i])
  213686. {
  213687. memcpy (dst, src, samps * sizeof (float));
  213688. }
  213689. else
  213690. {
  213691. jassert (dst == tempBuffer + (samps * i));
  213692. switch (inputChannelBitDepths[i])
  213693. {
  213694. case 16:
  213695. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213696. samps, inputChannelLittleEndian[i]);
  213697. break;
  213698. case 24:
  213699. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213700. samps, inputChannelLittleEndian[i]);
  213701. break;
  213702. case 32:
  213703. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213704. samps, inputChannelLittleEndian[i]);
  213705. break;
  213706. case 64:
  213707. jassertfalse;
  213708. break;
  213709. }
  213710. }
  213711. }
  213712. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213713. numActiveInputChans,
  213714. outBuffers,
  213715. numActiveOutputChans,
  213716. samps);
  213717. for (i = 0; i < numActiveOutputChans; ++i)
  213718. {
  213719. float* const src = outBuffers[i];
  213720. jassert (src != 0);
  213721. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213722. if (outputChannelIsFloat[i])
  213723. {
  213724. memcpy (dst, src, samps * sizeof (float));
  213725. }
  213726. else
  213727. {
  213728. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213729. switch (outputChannelBitDepths[i])
  213730. {
  213731. case 16:
  213732. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213733. samps, outputChannelLittleEndian[i]);
  213734. break;
  213735. case 24:
  213736. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213737. samps, outputChannelLittleEndian[i]);
  213738. break;
  213739. case 32:
  213740. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213741. samps, outputChannelLittleEndian[i]);
  213742. break;
  213743. case 64:
  213744. jassertfalse;
  213745. break;
  213746. }
  213747. }
  213748. }
  213749. }
  213750. else
  213751. {
  213752. for (int i = 0; i < numActiveOutputChans; ++i)
  213753. {
  213754. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213755. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213756. }
  213757. }
  213758. }
  213759. if (postOutput)
  213760. asioObject->outputReady();
  213761. }
  213762. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213763. {
  213764. if (currentASIODev[0] != 0)
  213765. currentASIODev[0]->callback (index);
  213766. return 0;
  213767. }
  213768. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213769. {
  213770. if (currentASIODev[1] != 0)
  213771. currentASIODev[1]->callback (index);
  213772. return 0;
  213773. }
  213774. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213775. {
  213776. if (currentASIODev[2] != 0)
  213777. currentASIODev[2]->callback (index);
  213778. return 0;
  213779. }
  213780. static void bufferSwitchCallback0 (long index, long)
  213781. {
  213782. if (currentASIODev[0] != 0)
  213783. currentASIODev[0]->callback (index);
  213784. }
  213785. static void bufferSwitchCallback1 (long index, long)
  213786. {
  213787. if (currentASIODev[1] != 0)
  213788. currentASIODev[1]->callback (index);
  213789. }
  213790. static void bufferSwitchCallback2 (long index, long)
  213791. {
  213792. if (currentASIODev[2] != 0)
  213793. currentASIODev[2]->callback (index);
  213794. }
  213795. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213796. {
  213797. return asioMessagesCallback (selector, value, 0);
  213798. }
  213799. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213800. {
  213801. return asioMessagesCallback (selector, value, 1);
  213802. }
  213803. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213804. {
  213805. return asioMessagesCallback (selector, value, 2);
  213806. }
  213807. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213808. {
  213809. switch (selector)
  213810. {
  213811. case kAsioSelectorSupported:
  213812. if (value == kAsioResetRequest
  213813. || value == kAsioEngineVersion
  213814. || value == kAsioResyncRequest
  213815. || value == kAsioLatenciesChanged
  213816. || value == kAsioSupportsInputMonitor)
  213817. return 1;
  213818. break;
  213819. case kAsioBufferSizeChange:
  213820. break;
  213821. case kAsioResetRequest:
  213822. if (currentASIODev[deviceIndex] != 0)
  213823. currentASIODev[deviceIndex]->resetRequest();
  213824. return 1;
  213825. case kAsioResyncRequest:
  213826. if (currentASIODev[deviceIndex] != 0)
  213827. currentASIODev[deviceIndex]->resyncRequest();
  213828. return 1;
  213829. case kAsioLatenciesChanged:
  213830. return 1;
  213831. case kAsioEngineVersion:
  213832. return 2;
  213833. case kAsioSupportsTimeInfo:
  213834. case kAsioSupportsTimeCode:
  213835. return 0;
  213836. }
  213837. return 0;
  213838. }
  213839. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  213840. {
  213841. }
  213842. static void convertInt16ToFloat (const char* src,
  213843. float* dest,
  213844. const int srcStrideBytes,
  213845. int numSamples,
  213846. const bool littleEndian) throw()
  213847. {
  213848. const double g = 1.0 / 32768.0;
  213849. if (littleEndian)
  213850. {
  213851. while (--numSamples >= 0)
  213852. {
  213853. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213854. src += srcStrideBytes;
  213855. }
  213856. }
  213857. else
  213858. {
  213859. while (--numSamples >= 0)
  213860. {
  213861. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213862. src += srcStrideBytes;
  213863. }
  213864. }
  213865. }
  213866. static void convertFloatToInt16 (const float* src,
  213867. char* dest,
  213868. const int dstStrideBytes,
  213869. int numSamples,
  213870. const bool littleEndian) throw()
  213871. {
  213872. const double maxVal = (double) 0x7fff;
  213873. if (littleEndian)
  213874. {
  213875. while (--numSamples >= 0)
  213876. {
  213877. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213878. dest += dstStrideBytes;
  213879. }
  213880. }
  213881. else
  213882. {
  213883. while (--numSamples >= 0)
  213884. {
  213885. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213886. dest += dstStrideBytes;
  213887. }
  213888. }
  213889. }
  213890. static void convertInt24ToFloat (const char* src,
  213891. float* dest,
  213892. const int srcStrideBytes,
  213893. int numSamples,
  213894. const bool littleEndian) throw()
  213895. {
  213896. const double g = 1.0 / 0x7fffff;
  213897. if (littleEndian)
  213898. {
  213899. while (--numSamples >= 0)
  213900. {
  213901. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213902. src += srcStrideBytes;
  213903. }
  213904. }
  213905. else
  213906. {
  213907. while (--numSamples >= 0)
  213908. {
  213909. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213910. src += srcStrideBytes;
  213911. }
  213912. }
  213913. }
  213914. static void convertFloatToInt24 (const float* src,
  213915. char* dest,
  213916. const int dstStrideBytes,
  213917. int numSamples,
  213918. const bool littleEndian) throw()
  213919. {
  213920. const double maxVal = (double) 0x7fffff;
  213921. if (littleEndian)
  213922. {
  213923. while (--numSamples >= 0)
  213924. {
  213925. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213926. dest += dstStrideBytes;
  213927. }
  213928. }
  213929. else
  213930. {
  213931. while (--numSamples >= 0)
  213932. {
  213933. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213934. dest += dstStrideBytes;
  213935. }
  213936. }
  213937. }
  213938. static void convertInt32ToFloat (const char* src,
  213939. float* dest,
  213940. const int srcStrideBytes,
  213941. int numSamples,
  213942. const bool littleEndian) throw()
  213943. {
  213944. const double g = 1.0 / 0x7fffffff;
  213945. if (littleEndian)
  213946. {
  213947. while (--numSamples >= 0)
  213948. {
  213949. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213950. src += srcStrideBytes;
  213951. }
  213952. }
  213953. else
  213954. {
  213955. while (--numSamples >= 0)
  213956. {
  213957. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213958. src += srcStrideBytes;
  213959. }
  213960. }
  213961. }
  213962. static void convertFloatToInt32 (const float* src,
  213963. char* dest,
  213964. const int dstStrideBytes,
  213965. int numSamples,
  213966. const bool littleEndian) throw()
  213967. {
  213968. const double maxVal = (double) 0x7fffffff;
  213969. if (littleEndian)
  213970. {
  213971. while (--numSamples >= 0)
  213972. {
  213973. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213974. dest += dstStrideBytes;
  213975. }
  213976. }
  213977. else
  213978. {
  213979. while (--numSamples >= 0)
  213980. {
  213981. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213982. dest += dstStrideBytes;
  213983. }
  213984. }
  213985. }
  213986. static void typeToFormatParameters (const long type,
  213987. int& bitDepth,
  213988. int& byteStride,
  213989. bool& formatIsFloat,
  213990. bool& littleEndian) throw()
  213991. {
  213992. bitDepth = 0;
  213993. littleEndian = false;
  213994. formatIsFloat = false;
  213995. switch (type)
  213996. {
  213997. case ASIOSTInt16MSB:
  213998. case ASIOSTInt16LSB:
  213999. case ASIOSTInt32MSB16:
  214000. case ASIOSTInt32LSB16:
  214001. bitDepth = 16; break;
  214002. case ASIOSTFloat32MSB:
  214003. case ASIOSTFloat32LSB:
  214004. formatIsFloat = true;
  214005. bitDepth = 32; break;
  214006. case ASIOSTInt32MSB:
  214007. case ASIOSTInt32LSB:
  214008. bitDepth = 32; break;
  214009. case ASIOSTInt24MSB:
  214010. case ASIOSTInt24LSB:
  214011. case ASIOSTInt32MSB24:
  214012. case ASIOSTInt32LSB24:
  214013. case ASIOSTInt32MSB18:
  214014. case ASIOSTInt32MSB20:
  214015. case ASIOSTInt32LSB18:
  214016. case ASIOSTInt32LSB20:
  214017. bitDepth = 24; break;
  214018. case ASIOSTFloat64MSB:
  214019. case ASIOSTFloat64LSB:
  214020. default:
  214021. bitDepth = 64;
  214022. break;
  214023. }
  214024. switch (type)
  214025. {
  214026. case ASIOSTInt16MSB:
  214027. case ASIOSTInt32MSB16:
  214028. case ASIOSTFloat32MSB:
  214029. case ASIOSTFloat64MSB:
  214030. case ASIOSTInt32MSB:
  214031. case ASIOSTInt32MSB18:
  214032. case ASIOSTInt32MSB20:
  214033. case ASIOSTInt32MSB24:
  214034. case ASIOSTInt24MSB:
  214035. littleEndian = false; break;
  214036. case ASIOSTInt16LSB:
  214037. case ASIOSTInt32LSB16:
  214038. case ASIOSTFloat32LSB:
  214039. case ASIOSTFloat64LSB:
  214040. case ASIOSTInt32LSB:
  214041. case ASIOSTInt32LSB18:
  214042. case ASIOSTInt32LSB20:
  214043. case ASIOSTInt32LSB24:
  214044. case ASIOSTInt24LSB:
  214045. littleEndian = true; break;
  214046. default:
  214047. break;
  214048. }
  214049. switch (type)
  214050. {
  214051. case ASIOSTInt16LSB:
  214052. case ASIOSTInt16MSB:
  214053. byteStride = 2; break;
  214054. case ASIOSTInt24LSB:
  214055. case ASIOSTInt24MSB:
  214056. byteStride = 3; break;
  214057. case ASIOSTInt32MSB16:
  214058. case ASIOSTInt32LSB16:
  214059. case ASIOSTInt32MSB:
  214060. case ASIOSTInt32MSB18:
  214061. case ASIOSTInt32MSB20:
  214062. case ASIOSTInt32MSB24:
  214063. case ASIOSTInt32LSB:
  214064. case ASIOSTInt32LSB18:
  214065. case ASIOSTInt32LSB20:
  214066. case ASIOSTInt32LSB24:
  214067. case ASIOSTFloat32LSB:
  214068. case ASIOSTFloat32MSB:
  214069. byteStride = 4; break;
  214070. case ASIOSTFloat64MSB:
  214071. case ASIOSTFloat64LSB:
  214072. byteStride = 8; break;
  214073. default:
  214074. break;
  214075. }
  214076. }
  214077. };
  214078. class ASIOAudioIODeviceType : public AudioIODeviceType
  214079. {
  214080. public:
  214081. ASIOAudioIODeviceType()
  214082. : AudioIODeviceType ("ASIO"),
  214083. hasScanned (false)
  214084. {
  214085. CoInitialize (0);
  214086. }
  214087. ~ASIOAudioIODeviceType()
  214088. {
  214089. }
  214090. void scanForDevices()
  214091. {
  214092. hasScanned = true;
  214093. deviceNames.clear();
  214094. classIds.clear();
  214095. HKEY hk = 0;
  214096. int index = 0;
  214097. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214098. {
  214099. for (;;)
  214100. {
  214101. char name [256];
  214102. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214103. {
  214104. addDriverInfo (name, hk);
  214105. }
  214106. else
  214107. {
  214108. break;
  214109. }
  214110. }
  214111. RegCloseKey (hk);
  214112. }
  214113. }
  214114. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214115. {
  214116. jassert (hasScanned); // need to call scanForDevices() before doing this
  214117. return deviceNames;
  214118. }
  214119. int getDefaultDeviceIndex (bool) const
  214120. {
  214121. jassert (hasScanned); // need to call scanForDevices() before doing this
  214122. for (int i = deviceNames.size(); --i >= 0;)
  214123. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214124. return i; // asio4all is a safe choice for a default..
  214125. #if JUCE_DEBUG
  214126. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214127. return 1; // (the digi m-box driver crashes the app when you run
  214128. // it in the debugger, which can be a bit annoying)
  214129. #endif
  214130. return 0;
  214131. }
  214132. static int findFreeSlot()
  214133. {
  214134. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214135. if (currentASIODev[i] == 0)
  214136. return i;
  214137. jassertfalse; // unfortunately you can only have a finite number
  214138. // of ASIO devices open at the same time..
  214139. return -1;
  214140. }
  214141. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214142. {
  214143. jassert (hasScanned); // need to call scanForDevices() before doing this
  214144. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214145. }
  214146. bool hasSeparateInputsAndOutputs() const { return false; }
  214147. AudioIODevice* createDevice (const String& outputDeviceName,
  214148. const String& inputDeviceName)
  214149. {
  214150. // ASIO can't open two different devices for input and output - they must be the same one.
  214151. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214152. jassert (hasScanned); // need to call scanForDevices() before doing this
  214153. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214154. : inputDeviceName);
  214155. if (index >= 0)
  214156. {
  214157. const int freeSlot = findFreeSlot();
  214158. if (freeSlot >= 0)
  214159. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214160. }
  214161. return 0;
  214162. }
  214163. juce_UseDebuggingNewOperator
  214164. private:
  214165. StringArray deviceNames;
  214166. OwnedArray <CLSID> classIds;
  214167. bool hasScanned;
  214168. static bool checkClassIsOk (const String& classId)
  214169. {
  214170. HKEY hk = 0;
  214171. bool ok = false;
  214172. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214173. {
  214174. int index = 0;
  214175. for (;;)
  214176. {
  214177. WCHAR buf [512];
  214178. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214179. {
  214180. if (classId.equalsIgnoreCase (buf))
  214181. {
  214182. HKEY subKey, pathKey;
  214183. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214184. {
  214185. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214186. {
  214187. WCHAR pathName [1024];
  214188. DWORD dtype = REG_SZ;
  214189. DWORD dsize = sizeof (pathName);
  214190. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214191. ok = File (pathName).exists();
  214192. RegCloseKey (pathKey);
  214193. }
  214194. RegCloseKey (subKey);
  214195. }
  214196. break;
  214197. }
  214198. }
  214199. else
  214200. {
  214201. break;
  214202. }
  214203. }
  214204. RegCloseKey (hk);
  214205. }
  214206. return ok;
  214207. }
  214208. void addDriverInfo (const String& keyName, HKEY hk)
  214209. {
  214210. HKEY subKey;
  214211. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214212. {
  214213. WCHAR buf [256];
  214214. zerostruct (buf);
  214215. DWORD dtype = REG_SZ;
  214216. DWORD dsize = sizeof (buf);
  214217. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214218. {
  214219. if (dsize > 0 && checkClassIsOk (buf))
  214220. {
  214221. CLSID classId;
  214222. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214223. {
  214224. dtype = REG_SZ;
  214225. dsize = sizeof (buf);
  214226. String deviceName;
  214227. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214228. deviceName = buf;
  214229. else
  214230. deviceName = keyName;
  214231. log ("found " + deviceName);
  214232. deviceNames.add (deviceName);
  214233. classIds.add (new CLSID (classId));
  214234. }
  214235. }
  214236. RegCloseKey (subKey);
  214237. }
  214238. }
  214239. }
  214240. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214241. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214242. };
  214243. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214244. {
  214245. return new ASIOAudioIODeviceType();
  214246. }
  214247. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214248. void* guid,
  214249. const String& optionalDllForDirectLoading)
  214250. {
  214251. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214252. if (freeSlot < 0)
  214253. return 0;
  214254. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214255. }
  214256. #undef log
  214257. #endif
  214258. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214259. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214260. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214261. // compiled on its own).
  214262. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214263. END_JUCE_NAMESPACE
  214264. extern "C"
  214265. {
  214266. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214267. typedef struct typeDSBUFFERDESC
  214268. {
  214269. DWORD dwSize;
  214270. DWORD dwFlags;
  214271. DWORD dwBufferBytes;
  214272. DWORD dwReserved;
  214273. LPWAVEFORMATEX lpwfxFormat;
  214274. GUID guid3DAlgorithm;
  214275. } DSBUFFERDESC;
  214276. struct IDirectSoundBuffer;
  214277. #undef INTERFACE
  214278. #define INTERFACE IDirectSound
  214279. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214280. {
  214281. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214282. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214283. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214284. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214285. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214286. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214287. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214288. STDMETHOD(Compact) (THIS) PURE;
  214289. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214290. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214291. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214292. };
  214293. #undef INTERFACE
  214294. #define INTERFACE IDirectSoundBuffer
  214295. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214296. {
  214297. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214298. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214299. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214300. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214301. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214302. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214303. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214304. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214305. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214306. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214307. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214308. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214309. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214310. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214311. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214312. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214313. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214314. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214315. STDMETHOD(Stop) (THIS) PURE;
  214316. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214317. STDMETHOD(Restore) (THIS) PURE;
  214318. };
  214319. typedef struct typeDSCBUFFERDESC
  214320. {
  214321. DWORD dwSize;
  214322. DWORD dwFlags;
  214323. DWORD dwBufferBytes;
  214324. DWORD dwReserved;
  214325. LPWAVEFORMATEX lpwfxFormat;
  214326. } DSCBUFFERDESC;
  214327. struct IDirectSoundCaptureBuffer;
  214328. #undef INTERFACE
  214329. #define INTERFACE IDirectSoundCapture
  214330. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214331. {
  214332. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214333. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214334. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214335. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214336. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214337. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214338. };
  214339. #undef INTERFACE
  214340. #define INTERFACE IDirectSoundCaptureBuffer
  214341. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214342. {
  214343. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214344. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214345. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214346. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214347. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214348. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214349. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214350. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214351. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214352. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214353. STDMETHOD(Stop) (THIS) PURE;
  214354. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214355. };
  214356. };
  214357. BEGIN_JUCE_NAMESPACE
  214358. static const String getDSErrorMessage (HRESULT hr)
  214359. {
  214360. const char* result = 0;
  214361. switch (hr)
  214362. {
  214363. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214364. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214365. case E_INVALIDARG: result = "Invalid parameter"; break;
  214366. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214367. case E_FAIL: result = "Generic error"; break;
  214368. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214369. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214370. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214371. case E_NOTIMPL: result = "Unsupported function"; break;
  214372. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214373. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214374. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214375. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214376. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214377. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214378. case E_NOINTERFACE: result = "No interface"; break;
  214379. case S_OK: result = "No error"; break;
  214380. default: return "Unknown error: " + String ((int) hr);
  214381. }
  214382. return result;
  214383. }
  214384. #define DS_DEBUGGING 1
  214385. #ifdef DS_DEBUGGING
  214386. #define CATCH JUCE_CATCH_EXCEPTION
  214387. #undef log
  214388. #define log(a) Logger::writeToLog(a);
  214389. #undef logError
  214390. #define logError(a) logDSError(a, __LINE__);
  214391. static void logDSError (HRESULT hr, int lineNum)
  214392. {
  214393. if (hr != S_OK)
  214394. {
  214395. String error ("DS error at line ");
  214396. error << lineNum << " - " << getDSErrorMessage (hr);
  214397. log (error);
  214398. }
  214399. }
  214400. #else
  214401. #define CATCH JUCE_CATCH_ALL
  214402. #define log(a)
  214403. #define logError(a)
  214404. #endif
  214405. #define DSOUND_FUNCTION(functionName, params) \
  214406. typedef HRESULT (WINAPI *type##functionName) params; \
  214407. static type##functionName ds##functionName = 0;
  214408. #define DSOUND_FUNCTION_LOAD(functionName) \
  214409. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214410. jassert (ds##functionName != 0);
  214411. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214412. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214413. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214414. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214415. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214416. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214417. static void initialiseDSoundFunctions()
  214418. {
  214419. if (dsDirectSoundCreate == 0)
  214420. {
  214421. HMODULE h = LoadLibraryA ("dsound.dll");
  214422. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214423. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214424. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214425. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214426. }
  214427. }
  214428. class DSoundInternalOutChannel
  214429. {
  214430. String name;
  214431. LPGUID guid;
  214432. int sampleRate, bufferSizeSamples;
  214433. float* leftBuffer;
  214434. float* rightBuffer;
  214435. IDirectSound* pDirectSound;
  214436. IDirectSoundBuffer* pOutputBuffer;
  214437. DWORD writeOffset;
  214438. int totalBytesPerBuffer;
  214439. int bytesPerBuffer;
  214440. unsigned int lastPlayCursor;
  214441. public:
  214442. int bitDepth;
  214443. bool doneFlag;
  214444. DSoundInternalOutChannel (const String& name_,
  214445. LPGUID guid_,
  214446. int rate,
  214447. int bufferSize,
  214448. float* left,
  214449. float* right)
  214450. : name (name_),
  214451. guid (guid_),
  214452. sampleRate (rate),
  214453. bufferSizeSamples (bufferSize),
  214454. leftBuffer (left),
  214455. rightBuffer (right),
  214456. pDirectSound (0),
  214457. pOutputBuffer (0),
  214458. bitDepth (16)
  214459. {
  214460. }
  214461. ~DSoundInternalOutChannel()
  214462. {
  214463. close();
  214464. }
  214465. void close()
  214466. {
  214467. HRESULT hr;
  214468. if (pOutputBuffer != 0)
  214469. {
  214470. JUCE_TRY
  214471. {
  214472. log ("closing dsound out: " + name);
  214473. hr = pOutputBuffer->Stop();
  214474. logError (hr);
  214475. }
  214476. CATCH
  214477. JUCE_TRY
  214478. {
  214479. hr = pOutputBuffer->Release();
  214480. logError (hr);
  214481. }
  214482. CATCH
  214483. pOutputBuffer = 0;
  214484. }
  214485. if (pDirectSound != 0)
  214486. {
  214487. JUCE_TRY
  214488. {
  214489. hr = pDirectSound->Release();
  214490. logError (hr);
  214491. }
  214492. CATCH
  214493. pDirectSound = 0;
  214494. }
  214495. }
  214496. const String open()
  214497. {
  214498. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214499. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214500. pDirectSound = 0;
  214501. pOutputBuffer = 0;
  214502. writeOffset = 0;
  214503. String error;
  214504. HRESULT hr = E_NOINTERFACE;
  214505. if (dsDirectSoundCreate != 0)
  214506. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214507. if (hr == S_OK)
  214508. {
  214509. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214510. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214511. const int numChannels = 2;
  214512. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214513. logError (hr);
  214514. if (hr == S_OK)
  214515. {
  214516. IDirectSoundBuffer* pPrimaryBuffer;
  214517. DSBUFFERDESC primaryDesc;
  214518. zerostruct (primaryDesc);
  214519. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214520. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214521. primaryDesc.dwBufferBytes = 0;
  214522. primaryDesc.lpwfxFormat = 0;
  214523. log ("opening dsound out step 2");
  214524. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214525. logError (hr);
  214526. if (hr == S_OK)
  214527. {
  214528. WAVEFORMATEX wfFormat;
  214529. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214530. wfFormat.nChannels = (unsigned short) numChannels;
  214531. wfFormat.nSamplesPerSec = sampleRate;
  214532. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214533. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214534. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214535. wfFormat.cbSize = 0;
  214536. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214537. logError (hr);
  214538. if (hr == S_OK)
  214539. {
  214540. DSBUFFERDESC secondaryDesc;
  214541. zerostruct (secondaryDesc);
  214542. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214543. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214544. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214545. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214546. secondaryDesc.lpwfxFormat = &wfFormat;
  214547. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214548. logError (hr);
  214549. if (hr == S_OK)
  214550. {
  214551. log ("opening dsound out step 3");
  214552. DWORD dwDataLen;
  214553. unsigned char* pDSBuffData;
  214554. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214555. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214556. logError (hr);
  214557. if (hr == S_OK)
  214558. {
  214559. zeromem (pDSBuffData, dwDataLen);
  214560. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214561. if (hr == S_OK)
  214562. {
  214563. hr = pOutputBuffer->SetCurrentPosition (0);
  214564. if (hr == S_OK)
  214565. {
  214566. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214567. if (hr == S_OK)
  214568. return String::empty;
  214569. }
  214570. }
  214571. }
  214572. }
  214573. }
  214574. }
  214575. }
  214576. }
  214577. error = getDSErrorMessage (hr);
  214578. close();
  214579. return error;
  214580. }
  214581. void synchronisePosition()
  214582. {
  214583. if (pOutputBuffer != 0)
  214584. {
  214585. DWORD playCursor;
  214586. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214587. }
  214588. }
  214589. bool service()
  214590. {
  214591. if (pOutputBuffer == 0)
  214592. return true;
  214593. DWORD playCursor, writeCursor;
  214594. for (;;)
  214595. {
  214596. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214597. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214598. {
  214599. pOutputBuffer->Restore();
  214600. continue;
  214601. }
  214602. if (hr == S_OK)
  214603. break;
  214604. logError (hr);
  214605. jassertfalse;
  214606. return true;
  214607. }
  214608. int playWriteGap = writeCursor - playCursor;
  214609. if (playWriteGap < 0)
  214610. playWriteGap += totalBytesPerBuffer;
  214611. int bytesEmpty = playCursor - writeOffset;
  214612. if (bytesEmpty < 0)
  214613. bytesEmpty += totalBytesPerBuffer;
  214614. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214615. {
  214616. writeOffset = writeCursor;
  214617. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214618. }
  214619. if (bytesEmpty >= bytesPerBuffer)
  214620. {
  214621. void* lpbuf1 = 0;
  214622. void* lpbuf2 = 0;
  214623. DWORD dwSize1 = 0;
  214624. DWORD dwSize2 = 0;
  214625. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214626. bytesPerBuffer,
  214627. &lpbuf1, &dwSize1,
  214628. &lpbuf2, &dwSize2, 0);
  214629. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214630. {
  214631. pOutputBuffer->Restore();
  214632. hr = pOutputBuffer->Lock (writeOffset,
  214633. bytesPerBuffer,
  214634. &lpbuf1, &dwSize1,
  214635. &lpbuf2, &dwSize2, 0);
  214636. }
  214637. if (hr == S_OK)
  214638. {
  214639. if (bitDepth == 16)
  214640. {
  214641. const float gainL = 32767.0f;
  214642. const float gainR = 32767.0f;
  214643. int* dest = static_cast<int*> (lpbuf1);
  214644. const float* left = leftBuffer;
  214645. const float* right = rightBuffer;
  214646. int samples1 = dwSize1 >> 2;
  214647. int samples2 = dwSize2 >> 2;
  214648. if (left == 0)
  214649. {
  214650. while (--samples1 >= 0)
  214651. {
  214652. int r = roundToInt (gainR * *right++);
  214653. if (r < -32768)
  214654. r = -32768;
  214655. else if (r > 32767)
  214656. r = 32767;
  214657. *dest++ = (r << 16);
  214658. }
  214659. dest = static_cast<int*> (lpbuf2);
  214660. while (--samples2 >= 0)
  214661. {
  214662. int r = roundToInt (gainR * *right++);
  214663. if (r < -32768)
  214664. r = -32768;
  214665. else if (r > 32767)
  214666. r = 32767;
  214667. *dest++ = (r << 16);
  214668. }
  214669. }
  214670. else if (right == 0)
  214671. {
  214672. while (--samples1 >= 0)
  214673. {
  214674. int l = roundToInt (gainL * *left++);
  214675. if (l < -32768)
  214676. l = -32768;
  214677. else if (l > 32767)
  214678. l = 32767;
  214679. l &= 0xffff;
  214680. *dest++ = l;
  214681. }
  214682. dest = static_cast<int*> (lpbuf2);
  214683. while (--samples2 >= 0)
  214684. {
  214685. int l = roundToInt (gainL * *left++);
  214686. if (l < -32768)
  214687. l = -32768;
  214688. else if (l > 32767)
  214689. l = 32767;
  214690. l &= 0xffff;
  214691. *dest++ = l;
  214692. }
  214693. }
  214694. else
  214695. {
  214696. while (--samples1 >= 0)
  214697. {
  214698. int l = roundToInt (gainL * *left++);
  214699. if (l < -32768)
  214700. l = -32768;
  214701. else if (l > 32767)
  214702. l = 32767;
  214703. l &= 0xffff;
  214704. int r = roundToInt (gainR * *right++);
  214705. if (r < -32768)
  214706. r = -32768;
  214707. else if (r > 32767)
  214708. r = 32767;
  214709. *dest++ = (r << 16) | l;
  214710. }
  214711. dest = static_cast<int*> (lpbuf2);
  214712. while (--samples2 >= 0)
  214713. {
  214714. int l = roundToInt (gainL * *left++);
  214715. if (l < -32768)
  214716. l = -32768;
  214717. else if (l > 32767)
  214718. l = 32767;
  214719. l &= 0xffff;
  214720. int r = roundToInt (gainR * *right++);
  214721. if (r < -32768)
  214722. r = -32768;
  214723. else if (r > 32767)
  214724. r = 32767;
  214725. *dest++ = (r << 16) | l;
  214726. }
  214727. }
  214728. }
  214729. else
  214730. {
  214731. jassertfalse;
  214732. }
  214733. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214734. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214735. }
  214736. else
  214737. {
  214738. jassertfalse;
  214739. logError (hr);
  214740. }
  214741. bytesEmpty -= bytesPerBuffer;
  214742. return true;
  214743. }
  214744. else
  214745. {
  214746. return false;
  214747. }
  214748. }
  214749. };
  214750. struct DSoundInternalInChannel
  214751. {
  214752. String name;
  214753. LPGUID guid;
  214754. int sampleRate, bufferSizeSamples;
  214755. float* leftBuffer;
  214756. float* rightBuffer;
  214757. IDirectSound* pDirectSound;
  214758. IDirectSoundCapture* pDirectSoundCapture;
  214759. IDirectSoundCaptureBuffer* pInputBuffer;
  214760. public:
  214761. unsigned int readOffset;
  214762. int bytesPerBuffer, totalBytesPerBuffer;
  214763. int bitDepth;
  214764. bool doneFlag;
  214765. DSoundInternalInChannel (const String& name_,
  214766. LPGUID guid_,
  214767. int rate,
  214768. int bufferSize,
  214769. float* left,
  214770. float* right)
  214771. : name (name_),
  214772. guid (guid_),
  214773. sampleRate (rate),
  214774. bufferSizeSamples (bufferSize),
  214775. leftBuffer (left),
  214776. rightBuffer (right),
  214777. pDirectSound (0),
  214778. pDirectSoundCapture (0),
  214779. pInputBuffer (0),
  214780. bitDepth (16)
  214781. {
  214782. }
  214783. ~DSoundInternalInChannel()
  214784. {
  214785. close();
  214786. }
  214787. void close()
  214788. {
  214789. HRESULT hr;
  214790. if (pInputBuffer != 0)
  214791. {
  214792. JUCE_TRY
  214793. {
  214794. log ("closing dsound in: " + name);
  214795. hr = pInputBuffer->Stop();
  214796. logError (hr);
  214797. }
  214798. CATCH
  214799. JUCE_TRY
  214800. {
  214801. hr = pInputBuffer->Release();
  214802. logError (hr);
  214803. }
  214804. CATCH
  214805. pInputBuffer = 0;
  214806. }
  214807. if (pDirectSoundCapture != 0)
  214808. {
  214809. JUCE_TRY
  214810. {
  214811. hr = pDirectSoundCapture->Release();
  214812. logError (hr);
  214813. }
  214814. CATCH
  214815. pDirectSoundCapture = 0;
  214816. }
  214817. if (pDirectSound != 0)
  214818. {
  214819. JUCE_TRY
  214820. {
  214821. hr = pDirectSound->Release();
  214822. logError (hr);
  214823. }
  214824. CATCH
  214825. pDirectSound = 0;
  214826. }
  214827. }
  214828. const String open()
  214829. {
  214830. log ("opening dsound in device: " + name
  214831. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214832. pDirectSound = 0;
  214833. pDirectSoundCapture = 0;
  214834. pInputBuffer = 0;
  214835. readOffset = 0;
  214836. totalBytesPerBuffer = 0;
  214837. String error;
  214838. HRESULT hr = E_NOINTERFACE;
  214839. if (dsDirectSoundCaptureCreate != 0)
  214840. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214841. logError (hr);
  214842. if (hr == S_OK)
  214843. {
  214844. const int numChannels = 2;
  214845. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214846. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214847. WAVEFORMATEX wfFormat;
  214848. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214849. wfFormat.nChannels = (unsigned short)numChannels;
  214850. wfFormat.nSamplesPerSec = sampleRate;
  214851. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214852. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214853. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214854. wfFormat.cbSize = 0;
  214855. DSCBUFFERDESC captureDesc;
  214856. zerostruct (captureDesc);
  214857. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214858. captureDesc.dwFlags = 0;
  214859. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214860. captureDesc.lpwfxFormat = &wfFormat;
  214861. log ("opening dsound in step 2");
  214862. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214863. logError (hr);
  214864. if (hr == S_OK)
  214865. {
  214866. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214867. logError (hr);
  214868. if (hr == S_OK)
  214869. return String::empty;
  214870. }
  214871. }
  214872. error = getDSErrorMessage (hr);
  214873. close();
  214874. return error;
  214875. }
  214876. void synchronisePosition()
  214877. {
  214878. if (pInputBuffer != 0)
  214879. {
  214880. DWORD capturePos;
  214881. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214882. }
  214883. }
  214884. bool service()
  214885. {
  214886. if (pInputBuffer == 0)
  214887. return true;
  214888. DWORD capturePos, readPos;
  214889. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214890. logError (hr);
  214891. if (hr != S_OK)
  214892. return true;
  214893. int bytesFilled = readPos - readOffset;
  214894. if (bytesFilled < 0)
  214895. bytesFilled += totalBytesPerBuffer;
  214896. if (bytesFilled >= bytesPerBuffer)
  214897. {
  214898. LPBYTE lpbuf1 = 0;
  214899. LPBYTE lpbuf2 = 0;
  214900. DWORD dwsize1 = 0;
  214901. DWORD dwsize2 = 0;
  214902. HRESULT hr = pInputBuffer->Lock (readOffset,
  214903. bytesPerBuffer,
  214904. (void**) &lpbuf1, &dwsize1,
  214905. (void**) &lpbuf2, &dwsize2, 0);
  214906. if (hr == S_OK)
  214907. {
  214908. if (bitDepth == 16)
  214909. {
  214910. const float g = 1.0f / 32768.0f;
  214911. float* destL = leftBuffer;
  214912. float* destR = rightBuffer;
  214913. int samples1 = dwsize1 >> 2;
  214914. int samples2 = dwsize2 >> 2;
  214915. const short* src = (const short*)lpbuf1;
  214916. if (destL == 0)
  214917. {
  214918. while (--samples1 >= 0)
  214919. {
  214920. ++src;
  214921. *destR++ = *src++ * g;
  214922. }
  214923. src = (const short*)lpbuf2;
  214924. while (--samples2 >= 0)
  214925. {
  214926. ++src;
  214927. *destR++ = *src++ * g;
  214928. }
  214929. }
  214930. else if (destR == 0)
  214931. {
  214932. while (--samples1 >= 0)
  214933. {
  214934. *destL++ = *src++ * g;
  214935. ++src;
  214936. }
  214937. src = (const short*)lpbuf2;
  214938. while (--samples2 >= 0)
  214939. {
  214940. *destL++ = *src++ * g;
  214941. ++src;
  214942. }
  214943. }
  214944. else
  214945. {
  214946. while (--samples1 >= 0)
  214947. {
  214948. *destL++ = *src++ * g;
  214949. *destR++ = *src++ * g;
  214950. }
  214951. src = (const short*)lpbuf2;
  214952. while (--samples2 >= 0)
  214953. {
  214954. *destL++ = *src++ * g;
  214955. *destR++ = *src++ * g;
  214956. }
  214957. }
  214958. }
  214959. else
  214960. {
  214961. jassertfalse;
  214962. }
  214963. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214964. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214965. }
  214966. else
  214967. {
  214968. logError (hr);
  214969. jassertfalse;
  214970. }
  214971. bytesFilled -= bytesPerBuffer;
  214972. return true;
  214973. }
  214974. else
  214975. {
  214976. return false;
  214977. }
  214978. }
  214979. };
  214980. class DSoundAudioIODevice : public AudioIODevice,
  214981. public Thread
  214982. {
  214983. public:
  214984. DSoundAudioIODevice (const String& deviceName,
  214985. const int outputDeviceIndex_,
  214986. const int inputDeviceIndex_)
  214987. : AudioIODevice (deviceName, "DirectSound"),
  214988. Thread ("Juce DSound"),
  214989. isOpen_ (false),
  214990. isStarted (false),
  214991. outputDeviceIndex (outputDeviceIndex_),
  214992. inputDeviceIndex (inputDeviceIndex_),
  214993. totalSamplesOut (0),
  214994. sampleRate (0.0),
  214995. inputBuffers (1, 1),
  214996. outputBuffers (1, 1),
  214997. callback (0),
  214998. bufferSizeSamples (0)
  214999. {
  215000. if (outputDeviceIndex_ >= 0)
  215001. {
  215002. outChannels.add (TRANS("Left"));
  215003. outChannels.add (TRANS("Right"));
  215004. }
  215005. if (inputDeviceIndex_ >= 0)
  215006. {
  215007. inChannels.add (TRANS("Left"));
  215008. inChannels.add (TRANS("Right"));
  215009. }
  215010. }
  215011. ~DSoundAudioIODevice()
  215012. {
  215013. close();
  215014. }
  215015. const StringArray getOutputChannelNames()
  215016. {
  215017. return outChannels;
  215018. }
  215019. const StringArray getInputChannelNames()
  215020. {
  215021. return inChannels;
  215022. }
  215023. int getNumSampleRates()
  215024. {
  215025. return 4;
  215026. }
  215027. double getSampleRate (int index)
  215028. {
  215029. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215030. return samps [jlimit (0, 3, index)];
  215031. }
  215032. int getNumBufferSizesAvailable()
  215033. {
  215034. return 50;
  215035. }
  215036. int getBufferSizeSamples (int index)
  215037. {
  215038. int n = 64;
  215039. for (int i = 0; i < index; ++i)
  215040. n += (n < 512) ? 32
  215041. : ((n < 1024) ? 64
  215042. : ((n < 2048) ? 128 : 256));
  215043. return n;
  215044. }
  215045. int getDefaultBufferSize()
  215046. {
  215047. return 2560;
  215048. }
  215049. const String open (const BigInteger& inputChannels,
  215050. const BigInteger& outputChannels,
  215051. double sampleRate,
  215052. int bufferSizeSamples)
  215053. {
  215054. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215055. isOpen_ = lastError.isEmpty();
  215056. return lastError;
  215057. }
  215058. void close()
  215059. {
  215060. stop();
  215061. if (isOpen_)
  215062. {
  215063. closeDevice();
  215064. isOpen_ = false;
  215065. }
  215066. }
  215067. bool isOpen()
  215068. {
  215069. return isOpen_ && isThreadRunning();
  215070. }
  215071. int getCurrentBufferSizeSamples()
  215072. {
  215073. return bufferSizeSamples;
  215074. }
  215075. double getCurrentSampleRate()
  215076. {
  215077. return sampleRate;
  215078. }
  215079. int getCurrentBitDepth()
  215080. {
  215081. int i, bits = 256;
  215082. for (i = inChans.size(); --i >= 0;)
  215083. bits = jmin (bits, inChans[i]->bitDepth);
  215084. for (i = outChans.size(); --i >= 0;)
  215085. bits = jmin (bits, outChans[i]->bitDepth);
  215086. if (bits > 32)
  215087. bits = 16;
  215088. return bits;
  215089. }
  215090. const BigInteger getActiveOutputChannels() const
  215091. {
  215092. return enabledOutputs;
  215093. }
  215094. const BigInteger getActiveInputChannels() const
  215095. {
  215096. return enabledInputs;
  215097. }
  215098. int getOutputLatencyInSamples()
  215099. {
  215100. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215101. }
  215102. int getInputLatencyInSamples()
  215103. {
  215104. return getOutputLatencyInSamples();
  215105. }
  215106. void start (AudioIODeviceCallback* call)
  215107. {
  215108. if (isOpen_ && call != 0 && ! isStarted)
  215109. {
  215110. if (! isThreadRunning())
  215111. {
  215112. // something gone wrong and the thread's stopped..
  215113. isOpen_ = false;
  215114. return;
  215115. }
  215116. call->audioDeviceAboutToStart (this);
  215117. const ScopedLock sl (startStopLock);
  215118. callback = call;
  215119. isStarted = true;
  215120. }
  215121. }
  215122. void stop()
  215123. {
  215124. if (isStarted)
  215125. {
  215126. AudioIODeviceCallback* const callbackLocal = callback;
  215127. {
  215128. const ScopedLock sl (startStopLock);
  215129. isStarted = false;
  215130. }
  215131. if (callbackLocal != 0)
  215132. callbackLocal->audioDeviceStopped();
  215133. }
  215134. }
  215135. bool isPlaying()
  215136. {
  215137. return isStarted && isOpen_ && isThreadRunning();
  215138. }
  215139. const String getLastError()
  215140. {
  215141. return lastError;
  215142. }
  215143. juce_UseDebuggingNewOperator
  215144. StringArray inChannels, outChannels;
  215145. int outputDeviceIndex, inputDeviceIndex;
  215146. private:
  215147. bool isOpen_;
  215148. bool isStarted;
  215149. String lastError;
  215150. OwnedArray <DSoundInternalInChannel> inChans;
  215151. OwnedArray <DSoundInternalOutChannel> outChans;
  215152. WaitableEvent startEvent;
  215153. int bufferSizeSamples;
  215154. int volatile totalSamplesOut;
  215155. int64 volatile lastBlockTime;
  215156. double sampleRate;
  215157. BigInteger enabledInputs, enabledOutputs;
  215158. AudioSampleBuffer inputBuffers, outputBuffers;
  215159. AudioIODeviceCallback* callback;
  215160. CriticalSection startStopLock;
  215161. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215162. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215163. const String openDevice (const BigInteger& inputChannels,
  215164. const BigInteger& outputChannels,
  215165. double sampleRate_,
  215166. int bufferSizeSamples_);
  215167. void closeDevice()
  215168. {
  215169. isStarted = false;
  215170. stopThread (5000);
  215171. inChans.clear();
  215172. outChans.clear();
  215173. inputBuffers.setSize (1, 1);
  215174. outputBuffers.setSize (1, 1);
  215175. }
  215176. void resync()
  215177. {
  215178. if (! threadShouldExit())
  215179. {
  215180. sleep (5);
  215181. int i;
  215182. for (i = 0; i < outChans.size(); ++i)
  215183. outChans.getUnchecked(i)->synchronisePosition();
  215184. for (i = 0; i < inChans.size(); ++i)
  215185. inChans.getUnchecked(i)->synchronisePosition();
  215186. }
  215187. }
  215188. public:
  215189. void run()
  215190. {
  215191. while (! threadShouldExit())
  215192. {
  215193. if (wait (100))
  215194. break;
  215195. }
  215196. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215197. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215198. while (! threadShouldExit())
  215199. {
  215200. int numToDo = 0;
  215201. uint32 startTime = Time::getMillisecondCounter();
  215202. int i;
  215203. for (i = inChans.size(); --i >= 0;)
  215204. {
  215205. inChans.getUnchecked(i)->doneFlag = false;
  215206. ++numToDo;
  215207. }
  215208. for (i = outChans.size(); --i >= 0;)
  215209. {
  215210. outChans.getUnchecked(i)->doneFlag = false;
  215211. ++numToDo;
  215212. }
  215213. if (numToDo > 0)
  215214. {
  215215. const int maxCount = 3;
  215216. int count = maxCount;
  215217. for (;;)
  215218. {
  215219. for (i = inChans.size(); --i >= 0;)
  215220. {
  215221. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215222. if ((! in->doneFlag) && in->service())
  215223. {
  215224. in->doneFlag = true;
  215225. --numToDo;
  215226. }
  215227. }
  215228. for (i = outChans.size(); --i >= 0;)
  215229. {
  215230. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215231. if ((! out->doneFlag) && out->service())
  215232. {
  215233. out->doneFlag = true;
  215234. --numToDo;
  215235. }
  215236. }
  215237. if (numToDo <= 0)
  215238. break;
  215239. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215240. {
  215241. resync();
  215242. break;
  215243. }
  215244. if (--count <= 0)
  215245. {
  215246. Sleep (1);
  215247. count = maxCount;
  215248. }
  215249. if (threadShouldExit())
  215250. return;
  215251. }
  215252. }
  215253. else
  215254. {
  215255. sleep (1);
  215256. }
  215257. const ScopedLock sl (startStopLock);
  215258. if (isStarted)
  215259. {
  215260. JUCE_TRY
  215261. {
  215262. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215263. inputBuffers.getNumChannels(),
  215264. outputBuffers.getArrayOfChannels(),
  215265. outputBuffers.getNumChannels(),
  215266. bufferSizeSamples);
  215267. }
  215268. JUCE_CATCH_EXCEPTION
  215269. totalSamplesOut += bufferSizeSamples;
  215270. }
  215271. else
  215272. {
  215273. outputBuffers.clear();
  215274. totalSamplesOut = 0;
  215275. sleep (1);
  215276. }
  215277. }
  215278. }
  215279. };
  215280. class DSoundAudioIODeviceType : public AudioIODeviceType
  215281. {
  215282. public:
  215283. DSoundAudioIODeviceType()
  215284. : AudioIODeviceType ("DirectSound"),
  215285. hasScanned (false)
  215286. {
  215287. initialiseDSoundFunctions();
  215288. }
  215289. ~DSoundAudioIODeviceType()
  215290. {
  215291. }
  215292. void scanForDevices()
  215293. {
  215294. hasScanned = true;
  215295. outputDeviceNames.clear();
  215296. outputGuids.clear();
  215297. inputDeviceNames.clear();
  215298. inputGuids.clear();
  215299. if (dsDirectSoundEnumerateW != 0)
  215300. {
  215301. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215302. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215303. }
  215304. }
  215305. const StringArray getDeviceNames (bool wantInputNames) const
  215306. {
  215307. jassert (hasScanned); // need to call scanForDevices() before doing this
  215308. return wantInputNames ? inputDeviceNames
  215309. : outputDeviceNames;
  215310. }
  215311. int getDefaultDeviceIndex (bool /*forInput*/) const
  215312. {
  215313. jassert (hasScanned); // need to call scanForDevices() before doing this
  215314. return 0;
  215315. }
  215316. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215317. {
  215318. jassert (hasScanned); // need to call scanForDevices() before doing this
  215319. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215320. if (d == 0)
  215321. return -1;
  215322. return asInput ? d->inputDeviceIndex
  215323. : d->outputDeviceIndex;
  215324. }
  215325. bool hasSeparateInputsAndOutputs() const { return true; }
  215326. AudioIODevice* createDevice (const String& outputDeviceName,
  215327. const String& inputDeviceName)
  215328. {
  215329. jassert (hasScanned); // need to call scanForDevices() before doing this
  215330. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215331. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215332. if (outputIndex >= 0 || inputIndex >= 0)
  215333. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215334. : inputDeviceName,
  215335. outputIndex, inputIndex);
  215336. return 0;
  215337. }
  215338. juce_UseDebuggingNewOperator
  215339. StringArray outputDeviceNames;
  215340. OwnedArray <GUID> outputGuids;
  215341. StringArray inputDeviceNames;
  215342. OwnedArray <GUID> inputGuids;
  215343. private:
  215344. bool hasScanned;
  215345. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215346. {
  215347. desc = desc.trim();
  215348. if (desc.isNotEmpty())
  215349. {
  215350. const String origDesc (desc);
  215351. int n = 2;
  215352. while (outputDeviceNames.contains (desc))
  215353. desc = origDesc + " (" + String (n++) + ")";
  215354. outputDeviceNames.add (desc);
  215355. if (lpGUID != 0)
  215356. outputGuids.add (new GUID (*lpGUID));
  215357. else
  215358. outputGuids.add (0);
  215359. }
  215360. return TRUE;
  215361. }
  215362. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215363. {
  215364. return ((DSoundAudioIODeviceType*) object)
  215365. ->outputEnumProc (lpGUID, String (description));
  215366. }
  215367. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215368. {
  215369. return ((DSoundAudioIODeviceType*) object)
  215370. ->outputEnumProc (lpGUID, String (description));
  215371. }
  215372. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215373. {
  215374. desc = desc.trim();
  215375. if (desc.isNotEmpty())
  215376. {
  215377. const String origDesc (desc);
  215378. int n = 2;
  215379. while (inputDeviceNames.contains (desc))
  215380. desc = origDesc + " (" + String (n++) + ")";
  215381. inputDeviceNames.add (desc);
  215382. if (lpGUID != 0)
  215383. inputGuids.add (new GUID (*lpGUID));
  215384. else
  215385. inputGuids.add (0);
  215386. }
  215387. return TRUE;
  215388. }
  215389. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215390. {
  215391. return ((DSoundAudioIODeviceType*) object)
  215392. ->inputEnumProc (lpGUID, String (description));
  215393. }
  215394. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215395. {
  215396. return ((DSoundAudioIODeviceType*) object)
  215397. ->inputEnumProc (lpGUID, String (description));
  215398. }
  215399. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215400. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215401. };
  215402. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215403. const BigInteger& outputChannels,
  215404. double sampleRate_,
  215405. int bufferSizeSamples_)
  215406. {
  215407. closeDevice();
  215408. totalSamplesOut = 0;
  215409. sampleRate = sampleRate_;
  215410. if (bufferSizeSamples_ <= 0)
  215411. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215412. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215413. DSoundAudioIODeviceType dlh;
  215414. dlh.scanForDevices();
  215415. enabledInputs = inputChannels;
  215416. enabledInputs.setRange (inChannels.size(),
  215417. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215418. false);
  215419. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215420. inputBuffers.clear();
  215421. int i, numIns = 0;
  215422. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215423. {
  215424. float* left = 0;
  215425. if (enabledInputs[i])
  215426. left = inputBuffers.getSampleData (numIns++);
  215427. float* right = 0;
  215428. if (enabledInputs[i + 1])
  215429. right = inputBuffers.getSampleData (numIns++);
  215430. if (left != 0 || right != 0)
  215431. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215432. dlh.inputGuids [inputDeviceIndex],
  215433. (int) sampleRate, bufferSizeSamples,
  215434. left, right));
  215435. }
  215436. enabledOutputs = outputChannels;
  215437. enabledOutputs.setRange (outChannels.size(),
  215438. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215439. false);
  215440. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215441. outputBuffers.clear();
  215442. int numOuts = 0;
  215443. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215444. {
  215445. float* left = 0;
  215446. if (enabledOutputs[i])
  215447. left = outputBuffers.getSampleData (numOuts++);
  215448. float* right = 0;
  215449. if (enabledOutputs[i + 1])
  215450. right = outputBuffers.getSampleData (numOuts++);
  215451. if (left != 0 || right != 0)
  215452. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215453. dlh.outputGuids [outputDeviceIndex],
  215454. (int) sampleRate, bufferSizeSamples,
  215455. left, right));
  215456. }
  215457. String error;
  215458. // boost our priority while opening the devices to try to get better sync between them
  215459. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215460. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215461. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215462. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215463. for (i = 0; i < outChans.size(); ++i)
  215464. {
  215465. error = outChans[i]->open();
  215466. if (error.isNotEmpty())
  215467. {
  215468. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215469. break;
  215470. }
  215471. }
  215472. if (error.isEmpty())
  215473. {
  215474. for (i = 0; i < inChans.size(); ++i)
  215475. {
  215476. error = inChans[i]->open();
  215477. if (error.isNotEmpty())
  215478. {
  215479. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215480. break;
  215481. }
  215482. }
  215483. }
  215484. if (error.isEmpty())
  215485. {
  215486. totalSamplesOut = 0;
  215487. for (i = 0; i < outChans.size(); ++i)
  215488. outChans.getUnchecked(i)->synchronisePosition();
  215489. for (i = 0; i < inChans.size(); ++i)
  215490. inChans.getUnchecked(i)->synchronisePosition();
  215491. startThread (9);
  215492. sleep (10);
  215493. notify();
  215494. }
  215495. else
  215496. {
  215497. log (error);
  215498. }
  215499. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215500. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215501. return error;
  215502. }
  215503. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215504. {
  215505. return new DSoundAudioIODeviceType();
  215506. }
  215507. #undef log
  215508. #endif
  215509. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215510. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215511. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215512. // compiled on its own).
  215513. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215514. #ifndef WASAPI_ENABLE_LOGGING
  215515. #define WASAPI_ENABLE_LOGGING 1
  215516. #endif
  215517. namespace WasapiClasses
  215518. {
  215519. static void logFailure (HRESULT hr)
  215520. {
  215521. (void) hr;
  215522. #if WASAPI_ENABLE_LOGGING
  215523. if (FAILED (hr))
  215524. {
  215525. String e;
  215526. e << Time::getCurrentTime().toString (true, true, true, true)
  215527. << " -- WASAPI error: ";
  215528. switch (hr)
  215529. {
  215530. case E_POINTER: e << "E_POINTER"; break;
  215531. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215532. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215533. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215534. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215535. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215536. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215537. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215538. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215539. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215540. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215541. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215542. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215543. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215544. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215545. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215546. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215547. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215548. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215549. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215550. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215551. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215552. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215553. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215554. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215555. default: e << String::toHexString ((int) hr); break;
  215556. }
  215557. DBG (e);
  215558. jassertfalse;
  215559. }
  215560. #endif
  215561. }
  215562. static bool check (HRESULT hr)
  215563. {
  215564. logFailure (hr);
  215565. return SUCCEEDED (hr);
  215566. }
  215567. static const String getDeviceID (IMMDevice* const device)
  215568. {
  215569. String s;
  215570. WCHAR* deviceId = 0;
  215571. if (check (device->GetId (&deviceId)))
  215572. {
  215573. s = String (deviceId);
  215574. CoTaskMemFree (deviceId);
  215575. }
  215576. return s;
  215577. }
  215578. static EDataFlow getDataFlow (IMMDevice* const device)
  215579. {
  215580. EDataFlow flow = eRender;
  215581. ComSmartPtr <IMMEndpoint> endPoint;
  215582. if (check (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  215583. (void) check (endPoint->GetDataFlow (&flow));
  215584. return flow;
  215585. }
  215586. static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215587. {
  215588. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215589. }
  215590. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215591. {
  215592. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215593. : sizeof (WAVEFORMATEX));
  215594. }
  215595. class WASAPIDeviceBase
  215596. {
  215597. public:
  215598. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215599. : device (device_),
  215600. sampleRate (0),
  215601. numChannels (0),
  215602. actualNumChannels (0),
  215603. defaultSampleRate (0),
  215604. minBufferSize (0),
  215605. defaultBufferSize (0),
  215606. latencySamples (0),
  215607. useExclusiveMode (useExclusiveMode_)
  215608. {
  215609. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215610. ComSmartPtr <IAudioClient> tempClient (createClient());
  215611. if (tempClient == 0)
  215612. return;
  215613. REFERENCE_TIME defaultPeriod, minPeriod;
  215614. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215615. return;
  215616. WAVEFORMATEX* mixFormat = 0;
  215617. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215618. return;
  215619. WAVEFORMATEXTENSIBLE format;
  215620. copyWavFormat (format, mixFormat);
  215621. CoTaskMemFree (mixFormat);
  215622. actualNumChannels = numChannels = format.Format.nChannels;
  215623. defaultSampleRate = format.Format.nSamplesPerSec;
  215624. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215625. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215626. rates.addUsingDefaultSort (defaultSampleRate);
  215627. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215628. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215629. {
  215630. if (ratesToTest[i] == defaultSampleRate)
  215631. continue;
  215632. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215633. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215634. (WAVEFORMATEX*) &format, 0)))
  215635. if (! rates.contains (ratesToTest[i]))
  215636. rates.addUsingDefaultSort (ratesToTest[i]);
  215637. }
  215638. }
  215639. ~WASAPIDeviceBase()
  215640. {
  215641. device = 0;
  215642. CloseHandle (clientEvent);
  215643. }
  215644. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215645. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215646. {
  215647. sampleRate = newSampleRate;
  215648. channels = newChannels;
  215649. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215650. numChannels = channels.getHighestBit() + 1;
  215651. if (numChannels == 0)
  215652. return true;
  215653. client = createClient();
  215654. if (client != 0
  215655. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215656. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215657. {
  215658. channelMaps.clear();
  215659. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215660. if (channels[i])
  215661. channelMaps.add (i);
  215662. REFERENCE_TIME latency;
  215663. if (check (client->GetStreamLatency (&latency)))
  215664. latencySamples = refTimeToSamples (latency, sampleRate);
  215665. (void) check (client->GetBufferSize (&actualBufferSize));
  215666. return check (client->SetEventHandle (clientEvent));
  215667. }
  215668. return false;
  215669. }
  215670. void closeClient()
  215671. {
  215672. if (client != 0)
  215673. client->Stop();
  215674. client = 0;
  215675. ResetEvent (clientEvent);
  215676. }
  215677. ComSmartPtr <IMMDevice> device;
  215678. ComSmartPtr <IAudioClient> client;
  215679. double sampleRate, defaultSampleRate;
  215680. int numChannels, actualNumChannels;
  215681. int minBufferSize, defaultBufferSize, latencySamples;
  215682. const bool useExclusiveMode;
  215683. Array <double> rates;
  215684. HANDLE clientEvent;
  215685. BigInteger channels;
  215686. Array <int> channelMaps;
  215687. UINT32 actualBufferSize;
  215688. int bytesPerSample;
  215689. virtual void updateFormat (bool isFloat) = 0;
  215690. private:
  215691. const ComSmartPtr <IAudioClient> createClient()
  215692. {
  215693. ComSmartPtr <IAudioClient> client;
  215694. if (device != 0)
  215695. {
  215696. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  215697. logFailure (hr);
  215698. }
  215699. return client;
  215700. }
  215701. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215702. {
  215703. WAVEFORMATEXTENSIBLE format;
  215704. zerostruct (format);
  215705. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215706. {
  215707. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215708. }
  215709. else
  215710. {
  215711. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215712. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215713. }
  215714. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215715. format.Format.nChannels = (WORD) numChannels;
  215716. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215717. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215718. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215719. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215720. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215721. switch (numChannels)
  215722. {
  215723. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215724. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215725. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215726. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215727. 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;
  215728. default: break;
  215729. }
  215730. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215731. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215732. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215733. logFailure (hr);
  215734. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215735. {
  215736. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215737. hr = S_OK;
  215738. }
  215739. CoTaskMemFree (nearestFormat);
  215740. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215741. if (useExclusiveMode)
  215742. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215743. GUID session;
  215744. if (hr == S_OK
  215745. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215746. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215747. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215748. {
  215749. actualNumChannels = format.Format.nChannels;
  215750. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215751. bytesPerSample = format.Format.wBitsPerSample / 8;
  215752. updateFormat (isFloat);
  215753. return true;
  215754. }
  215755. return false;
  215756. }
  215757. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215758. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215759. };
  215760. class WASAPIInputDevice : public WASAPIDeviceBase
  215761. {
  215762. public:
  215763. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215764. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215765. reservoir (1, 1)
  215766. {
  215767. }
  215768. ~WASAPIInputDevice()
  215769. {
  215770. close();
  215771. }
  215772. bool open (const double newSampleRate, const BigInteger& newChannels)
  215773. {
  215774. reservoirSize = 0;
  215775. reservoirCapacity = 16384;
  215776. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215777. return openClient (newSampleRate, newChannels)
  215778. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  215779. }
  215780. void close()
  215781. {
  215782. closeClient();
  215783. captureClient = 0;
  215784. reservoir.setSize (0);
  215785. }
  215786. void updateFormat (bool isFloat)
  215787. {
  215788. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215789. if (isFloat)
  215790. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215791. else if (bytesPerSample == 4)
  215792. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215793. else if (bytesPerSample == 3)
  215794. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215795. else
  215796. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215797. }
  215798. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215799. {
  215800. if (numChannels <= 0)
  215801. return;
  215802. int offset = 0;
  215803. while (bufferSize > 0)
  215804. {
  215805. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215806. {
  215807. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215808. for (int i = 0; i < numDestBuffers; ++i)
  215809. converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215810. bufferSize -= samplesToDo;
  215811. offset += samplesToDo;
  215812. reservoirSize -= samplesToDo;
  215813. }
  215814. else
  215815. {
  215816. UINT32 packetLength = 0;
  215817. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215818. break;
  215819. if (packetLength == 0)
  215820. {
  215821. if (thread.threadShouldExit())
  215822. break;
  215823. Thread::sleep (1);
  215824. continue;
  215825. }
  215826. uint8* inputData = 0;
  215827. UINT32 numSamplesAvailable;
  215828. DWORD flags;
  215829. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215830. {
  215831. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215832. for (int i = 0; i < numDestBuffers; ++i)
  215833. converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215834. bufferSize -= samplesToDo;
  215835. offset += samplesToDo;
  215836. if (samplesToDo < (int) numSamplesAvailable)
  215837. {
  215838. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215839. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215840. bytesPerSample * actualNumChannels * reservoirSize);
  215841. }
  215842. captureClient->ReleaseBuffer (numSamplesAvailable);
  215843. }
  215844. }
  215845. }
  215846. }
  215847. ComSmartPtr <IAudioCaptureClient> captureClient;
  215848. MemoryBlock reservoir;
  215849. int reservoirSize, reservoirCapacity;
  215850. ScopedPointer <AudioData::Converter> converter;
  215851. private:
  215852. WASAPIInputDevice (const WASAPIInputDevice&);
  215853. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215854. };
  215855. class WASAPIOutputDevice : public WASAPIDeviceBase
  215856. {
  215857. public:
  215858. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215859. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215860. {
  215861. }
  215862. ~WASAPIOutputDevice()
  215863. {
  215864. close();
  215865. }
  215866. bool open (const double newSampleRate, const BigInteger& newChannels)
  215867. {
  215868. return openClient (newSampleRate, newChannels)
  215869. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  215870. }
  215871. void close()
  215872. {
  215873. closeClient();
  215874. renderClient = 0;
  215875. }
  215876. void updateFormat (bool isFloat)
  215877. {
  215878. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215879. if (isFloat)
  215880. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215881. else if (bytesPerSample == 4)
  215882. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215883. else if (bytesPerSample == 3)
  215884. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215885. else
  215886. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215887. }
  215888. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215889. {
  215890. if (numChannels <= 0)
  215891. return;
  215892. int offset = 0;
  215893. while (bufferSize > 0)
  215894. {
  215895. UINT32 padding = 0;
  215896. if (! check (client->GetCurrentPadding (&padding)))
  215897. return;
  215898. int samplesToDo = useExclusiveMode ? bufferSize
  215899. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215900. if (samplesToDo <= 0)
  215901. {
  215902. if (thread.threadShouldExit())
  215903. break;
  215904. Thread::sleep (0);
  215905. continue;
  215906. }
  215907. uint8* outputData = 0;
  215908. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215909. {
  215910. for (int i = 0; i < numSrcBuffers; ++i)
  215911. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo);
  215912. renderClient->ReleaseBuffer (samplesToDo, 0);
  215913. offset += samplesToDo;
  215914. bufferSize -= samplesToDo;
  215915. }
  215916. }
  215917. }
  215918. ComSmartPtr <IAudioRenderClient> renderClient;
  215919. ScopedPointer <AudioData::Converter> converter;
  215920. private:
  215921. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215922. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215923. };
  215924. class WASAPIAudioIODevice : public AudioIODevice,
  215925. public Thread
  215926. {
  215927. public:
  215928. WASAPIAudioIODevice (const String& deviceName,
  215929. const String& outputDeviceId_,
  215930. const String& inputDeviceId_,
  215931. const bool useExclusiveMode_)
  215932. : AudioIODevice (deviceName, "Windows Audio"),
  215933. Thread ("Juce WASAPI"),
  215934. isOpen_ (false),
  215935. isStarted (false),
  215936. outputDeviceId (outputDeviceId_),
  215937. inputDeviceId (inputDeviceId_),
  215938. useExclusiveMode (useExclusiveMode_),
  215939. currentBufferSizeSamples (0),
  215940. currentSampleRate (0),
  215941. callback (0)
  215942. {
  215943. }
  215944. ~WASAPIAudioIODevice()
  215945. {
  215946. close();
  215947. }
  215948. bool initialise()
  215949. {
  215950. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215951. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215952. latencyIn = latencyOut = 0;
  215953. Array <double> ratesIn, ratesOut;
  215954. if (createDevices())
  215955. {
  215956. jassert (inputDevice != 0 || outputDevice != 0);
  215957. if (inputDevice != 0 && outputDevice != 0)
  215958. {
  215959. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215960. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215961. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215962. sampleRates = inputDevice->rates;
  215963. sampleRates.removeValuesNotIn (outputDevice->rates);
  215964. }
  215965. else
  215966. {
  215967. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215968. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215969. defaultSampleRate = d->defaultSampleRate;
  215970. minBufferSize = d->minBufferSize;
  215971. defaultBufferSize = d->defaultBufferSize;
  215972. sampleRates = d->rates;
  215973. }
  215974. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215975. if (minBufferSize != defaultBufferSize)
  215976. bufferSizes.addUsingDefaultSort (minBufferSize);
  215977. int n = 64;
  215978. for (int i = 0; i < 40; ++i)
  215979. {
  215980. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215981. bufferSizes.addUsingDefaultSort (n);
  215982. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215983. }
  215984. return true;
  215985. }
  215986. return false;
  215987. }
  215988. const StringArray getOutputChannelNames()
  215989. {
  215990. StringArray outChannels;
  215991. if (outputDevice != 0)
  215992. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215993. outChannels.add ("Output channel " + String (i));
  215994. return outChannels;
  215995. }
  215996. const StringArray getInputChannelNames()
  215997. {
  215998. StringArray inChannels;
  215999. if (inputDevice != 0)
  216000. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216001. inChannels.add ("Input channel " + String (i));
  216002. return inChannels;
  216003. }
  216004. int getNumSampleRates() { return sampleRates.size(); }
  216005. double getSampleRate (int index) { return sampleRates [index]; }
  216006. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216007. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216008. int getDefaultBufferSize() { return defaultBufferSize; }
  216009. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216010. double getCurrentSampleRate() { return currentSampleRate; }
  216011. int getCurrentBitDepth() { return 32; }
  216012. int getOutputLatencyInSamples() { return latencyOut; }
  216013. int getInputLatencyInSamples() { return latencyIn; }
  216014. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216015. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216016. const String getLastError() { return lastError; }
  216017. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216018. double sampleRate, int bufferSizeSamples)
  216019. {
  216020. close();
  216021. lastError = String::empty;
  216022. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216023. {
  216024. lastError = "The input and output devices don't share a common sample rate!";
  216025. return lastError;
  216026. }
  216027. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216028. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216029. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216030. {
  216031. lastError = "Couldn't open the input device!";
  216032. return lastError;
  216033. }
  216034. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216035. {
  216036. close();
  216037. lastError = "Couldn't open the output device!";
  216038. return lastError;
  216039. }
  216040. if (inputDevice != 0)
  216041. ResetEvent (inputDevice->clientEvent);
  216042. if (outputDevice != 0)
  216043. ResetEvent (outputDevice->clientEvent);
  216044. startThread (8);
  216045. Thread::sleep (5);
  216046. if (inputDevice != 0 && inputDevice->client != 0)
  216047. {
  216048. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216049. HRESULT hr = inputDevice->client->Start();
  216050. logFailure (hr); //xxx handle this
  216051. }
  216052. if (outputDevice != 0 && outputDevice->client != 0)
  216053. {
  216054. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216055. HRESULT hr = outputDevice->client->Start();
  216056. logFailure (hr); //xxx handle this
  216057. }
  216058. isOpen_ = true;
  216059. return lastError;
  216060. }
  216061. void close()
  216062. {
  216063. stop();
  216064. if (inputDevice != 0)
  216065. SetEvent (inputDevice->clientEvent);
  216066. if (outputDevice != 0)
  216067. SetEvent (outputDevice->clientEvent);
  216068. stopThread (5000);
  216069. if (inputDevice != 0)
  216070. inputDevice->close();
  216071. if (outputDevice != 0)
  216072. outputDevice->close();
  216073. isOpen_ = false;
  216074. }
  216075. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216076. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216077. void start (AudioIODeviceCallback* call)
  216078. {
  216079. if (isOpen_ && call != 0 && ! isStarted)
  216080. {
  216081. if (! isThreadRunning())
  216082. {
  216083. // something's gone wrong and the thread's stopped..
  216084. isOpen_ = false;
  216085. return;
  216086. }
  216087. call->audioDeviceAboutToStart (this);
  216088. const ScopedLock sl (startStopLock);
  216089. callback = call;
  216090. isStarted = true;
  216091. }
  216092. }
  216093. void stop()
  216094. {
  216095. if (isStarted)
  216096. {
  216097. AudioIODeviceCallback* const callbackLocal = callback;
  216098. {
  216099. const ScopedLock sl (startStopLock);
  216100. isStarted = false;
  216101. }
  216102. if (callbackLocal != 0)
  216103. callbackLocal->audioDeviceStopped();
  216104. }
  216105. }
  216106. void setMMThreadPriority()
  216107. {
  216108. DynamicLibraryLoader dll ("avrt.dll");
  216109. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216110. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216111. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216112. {
  216113. DWORD dummy = 0;
  216114. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216115. if (h != 0)
  216116. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216117. }
  216118. }
  216119. void run()
  216120. {
  216121. setMMThreadPriority();
  216122. const int bufferSize = currentBufferSizeSamples;
  216123. HANDLE events[2];
  216124. int numEvents = 0;
  216125. if (inputDevice != 0)
  216126. events [numEvents++] = inputDevice->clientEvent;
  216127. if (outputDevice != 0)
  216128. events [numEvents++] = outputDevice->clientEvent;
  216129. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216130. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216131. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216132. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216133. float** const inputBuffers = ins.getArrayOfChannels();
  216134. float** const outputBuffers = outs.getArrayOfChannels();
  216135. ins.clear();
  216136. while (! threadShouldExit())
  216137. {
  216138. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216139. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216140. if (result == WAIT_TIMEOUT)
  216141. continue;
  216142. if (threadShouldExit())
  216143. break;
  216144. if (inputDevice != 0)
  216145. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216146. // Make the callback..
  216147. {
  216148. const ScopedLock sl (startStopLock);
  216149. if (isStarted)
  216150. {
  216151. JUCE_TRY
  216152. {
  216153. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216154. numInputBuffers,
  216155. outputBuffers,
  216156. numOutputBuffers,
  216157. bufferSize);
  216158. }
  216159. JUCE_CATCH_EXCEPTION
  216160. }
  216161. else
  216162. {
  216163. outs.clear();
  216164. }
  216165. }
  216166. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216167. continue;
  216168. if (outputDevice != 0)
  216169. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216170. }
  216171. }
  216172. juce_UseDebuggingNewOperator
  216173. String outputDeviceId, inputDeviceId;
  216174. String lastError;
  216175. private:
  216176. // Device stats...
  216177. ScopedPointer<WASAPIInputDevice> inputDevice;
  216178. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216179. const bool useExclusiveMode;
  216180. double defaultSampleRate;
  216181. int minBufferSize, defaultBufferSize;
  216182. int latencyIn, latencyOut;
  216183. Array <double> sampleRates;
  216184. Array <int> bufferSizes;
  216185. // Active state...
  216186. bool isOpen_, isStarted;
  216187. int currentBufferSizeSamples;
  216188. double currentSampleRate;
  216189. AudioIODeviceCallback* callback;
  216190. CriticalSection startStopLock;
  216191. bool createDevices()
  216192. {
  216193. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216194. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216195. return false;
  216196. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216197. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  216198. return false;
  216199. UINT32 numDevices = 0;
  216200. if (! check (deviceCollection->GetCount (&numDevices)))
  216201. return false;
  216202. for (UINT32 i = 0; i < numDevices; ++i)
  216203. {
  216204. ComSmartPtr <IMMDevice> device;
  216205. if (! check (deviceCollection->Item (i, &device)))
  216206. continue;
  216207. const String deviceId (getDeviceID (device));
  216208. if (deviceId.isEmpty())
  216209. continue;
  216210. const EDataFlow flow = getDataFlow (device);
  216211. if (deviceId == inputDeviceId && flow == eCapture)
  216212. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216213. else if (deviceId == outputDeviceId && flow == eRender)
  216214. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216215. }
  216216. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216217. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216218. }
  216219. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216220. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216221. };
  216222. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216223. {
  216224. public:
  216225. WASAPIAudioIODeviceType()
  216226. : AudioIODeviceType ("Windows Audio"),
  216227. hasScanned (false)
  216228. {
  216229. }
  216230. ~WASAPIAudioIODeviceType()
  216231. {
  216232. }
  216233. void scanForDevices()
  216234. {
  216235. hasScanned = true;
  216236. outputDeviceNames.clear();
  216237. inputDeviceNames.clear();
  216238. outputDeviceIds.clear();
  216239. inputDeviceIds.clear();
  216240. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216241. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216242. return;
  216243. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216244. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216245. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216246. UINT32 numDevices = 0;
  216247. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  216248. && check (deviceCollection->GetCount (&numDevices))))
  216249. return;
  216250. for (UINT32 i = 0; i < numDevices; ++i)
  216251. {
  216252. ComSmartPtr <IMMDevice> device;
  216253. if (! check (deviceCollection->Item (i, &device)))
  216254. continue;
  216255. const String deviceId (getDeviceID (device));
  216256. DWORD state = 0;
  216257. if (! check (device->GetState (&state)))
  216258. continue;
  216259. if (state != DEVICE_STATE_ACTIVE)
  216260. continue;
  216261. String name;
  216262. {
  216263. ComSmartPtr <IPropertyStore> properties;
  216264. if (! check (device->OpenPropertyStore (STGM_READ, &properties)))
  216265. continue;
  216266. PROPVARIANT value;
  216267. PropVariantInit (&value);
  216268. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216269. name = value.pwszVal;
  216270. PropVariantClear (&value);
  216271. }
  216272. const EDataFlow flow = getDataFlow (device);
  216273. if (flow == eRender)
  216274. {
  216275. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216276. outputDeviceIds.insert (index, deviceId);
  216277. outputDeviceNames.insert (index, name);
  216278. }
  216279. else if (flow == eCapture)
  216280. {
  216281. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216282. inputDeviceIds.insert (index, deviceId);
  216283. inputDeviceNames.insert (index, name);
  216284. }
  216285. }
  216286. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216287. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216288. }
  216289. const StringArray getDeviceNames (bool wantInputNames) const
  216290. {
  216291. jassert (hasScanned); // need to call scanForDevices() before doing this
  216292. return wantInputNames ? inputDeviceNames
  216293. : outputDeviceNames;
  216294. }
  216295. int getDefaultDeviceIndex (bool /*forInput*/) const
  216296. {
  216297. jassert (hasScanned); // need to call scanForDevices() before doing this
  216298. return 0;
  216299. }
  216300. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216301. {
  216302. jassert (hasScanned); // need to call scanForDevices() before doing this
  216303. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216304. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216305. : outputDeviceIds.indexOf (d->outputDeviceId));
  216306. }
  216307. bool hasSeparateInputsAndOutputs() const { return true; }
  216308. AudioIODevice* createDevice (const String& outputDeviceName,
  216309. const String& inputDeviceName)
  216310. {
  216311. jassert (hasScanned); // need to call scanForDevices() before doing this
  216312. const bool useExclusiveMode = false;
  216313. ScopedPointer<WASAPIAudioIODevice> device;
  216314. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216315. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216316. if (outputIndex >= 0 || inputIndex >= 0)
  216317. {
  216318. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216319. : inputDeviceName,
  216320. outputDeviceIds [outputIndex],
  216321. inputDeviceIds [inputIndex],
  216322. useExclusiveMode);
  216323. if (! device->initialise())
  216324. device = 0;
  216325. }
  216326. return device.release();
  216327. }
  216328. juce_UseDebuggingNewOperator
  216329. StringArray outputDeviceNames, outputDeviceIds;
  216330. StringArray inputDeviceNames, inputDeviceIds;
  216331. private:
  216332. bool hasScanned;
  216333. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216334. {
  216335. String s;
  216336. IMMDevice* dev = 0;
  216337. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216338. eMultimedia, &dev)))
  216339. {
  216340. WCHAR* deviceId = 0;
  216341. if (check (dev->GetId (&deviceId)))
  216342. {
  216343. s = String (deviceId);
  216344. CoTaskMemFree (deviceId);
  216345. }
  216346. dev->Release();
  216347. }
  216348. return s;
  216349. }
  216350. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216351. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216352. };
  216353. }
  216354. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216355. {
  216356. return new WasapiClasses::WASAPIAudioIODeviceType();
  216357. }
  216358. #endif
  216359. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216360. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216361. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216362. // compiled on its own).
  216363. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216364. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216365. {
  216366. public:
  216367. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216368. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216369. const ComSmartPtr <IBaseFilter>& filter_,
  216370. int minWidth, int minHeight,
  216371. int maxWidth, int maxHeight)
  216372. : owner (owner_),
  216373. captureGraphBuilder (captureGraphBuilder_),
  216374. filter (filter_),
  216375. ok (false),
  216376. imageNeedsFlipping (false),
  216377. width (0),
  216378. height (0),
  216379. activeUsers (0),
  216380. recordNextFrameTime (false)
  216381. {
  216382. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216383. if (FAILED (hr))
  216384. return;
  216385. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216386. if (FAILED (hr))
  216387. return;
  216388. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  216389. if (FAILED (hr))
  216390. return;
  216391. {
  216392. ComSmartPtr <IAMStreamConfig> streamConfig;
  216393. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216394. IID_IAMStreamConfig, (void**) &streamConfig);
  216395. if (streamConfig != 0)
  216396. {
  216397. getVideoSizes (streamConfig);
  216398. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216399. return;
  216400. }
  216401. }
  216402. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216403. if (FAILED (hr))
  216404. return;
  216405. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216406. if (FAILED (hr))
  216407. return;
  216408. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216409. if (FAILED (hr))
  216410. return;
  216411. if (! connectFilters (filter, smartTee))
  216412. return;
  216413. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216414. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216415. if (FAILED (hr))
  216416. return;
  216417. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  216418. if (FAILED (hr))
  216419. return;
  216420. AM_MEDIA_TYPE mt;
  216421. zerostruct (mt);
  216422. mt.majortype = MEDIATYPE_Video;
  216423. mt.subtype = MEDIASUBTYPE_RGB24;
  216424. mt.formattype = FORMAT_VideoInfo;
  216425. sampleGrabber->SetMediaType (&mt);
  216426. callback = new GrabberCallback (*this);
  216427. sampleGrabber->SetCallback (callback, 1);
  216428. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216429. if (FAILED (hr))
  216430. return;
  216431. ComSmartPtr <IPin> grabberInputPin;
  216432. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  216433. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  216434. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  216435. return;
  216436. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216437. if (FAILED (hr))
  216438. return;
  216439. zerostruct (mt);
  216440. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216441. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216442. width = pVih->bmiHeader.biWidth;
  216443. height = pVih->bmiHeader.biHeight;
  216444. ComSmartPtr <IBaseFilter> nullFilter;
  216445. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216446. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216447. if (connectFilters (sampleGrabberBase, nullFilter)
  216448. && addGraphToRot())
  216449. {
  216450. activeImage = Image (Image::RGB, width, height, true);
  216451. loadingImage = Image (Image::RGB, width, height, true);
  216452. ok = true;
  216453. }
  216454. }
  216455. ~DShowCameraDeviceInteral()
  216456. {
  216457. if (mediaControl != 0)
  216458. mediaControl->Stop();
  216459. removeGraphFromRot();
  216460. for (int i = viewerComps.size(); --i >= 0;)
  216461. viewerComps.getUnchecked(i)->ownerDeleted();
  216462. callback = 0;
  216463. graphBuilder = 0;
  216464. sampleGrabber = 0;
  216465. mediaControl = 0;
  216466. filter = 0;
  216467. captureGraphBuilder = 0;
  216468. smartTee = 0;
  216469. smartTeePreviewOutputPin = 0;
  216470. smartTeeCaptureOutputPin = 0;
  216471. asfWriter = 0;
  216472. }
  216473. void addUser()
  216474. {
  216475. if (ok && activeUsers++ == 0)
  216476. mediaControl->Run();
  216477. }
  216478. void removeUser()
  216479. {
  216480. if (ok && --activeUsers == 0)
  216481. mediaControl->Stop();
  216482. }
  216483. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216484. {
  216485. if (recordNextFrameTime)
  216486. {
  216487. const double defaultCameraLatency = 0.1;
  216488. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216489. recordNextFrameTime = false;
  216490. ComSmartPtr <IPin> pin;
  216491. if (getPin (filter, PINDIR_OUTPUT, &pin))
  216492. {
  216493. ComSmartPtr <IAMPushSource> pushSource;
  216494. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  216495. if (pushSource != 0)
  216496. {
  216497. REFERENCE_TIME latency = 0;
  216498. hr = pushSource->GetLatency (&latency);
  216499. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216500. }
  216501. }
  216502. }
  216503. {
  216504. const int lineStride = width * 3;
  216505. const ScopedLock sl (imageSwapLock);
  216506. {
  216507. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216508. for (int i = 0; i < height; ++i)
  216509. memcpy (destData.getLinePointer ((height - 1) - i),
  216510. buffer + lineStride * i,
  216511. lineStride);
  216512. }
  216513. imageNeedsFlipping = true;
  216514. }
  216515. if (listeners.size() > 0)
  216516. callListeners (loadingImage);
  216517. sendChangeMessage (this);
  216518. }
  216519. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216520. {
  216521. if (imageNeedsFlipping)
  216522. {
  216523. const ScopedLock sl (imageSwapLock);
  216524. swapVariables (loadingImage, activeImage);
  216525. imageNeedsFlipping = false;
  216526. }
  216527. RectanglePlacement rp (RectanglePlacement::centred);
  216528. double dx = 0, dy = 0, dw = width, dh = height;
  216529. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216530. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216531. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216532. g.saveState();
  216533. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216534. g.fillAll (Colours::black);
  216535. g.restoreState();
  216536. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216537. }
  216538. bool createFileCaptureFilter (const File& file)
  216539. {
  216540. removeFileCaptureFilter();
  216541. file.deleteFile();
  216542. mediaControl->Stop();
  216543. firstRecordedTime = Time();
  216544. recordNextFrameTime = true;
  216545. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216546. if (SUCCEEDED (hr))
  216547. {
  216548. ComSmartPtr <IFileSinkFilter> fileSink;
  216549. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  216550. if (SUCCEEDED (hr))
  216551. {
  216552. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216553. if (SUCCEEDED (hr))
  216554. {
  216555. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216556. if (SUCCEEDED (hr))
  216557. {
  216558. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216559. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  216560. asfConfig->SetIndexMode (true);
  216561. ComSmartPtr <IWMProfileManager> profileManager;
  216562. hr = WMCreateProfileManager (&profileManager);
  216563. // This gibberish is the DirectShow profile for a video-only wmv file.
  216564. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216565. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216566. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216567. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216568. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216569. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216570. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216571. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216572. prof = prof.replace ("$WIDTH", String (width))
  216573. .replace ("$HEIGHT", String (height));
  216574. ComSmartPtr <IWMProfile> currentProfile;
  216575. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  216576. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216577. if (SUCCEEDED (hr))
  216578. {
  216579. ComSmartPtr <IPin> asfWriterInputPin;
  216580. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  216581. {
  216582. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216583. if (SUCCEEDED (hr)
  216584. && ok && activeUsers > 0
  216585. && SUCCEEDED (mediaControl->Run()))
  216586. {
  216587. return true;
  216588. }
  216589. }
  216590. }
  216591. }
  216592. }
  216593. }
  216594. }
  216595. removeFileCaptureFilter();
  216596. if (ok && activeUsers > 0)
  216597. mediaControl->Run();
  216598. return false;
  216599. }
  216600. void removeFileCaptureFilter()
  216601. {
  216602. mediaControl->Stop();
  216603. if (asfWriter != 0)
  216604. {
  216605. graphBuilder->RemoveFilter (asfWriter);
  216606. asfWriter = 0;
  216607. }
  216608. if (ok && activeUsers > 0)
  216609. mediaControl->Run();
  216610. }
  216611. void addListener (CameraDevice::Listener* listenerToAdd)
  216612. {
  216613. const ScopedLock sl (listenerLock);
  216614. if (listeners.size() == 0)
  216615. addUser();
  216616. listeners.addIfNotAlreadyThere (listenerToAdd);
  216617. }
  216618. void removeListener (CameraDevice::Listener* listenerToRemove)
  216619. {
  216620. const ScopedLock sl (listenerLock);
  216621. listeners.removeValue (listenerToRemove);
  216622. if (listeners.size() == 0)
  216623. removeUser();
  216624. }
  216625. void callListeners (const Image& image)
  216626. {
  216627. const ScopedLock sl (listenerLock);
  216628. for (int i = listeners.size(); --i >= 0;)
  216629. {
  216630. CameraDevice::Listener* const l = listeners[i];
  216631. if (l != 0)
  216632. l->imageReceived (image);
  216633. }
  216634. }
  216635. class DShowCaptureViewerComp : public Component,
  216636. public ChangeListener
  216637. {
  216638. public:
  216639. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216640. : owner (owner_)
  216641. {
  216642. setOpaque (true);
  216643. owner->addChangeListener (this);
  216644. owner->addUser();
  216645. owner->viewerComps.add (this);
  216646. setSize (owner_->width, owner_->height);
  216647. }
  216648. ~DShowCaptureViewerComp()
  216649. {
  216650. if (owner != 0)
  216651. {
  216652. owner->viewerComps.removeValue (this);
  216653. owner->removeUser();
  216654. owner->removeChangeListener (this);
  216655. }
  216656. }
  216657. void ownerDeleted()
  216658. {
  216659. owner = 0;
  216660. }
  216661. void paint (Graphics& g)
  216662. {
  216663. g.setColour (Colours::black);
  216664. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216665. if (owner != 0)
  216666. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216667. else
  216668. g.fillAll (Colours::black);
  216669. }
  216670. void changeListenerCallback (void*)
  216671. {
  216672. repaint();
  216673. }
  216674. private:
  216675. DShowCameraDeviceInteral* owner;
  216676. };
  216677. bool ok;
  216678. int width, height;
  216679. Time firstRecordedTime;
  216680. Array <DShowCaptureViewerComp*> viewerComps;
  216681. private:
  216682. CameraDevice* const owner;
  216683. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216684. ComSmartPtr <IBaseFilter> filter;
  216685. ComSmartPtr <IBaseFilter> smartTee;
  216686. ComSmartPtr <IGraphBuilder> graphBuilder;
  216687. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216688. ComSmartPtr <IMediaControl> mediaControl;
  216689. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216690. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216691. ComSmartPtr <IBaseFilter> asfWriter;
  216692. int activeUsers;
  216693. Array <int> widths, heights;
  216694. DWORD graphRegistrationID;
  216695. CriticalSection imageSwapLock;
  216696. bool imageNeedsFlipping;
  216697. Image loadingImage;
  216698. Image activeImage;
  216699. bool recordNextFrameTime;
  216700. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216701. {
  216702. widths.clear();
  216703. heights.clear();
  216704. int count = 0, size = 0;
  216705. streamConfig->GetNumberOfCapabilities (&count, &size);
  216706. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216707. {
  216708. for (int i = 0; i < count; ++i)
  216709. {
  216710. VIDEO_STREAM_CONFIG_CAPS scc;
  216711. AM_MEDIA_TYPE* config;
  216712. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216713. if (SUCCEEDED (hr))
  216714. {
  216715. const int w = scc.InputSize.cx;
  216716. const int h = scc.InputSize.cy;
  216717. bool duplicate = false;
  216718. for (int j = widths.size(); --j >= 0;)
  216719. {
  216720. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216721. {
  216722. duplicate = true;
  216723. break;
  216724. }
  216725. }
  216726. if (! duplicate)
  216727. {
  216728. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216729. widths.add (w);
  216730. heights.add (h);
  216731. }
  216732. deleteMediaType (config);
  216733. }
  216734. }
  216735. }
  216736. }
  216737. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216738. const int minWidth, const int minHeight,
  216739. const int maxWidth, const int maxHeight)
  216740. {
  216741. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216742. streamConfig->GetNumberOfCapabilities (&count, &size);
  216743. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216744. {
  216745. AM_MEDIA_TYPE* config;
  216746. VIDEO_STREAM_CONFIG_CAPS scc;
  216747. for (int i = 0; i < count; ++i)
  216748. {
  216749. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216750. if (SUCCEEDED (hr))
  216751. {
  216752. if (scc.InputSize.cx >= minWidth
  216753. && scc.InputSize.cy >= minHeight
  216754. && scc.InputSize.cx <= maxWidth
  216755. && scc.InputSize.cy <= maxHeight)
  216756. {
  216757. int area = scc.InputSize.cx * scc.InputSize.cy;
  216758. if (area > bestArea)
  216759. {
  216760. bestIndex = i;
  216761. bestArea = area;
  216762. }
  216763. }
  216764. deleteMediaType (config);
  216765. }
  216766. }
  216767. if (bestIndex >= 0)
  216768. {
  216769. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216770. hr = streamConfig->SetFormat (config);
  216771. deleteMediaType (config);
  216772. return SUCCEEDED (hr);
  216773. }
  216774. }
  216775. return false;
  216776. }
  216777. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  216778. {
  216779. ComSmartPtr <IEnumPins> enumerator;
  216780. ComSmartPtr <IPin> pin;
  216781. filter->EnumPins (&enumerator);
  216782. while (enumerator->Next (1, &pin, 0) == S_OK)
  216783. {
  216784. PIN_DIRECTION dir;
  216785. pin->QueryDirection (&dir);
  216786. if (wantedDirection == dir)
  216787. {
  216788. PIN_INFO info;
  216789. zerostruct (info);
  216790. pin->QueryPinInfo (&info);
  216791. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216792. {
  216793. pin->AddRef();
  216794. *result = pin;
  216795. return true;
  216796. }
  216797. }
  216798. }
  216799. return false;
  216800. }
  216801. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216802. {
  216803. ComSmartPtr <IPin> in, out;
  216804. return getPin (first, PINDIR_OUTPUT, &out)
  216805. && getPin (second, PINDIR_INPUT, &in)
  216806. && SUCCEEDED (graphBuilder->Connect (out, in));
  216807. }
  216808. bool addGraphToRot()
  216809. {
  216810. ComSmartPtr <IRunningObjectTable> rot;
  216811. if (FAILED (GetRunningObjectTable (0, &rot)))
  216812. return false;
  216813. ComSmartPtr <IMoniker> moniker;
  216814. WCHAR buffer[128];
  216815. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  216816. if (FAILED (hr))
  216817. return false;
  216818. graphRegistrationID = 0;
  216819. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216820. }
  216821. void removeGraphFromRot()
  216822. {
  216823. ComSmartPtr <IRunningObjectTable> rot;
  216824. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  216825. rot->Revoke (graphRegistrationID);
  216826. }
  216827. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216828. {
  216829. if (pmt->cbFormat != 0)
  216830. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216831. if (pmt->pUnk != 0)
  216832. pmt->pUnk->Release();
  216833. CoTaskMemFree (pmt);
  216834. }
  216835. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216836. {
  216837. public:
  216838. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216839. : owner (owner_)
  216840. {
  216841. }
  216842. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216843. {
  216844. return E_FAIL;
  216845. }
  216846. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216847. {
  216848. owner.handleFrame (time, buffer, bufferSize);
  216849. return S_OK;
  216850. }
  216851. private:
  216852. DShowCameraDeviceInteral& owner;
  216853. GrabberCallback (const GrabberCallback&);
  216854. GrabberCallback& operator= (const GrabberCallback&);
  216855. };
  216856. ComSmartPtr <GrabberCallback> callback;
  216857. Array <CameraDevice::Listener*> listeners;
  216858. CriticalSection listenerLock;
  216859. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216860. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216861. };
  216862. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216863. : name (name_)
  216864. {
  216865. isRecording = false;
  216866. }
  216867. CameraDevice::~CameraDevice()
  216868. {
  216869. stopRecording();
  216870. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216871. internal = 0;
  216872. }
  216873. Component* CameraDevice::createViewerComponent()
  216874. {
  216875. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216876. }
  216877. const String CameraDevice::getFileExtension()
  216878. {
  216879. return ".wmv";
  216880. }
  216881. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216882. {
  216883. stopRecording();
  216884. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216885. d->addUser();
  216886. isRecording = d->createFileCaptureFilter (file);
  216887. }
  216888. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216889. {
  216890. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216891. return d->firstRecordedTime;
  216892. }
  216893. void CameraDevice::stopRecording()
  216894. {
  216895. if (isRecording)
  216896. {
  216897. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216898. d->removeFileCaptureFilter();
  216899. d->removeUser();
  216900. isRecording = false;
  216901. }
  216902. }
  216903. void CameraDevice::addListener (Listener* listenerToAdd)
  216904. {
  216905. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216906. if (listenerToAdd != 0)
  216907. d->addListener (listenerToAdd);
  216908. }
  216909. void CameraDevice::removeListener (Listener* listenerToRemove)
  216910. {
  216911. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216912. if (listenerToRemove != 0)
  216913. d->removeListener (listenerToRemove);
  216914. }
  216915. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216916. const int deviceIndexToOpen,
  216917. String& name)
  216918. {
  216919. int index = 0;
  216920. ComSmartPtr <IBaseFilter> result;
  216921. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216922. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216923. if (SUCCEEDED (hr))
  216924. {
  216925. ComSmartPtr <IEnumMoniker> enumerator;
  216926. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  216927. if (SUCCEEDED (hr) && enumerator != 0)
  216928. {
  216929. ComSmartPtr <IBaseFilter> captureFilter;
  216930. ComSmartPtr <IMoniker> moniker;
  216931. ULONG fetched;
  216932. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  216933. {
  216934. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  216935. if (SUCCEEDED (hr))
  216936. {
  216937. ComSmartPtr <IPropertyBag> propertyBag;
  216938. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  216939. if (SUCCEEDED (hr))
  216940. {
  216941. VARIANT var;
  216942. var.vt = VT_BSTR;
  216943. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216944. propertyBag = 0;
  216945. if (SUCCEEDED (hr))
  216946. {
  216947. if (names != 0)
  216948. names->add (var.bstrVal);
  216949. if (index == deviceIndexToOpen)
  216950. {
  216951. name = var.bstrVal;
  216952. result = captureFilter;
  216953. captureFilter = 0;
  216954. break;
  216955. }
  216956. ++index;
  216957. }
  216958. moniker = 0;
  216959. }
  216960. captureFilter = 0;
  216961. }
  216962. }
  216963. }
  216964. }
  216965. return result;
  216966. }
  216967. const StringArray CameraDevice::getAvailableDevices()
  216968. {
  216969. StringArray devs;
  216970. String dummy;
  216971. enumerateCameras (&devs, -1, dummy);
  216972. return devs;
  216973. }
  216974. CameraDevice* CameraDevice::openDevice (int index,
  216975. int minWidth, int minHeight,
  216976. int maxWidth, int maxHeight)
  216977. {
  216978. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216979. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216980. if (SUCCEEDED (hr))
  216981. {
  216982. String name;
  216983. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216984. if (filter != 0)
  216985. {
  216986. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216987. DShowCameraDeviceInteral* const intern
  216988. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216989. minWidth, minHeight, maxWidth, maxHeight);
  216990. cam->internal = intern;
  216991. if (intern->ok)
  216992. return cam.release();
  216993. }
  216994. }
  216995. return 0;
  216996. }
  216997. #endif
  216998. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216999. #endif
  217000. // Auto-link the other win32 libs that are needed by library calls..
  217001. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217002. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217003. // Auto-links to various win32 libs that are needed by library calls..
  217004. #pragma comment(lib, "kernel32.lib")
  217005. #pragma comment(lib, "user32.lib")
  217006. #pragma comment(lib, "shell32.lib")
  217007. #pragma comment(lib, "gdi32.lib")
  217008. #pragma comment(lib, "vfw32.lib")
  217009. #pragma comment(lib, "comdlg32.lib")
  217010. #pragma comment(lib, "winmm.lib")
  217011. #pragma comment(lib, "wininet.lib")
  217012. #pragma comment(lib, "ole32.lib")
  217013. #pragma comment(lib, "oleaut32.lib")
  217014. #pragma comment(lib, "advapi32.lib")
  217015. #pragma comment(lib, "ws2_32.lib")
  217016. #pragma comment(lib, "version.lib")
  217017. #ifdef _NATIVE_WCHAR_T_DEFINED
  217018. #ifdef _DEBUG
  217019. #pragma comment(lib, "comsuppwd.lib")
  217020. #else
  217021. #pragma comment(lib, "comsuppw.lib")
  217022. #endif
  217023. #else
  217024. #ifdef _DEBUG
  217025. #pragma comment(lib, "comsuppd.lib")
  217026. #else
  217027. #pragma comment(lib, "comsupp.lib")
  217028. #endif
  217029. #endif
  217030. #if JUCE_OPENGL
  217031. #pragma comment(lib, "OpenGL32.Lib")
  217032. #pragma comment(lib, "GlU32.Lib")
  217033. #endif
  217034. #if JUCE_QUICKTIME
  217035. #pragma comment (lib, "QTMLClient.lib")
  217036. #endif
  217037. #if JUCE_USE_CAMERA
  217038. #pragma comment (lib, "Strmiids.lib")
  217039. #pragma comment (lib, "wmvcore.lib")
  217040. #endif
  217041. #if JUCE_DIRECT2D
  217042. #pragma comment (lib, "Dwrite.lib")
  217043. #pragma comment (lib, "D2d1.lib")
  217044. #endif
  217045. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217046. #endif
  217047. END_JUCE_NAMESPACE
  217048. #endif
  217049. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217050. #endif
  217051. #if JUCE_LINUX
  217052. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217053. /*
  217054. This file wraps together all the mac-specific code, so that
  217055. we can include all the native headers just once, and compile all our
  217056. platform-specific stuff in one big lump, keeping it out of the way of
  217057. the rest of the codebase.
  217058. */
  217059. #if JUCE_LINUX
  217060. BEGIN_JUCE_NAMESPACE
  217061. #define JUCE_INCLUDED_FILE 1
  217062. // Now include the actual code files..
  217063. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217064. /*
  217065. This file contains posix routines that are common to both the Linux and Mac builds.
  217066. It gets included directly in the cpp files for these platforms.
  217067. */
  217068. CriticalSection::CriticalSection() throw()
  217069. {
  217070. pthread_mutexattr_t atts;
  217071. pthread_mutexattr_init (&atts);
  217072. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217073. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217074. pthread_mutex_init (&internal, &atts);
  217075. }
  217076. CriticalSection::~CriticalSection() throw()
  217077. {
  217078. pthread_mutex_destroy (&internal);
  217079. }
  217080. void CriticalSection::enter() const throw()
  217081. {
  217082. pthread_mutex_lock (&internal);
  217083. }
  217084. bool CriticalSection::tryEnter() const throw()
  217085. {
  217086. return pthread_mutex_trylock (&internal) == 0;
  217087. }
  217088. void CriticalSection::exit() const throw()
  217089. {
  217090. pthread_mutex_unlock (&internal);
  217091. }
  217092. class WaitableEventImpl
  217093. {
  217094. public:
  217095. WaitableEventImpl (const bool manualReset_)
  217096. : triggered (false),
  217097. manualReset (manualReset_)
  217098. {
  217099. pthread_cond_init (&condition, 0);
  217100. pthread_mutexattr_t atts;
  217101. pthread_mutexattr_init (&atts);
  217102. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217103. pthread_mutex_init (&mutex, &atts);
  217104. }
  217105. ~WaitableEventImpl()
  217106. {
  217107. pthread_cond_destroy (&condition);
  217108. pthread_mutex_destroy (&mutex);
  217109. }
  217110. bool wait (const int timeOutMillisecs) throw()
  217111. {
  217112. pthread_mutex_lock (&mutex);
  217113. if (! triggered)
  217114. {
  217115. if (timeOutMillisecs < 0)
  217116. {
  217117. do
  217118. {
  217119. pthread_cond_wait (&condition, &mutex);
  217120. }
  217121. while (! triggered);
  217122. }
  217123. else
  217124. {
  217125. struct timeval now;
  217126. gettimeofday (&now, 0);
  217127. struct timespec time;
  217128. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217129. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217130. if (time.tv_nsec >= 1000000000)
  217131. {
  217132. time.tv_nsec -= 1000000000;
  217133. time.tv_sec++;
  217134. }
  217135. do
  217136. {
  217137. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217138. {
  217139. pthread_mutex_unlock (&mutex);
  217140. return false;
  217141. }
  217142. }
  217143. while (! triggered);
  217144. }
  217145. }
  217146. if (! manualReset)
  217147. triggered = false;
  217148. pthread_mutex_unlock (&mutex);
  217149. return true;
  217150. }
  217151. void signal() throw()
  217152. {
  217153. pthread_mutex_lock (&mutex);
  217154. triggered = true;
  217155. pthread_cond_broadcast (&condition);
  217156. pthread_mutex_unlock (&mutex);
  217157. }
  217158. void reset() throw()
  217159. {
  217160. pthread_mutex_lock (&mutex);
  217161. triggered = false;
  217162. pthread_mutex_unlock (&mutex);
  217163. }
  217164. private:
  217165. pthread_cond_t condition;
  217166. pthread_mutex_t mutex;
  217167. bool triggered;
  217168. const bool manualReset;
  217169. WaitableEventImpl (const WaitableEventImpl&);
  217170. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217171. };
  217172. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217173. : internal (new WaitableEventImpl (manualReset))
  217174. {
  217175. }
  217176. WaitableEvent::~WaitableEvent() throw()
  217177. {
  217178. delete static_cast <WaitableEventImpl*> (internal);
  217179. }
  217180. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217181. {
  217182. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217183. }
  217184. void WaitableEvent::signal() const throw()
  217185. {
  217186. static_cast <WaitableEventImpl*> (internal)->signal();
  217187. }
  217188. void WaitableEvent::reset() const throw()
  217189. {
  217190. static_cast <WaitableEventImpl*> (internal)->reset();
  217191. }
  217192. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217193. {
  217194. struct timespec time;
  217195. time.tv_sec = millisecs / 1000;
  217196. time.tv_nsec = (millisecs % 1000) * 1000000;
  217197. nanosleep (&time, 0);
  217198. }
  217199. const juce_wchar File::separator = '/';
  217200. const String File::separatorString ("/");
  217201. const File File::getCurrentWorkingDirectory()
  217202. {
  217203. HeapBlock<char> heapBuffer;
  217204. char localBuffer [1024];
  217205. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217206. int bufferSize = 4096;
  217207. while (cwd == 0 && errno == ERANGE)
  217208. {
  217209. heapBuffer.malloc (bufferSize);
  217210. cwd = getcwd (heapBuffer, bufferSize - 1);
  217211. bufferSize += 1024;
  217212. }
  217213. return File (String::fromUTF8 (cwd));
  217214. }
  217215. bool File::setAsCurrentWorkingDirectory() const
  217216. {
  217217. return chdir (getFullPathName().toUTF8()) == 0;
  217218. }
  217219. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217220. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217221. #else
  217222. typedef struct stat juce_statStruct;
  217223. #endif
  217224. static bool juce_stat (const String& fileName, juce_statStruct& info)
  217225. {
  217226. return fileName.isNotEmpty()
  217227. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217228. && (stat64 (fileName.toUTF8(), &info) == 0);
  217229. #else
  217230. && (stat (fileName.toUTF8(), &info) == 0);
  217231. #endif
  217232. }
  217233. bool File::isDirectory() const
  217234. {
  217235. juce_statStruct info;
  217236. return fullPath.isEmpty()
  217237. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217238. }
  217239. bool File::exists() const
  217240. {
  217241. return fullPath.isNotEmpty()
  217242. && access (fullPath.toUTF8(), F_OK) == 0;
  217243. }
  217244. bool File::existsAsFile() const
  217245. {
  217246. return exists() && ! isDirectory();
  217247. }
  217248. int64 File::getSize() const
  217249. {
  217250. juce_statStruct info;
  217251. return juce_stat (fullPath, info) ? info.st_size : 0;
  217252. }
  217253. bool File::hasWriteAccess() const
  217254. {
  217255. if (exists())
  217256. return access (fullPath.toUTF8(), W_OK) == 0;
  217257. if ((! isDirectory()) && fullPath.containsChar (separator))
  217258. return getParentDirectory().hasWriteAccess();
  217259. return false;
  217260. }
  217261. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217262. {
  217263. juce_statStruct info;
  217264. if (! juce_stat (fullPath, info))
  217265. return false;
  217266. info.st_mode &= 0777; // Just permissions
  217267. if (shouldBeReadOnly)
  217268. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217269. else
  217270. // Give everybody write permission?
  217271. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217272. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217273. }
  217274. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217275. {
  217276. modificationTime = 0;
  217277. accessTime = 0;
  217278. creationTime = 0;
  217279. juce_statStruct info;
  217280. if (juce_stat (fullPath, info))
  217281. {
  217282. modificationTime = (int64) info.st_mtime * 1000;
  217283. accessTime = (int64) info.st_atime * 1000;
  217284. creationTime = (int64) info.st_ctime * 1000;
  217285. }
  217286. }
  217287. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217288. {
  217289. struct utimbuf times;
  217290. times.actime = (time_t) (accessTime / 1000);
  217291. times.modtime = (time_t) (modificationTime / 1000);
  217292. return utime (fullPath.toUTF8(), &times) == 0;
  217293. }
  217294. bool File::deleteFile() const
  217295. {
  217296. if (! exists())
  217297. return true;
  217298. else if (isDirectory())
  217299. return rmdir (fullPath.toUTF8()) == 0;
  217300. else
  217301. return remove (fullPath.toUTF8()) == 0;
  217302. }
  217303. bool File::moveInternal (const File& dest) const
  217304. {
  217305. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217306. return true;
  217307. if (hasWriteAccess() && copyInternal (dest))
  217308. {
  217309. if (deleteFile())
  217310. return true;
  217311. dest.deleteFile();
  217312. }
  217313. return false;
  217314. }
  217315. void File::createDirectoryInternal (const String& fileName) const
  217316. {
  217317. mkdir (fileName.toUTF8(), 0777);
  217318. }
  217319. int64 juce_fileSetPosition (void* handle, int64 pos)
  217320. {
  217321. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217322. return pos;
  217323. return -1;
  217324. }
  217325. void FileInputStream::openHandle()
  217326. {
  217327. totalSize = file.getSize();
  217328. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217329. if (f != -1)
  217330. fileHandle = (void*) f;
  217331. }
  217332. void FileInputStream::closeHandle()
  217333. {
  217334. if (fileHandle != 0)
  217335. {
  217336. close ((int) (pointer_sized_int) fileHandle);
  217337. fileHandle = 0;
  217338. }
  217339. }
  217340. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217341. {
  217342. if (fileHandle != 0)
  217343. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217344. return 0;
  217345. }
  217346. void FileOutputStream::openHandle()
  217347. {
  217348. if (file.exists())
  217349. {
  217350. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217351. if (f != -1)
  217352. {
  217353. currentPosition = lseek (f, 0, SEEK_END);
  217354. if (currentPosition >= 0)
  217355. fileHandle = (void*) f;
  217356. else
  217357. close (f);
  217358. }
  217359. }
  217360. else
  217361. {
  217362. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217363. if (f != -1)
  217364. fileHandle = (void*) f;
  217365. }
  217366. }
  217367. void FileOutputStream::closeHandle()
  217368. {
  217369. if (fileHandle != 0)
  217370. {
  217371. close ((int) (pointer_sized_int) fileHandle);
  217372. fileHandle = 0;
  217373. }
  217374. }
  217375. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217376. {
  217377. if (fileHandle != 0)
  217378. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217379. return 0;
  217380. }
  217381. void FileOutputStream::flushInternal()
  217382. {
  217383. if (fileHandle != 0)
  217384. fsync ((int) (pointer_sized_int) fileHandle);
  217385. }
  217386. const File juce_getExecutableFile()
  217387. {
  217388. Dl_info exeInfo;
  217389. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217390. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217391. }
  217392. // if this file doesn't exist, find a parent of it that does..
  217393. static bool juce_doStatFS (File f, struct statfs& result)
  217394. {
  217395. for (int i = 5; --i >= 0;)
  217396. {
  217397. if (f.exists())
  217398. break;
  217399. f = f.getParentDirectory();
  217400. }
  217401. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217402. }
  217403. int64 File::getBytesFreeOnVolume() const
  217404. {
  217405. struct statfs buf;
  217406. if (juce_doStatFS (*this, buf))
  217407. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217408. return 0;
  217409. }
  217410. int64 File::getVolumeTotalSize() const
  217411. {
  217412. struct statfs buf;
  217413. if (juce_doStatFS (*this, buf))
  217414. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217415. return 0;
  217416. }
  217417. const String File::getVolumeLabel() const
  217418. {
  217419. #if JUCE_MAC
  217420. struct VolAttrBuf
  217421. {
  217422. u_int32_t length;
  217423. attrreference_t mountPointRef;
  217424. char mountPointSpace [MAXPATHLEN];
  217425. } attrBuf;
  217426. struct attrlist attrList;
  217427. zerostruct (attrList);
  217428. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217429. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217430. File f (*this);
  217431. for (;;)
  217432. {
  217433. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217434. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217435. (int) attrBuf.mountPointRef.attr_length);
  217436. const File parent (f.getParentDirectory());
  217437. if (f == parent)
  217438. break;
  217439. f = parent;
  217440. }
  217441. #endif
  217442. return String::empty;
  217443. }
  217444. int File::getVolumeSerialNumber() const
  217445. {
  217446. return 0; // xxx
  217447. }
  217448. void juce_runSystemCommand (const String& command)
  217449. {
  217450. int result = system (command.toUTF8());
  217451. (void) result;
  217452. }
  217453. const String juce_getOutputFromCommand (const String& command)
  217454. {
  217455. // slight bodge here, as we just pipe the output into a temp file and read it...
  217456. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217457. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217458. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217459. String result (tempFile.loadFileAsString());
  217460. tempFile.deleteFile();
  217461. return result;
  217462. }
  217463. class InterProcessLock::Pimpl
  217464. {
  217465. public:
  217466. Pimpl (const String& name, const int timeOutMillisecs)
  217467. : handle (0), refCount (1)
  217468. {
  217469. #if JUCE_MAC
  217470. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217471. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217472. #else
  217473. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217474. #endif
  217475. temp.create();
  217476. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217477. if (handle != 0)
  217478. {
  217479. struct flock fl;
  217480. zerostruct (fl);
  217481. fl.l_whence = SEEK_SET;
  217482. fl.l_type = F_WRLCK;
  217483. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217484. for (;;)
  217485. {
  217486. const int result = fcntl (handle, F_SETLK, &fl);
  217487. if (result >= 0)
  217488. return;
  217489. if (errno != EINTR)
  217490. {
  217491. if (timeOutMillisecs == 0
  217492. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217493. break;
  217494. Thread::sleep (10);
  217495. }
  217496. }
  217497. }
  217498. closeFile();
  217499. }
  217500. ~Pimpl()
  217501. {
  217502. closeFile();
  217503. }
  217504. void closeFile()
  217505. {
  217506. if (handle != 0)
  217507. {
  217508. struct flock fl;
  217509. zerostruct (fl);
  217510. fl.l_whence = SEEK_SET;
  217511. fl.l_type = F_UNLCK;
  217512. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217513. {}
  217514. close (handle);
  217515. handle = 0;
  217516. }
  217517. }
  217518. int handle, refCount;
  217519. };
  217520. InterProcessLock::InterProcessLock (const String& name_)
  217521. : name (name_)
  217522. {
  217523. }
  217524. InterProcessLock::~InterProcessLock()
  217525. {
  217526. }
  217527. bool InterProcessLock::enter (const int timeOutMillisecs)
  217528. {
  217529. const ScopedLock sl (lock);
  217530. if (pimpl == 0)
  217531. {
  217532. pimpl = new Pimpl (name, timeOutMillisecs);
  217533. if (pimpl->handle == 0)
  217534. pimpl = 0;
  217535. }
  217536. else
  217537. {
  217538. pimpl->refCount++;
  217539. }
  217540. return pimpl != 0;
  217541. }
  217542. void InterProcessLock::exit()
  217543. {
  217544. const ScopedLock sl (lock);
  217545. // Trying to release the lock too many times!
  217546. jassert (pimpl != 0);
  217547. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217548. pimpl = 0;
  217549. }
  217550. void JUCE_API juce_threadEntryPoint (void*);
  217551. void* threadEntryProc (void* userData)
  217552. {
  217553. JUCE_AUTORELEASEPOOL
  217554. juce_threadEntryPoint (userData);
  217555. return 0;
  217556. }
  217557. void* juce_createThread (void* userData)
  217558. {
  217559. pthread_t handle = 0;
  217560. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217561. {
  217562. pthread_detach (handle);
  217563. return (void*) handle;
  217564. }
  217565. return 0;
  217566. }
  217567. void juce_killThread (void* handle)
  217568. {
  217569. if (handle != 0)
  217570. pthread_cancel ((pthread_t) handle);
  217571. }
  217572. void juce_setCurrentThreadName (const String& /*name*/)
  217573. {
  217574. }
  217575. bool juce_setThreadPriority (void* handle, int priority)
  217576. {
  217577. struct sched_param param;
  217578. int policy;
  217579. priority = jlimit (0, 10, priority);
  217580. if (handle == 0)
  217581. handle = (void*) pthread_self();
  217582. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217583. return false;
  217584. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217585. const int minPriority = sched_get_priority_min (policy);
  217586. const int maxPriority = sched_get_priority_max (policy);
  217587. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217588. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217589. }
  217590. Thread::ThreadID Thread::getCurrentThreadId()
  217591. {
  217592. return (ThreadID) pthread_self();
  217593. }
  217594. void Thread::yield()
  217595. {
  217596. sched_yield();
  217597. }
  217598. /* Remove this macro if you're having problems compiling the cpu affinity
  217599. calls (the API for these has changed about quite a bit in various Linux
  217600. versions, and a lot of distros seem to ship with obsolete versions)
  217601. */
  217602. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217603. #define SUPPORT_AFFINITIES 1
  217604. #endif
  217605. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217606. {
  217607. #if SUPPORT_AFFINITIES
  217608. cpu_set_t affinity;
  217609. CPU_ZERO (&affinity);
  217610. for (int i = 0; i < 32; ++i)
  217611. if ((affinityMask & (1 << i)) != 0)
  217612. CPU_SET (i, &affinity);
  217613. /*
  217614. N.B. If this line causes a compile error, then you've probably not got the latest
  217615. version of glibc installed.
  217616. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217617. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217618. */
  217619. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217620. sched_yield();
  217621. #else
  217622. /* affinities aren't supported because either the appropriate header files weren't found,
  217623. or the SUPPORT_AFFINITIES macro was turned off
  217624. */
  217625. jassertfalse;
  217626. #endif
  217627. }
  217628. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217629. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217630. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217631. // compiled on its own).
  217632. #if JUCE_INCLUDED_FILE
  217633. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217634. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217635. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217636. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217637. bool File::copyInternal (const File& dest) const
  217638. {
  217639. FileInputStream in (*this);
  217640. if (dest.deleteFile())
  217641. {
  217642. {
  217643. FileOutputStream out (dest);
  217644. if (out.failedToOpen())
  217645. return false;
  217646. if (out.writeFromInputStream (in, -1) == getSize())
  217647. return true;
  217648. }
  217649. dest.deleteFile();
  217650. }
  217651. return false;
  217652. }
  217653. void File::findFileSystemRoots (Array<File>& destArray)
  217654. {
  217655. destArray.add (File ("/"));
  217656. }
  217657. bool File::isOnCDRomDrive() const
  217658. {
  217659. struct statfs buf;
  217660. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217661. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217662. }
  217663. bool File::isOnHardDisk() const
  217664. {
  217665. struct statfs buf;
  217666. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217667. {
  217668. switch (buf.f_type)
  217669. {
  217670. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217671. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217672. case U_NFS_SUPER_MAGIC: // Network NFS
  217673. case U_SMB_SUPER_MAGIC: // Network Samba
  217674. return false;
  217675. default:
  217676. // Assume anything else is a hard-disk (but note it could
  217677. // be a RAM disk. There isn't a good way of determining
  217678. // this for sure)
  217679. return true;
  217680. }
  217681. }
  217682. // Assume so if this fails for some reason
  217683. return true;
  217684. }
  217685. bool File::isOnRemovableDrive() const
  217686. {
  217687. jassertfalse; // xxx not implemented for linux!
  217688. return false;
  217689. }
  217690. bool File::isHidden() const
  217691. {
  217692. return getFileName().startsWithChar ('.');
  217693. }
  217694. static const File juce_readlink (const char* const utf8, const File& defaultFile)
  217695. {
  217696. const int size = 8192;
  217697. HeapBlock<char> buffer;
  217698. buffer.malloc (size + 4);
  217699. const size_t numBytes = readlink (utf8, buffer, size);
  217700. if (numBytes > 0 && numBytes <= size)
  217701. return File (String::fromUTF8 (buffer, (int) numBytes));
  217702. return defaultFile;
  217703. }
  217704. const File File::getLinkedTarget() const
  217705. {
  217706. return juce_readlink (getFullPathName().toUTF8(), *this);
  217707. }
  217708. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217709. const File File::getSpecialLocation (const SpecialLocationType type)
  217710. {
  217711. switch (type)
  217712. {
  217713. case userHomeDirectory:
  217714. {
  217715. const char* homeDir = getenv ("HOME");
  217716. if (homeDir == 0)
  217717. {
  217718. struct passwd* const pw = getpwuid (getuid());
  217719. if (pw != 0)
  217720. homeDir = pw->pw_dir;
  217721. }
  217722. return File (String::fromUTF8 (homeDir));
  217723. }
  217724. case userDocumentsDirectory:
  217725. case userMusicDirectory:
  217726. case userMoviesDirectory:
  217727. case userApplicationDataDirectory:
  217728. return File ("~");
  217729. case userDesktopDirectory:
  217730. return File ("~/Desktop");
  217731. case commonApplicationDataDirectory:
  217732. return File ("/var");
  217733. case globalApplicationsDirectory:
  217734. return File ("/usr");
  217735. case tempDirectory:
  217736. {
  217737. File tmp ("/var/tmp");
  217738. if (! tmp.isDirectory())
  217739. {
  217740. tmp = "/tmp";
  217741. if (! tmp.isDirectory())
  217742. tmp = File::getCurrentWorkingDirectory();
  217743. }
  217744. return tmp;
  217745. }
  217746. case invokedExecutableFile:
  217747. if (juce_Argv0 != 0)
  217748. return File (String::fromUTF8 (juce_Argv0));
  217749. // deliberate fall-through...
  217750. case currentExecutableFile:
  217751. case currentApplicationFile:
  217752. return juce_getExecutableFile();
  217753. case hostApplicationPath:
  217754. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217755. default:
  217756. jassertfalse; // unknown type?
  217757. break;
  217758. }
  217759. return File::nonexistent;
  217760. }
  217761. const String File::getVersion() const
  217762. {
  217763. return String::empty; // xxx not yet implemented
  217764. }
  217765. bool File::moveToTrash() const
  217766. {
  217767. if (! exists())
  217768. return true;
  217769. File trashCan ("~/.Trash");
  217770. if (! trashCan.isDirectory())
  217771. trashCan = "~/.local/share/Trash/files";
  217772. if (! trashCan.isDirectory())
  217773. return false;
  217774. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217775. getFileExtension()));
  217776. }
  217777. class DirectoryIterator::NativeIterator::Pimpl
  217778. {
  217779. public:
  217780. Pimpl (const File& directory, const String& wildCard_)
  217781. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217782. wildCard (wildCard_),
  217783. dir (opendir (directory.getFullPathName().toUTF8()))
  217784. {
  217785. if (wildCard == "*.*")
  217786. wildCard = "*";
  217787. wildcardUTF8 = wildCard.toUTF8();
  217788. }
  217789. ~Pimpl()
  217790. {
  217791. if (dir != 0)
  217792. closedir (dir);
  217793. }
  217794. bool next (String& filenameFound,
  217795. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217796. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217797. {
  217798. if (dir == 0)
  217799. return false;
  217800. for (;;)
  217801. {
  217802. struct dirent* const de = readdir (dir);
  217803. if (de == 0)
  217804. return false;
  217805. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217806. {
  217807. filenameFound = String::fromUTF8 (de->d_name);
  217808. const String path (parentDir + filenameFound);
  217809. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217810. {
  217811. struct stat info;
  217812. const bool statOk = juce_stat (path, info);
  217813. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217814. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217815. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217816. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217817. }
  217818. if (isHidden != 0)
  217819. *isHidden = filenameFound.startsWithChar ('.');
  217820. if (isReadOnly != 0)
  217821. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217822. return true;
  217823. }
  217824. }
  217825. }
  217826. private:
  217827. String parentDir, wildCard;
  217828. const char* wildcardUTF8;
  217829. DIR* dir;
  217830. Pimpl (const Pimpl&);
  217831. Pimpl& operator= (const Pimpl&);
  217832. };
  217833. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217834. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217835. {
  217836. }
  217837. DirectoryIterator::NativeIterator::~NativeIterator()
  217838. {
  217839. }
  217840. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217841. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217842. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217843. {
  217844. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217845. }
  217846. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217847. {
  217848. String cmdString (fileName.replace (" ", "\\ ",false));
  217849. cmdString << " " << parameters;
  217850. if (URL::isProbablyAWebsiteURL (fileName)
  217851. || cmdString.startsWithIgnoreCase ("file:")
  217852. || URL::isProbablyAnEmailAddress (fileName))
  217853. {
  217854. // create a command that tries to launch a bunch of likely browsers
  217855. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217856. StringArray cmdLines;
  217857. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217858. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217859. cmdString = cmdLines.joinIntoString (" || ");
  217860. }
  217861. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217862. const int cpid = fork();
  217863. if (cpid == 0)
  217864. {
  217865. setsid();
  217866. // Child process
  217867. execve (argv[0], (char**) argv, environ);
  217868. exit (0);
  217869. }
  217870. return cpid >= 0;
  217871. }
  217872. void File::revealToUser() const
  217873. {
  217874. if (isDirectory())
  217875. startAsProcess();
  217876. else if (getParentDirectory().exists())
  217877. getParentDirectory().startAsProcess();
  217878. }
  217879. #endif
  217880. /*** End of inlined file: juce_linux_Files.cpp ***/
  217881. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217882. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217883. // compiled on its own).
  217884. #if JUCE_INCLUDED_FILE
  217885. struct NamedPipeInternal
  217886. {
  217887. String pipeInName, pipeOutName;
  217888. int pipeIn, pipeOut;
  217889. bool volatile createdPipe, blocked, stopReadOperation;
  217890. static void signalHandler (int) {}
  217891. };
  217892. void NamedPipe::cancelPendingReads()
  217893. {
  217894. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217895. {
  217896. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217897. intern->stopReadOperation = true;
  217898. char buffer [1] = { 0 };
  217899. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217900. (void) bytesWritten;
  217901. int timeout = 2000;
  217902. while (intern->blocked && --timeout >= 0)
  217903. Thread::sleep (2);
  217904. intern->stopReadOperation = false;
  217905. }
  217906. }
  217907. void NamedPipe::close()
  217908. {
  217909. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217910. if (intern != 0)
  217911. {
  217912. internal = 0;
  217913. if (intern->pipeIn != -1)
  217914. ::close (intern->pipeIn);
  217915. if (intern->pipeOut != -1)
  217916. ::close (intern->pipeOut);
  217917. if (intern->createdPipe)
  217918. {
  217919. unlink (intern->pipeInName.toUTF8());
  217920. unlink (intern->pipeOutName.toUTF8());
  217921. }
  217922. delete intern;
  217923. }
  217924. }
  217925. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217926. {
  217927. close();
  217928. NamedPipeInternal* const intern = new NamedPipeInternal();
  217929. internal = intern;
  217930. intern->createdPipe = createPipe;
  217931. intern->blocked = false;
  217932. intern->stopReadOperation = false;
  217933. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217934. siginterrupt (SIGPIPE, 1);
  217935. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217936. intern->pipeInName = pipePath + "_in";
  217937. intern->pipeOutName = pipePath + "_out";
  217938. intern->pipeIn = -1;
  217939. intern->pipeOut = -1;
  217940. if (createPipe)
  217941. {
  217942. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217943. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217944. {
  217945. delete intern;
  217946. internal = 0;
  217947. return false;
  217948. }
  217949. }
  217950. return true;
  217951. }
  217952. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217953. {
  217954. int bytesRead = -1;
  217955. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217956. if (intern != 0)
  217957. {
  217958. intern->blocked = true;
  217959. if (intern->pipeIn == -1)
  217960. {
  217961. if (intern->createdPipe)
  217962. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217963. else
  217964. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217965. if (intern->pipeIn == -1)
  217966. {
  217967. intern->blocked = false;
  217968. return -1;
  217969. }
  217970. }
  217971. bytesRead = 0;
  217972. char* p = static_cast<char*> (destBuffer);
  217973. while (bytesRead < maxBytesToRead)
  217974. {
  217975. const int bytesThisTime = maxBytesToRead - bytesRead;
  217976. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217977. if (numRead <= 0 || intern->stopReadOperation)
  217978. {
  217979. bytesRead = -1;
  217980. break;
  217981. }
  217982. bytesRead += numRead;
  217983. p += bytesRead;
  217984. }
  217985. intern->blocked = false;
  217986. }
  217987. return bytesRead;
  217988. }
  217989. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217990. {
  217991. int bytesWritten = -1;
  217992. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217993. if (intern != 0)
  217994. {
  217995. if (intern->pipeOut == -1)
  217996. {
  217997. if (intern->createdPipe)
  217998. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217999. else
  218000. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218001. if (intern->pipeOut == -1)
  218002. {
  218003. return -1;
  218004. }
  218005. }
  218006. const char* p = static_cast<const char*> (sourceBuffer);
  218007. bytesWritten = 0;
  218008. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218009. while (bytesWritten < numBytesToWrite
  218010. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218011. {
  218012. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218013. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218014. if (numWritten <= 0)
  218015. {
  218016. bytesWritten = -1;
  218017. break;
  218018. }
  218019. bytesWritten += numWritten;
  218020. p += bytesWritten;
  218021. }
  218022. }
  218023. return bytesWritten;
  218024. }
  218025. #endif
  218026. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218027. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218028. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218029. // compiled on its own).
  218030. #if JUCE_INCLUDED_FILE
  218031. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218032. {
  218033. int numResults = 0;
  218034. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218035. if (s != -1)
  218036. {
  218037. char buf [1024];
  218038. struct ifconf ifc;
  218039. ifc.ifc_len = sizeof (buf);
  218040. ifc.ifc_buf = buf;
  218041. ioctl (s, SIOCGIFCONF, &ifc);
  218042. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218043. {
  218044. struct ifreq ifr;
  218045. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218046. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218047. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218048. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218049. && numResults < maxNum)
  218050. {
  218051. int64 a = 0;
  218052. for (int j = 6; --j >= 0;)
  218053. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218054. *addresses++ = a;
  218055. ++numResults;
  218056. }
  218057. }
  218058. close (s);
  218059. }
  218060. return numResults;
  218061. }
  218062. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218063. const String& emailSubject,
  218064. const String& bodyText,
  218065. const StringArray& filesToAttach)
  218066. {
  218067. jassertfalse; // xxx todo
  218068. return false;
  218069. }
  218070. /** A HTTP input stream that uses sockets.
  218071. */
  218072. class JUCE_HTTPSocketStream
  218073. {
  218074. public:
  218075. JUCE_HTTPSocketStream()
  218076. : readPosition (0),
  218077. socketHandle (-1),
  218078. levelsOfRedirection (0),
  218079. timeoutSeconds (15)
  218080. {
  218081. }
  218082. ~JUCE_HTTPSocketStream()
  218083. {
  218084. closeSocket();
  218085. }
  218086. bool open (const String& url,
  218087. const String& headers,
  218088. const MemoryBlock& postData,
  218089. const bool isPost,
  218090. URL::OpenStreamProgressCallback* callback,
  218091. void* callbackContext,
  218092. int timeOutMs)
  218093. {
  218094. closeSocket();
  218095. uint32 timeOutTime = Time::getMillisecondCounter();
  218096. if (timeOutMs == 0)
  218097. timeOutTime += 60000;
  218098. else if (timeOutMs < 0)
  218099. timeOutTime = 0xffffffff;
  218100. else
  218101. timeOutTime += timeOutMs;
  218102. String hostName, hostPath;
  218103. int hostPort;
  218104. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218105. return false;
  218106. const struct hostent* host = 0;
  218107. int port = 0;
  218108. String proxyName, proxyPath;
  218109. int proxyPort = 0;
  218110. String proxyURL (getenv ("http_proxy"));
  218111. if (proxyURL.startsWithIgnoreCase ("http://"))
  218112. {
  218113. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218114. return false;
  218115. host = gethostbyname (proxyName.toUTF8());
  218116. port = proxyPort;
  218117. }
  218118. else
  218119. {
  218120. host = gethostbyname (hostName.toUTF8());
  218121. port = hostPort;
  218122. }
  218123. if (host == 0)
  218124. return false;
  218125. struct sockaddr_in address;
  218126. zerostruct (address);
  218127. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218128. address.sin_family = host->h_addrtype;
  218129. address.sin_port = htons (port);
  218130. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218131. if (socketHandle == -1)
  218132. return false;
  218133. int receiveBufferSize = 16384;
  218134. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218135. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218136. #if JUCE_MAC
  218137. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218138. #endif
  218139. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218140. {
  218141. closeSocket();
  218142. return false;
  218143. }
  218144. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218145. proxyName, proxyPort,
  218146. hostPath, url,
  218147. headers, postData,
  218148. isPost));
  218149. size_t totalHeaderSent = 0;
  218150. while (totalHeaderSent < requestHeader.getSize())
  218151. {
  218152. if (Time::getMillisecondCounter() > timeOutTime)
  218153. {
  218154. closeSocket();
  218155. return false;
  218156. }
  218157. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218158. if (send (socketHandle,
  218159. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218160. numToSend, 0)
  218161. != numToSend)
  218162. {
  218163. closeSocket();
  218164. return false;
  218165. }
  218166. totalHeaderSent += numToSend;
  218167. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218168. {
  218169. closeSocket();
  218170. return false;
  218171. }
  218172. }
  218173. const String responseHeader (readResponse (timeOutTime));
  218174. if (responseHeader.isNotEmpty())
  218175. {
  218176. //DBG (responseHeader);
  218177. headerLines.clear();
  218178. headerLines.addLines (responseHeader);
  218179. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218180. .substring (0, 3).getIntValue();
  218181. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218182. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218183. String location (findHeaderItem (headerLines, "Location:"));
  218184. if (statusCode >= 300 && statusCode < 400
  218185. && location.isNotEmpty())
  218186. {
  218187. if (! location.startsWithIgnoreCase ("http://"))
  218188. location = "http://" + location;
  218189. if (levelsOfRedirection++ < 3)
  218190. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218191. }
  218192. else
  218193. {
  218194. levelsOfRedirection = 0;
  218195. return true;
  218196. }
  218197. }
  218198. closeSocket();
  218199. return false;
  218200. }
  218201. int read (void* buffer, int bytesToRead)
  218202. {
  218203. fd_set readbits;
  218204. FD_ZERO (&readbits);
  218205. FD_SET (socketHandle, &readbits);
  218206. struct timeval tv;
  218207. tv.tv_sec = timeoutSeconds;
  218208. tv.tv_usec = 0;
  218209. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218210. return 0; // (timeout)
  218211. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218212. readPosition += bytesRead;
  218213. return bytesRead;
  218214. }
  218215. int readPosition;
  218216. StringArray headerLines;
  218217. juce_UseDebuggingNewOperator
  218218. private:
  218219. int socketHandle, levelsOfRedirection;
  218220. const int timeoutSeconds;
  218221. void closeSocket()
  218222. {
  218223. if (socketHandle >= 0)
  218224. close (socketHandle);
  218225. socketHandle = -1;
  218226. }
  218227. const MemoryBlock createRequestHeader (const String& hostName,
  218228. const int hostPort,
  218229. const String& proxyName,
  218230. const int proxyPort,
  218231. const String& hostPath,
  218232. const String& originalURL,
  218233. const String& headers,
  218234. const MemoryBlock& postData,
  218235. const bool isPost)
  218236. {
  218237. String header (isPost ? "POST " : "GET ");
  218238. if (proxyName.isEmpty())
  218239. {
  218240. header << hostPath << " HTTP/1.0\r\nHost: "
  218241. << hostName << ':' << hostPort;
  218242. }
  218243. else
  218244. {
  218245. header << originalURL << " HTTP/1.0\r\nHost: "
  218246. << proxyName << ':' << proxyPort;
  218247. }
  218248. header << "\r\nUser-Agent: JUCE/"
  218249. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218250. << "\r\nConnection: Close\r\nContent-Length: "
  218251. << postData.getSize() << "\r\n"
  218252. << headers << "\r\n";
  218253. MemoryBlock mb;
  218254. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218255. mb.append (postData.getData(), postData.getSize());
  218256. return mb;
  218257. }
  218258. const String readResponse (const uint32 timeOutTime)
  218259. {
  218260. int bytesRead = 0, numConsecutiveLFs = 0;
  218261. MemoryBlock buffer (1024, true);
  218262. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218263. && Time::getMillisecondCounter() <= timeOutTime)
  218264. {
  218265. fd_set readbits;
  218266. FD_ZERO (&readbits);
  218267. FD_SET (socketHandle, &readbits);
  218268. struct timeval tv;
  218269. tv.tv_sec = timeoutSeconds;
  218270. tv.tv_usec = 0;
  218271. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218272. return String::empty; // (timeout)
  218273. buffer.ensureSize (bytesRead + 8, true);
  218274. char* const dest = (char*) buffer.getData() + bytesRead;
  218275. if (recv (socketHandle, dest, 1, 0) == -1)
  218276. return String::empty;
  218277. const char lastByte = *dest;
  218278. ++bytesRead;
  218279. if (lastByte == '\n')
  218280. ++numConsecutiveLFs;
  218281. else if (lastByte != '\r')
  218282. numConsecutiveLFs = 0;
  218283. }
  218284. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218285. if (header.startsWithIgnoreCase ("HTTP/"))
  218286. return header.trimEnd();
  218287. return String::empty;
  218288. }
  218289. static bool decomposeURL (const String& url,
  218290. String& host, String& path, int& port)
  218291. {
  218292. if (! url.startsWithIgnoreCase ("http://"))
  218293. return false;
  218294. const int nextSlash = url.indexOfChar (7, '/');
  218295. int nextColon = url.indexOfChar (7, ':');
  218296. if (nextColon > nextSlash && nextSlash > 0)
  218297. nextColon = -1;
  218298. if (nextColon >= 0)
  218299. {
  218300. host = url.substring (7, nextColon);
  218301. if (nextSlash >= 0)
  218302. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218303. else
  218304. port = url.substring (nextColon + 1).getIntValue();
  218305. }
  218306. else
  218307. {
  218308. port = 80;
  218309. if (nextSlash >= 0)
  218310. host = url.substring (7, nextSlash);
  218311. else
  218312. host = url.substring (7);
  218313. }
  218314. if (nextSlash >= 0)
  218315. path = url.substring (nextSlash);
  218316. else
  218317. path = "/";
  218318. return true;
  218319. }
  218320. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218321. {
  218322. for (int i = 0; i < lines.size(); ++i)
  218323. if (lines[i].startsWithIgnoreCase (itemName))
  218324. return lines[i].substring (itemName.length()).trim();
  218325. return String::empty;
  218326. }
  218327. };
  218328. void* juce_openInternetFile (const String& url,
  218329. const String& headers,
  218330. const MemoryBlock& postData,
  218331. const bool isPost,
  218332. URL::OpenStreamProgressCallback* callback,
  218333. void* callbackContext,
  218334. int timeOutMs)
  218335. {
  218336. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218337. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218338. return s.release();
  218339. return 0;
  218340. }
  218341. void juce_closeInternetFile (void* handle)
  218342. {
  218343. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218344. }
  218345. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218346. {
  218347. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218348. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218349. }
  218350. int64 juce_getInternetFileContentLength (void* handle)
  218351. {
  218352. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218353. if (s != 0)
  218354. {
  218355. //xxx todo
  218356. jassertfalse
  218357. }
  218358. return -1;
  218359. }
  218360. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218361. {
  218362. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218363. if (s != 0)
  218364. {
  218365. for (int i = 0; i < s->headerLines.size(); ++i)
  218366. {
  218367. const String& headersEntry = s->headerLines[i];
  218368. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218369. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218370. const String previousValue (headers [key]);
  218371. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218372. }
  218373. }
  218374. }
  218375. int juce_seekInInternetFile (void* handle, int newPosition)
  218376. {
  218377. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218378. return s != 0 ? s->readPosition : 0;
  218379. }
  218380. #endif
  218381. /*** End of inlined file: juce_linux_Network.cpp ***/
  218382. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218383. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218384. // compiled on its own).
  218385. #if JUCE_INCLUDED_FILE
  218386. void Logger::outputDebugString (const String& text)
  218387. {
  218388. std::cerr << text << std::endl;
  218389. }
  218390. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218391. {
  218392. return Linux;
  218393. }
  218394. const String SystemStats::getOperatingSystemName()
  218395. {
  218396. return "Linux";
  218397. }
  218398. bool SystemStats::isOperatingSystem64Bit()
  218399. {
  218400. #if JUCE_64BIT
  218401. return true;
  218402. #else
  218403. //xxx not sure how to find this out?..
  218404. return false;
  218405. #endif
  218406. }
  218407. static const String juce_getCpuInfo (const char* const key)
  218408. {
  218409. StringArray lines;
  218410. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218411. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218412. if (lines[i].startsWithIgnoreCase (key))
  218413. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218414. return String::empty;
  218415. }
  218416. const String SystemStats::getCpuVendor()
  218417. {
  218418. return juce_getCpuInfo ("vendor_id");
  218419. }
  218420. int SystemStats::getCpuSpeedInMegaherz()
  218421. {
  218422. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218423. }
  218424. int SystemStats::getMemorySizeInMegabytes()
  218425. {
  218426. struct sysinfo sysi;
  218427. if (sysinfo (&sysi) == 0)
  218428. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218429. return 0;
  218430. }
  218431. int SystemStats::getPageSize()
  218432. {
  218433. return sysconf (_SC_PAGESIZE);
  218434. }
  218435. const String SystemStats::getLogonName()
  218436. {
  218437. const char* user = getenv ("USER");
  218438. if (user == 0)
  218439. {
  218440. struct passwd* const pw = getpwuid (getuid());
  218441. if (pw != 0)
  218442. user = pw->pw_name;
  218443. }
  218444. return String::fromUTF8 (user);
  218445. }
  218446. const String SystemStats::getFullUserName()
  218447. {
  218448. return getLogonName();
  218449. }
  218450. void SystemStats::initialiseStats()
  218451. {
  218452. const String flags (juce_getCpuInfo ("flags"));
  218453. cpuFlags.hasMMX = flags.contains ("mmx");
  218454. cpuFlags.hasSSE = flags.contains ("sse");
  218455. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218456. cpuFlags.has3DNow = flags.contains ("3dnow");
  218457. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218458. }
  218459. void PlatformUtilities::fpuReset()
  218460. {
  218461. }
  218462. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218463. {
  218464. if (gettimeofday (t, 0) != 0)
  218465. return false;
  218466. static unsigned int calibrate = 0;
  218467. static bool calibrated = false;
  218468. if (! calibrated)
  218469. {
  218470. calibrated = true;
  218471. struct sysinfo sysi;
  218472. if (sysinfo (&sysi) == 0)
  218473. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218474. }
  218475. t->tv_sec -= calibrate;
  218476. return true;
  218477. }
  218478. uint32 juce_millisecondsSinceStartup() throw()
  218479. {
  218480. timeval t;
  218481. if (juce_getTimeSinceStartup (&t))
  218482. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218483. return 0;
  218484. }
  218485. int64 Time::getHighResolutionTicks() throw()
  218486. {
  218487. timeval t;
  218488. if (juce_getTimeSinceStartup (&t))
  218489. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218490. return 0;
  218491. }
  218492. int64 Time::getHighResolutionTicksPerSecond() throw()
  218493. {
  218494. return 1000000; // (microseconds)
  218495. }
  218496. double Time::getMillisecondCounterHiRes() throw()
  218497. {
  218498. return getHighResolutionTicks() * 0.001;
  218499. }
  218500. bool Time::setSystemTimeToThisTime() const
  218501. {
  218502. timeval t;
  218503. t.tv_sec = millisSinceEpoch % 1000000;
  218504. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218505. return settimeofday (&t, 0) ? false : true;
  218506. }
  218507. #endif
  218508. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218509. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218510. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218511. // compiled on its own).
  218512. #if JUCE_INCLUDED_FILE
  218513. /*
  218514. Note that a lot of methods that you'd expect to find in this file actually
  218515. live in juce_posix_SharedCode.h!
  218516. */
  218517. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218518. void Process::setPriority (ProcessPriority prior)
  218519. {
  218520. struct sched_param param;
  218521. int policy, maxp, minp;
  218522. const int p = (int) prior;
  218523. if (p <= 1)
  218524. policy = SCHED_OTHER;
  218525. else
  218526. policy = SCHED_RR;
  218527. minp = sched_get_priority_min (policy);
  218528. maxp = sched_get_priority_max (policy);
  218529. if (p < 2)
  218530. param.sched_priority = 0;
  218531. else if (p == 2 )
  218532. // Set to middle of lower realtime priority range
  218533. param.sched_priority = minp + (maxp - minp) / 4;
  218534. else
  218535. // Set to middle of higher realtime priority range
  218536. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218537. pthread_setschedparam (pthread_self(), policy, &param);
  218538. }
  218539. void Process::terminate()
  218540. {
  218541. exit (0);
  218542. }
  218543. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218544. {
  218545. static char testResult = 0;
  218546. if (testResult == 0)
  218547. {
  218548. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218549. if (testResult >= 0)
  218550. {
  218551. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218552. testResult = 1;
  218553. }
  218554. }
  218555. return testResult < 0;
  218556. }
  218557. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218558. {
  218559. return juce_isRunningUnderDebugger();
  218560. }
  218561. void Process::raisePrivilege()
  218562. {
  218563. // If running suid root, change effective user
  218564. // to root
  218565. if (geteuid() != 0 && getuid() == 0)
  218566. {
  218567. setreuid (geteuid(), getuid());
  218568. setregid (getegid(), getgid());
  218569. }
  218570. }
  218571. void Process::lowerPrivilege()
  218572. {
  218573. // If runing suid root, change effective user
  218574. // back to real user
  218575. if (geteuid() == 0 && getuid() != 0)
  218576. {
  218577. setreuid (geteuid(), getuid());
  218578. setregid (getegid(), getgid());
  218579. }
  218580. }
  218581. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218582. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218583. {
  218584. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218585. }
  218586. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218587. {
  218588. dlclose(handle);
  218589. }
  218590. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218591. {
  218592. return dlsym (libraryHandle, procedureName.toCString());
  218593. }
  218594. #endif
  218595. #endif
  218596. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218597. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218598. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218599. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218600. // compiled on its own).
  218601. #if JUCE_INCLUDED_FILE
  218602. extern Display* display;
  218603. extern Window juce_messageWindowHandle;
  218604. namespace ClipboardHelpers
  218605. {
  218606. static String localClipboardContent;
  218607. static Atom atom_UTF8_STRING;
  218608. static Atom atom_CLIPBOARD;
  218609. static Atom atom_TARGETS;
  218610. static void initSelectionAtoms()
  218611. {
  218612. static bool isInitialised = false;
  218613. if (! isInitialised)
  218614. {
  218615. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218616. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218617. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218618. }
  218619. }
  218620. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218621. // works only for strings shorter than 1000000 bytes
  218622. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218623. {
  218624. String returnData;
  218625. char* clipData;
  218626. Atom actualType;
  218627. int actualFormat;
  218628. unsigned long numItems, bytesLeft;
  218629. if (XGetWindowProperty (display, window, prop,
  218630. 0L /* offset */, 1000000 /* length (max) */, False,
  218631. AnyPropertyType /* format */,
  218632. &actualType, &actualFormat, &numItems, &bytesLeft,
  218633. (unsigned char**) &clipData) == Success)
  218634. {
  218635. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218636. returnData = String::fromUTF8 (clipData, numItems);
  218637. else if (actualType == XA_STRING && actualFormat == 8)
  218638. returnData = String (clipData, numItems);
  218639. if (clipData != 0)
  218640. XFree (clipData);
  218641. jassert (bytesLeft == 0 || numItems == 1000000);
  218642. }
  218643. XDeleteProperty (display, window, prop);
  218644. return returnData;
  218645. }
  218646. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218647. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218648. {
  218649. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218650. // The selection owner will be asked to set the JUCE_SEL property on the
  218651. // juce_messageWindowHandle with the selection content
  218652. XConvertSelection (display, selection, requestedFormat, property_name,
  218653. juce_messageWindowHandle, CurrentTime);
  218654. int count = 50; // will wait at most for 200 ms
  218655. while (--count >= 0)
  218656. {
  218657. XEvent event;
  218658. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218659. {
  218660. if (event.xselection.property == property_name)
  218661. {
  218662. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218663. selectionContent = readWindowProperty (event.xselection.requestor,
  218664. event.xselection.property,
  218665. requestedFormat);
  218666. return true;
  218667. }
  218668. else
  218669. {
  218670. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218671. }
  218672. }
  218673. // not very elegant.. we could do a select() or something like that...
  218674. // however clipboard content requesting is inherently slow on x11, it
  218675. // often takes 50ms or more so...
  218676. Thread::sleep (4);
  218677. }
  218678. return false;
  218679. }
  218680. }
  218681. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218682. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218683. {
  218684. ClipboardHelpers::initSelectionAtoms();
  218685. // the selection content is sent to the target window as a window property
  218686. XSelectionEvent reply;
  218687. reply.type = SelectionNotify;
  218688. reply.display = evt.display;
  218689. reply.requestor = evt.requestor;
  218690. reply.selection = evt.selection;
  218691. reply.target = evt.target;
  218692. reply.property = None; // == "fail"
  218693. reply.time = evt.time;
  218694. HeapBlock <char> data;
  218695. int propertyFormat = 0, numDataItems = 0;
  218696. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218697. {
  218698. if (evt.target == XA_STRING)
  218699. {
  218700. // format data according to system locale
  218701. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218702. data.calloc (numDataItems + 1);
  218703. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218704. propertyFormat = 8; // bits/item
  218705. }
  218706. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218707. {
  218708. // translate to utf8
  218709. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218710. data.calloc (numDataItems + 1);
  218711. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218712. propertyFormat = 8; // bits/item
  218713. }
  218714. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218715. {
  218716. // another application wants to know what we are able to send
  218717. numDataItems = 2;
  218718. propertyFormat = 32; // atoms are 32-bit
  218719. data.calloc (numDataItems * 4);
  218720. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218721. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218722. atoms[1] = XA_STRING;
  218723. }
  218724. }
  218725. else
  218726. {
  218727. DBG ("requested unsupported clipboard");
  218728. }
  218729. if (data != 0)
  218730. {
  218731. const int maxReasonableSelectionSize = 1000000;
  218732. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218733. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218734. {
  218735. XChangeProperty (evt.display, evt.requestor,
  218736. evt.property, evt.target,
  218737. propertyFormat /* 8 or 32 */, PropModeReplace,
  218738. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218739. reply.property = evt.property; // " == success"
  218740. }
  218741. }
  218742. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218743. }
  218744. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218745. {
  218746. ClipboardHelpers::initSelectionAtoms();
  218747. ClipboardHelpers::localClipboardContent = clipText;
  218748. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218749. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218750. }
  218751. const String SystemClipboard::getTextFromClipboard()
  218752. {
  218753. ClipboardHelpers::initSelectionAtoms();
  218754. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218755. level" clipboard that is supposed to be filled by ctrl-C
  218756. etc). When a clipboard manager is running, the content of this
  218757. selection is preserved even when the original selection owner
  218758. exits.
  218759. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218760. filled by good old x11 apps such as xterm)
  218761. */
  218762. String content;
  218763. Atom selection = XA_PRIMARY;
  218764. Window selectionOwner = None;
  218765. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218766. {
  218767. selection = ClipboardHelpers::atom_CLIPBOARD;
  218768. selectionOwner = XGetSelectionOwner (display, selection);
  218769. }
  218770. if (selectionOwner != None)
  218771. {
  218772. if (selectionOwner == juce_messageWindowHandle)
  218773. {
  218774. content = ClipboardHelpers::localClipboardContent;
  218775. }
  218776. else
  218777. {
  218778. // first try: we want an utf8 string
  218779. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218780. if (! ok)
  218781. {
  218782. // second chance, ask for a good old locale-dependent string ..
  218783. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218784. }
  218785. }
  218786. }
  218787. return content;
  218788. }
  218789. #endif
  218790. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218791. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218792. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218793. // compiled on its own).
  218794. #if JUCE_INCLUDED_FILE
  218795. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218796. #define JUCE_DEBUG_XERRORS 1
  218797. #endif
  218798. Display* display = 0;
  218799. Window juce_messageWindowHandle = None;
  218800. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218801. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218802. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218803. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218804. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218805. class InternalMessageQueue
  218806. {
  218807. public:
  218808. InternalMessageQueue()
  218809. : bytesInSocket (0),
  218810. totalEventCount (0)
  218811. {
  218812. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218813. (void) ret; jassert (ret == 0);
  218814. //setNonBlocking (fd[0]);
  218815. //setNonBlocking (fd[1]);
  218816. }
  218817. ~InternalMessageQueue()
  218818. {
  218819. close (fd[0]);
  218820. close (fd[1]);
  218821. clearSingletonInstance();
  218822. }
  218823. void postMessage (Message* msg)
  218824. {
  218825. const int maxBytesInSocketQueue = 128;
  218826. ScopedLock sl (lock);
  218827. queue.add (msg);
  218828. if (bytesInSocket < maxBytesInSocketQueue)
  218829. {
  218830. ++bytesInSocket;
  218831. ScopedUnlock ul (lock);
  218832. const unsigned char x = 0xff;
  218833. size_t bytesWritten = write (fd[0], &x, 1);
  218834. (void) bytesWritten;
  218835. }
  218836. }
  218837. bool isEmpty() const
  218838. {
  218839. ScopedLock sl (lock);
  218840. return queue.size() == 0;
  218841. }
  218842. bool dispatchNextEvent()
  218843. {
  218844. // This alternates between giving priority to XEvents or internal messages,
  218845. // to keep everything running smoothly..
  218846. if ((++totalEventCount & 1) != 0)
  218847. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218848. else
  218849. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218850. }
  218851. // Wait for an event (either XEvent, or an internal Message)
  218852. bool sleepUntilEvent (const int timeoutMs)
  218853. {
  218854. if (! isEmpty())
  218855. return true;
  218856. if (display != 0)
  218857. {
  218858. ScopedXLock xlock;
  218859. if (XPending (display))
  218860. return true;
  218861. }
  218862. struct timeval tv;
  218863. tv.tv_sec = 0;
  218864. tv.tv_usec = timeoutMs * 1000;
  218865. int fd0 = getWaitHandle();
  218866. int fdmax = fd0;
  218867. fd_set readset;
  218868. FD_ZERO (&readset);
  218869. FD_SET (fd0, &readset);
  218870. if (display != 0)
  218871. {
  218872. ScopedXLock xlock;
  218873. int fd1 = XConnectionNumber (display);
  218874. FD_SET (fd1, &readset);
  218875. fdmax = jmax (fd0, fd1);
  218876. }
  218877. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218878. return (ret > 0); // ret <= 0 if error or timeout
  218879. }
  218880. struct MessageThreadFuncCall
  218881. {
  218882. enum { uniqueID = 0x73774623 };
  218883. MessageCallbackFunction* func;
  218884. void* parameter;
  218885. void* result;
  218886. CriticalSection lock;
  218887. WaitableEvent event;
  218888. };
  218889. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218890. private:
  218891. CriticalSection lock;
  218892. OwnedArray <Message> queue;
  218893. int fd[2];
  218894. int bytesInSocket;
  218895. int totalEventCount;
  218896. int getWaitHandle() const throw() { return fd[1]; }
  218897. static bool setNonBlocking (int handle)
  218898. {
  218899. int socketFlags = fcntl (handle, F_GETFL, 0);
  218900. if (socketFlags == -1)
  218901. return false;
  218902. socketFlags |= O_NONBLOCK;
  218903. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218904. }
  218905. static bool dispatchNextXEvent()
  218906. {
  218907. if (display == 0)
  218908. return false;
  218909. XEvent evt;
  218910. {
  218911. ScopedXLock xlock;
  218912. if (! XPending (display))
  218913. return false;
  218914. XNextEvent (display, &evt);
  218915. }
  218916. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218917. juce_handleSelectionRequest (evt.xselectionrequest);
  218918. else if (evt.xany.window != juce_messageWindowHandle)
  218919. juce_windowMessageReceive (&evt);
  218920. return true;
  218921. }
  218922. Message* popNextMessage()
  218923. {
  218924. ScopedLock sl (lock);
  218925. if (bytesInSocket > 0)
  218926. {
  218927. --bytesInSocket;
  218928. ScopedUnlock ul (lock);
  218929. unsigned char x;
  218930. size_t numBytes = read (fd[1], &x, 1);
  218931. (void) numBytes;
  218932. }
  218933. return queue.removeAndReturn (0);
  218934. }
  218935. bool dispatchNextInternalMessage()
  218936. {
  218937. ScopedPointer <Message> msg (popNextMessage());
  218938. if (msg == 0)
  218939. return false;
  218940. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218941. {
  218942. // Handle callback message
  218943. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218944. call->result = (*(call->func)) (call->parameter);
  218945. call->event.signal();
  218946. }
  218947. else
  218948. {
  218949. // Handle "normal" messages
  218950. MessageManager::getInstance()->deliverMessage (msg.release());
  218951. }
  218952. return true;
  218953. }
  218954. };
  218955. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218956. namespace LinuxErrorHandling
  218957. {
  218958. static bool errorOccurred = false;
  218959. static bool keyboardBreakOccurred = false;
  218960. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218961. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218962. // Usually happens when client-server connection is broken
  218963. static int ioErrorHandler (Display* display)
  218964. {
  218965. DBG ("ERROR: connection to X server broken.. terminating.");
  218966. if (JUCEApplication::isStandaloneApp())
  218967. MessageManager::getInstance()->stopDispatchLoop();
  218968. errorOccurred = true;
  218969. return 0;
  218970. }
  218971. // A protocol error has occurred
  218972. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218973. {
  218974. #if JUCE_DEBUG_XERRORS
  218975. char errorStr[64] = { 0 };
  218976. char requestStr[64] = { 0 };
  218977. XGetErrorText (display, event->error_code, errorStr, 64);
  218978. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218979. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218980. #endif
  218981. return 0;
  218982. }
  218983. static void installXErrorHandlers()
  218984. {
  218985. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218986. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218987. }
  218988. static void removeXErrorHandlers()
  218989. {
  218990. XSetIOErrorHandler (oldIOErrorHandler);
  218991. oldIOErrorHandler = 0;
  218992. XSetErrorHandler (oldErrorHandler);
  218993. oldErrorHandler = 0;
  218994. }
  218995. static void keyboardBreakSignalHandler (int sig)
  218996. {
  218997. if (sig == SIGINT)
  218998. keyboardBreakOccurred = true;
  218999. }
  219000. static void installKeyboardBreakHandler()
  219001. {
  219002. struct sigaction saction;
  219003. sigset_t maskSet;
  219004. sigemptyset (&maskSet);
  219005. saction.sa_handler = keyboardBreakSignalHandler;
  219006. saction.sa_mask = maskSet;
  219007. saction.sa_flags = 0;
  219008. sigaction (SIGINT, &saction, 0);
  219009. }
  219010. }
  219011. void MessageManager::doPlatformSpecificInitialisation()
  219012. {
  219013. // Initialise xlib for multiple thread support
  219014. static bool initThreadCalled = false;
  219015. if (! initThreadCalled)
  219016. {
  219017. if (! XInitThreads())
  219018. {
  219019. // This is fatal! Print error and closedown
  219020. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219021. if (JUCEApplication::isStandaloneApp())
  219022. Process::terminate();
  219023. return;
  219024. }
  219025. initThreadCalled = true;
  219026. }
  219027. LinuxErrorHandling::installXErrorHandlers();
  219028. LinuxErrorHandling::installKeyboardBreakHandler();
  219029. // Create the internal message queue
  219030. InternalMessageQueue::getInstance();
  219031. // Try to connect to a display
  219032. String displayName (getenv ("DISPLAY"));
  219033. if (displayName.isEmpty())
  219034. displayName = ":0.0";
  219035. display = XOpenDisplay (displayName.toCString());
  219036. if (display != 0) // This is not fatal! we can run headless.
  219037. {
  219038. // Create a context to store user data associated with Windows we create in WindowDriver
  219039. windowHandleXContext = XUniqueContext();
  219040. // We're only interested in client messages for this window, which are always sent
  219041. XSetWindowAttributes swa;
  219042. swa.event_mask = NoEventMask;
  219043. // Create our message window (this will never be mapped)
  219044. const int screen = DefaultScreen (display);
  219045. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219046. 0, 0, 1, 1, 0, 0, InputOnly,
  219047. DefaultVisual (display, screen),
  219048. CWEventMask, &swa);
  219049. }
  219050. }
  219051. void MessageManager::doPlatformSpecificShutdown()
  219052. {
  219053. InternalMessageQueue::deleteInstance();
  219054. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219055. {
  219056. XDestroyWindow (display, juce_messageWindowHandle);
  219057. XCloseDisplay (display);
  219058. juce_messageWindowHandle = 0;
  219059. display = 0;
  219060. LinuxErrorHandling::removeXErrorHandlers();
  219061. }
  219062. }
  219063. bool juce_postMessageToSystemQueue (Message* message)
  219064. {
  219065. if (LinuxErrorHandling::errorOccurred)
  219066. return false;
  219067. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219068. return true;
  219069. }
  219070. void MessageManager::broadcastMessage (const String& value)
  219071. {
  219072. /* TODO */
  219073. }
  219074. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219075. {
  219076. if (LinuxErrorHandling::errorOccurred)
  219077. return 0;
  219078. if (isThisTheMessageThread())
  219079. return func (parameter);
  219080. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219081. messageCallContext.func = func;
  219082. messageCallContext.parameter = parameter;
  219083. InternalMessageQueue::getInstanceWithoutCreating()
  219084. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219085. 0, 0, &messageCallContext));
  219086. // Wait for it to complete before continuing
  219087. messageCallContext.event.wait();
  219088. return messageCallContext.result;
  219089. }
  219090. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219091. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219092. {
  219093. while (! LinuxErrorHandling::errorOccurred)
  219094. {
  219095. if (LinuxErrorHandling::keyboardBreakOccurred)
  219096. {
  219097. LinuxErrorHandling::errorOccurred = true;
  219098. if (JUCEApplication::isStandaloneApp())
  219099. Process::terminate();
  219100. break;
  219101. }
  219102. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219103. return true;
  219104. if (returnIfNoPendingMessages)
  219105. break;
  219106. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219107. }
  219108. return false;
  219109. }
  219110. #endif
  219111. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219112. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219113. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219114. // compiled on its own).
  219115. #if JUCE_INCLUDED_FILE
  219116. class FreeTypeFontFace
  219117. {
  219118. public:
  219119. enum FontStyle
  219120. {
  219121. Plain = 0,
  219122. Bold = 1,
  219123. Italic = 2
  219124. };
  219125. FreeTypeFontFace (const String& familyName)
  219126. : hasSerif (false),
  219127. monospaced (false)
  219128. {
  219129. family = familyName;
  219130. }
  219131. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219132. {
  219133. if (names [(int) style].fileName.isEmpty())
  219134. {
  219135. names [(int) style].fileName = name;
  219136. names [(int) style].faceIndex = faceIndex;
  219137. }
  219138. }
  219139. const String& getFamilyName() const throw() { return family; }
  219140. const String& getFileName (const int style, int& faceIndex) const throw()
  219141. {
  219142. faceIndex = names[style].faceIndex;
  219143. return names[style].fileName;
  219144. }
  219145. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219146. bool getMonospaced() const throw() { return monospaced; }
  219147. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219148. bool getSerif() const throw() { return hasSerif; }
  219149. private:
  219150. String family;
  219151. struct FontNameIndex
  219152. {
  219153. String fileName;
  219154. int faceIndex;
  219155. };
  219156. FontNameIndex names[4];
  219157. bool hasSerif, monospaced;
  219158. };
  219159. class FreeTypeInterface : public DeletedAtShutdown
  219160. {
  219161. public:
  219162. FreeTypeInterface()
  219163. : ftLib (0),
  219164. lastFace (0),
  219165. lastBold (false),
  219166. lastItalic (false)
  219167. {
  219168. if (FT_Init_FreeType (&ftLib) != 0)
  219169. {
  219170. ftLib = 0;
  219171. DBG ("Failed to initialize FreeType");
  219172. }
  219173. StringArray fontDirs;
  219174. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219175. fontDirs.removeEmptyStrings (true);
  219176. if (fontDirs.size() == 0)
  219177. {
  219178. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219179. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219180. if (fontsInfo != 0)
  219181. {
  219182. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219183. {
  219184. fontDirs.add (e->getAllSubText().trim());
  219185. }
  219186. }
  219187. }
  219188. if (fontDirs.size() == 0)
  219189. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219190. for (int i = 0; i < fontDirs.size(); ++i)
  219191. enumerateFaces (fontDirs[i]);
  219192. }
  219193. ~FreeTypeInterface()
  219194. {
  219195. if (lastFace != 0)
  219196. FT_Done_Face (lastFace);
  219197. if (ftLib != 0)
  219198. FT_Done_FreeType (ftLib);
  219199. clearSingletonInstance();
  219200. }
  219201. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219202. {
  219203. for (int i = 0; i < faces.size(); i++)
  219204. if (faces[i]->getFamilyName() == familyName)
  219205. return faces[i];
  219206. if (! create)
  219207. return 0;
  219208. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219209. faces.add (newFace);
  219210. return newFace;
  219211. }
  219212. // Enumerate all font faces available in a given directory
  219213. void enumerateFaces (const String& path)
  219214. {
  219215. File dirPath (path);
  219216. if (path.isEmpty() || ! dirPath.isDirectory())
  219217. return;
  219218. DirectoryIterator di (dirPath, true);
  219219. while (di.next())
  219220. {
  219221. File possible (di.getFile());
  219222. if (possible.hasFileExtension ("ttf")
  219223. || possible.hasFileExtension ("pfb")
  219224. || possible.hasFileExtension ("pcf"))
  219225. {
  219226. FT_Face face;
  219227. int faceIndex = 0;
  219228. int numFaces = 0;
  219229. do
  219230. {
  219231. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219232. faceIndex, &face) == 0)
  219233. {
  219234. if (faceIndex == 0)
  219235. numFaces = face->num_faces;
  219236. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219237. {
  219238. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219239. int style = (int) FreeTypeFontFace::Plain;
  219240. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219241. style |= (int) FreeTypeFontFace::Bold;
  219242. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219243. style |= (int) FreeTypeFontFace::Italic;
  219244. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219245. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219246. // Surely there must be a better way to do this?
  219247. const String name (face->family_name);
  219248. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219249. || name.containsIgnoreCase ("Verdana")
  219250. || name.containsIgnoreCase ("Arial")));
  219251. }
  219252. FT_Done_Face (face);
  219253. }
  219254. ++faceIndex;
  219255. }
  219256. while (faceIndex < numFaces);
  219257. }
  219258. }
  219259. }
  219260. // Create a FreeType face object for a given font
  219261. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219262. {
  219263. FT_Face face = 0;
  219264. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219265. {
  219266. face = lastFace;
  219267. }
  219268. else
  219269. {
  219270. if (lastFace != 0)
  219271. {
  219272. FT_Done_Face (lastFace);
  219273. lastFace = 0;
  219274. }
  219275. lastFontName = fontName;
  219276. lastBold = bold;
  219277. lastItalic = italic;
  219278. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219279. if (ftFace != 0)
  219280. {
  219281. int style = (int) FreeTypeFontFace::Plain;
  219282. if (bold)
  219283. style |= (int) FreeTypeFontFace::Bold;
  219284. if (italic)
  219285. style |= (int) FreeTypeFontFace::Italic;
  219286. int faceIndex;
  219287. String fileName (ftFace->getFileName (style, faceIndex));
  219288. if (fileName.isEmpty())
  219289. {
  219290. style ^= (int) FreeTypeFontFace::Bold;
  219291. fileName = ftFace->getFileName (style, faceIndex);
  219292. if (fileName.isEmpty())
  219293. {
  219294. style ^= (int) FreeTypeFontFace::Bold;
  219295. style ^= (int) FreeTypeFontFace::Italic;
  219296. fileName = ftFace->getFileName (style, faceIndex);
  219297. if (! fileName.length())
  219298. {
  219299. style ^= (int) FreeTypeFontFace::Bold;
  219300. fileName = ftFace->getFileName (style, faceIndex);
  219301. }
  219302. }
  219303. }
  219304. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219305. {
  219306. face = lastFace;
  219307. // If there isn't a unicode charmap then select the first one.
  219308. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219309. FT_Set_Charmap (face, face->charmaps[0]);
  219310. }
  219311. }
  219312. }
  219313. return face;
  219314. }
  219315. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219316. {
  219317. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219318. const float height = (float) (face->ascender - face->descender);
  219319. const float scaleX = 1.0f / height;
  219320. const float scaleY = -1.0f / height;
  219321. Path destShape;
  219322. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219323. || face->glyph->format != ft_glyph_format_outline)
  219324. {
  219325. return false;
  219326. }
  219327. const FT_Outline* const outline = &face->glyph->outline;
  219328. const short* const contours = outline->contours;
  219329. const char* const tags = outline->tags;
  219330. FT_Vector* const points = outline->points;
  219331. for (int c = 0; c < outline->n_contours; c++)
  219332. {
  219333. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219334. const int endPoint = contours[c];
  219335. for (int p = startPoint; p <= endPoint; p++)
  219336. {
  219337. const float x = scaleX * points[p].x;
  219338. const float y = scaleY * points[p].y;
  219339. if (p == startPoint)
  219340. {
  219341. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219342. {
  219343. float x2 = scaleX * points [endPoint].x;
  219344. float y2 = scaleY * points [endPoint].y;
  219345. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219346. {
  219347. x2 = (x + x2) * 0.5f;
  219348. y2 = (y + y2) * 0.5f;
  219349. }
  219350. destShape.startNewSubPath (x2, y2);
  219351. }
  219352. else
  219353. {
  219354. destShape.startNewSubPath (x, y);
  219355. }
  219356. }
  219357. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219358. {
  219359. if (p != startPoint)
  219360. destShape.lineTo (x, y);
  219361. }
  219362. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219363. {
  219364. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219365. float x2 = scaleX * points [nextIndex].x;
  219366. float y2 = scaleY * points [nextIndex].y;
  219367. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219368. {
  219369. x2 = (x + x2) * 0.5f;
  219370. y2 = (y + y2) * 0.5f;
  219371. }
  219372. else
  219373. {
  219374. ++p;
  219375. }
  219376. destShape.quadraticTo (x, y, x2, y2);
  219377. }
  219378. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219379. {
  219380. if (p >= endPoint)
  219381. return false;
  219382. const int next1 = p + 1;
  219383. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219384. const float x2 = scaleX * points [next1].x;
  219385. const float y2 = scaleY * points [next1].y;
  219386. const float x3 = scaleX * points [next2].x;
  219387. const float y3 = scaleY * points [next2].y;
  219388. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219389. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219390. return false;
  219391. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219392. p += 2;
  219393. }
  219394. }
  219395. destShape.closeSubPath();
  219396. }
  219397. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219398. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219399. addKerning (face, dest, character, glyphIndex);
  219400. return true;
  219401. }
  219402. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219403. {
  219404. const float height = (float) (face->ascender - face->descender);
  219405. uint32 rightGlyphIndex;
  219406. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219407. while (rightGlyphIndex != 0)
  219408. {
  219409. FT_Vector kerning;
  219410. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219411. {
  219412. if (kerning.x != 0)
  219413. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219414. }
  219415. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219416. }
  219417. }
  219418. // Add a glyph to a font
  219419. bool addGlyphToFont (const uint32 character, const String& fontName,
  219420. bool bold, bool italic, CustomTypeface& dest)
  219421. {
  219422. FT_Face face = createFT_Face (fontName, bold, italic);
  219423. return face != 0 && addGlyph (face, dest, character);
  219424. }
  219425. void getFamilyNames (StringArray& familyNames) const
  219426. {
  219427. for (int i = 0; i < faces.size(); i++)
  219428. familyNames.add (faces[i]->getFamilyName());
  219429. }
  219430. void getMonospacedNames (StringArray& monoSpaced) const
  219431. {
  219432. for (int i = 0; i < faces.size(); i++)
  219433. if (faces[i]->getMonospaced())
  219434. monoSpaced.add (faces[i]->getFamilyName());
  219435. }
  219436. void getSerifNames (StringArray& serif) const
  219437. {
  219438. for (int i = 0; i < faces.size(); i++)
  219439. if (faces[i]->getSerif())
  219440. serif.add (faces[i]->getFamilyName());
  219441. }
  219442. void getSansSerifNames (StringArray& sansSerif) const
  219443. {
  219444. for (int i = 0; i < faces.size(); i++)
  219445. if (! faces[i]->getSerif())
  219446. sansSerif.add (faces[i]->getFamilyName());
  219447. }
  219448. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219449. private:
  219450. FT_Library ftLib;
  219451. FT_Face lastFace;
  219452. String lastFontName;
  219453. bool lastBold, lastItalic;
  219454. OwnedArray<FreeTypeFontFace> faces;
  219455. };
  219456. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219457. class FreetypeTypeface : public CustomTypeface
  219458. {
  219459. public:
  219460. FreetypeTypeface (const Font& font)
  219461. {
  219462. FT_Face face = FreeTypeInterface::getInstance()
  219463. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219464. if (face == 0)
  219465. {
  219466. #if JUCE_DEBUG
  219467. String msg ("Failed to create typeface: ");
  219468. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219469. DBG (msg);
  219470. #endif
  219471. }
  219472. else
  219473. {
  219474. setCharacteristics (font.getTypefaceName(),
  219475. face->ascender / (float) (face->ascender - face->descender),
  219476. font.isBold(), font.isItalic(),
  219477. L' ');
  219478. }
  219479. }
  219480. bool loadGlyphIfPossible (juce_wchar character)
  219481. {
  219482. return FreeTypeInterface::getInstance()
  219483. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219484. }
  219485. };
  219486. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219487. {
  219488. return new FreetypeTypeface (font);
  219489. }
  219490. const StringArray Font::findAllTypefaceNames()
  219491. {
  219492. StringArray s;
  219493. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219494. s.sort (true);
  219495. return s;
  219496. }
  219497. static const String pickBestFont (const StringArray& names,
  219498. const char* const choicesString)
  219499. {
  219500. StringArray choices;
  219501. choices.addTokens (String (choicesString), ",", String::empty);
  219502. choices.trim();
  219503. choices.removeEmptyStrings();
  219504. int i, j;
  219505. for (j = 0; j < choices.size(); ++j)
  219506. if (names.contains (choices[j], true))
  219507. return choices[j];
  219508. for (j = 0; j < choices.size(); ++j)
  219509. for (i = 0; i < names.size(); i++)
  219510. if (names[i].startsWithIgnoreCase (choices[j]))
  219511. return names[i];
  219512. for (j = 0; j < choices.size(); ++j)
  219513. for (i = 0; i < names.size(); i++)
  219514. if (names[i].containsIgnoreCase (choices[j]))
  219515. return names[i];
  219516. return names[0];
  219517. }
  219518. static const String linux_getDefaultSansSerifFontName()
  219519. {
  219520. StringArray allFonts;
  219521. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219522. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219523. }
  219524. static const String linux_getDefaultSerifFontName()
  219525. {
  219526. StringArray allFonts;
  219527. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219528. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219529. }
  219530. static const String linux_getDefaultMonospacedFontName()
  219531. {
  219532. StringArray allFonts;
  219533. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219534. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219535. }
  219536. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219537. {
  219538. defaultSans = linux_getDefaultSansSerifFontName();
  219539. defaultSerif = linux_getDefaultSerifFontName();
  219540. defaultFixed = linux_getDefaultMonospacedFontName();
  219541. }
  219542. #endif
  219543. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219544. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219545. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219546. // compiled on its own).
  219547. #if JUCE_INCLUDED_FILE
  219548. // These are defined in juce_linux_Messaging.cpp
  219549. extern Display* display;
  219550. extern XContext windowHandleXContext;
  219551. namespace Atoms
  219552. {
  219553. enum ProtocolItems
  219554. {
  219555. TAKE_FOCUS = 0,
  219556. DELETE_WINDOW = 1,
  219557. PING = 2
  219558. };
  219559. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219560. ActiveWin, Pid, WindowType, WindowState,
  219561. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219562. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219563. XdndActionDescription, XdndActionCopy,
  219564. allowedActions[5],
  219565. allowedMimeTypes[2];
  219566. const unsigned long DndVersion = 3;
  219567. static void initialiseAtoms()
  219568. {
  219569. static bool atomsInitialised = false;
  219570. if (! atomsInitialised)
  219571. {
  219572. atomsInitialised = true;
  219573. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219574. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219575. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219576. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219577. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219578. State = XInternAtom (display, "WM_STATE", True);
  219579. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219580. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219581. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219582. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219583. XdndAware = XInternAtom (display, "XdndAware", False);
  219584. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219585. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219586. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219587. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219588. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219589. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219590. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219591. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219592. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219593. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219594. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219595. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219596. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219597. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219598. allowedActions[1] = XdndActionCopy;
  219599. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219600. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219601. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219602. }
  219603. }
  219604. }
  219605. namespace Keys
  219606. {
  219607. enum MouseButtons
  219608. {
  219609. NoButton = 0,
  219610. LeftButton = 1,
  219611. MiddleButton = 2,
  219612. RightButton = 3,
  219613. WheelUp = 4,
  219614. WheelDown = 5
  219615. };
  219616. static int AltMask = 0;
  219617. static int NumLockMask = 0;
  219618. static bool numLock = false;
  219619. static bool capsLock = false;
  219620. static char keyStates [32];
  219621. static const int extendedKeyModifier = 0x10000000;
  219622. }
  219623. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219624. {
  219625. int keysym;
  219626. if (keyCode & Keys::extendedKeyModifier)
  219627. {
  219628. keysym = 0xff00 | (keyCode & 0xff);
  219629. }
  219630. else
  219631. {
  219632. keysym = keyCode;
  219633. if (keysym == (XK_Tab & 0xff)
  219634. || keysym == (XK_Return & 0xff)
  219635. || keysym == (XK_Escape & 0xff)
  219636. || keysym == (XK_BackSpace & 0xff))
  219637. {
  219638. keysym |= 0xff00;
  219639. }
  219640. }
  219641. ScopedXLock xlock;
  219642. const int keycode = XKeysymToKeycode (display, keysym);
  219643. const int keybyte = keycode >> 3;
  219644. const int keybit = (1 << (keycode & 7));
  219645. return (Keys::keyStates [keybyte] & keybit) != 0;
  219646. }
  219647. #if JUCE_USE_XSHM
  219648. namespace XSHMHelpers
  219649. {
  219650. static int trappedErrorCode = 0;
  219651. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219652. {
  219653. trappedErrorCode = err->error_code;
  219654. return 0;
  219655. }
  219656. static bool isShmAvailable() throw()
  219657. {
  219658. static bool isChecked = false;
  219659. static bool isAvailable = false;
  219660. if (! isChecked)
  219661. {
  219662. isChecked = true;
  219663. int major, minor;
  219664. Bool pixmaps;
  219665. ScopedXLock xlock;
  219666. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219667. {
  219668. trappedErrorCode = 0;
  219669. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219670. XShmSegmentInfo segmentInfo;
  219671. zerostruct (segmentInfo);
  219672. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219673. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219674. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219675. xImage->bytes_per_line * xImage->height,
  219676. IPC_CREAT | 0777)) >= 0)
  219677. {
  219678. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219679. if (segmentInfo.shmaddr != (void*) -1)
  219680. {
  219681. segmentInfo.readOnly = False;
  219682. xImage->data = segmentInfo.shmaddr;
  219683. XSync (display, False);
  219684. if (XShmAttach (display, &segmentInfo) != 0)
  219685. {
  219686. XSync (display, False);
  219687. XShmDetach (display, &segmentInfo);
  219688. isAvailable = true;
  219689. }
  219690. }
  219691. XFlush (display);
  219692. XDestroyImage (xImage);
  219693. shmdt (segmentInfo.shmaddr);
  219694. }
  219695. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219696. XSetErrorHandler (oldHandler);
  219697. if (trappedErrorCode != 0)
  219698. isAvailable = false;
  219699. }
  219700. }
  219701. return isAvailable;
  219702. }
  219703. }
  219704. #endif
  219705. #if JUCE_USE_XRENDER
  219706. namespace XRender
  219707. {
  219708. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219709. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219710. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219711. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219712. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219713. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219714. static tXRenderFindFormat xRenderFindFormat = 0;
  219715. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219716. static bool isAvailable()
  219717. {
  219718. static bool hasLoaded = false;
  219719. if (! hasLoaded)
  219720. {
  219721. ScopedXLock xlock;
  219722. hasLoaded = true;
  219723. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219724. if (h != 0)
  219725. {
  219726. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219727. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219728. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219729. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219730. }
  219731. if (xRenderQueryVersion != 0
  219732. && xRenderFindStandardFormat != 0
  219733. && xRenderFindFormat != 0
  219734. && xRenderFindVisualFormat != 0)
  219735. {
  219736. int major, minor;
  219737. if (xRenderQueryVersion (display, &major, &minor))
  219738. return true;
  219739. }
  219740. xRenderQueryVersion = 0;
  219741. }
  219742. return xRenderQueryVersion != 0;
  219743. }
  219744. static XRenderPictFormat* findPictureFormat()
  219745. {
  219746. ScopedXLock xlock;
  219747. XRenderPictFormat* pictFormat = 0;
  219748. if (isAvailable())
  219749. {
  219750. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219751. if (pictFormat == 0)
  219752. {
  219753. XRenderPictFormat desiredFormat;
  219754. desiredFormat.type = PictTypeDirect;
  219755. desiredFormat.depth = 32;
  219756. desiredFormat.direct.alphaMask = 0xff;
  219757. desiredFormat.direct.redMask = 0xff;
  219758. desiredFormat.direct.greenMask = 0xff;
  219759. desiredFormat.direct.blueMask = 0xff;
  219760. desiredFormat.direct.alpha = 24;
  219761. desiredFormat.direct.red = 16;
  219762. desiredFormat.direct.green = 8;
  219763. desiredFormat.direct.blue = 0;
  219764. pictFormat = xRenderFindFormat (display,
  219765. PictFormatType | PictFormatDepth
  219766. | PictFormatRedMask | PictFormatRed
  219767. | PictFormatGreenMask | PictFormatGreen
  219768. | PictFormatBlueMask | PictFormatBlue
  219769. | PictFormatAlphaMask | PictFormatAlpha,
  219770. &desiredFormat,
  219771. 0);
  219772. }
  219773. }
  219774. return pictFormat;
  219775. }
  219776. }
  219777. #endif
  219778. namespace Visuals
  219779. {
  219780. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219781. {
  219782. ScopedXLock xlock;
  219783. Visual* visual = 0;
  219784. int numVisuals = 0;
  219785. long desiredMask = VisualNoMask;
  219786. XVisualInfo desiredVisual;
  219787. desiredVisual.screen = DefaultScreen (display);
  219788. desiredVisual.depth = desiredDepth;
  219789. desiredMask = VisualScreenMask | VisualDepthMask;
  219790. if (desiredDepth == 32)
  219791. {
  219792. desiredVisual.c_class = TrueColor;
  219793. desiredVisual.red_mask = 0x00FF0000;
  219794. desiredVisual.green_mask = 0x0000FF00;
  219795. desiredVisual.blue_mask = 0x000000FF;
  219796. desiredVisual.bits_per_rgb = 8;
  219797. desiredMask |= VisualClassMask;
  219798. desiredMask |= VisualRedMaskMask;
  219799. desiredMask |= VisualGreenMaskMask;
  219800. desiredMask |= VisualBlueMaskMask;
  219801. desiredMask |= VisualBitsPerRGBMask;
  219802. }
  219803. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219804. desiredMask,
  219805. &desiredVisual,
  219806. &numVisuals);
  219807. if (xvinfos != 0)
  219808. {
  219809. for (int i = 0; i < numVisuals; i++)
  219810. {
  219811. if (xvinfos[i].depth == desiredDepth)
  219812. {
  219813. visual = xvinfos[i].visual;
  219814. break;
  219815. }
  219816. }
  219817. XFree (xvinfos);
  219818. }
  219819. return visual;
  219820. }
  219821. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219822. {
  219823. Visual* visual = 0;
  219824. if (desiredDepth == 32)
  219825. {
  219826. #if JUCE_USE_XSHM
  219827. if (XSHMHelpers::isShmAvailable())
  219828. {
  219829. #if JUCE_USE_XRENDER
  219830. if (XRender::isAvailable())
  219831. {
  219832. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219833. if (pictFormat != 0)
  219834. {
  219835. int numVisuals = 0;
  219836. XVisualInfo desiredVisual;
  219837. desiredVisual.screen = DefaultScreen (display);
  219838. desiredVisual.depth = 32;
  219839. desiredVisual.bits_per_rgb = 8;
  219840. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219841. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219842. &desiredVisual, &numVisuals);
  219843. if (xvinfos != 0)
  219844. {
  219845. for (int i = 0; i < numVisuals; ++i)
  219846. {
  219847. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219848. if (pictVisualFormat != 0
  219849. && pictVisualFormat->type == PictTypeDirect
  219850. && pictVisualFormat->direct.alphaMask)
  219851. {
  219852. visual = xvinfos[i].visual;
  219853. matchedDepth = 32;
  219854. break;
  219855. }
  219856. }
  219857. XFree (xvinfos);
  219858. }
  219859. }
  219860. }
  219861. #endif
  219862. if (visual == 0)
  219863. {
  219864. visual = findVisualWithDepth (32);
  219865. if (visual != 0)
  219866. matchedDepth = 32;
  219867. }
  219868. }
  219869. #endif
  219870. }
  219871. if (visual == 0 && desiredDepth >= 24)
  219872. {
  219873. visual = findVisualWithDepth (24);
  219874. if (visual != 0)
  219875. matchedDepth = 24;
  219876. }
  219877. if (visual == 0 && desiredDepth >= 16)
  219878. {
  219879. visual = findVisualWithDepth (16);
  219880. if (visual != 0)
  219881. matchedDepth = 16;
  219882. }
  219883. return visual;
  219884. }
  219885. }
  219886. class XBitmapImage : public Image::SharedImage
  219887. {
  219888. public:
  219889. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219890. const bool clearImage, const int imageDepth_, Visual* visual)
  219891. : Image::SharedImage (format_, w, h),
  219892. imageDepth (imageDepth_),
  219893. gc (None)
  219894. {
  219895. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219896. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219897. lineStride = ((w * pixelStride + 3) & ~3);
  219898. ScopedXLock xlock;
  219899. #if JUCE_USE_XSHM
  219900. usingXShm = false;
  219901. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219902. {
  219903. zerostruct (segmentInfo);
  219904. segmentInfo.shmid = -1;
  219905. segmentInfo.shmaddr = (char *) -1;
  219906. segmentInfo.readOnly = False;
  219907. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219908. if (xImage != 0)
  219909. {
  219910. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219911. xImage->bytes_per_line * xImage->height,
  219912. IPC_CREAT | 0777)) >= 0)
  219913. {
  219914. if (segmentInfo.shmid != -1)
  219915. {
  219916. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219917. if (segmentInfo.shmaddr != (void*) -1)
  219918. {
  219919. segmentInfo.readOnly = False;
  219920. xImage->data = segmentInfo.shmaddr;
  219921. imageData = (uint8*) segmentInfo.shmaddr;
  219922. if (XShmAttach (display, &segmentInfo) != 0)
  219923. usingXShm = true;
  219924. else
  219925. jassertfalse;
  219926. }
  219927. else
  219928. {
  219929. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219930. }
  219931. }
  219932. }
  219933. }
  219934. }
  219935. if (! usingXShm)
  219936. #endif
  219937. {
  219938. imageDataAllocated.malloc (lineStride * h);
  219939. imageData = imageDataAllocated;
  219940. if (format_ == Image::ARGB && clearImage)
  219941. zeromem (imageData, h * lineStride);
  219942. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219943. xImage->width = w;
  219944. xImage->height = h;
  219945. xImage->xoffset = 0;
  219946. xImage->format = ZPixmap;
  219947. xImage->data = (char*) imageData;
  219948. xImage->byte_order = ImageByteOrder (display);
  219949. xImage->bitmap_unit = BitmapUnit (display);
  219950. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219951. xImage->bitmap_pad = 32;
  219952. xImage->depth = pixelStride * 8;
  219953. xImage->bytes_per_line = lineStride;
  219954. xImage->bits_per_pixel = pixelStride * 8;
  219955. xImage->red_mask = 0x00FF0000;
  219956. xImage->green_mask = 0x0000FF00;
  219957. xImage->blue_mask = 0x000000FF;
  219958. if (imageDepth == 16)
  219959. {
  219960. const int pixelStride = 2;
  219961. const int lineStride = ((w * pixelStride + 3) & ~3);
  219962. imageData16Bit.malloc (lineStride * h);
  219963. xImage->data = imageData16Bit;
  219964. xImage->bitmap_pad = 16;
  219965. xImage->depth = pixelStride * 8;
  219966. xImage->bytes_per_line = lineStride;
  219967. xImage->bits_per_pixel = pixelStride * 8;
  219968. xImage->red_mask = visual->red_mask;
  219969. xImage->green_mask = visual->green_mask;
  219970. xImage->blue_mask = visual->blue_mask;
  219971. }
  219972. if (! XInitImage (xImage))
  219973. jassertfalse;
  219974. }
  219975. }
  219976. ~XBitmapImage()
  219977. {
  219978. ScopedXLock xlock;
  219979. if (gc != None)
  219980. XFreeGC (display, gc);
  219981. #if JUCE_USE_XSHM
  219982. if (usingXShm)
  219983. {
  219984. XShmDetach (display, &segmentInfo);
  219985. XFlush (display);
  219986. XDestroyImage (xImage);
  219987. shmdt (segmentInfo.shmaddr);
  219988. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219989. }
  219990. else
  219991. #endif
  219992. {
  219993. xImage->data = 0;
  219994. XDestroyImage (xImage);
  219995. }
  219996. }
  219997. Image::ImageType getType() const { return Image::NativeImage; }
  219998. LowLevelGraphicsContext* createLowLevelContext()
  219999. {
  220000. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220001. }
  220002. SharedImage* clone()
  220003. {
  220004. jassertfalse;
  220005. return 0;
  220006. }
  220007. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220008. {
  220009. ScopedXLock xlock;
  220010. if (gc == None)
  220011. {
  220012. XGCValues gcvalues;
  220013. gcvalues.foreground = None;
  220014. gcvalues.background = None;
  220015. gcvalues.function = GXcopy;
  220016. gcvalues.plane_mask = AllPlanes;
  220017. gcvalues.clip_mask = None;
  220018. gcvalues.graphics_exposures = False;
  220019. gc = XCreateGC (display, window,
  220020. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220021. &gcvalues);
  220022. }
  220023. if (imageDepth == 16)
  220024. {
  220025. const uint32 rMask = xImage->red_mask;
  220026. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220027. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220028. const uint32 gMask = xImage->green_mask;
  220029. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220030. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220031. const uint32 bMask = xImage->blue_mask;
  220032. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220033. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220034. const Image::BitmapData srcData (Image (this), false);
  220035. for (int y = sy; y < sy + dh; ++y)
  220036. {
  220037. const uint8* p = srcData.getPixelPointer (sx, y);
  220038. for (int x = sx; x < sx + dw; ++x)
  220039. {
  220040. const PixelRGB* const pixel = (const PixelRGB*) p;
  220041. p += srcData.pixelStride;
  220042. XPutPixel (xImage, x, y,
  220043. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220044. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220045. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220046. }
  220047. }
  220048. }
  220049. // blit results to screen.
  220050. #if JUCE_USE_XSHM
  220051. if (usingXShm)
  220052. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220053. else
  220054. #endif
  220055. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220056. }
  220057. juce_UseDebuggingNewOperator
  220058. private:
  220059. XImage* xImage;
  220060. const int imageDepth;
  220061. HeapBlock <uint8> imageDataAllocated;
  220062. HeapBlock <char> imageData16Bit;
  220063. GC gc;
  220064. #if JUCE_USE_XSHM
  220065. XShmSegmentInfo segmentInfo;
  220066. bool usingXShm;
  220067. #endif
  220068. static int getShiftNeeded (const uint32 mask) throw()
  220069. {
  220070. for (int i = 32; --i >= 0;)
  220071. if (((mask >> i) & 1) != 0)
  220072. return i - 7;
  220073. jassertfalse;
  220074. return 0;
  220075. }
  220076. };
  220077. class LinuxComponentPeer : public ComponentPeer
  220078. {
  220079. public:
  220080. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220081. : ComponentPeer (component, windowStyleFlags),
  220082. windowH (0),
  220083. parentWindow (0),
  220084. wx (0),
  220085. wy (0),
  220086. ww (0),
  220087. wh (0),
  220088. fullScreen (false),
  220089. mapped (false),
  220090. visual (0),
  220091. depth (0)
  220092. {
  220093. // it's dangerous to create a window on a thread other than the message thread..
  220094. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220095. repainter = new LinuxRepaintManager (this);
  220096. createWindow();
  220097. setTitle (component->getName());
  220098. }
  220099. ~LinuxComponentPeer()
  220100. {
  220101. // it's dangerous to delete a window on a thread other than the message thread..
  220102. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220103. deleteIconPixmaps();
  220104. destroyWindow();
  220105. windowH = 0;
  220106. }
  220107. void* getNativeHandle() const
  220108. {
  220109. return (void*) windowH;
  220110. }
  220111. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220112. {
  220113. XPointer peer = 0;
  220114. ScopedXLock xlock;
  220115. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220116. {
  220117. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220118. peer = 0;
  220119. }
  220120. return (LinuxComponentPeer*) peer;
  220121. }
  220122. void setVisible (bool shouldBeVisible)
  220123. {
  220124. ScopedXLock xlock;
  220125. if (shouldBeVisible)
  220126. XMapWindow (display, windowH);
  220127. else
  220128. XUnmapWindow (display, windowH);
  220129. }
  220130. void setTitle (const String& title)
  220131. {
  220132. setWindowTitle (windowH, title);
  220133. }
  220134. void setPosition (int x, int y)
  220135. {
  220136. setBounds (x, y, ww, wh, false);
  220137. }
  220138. void setSize (int w, int h)
  220139. {
  220140. setBounds (wx, wy, w, h, false);
  220141. }
  220142. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220143. {
  220144. fullScreen = isNowFullScreen;
  220145. if (windowH != 0)
  220146. {
  220147. Component::SafePointer<Component> deletionChecker (component);
  220148. wx = x;
  220149. wy = y;
  220150. ww = jmax (1, w);
  220151. wh = jmax (1, h);
  220152. ScopedXLock xlock;
  220153. // Make sure the Window manager does what we want
  220154. XSizeHints* hints = XAllocSizeHints();
  220155. hints->flags = USSize | USPosition;
  220156. hints->width = ww;
  220157. hints->height = wh;
  220158. hints->x = wx;
  220159. hints->y = wy;
  220160. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220161. {
  220162. hints->min_width = hints->max_width = hints->width;
  220163. hints->min_height = hints->max_height = hints->height;
  220164. hints->flags |= PMinSize | PMaxSize;
  220165. }
  220166. XSetWMNormalHints (display, windowH, hints);
  220167. XFree (hints);
  220168. XMoveResizeWindow (display, windowH,
  220169. wx - windowBorder.getLeft(),
  220170. wy - windowBorder.getTop(), ww, wh);
  220171. if (deletionChecker != 0)
  220172. {
  220173. updateBorderSize();
  220174. handleMovedOrResized();
  220175. }
  220176. }
  220177. }
  220178. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220179. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220180. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220181. {
  220182. return relativePosition + getScreenPosition();
  220183. }
  220184. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220185. {
  220186. return screenPosition - getScreenPosition();
  220187. }
  220188. void setMinimised (bool shouldBeMinimised)
  220189. {
  220190. if (shouldBeMinimised)
  220191. {
  220192. Window root = RootWindow (display, DefaultScreen (display));
  220193. XClientMessageEvent clientMsg;
  220194. clientMsg.display = display;
  220195. clientMsg.window = windowH;
  220196. clientMsg.type = ClientMessage;
  220197. clientMsg.format = 32;
  220198. clientMsg.message_type = Atoms::ChangeState;
  220199. clientMsg.data.l[0] = IconicState;
  220200. ScopedXLock xlock;
  220201. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220202. }
  220203. else
  220204. {
  220205. setVisible (true);
  220206. }
  220207. }
  220208. bool isMinimised() const
  220209. {
  220210. bool minimised = false;
  220211. unsigned char* stateProp;
  220212. unsigned long nitems, bytesLeft;
  220213. Atom actualType;
  220214. int actualFormat;
  220215. ScopedXLock xlock;
  220216. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220217. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220218. &stateProp) == Success
  220219. && actualType == Atoms::State
  220220. && actualFormat == 32
  220221. && nitems > 0)
  220222. {
  220223. if (((unsigned long*) stateProp)[0] == IconicState)
  220224. minimised = true;
  220225. XFree (stateProp);
  220226. }
  220227. return minimised;
  220228. }
  220229. void setFullScreen (const bool shouldBeFullScreen)
  220230. {
  220231. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220232. setMinimised (false);
  220233. if (fullScreen != shouldBeFullScreen)
  220234. {
  220235. if (shouldBeFullScreen)
  220236. r = Desktop::getInstance().getMainMonitorArea();
  220237. if (! r.isEmpty())
  220238. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220239. getComponent()->repaint();
  220240. }
  220241. }
  220242. bool isFullScreen() const
  220243. {
  220244. return fullScreen;
  220245. }
  220246. bool isChildWindowOf (Window possibleParent) const
  220247. {
  220248. Window* windowList = 0;
  220249. uint32 windowListSize = 0;
  220250. Window parent, root;
  220251. ScopedXLock xlock;
  220252. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220253. {
  220254. if (windowList != 0)
  220255. XFree (windowList);
  220256. return parent == possibleParent;
  220257. }
  220258. return false;
  220259. }
  220260. bool isFrontWindow() const
  220261. {
  220262. Window* windowList = 0;
  220263. uint32 windowListSize = 0;
  220264. bool result = false;
  220265. ScopedXLock xlock;
  220266. Window parent, root = RootWindow (display, DefaultScreen (display));
  220267. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220268. {
  220269. for (int i = windowListSize; --i >= 0;)
  220270. {
  220271. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220272. if (peer != 0)
  220273. {
  220274. result = (peer == this);
  220275. break;
  220276. }
  220277. }
  220278. }
  220279. if (windowList != 0)
  220280. XFree (windowList);
  220281. return result;
  220282. }
  220283. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220284. {
  220285. int x = position.getX();
  220286. int y = position.getY();
  220287. if (((unsigned int) x) >= (unsigned int) ww
  220288. || ((unsigned int) y) >= (unsigned int) wh)
  220289. return false;
  220290. bool inFront = false;
  220291. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220292. {
  220293. Component* const c = Desktop::getInstance().getComponent (i);
  220294. if (inFront)
  220295. {
  220296. if (c->contains (x + wx - c->getScreenX(),
  220297. y + wy - c->getScreenY()))
  220298. {
  220299. return false;
  220300. }
  220301. }
  220302. else if (c == getComponent())
  220303. {
  220304. inFront = true;
  220305. }
  220306. }
  220307. if (trueIfInAChildWindow)
  220308. return true;
  220309. ::Window root, child;
  220310. unsigned int bw, depth;
  220311. int wx, wy, w, h;
  220312. ScopedXLock xlock;
  220313. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220314. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220315. &bw, &depth))
  220316. {
  220317. return false;
  220318. }
  220319. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220320. return false;
  220321. return child == None;
  220322. }
  220323. const BorderSize getFrameSize() const
  220324. {
  220325. return BorderSize();
  220326. }
  220327. bool setAlwaysOnTop (bool alwaysOnTop)
  220328. {
  220329. return false;
  220330. }
  220331. void toFront (bool makeActive)
  220332. {
  220333. if (makeActive)
  220334. {
  220335. setVisible (true);
  220336. grabFocus();
  220337. }
  220338. XEvent ev;
  220339. ev.xclient.type = ClientMessage;
  220340. ev.xclient.serial = 0;
  220341. ev.xclient.send_event = True;
  220342. ev.xclient.message_type = Atoms::ActiveWin;
  220343. ev.xclient.window = windowH;
  220344. ev.xclient.format = 32;
  220345. ev.xclient.data.l[0] = 2;
  220346. ev.xclient.data.l[1] = CurrentTime;
  220347. ev.xclient.data.l[2] = 0;
  220348. ev.xclient.data.l[3] = 0;
  220349. ev.xclient.data.l[4] = 0;
  220350. {
  220351. ScopedXLock xlock;
  220352. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220353. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220354. XWindowAttributes attr;
  220355. XGetWindowAttributes (display, windowH, &attr);
  220356. if (component->isAlwaysOnTop())
  220357. XRaiseWindow (display, windowH);
  220358. XSync (display, False);
  220359. }
  220360. handleBroughtToFront();
  220361. }
  220362. void toBehind (ComponentPeer* other)
  220363. {
  220364. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220365. jassert (otherPeer != 0); // wrong type of window?
  220366. if (otherPeer != 0)
  220367. {
  220368. setMinimised (false);
  220369. Window newStack[] = { otherPeer->windowH, windowH };
  220370. ScopedXLock xlock;
  220371. XRestackWindows (display, newStack, 2);
  220372. }
  220373. }
  220374. bool isFocused() const
  220375. {
  220376. int revert = 0;
  220377. Window focusedWindow = 0;
  220378. ScopedXLock xlock;
  220379. XGetInputFocus (display, &focusedWindow, &revert);
  220380. return focusedWindow == windowH;
  220381. }
  220382. void grabFocus()
  220383. {
  220384. XWindowAttributes atts;
  220385. ScopedXLock xlock;
  220386. if (windowH != 0
  220387. && XGetWindowAttributes (display, windowH, &atts)
  220388. && atts.map_state == IsViewable
  220389. && ! isFocused())
  220390. {
  220391. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220392. isActiveApplication = true;
  220393. }
  220394. }
  220395. void textInputRequired (const Point<int>&)
  220396. {
  220397. }
  220398. void repaint (const Rectangle<int>& area)
  220399. {
  220400. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220401. }
  220402. void performAnyPendingRepaintsNow()
  220403. {
  220404. repainter->performAnyPendingRepaintsNow();
  220405. }
  220406. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220407. {
  220408. ScopedXLock xlock;
  220409. const int width = image.getWidth();
  220410. const int height = image.getHeight();
  220411. HeapBlock <char> colour (width * height);
  220412. int index = 0;
  220413. for (int y = 0; y < height; ++y)
  220414. for (int x = 0; x < width; ++x)
  220415. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220416. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220417. 0, colour.getData(),
  220418. width, height, 32, 0);
  220419. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220420. width, height, 24);
  220421. GC gc = XCreateGC (display, pixmap, 0, 0);
  220422. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220423. XFreeGC (display, gc);
  220424. return pixmap;
  220425. }
  220426. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220427. {
  220428. ScopedXLock xlock;
  220429. const int width = image.getWidth();
  220430. const int height = image.getHeight();
  220431. const int stride = (width + 7) >> 3;
  220432. HeapBlock <char> mask;
  220433. mask.calloc (stride * height);
  220434. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220435. for (int y = 0; y < height; ++y)
  220436. {
  220437. for (int x = 0; x < width; ++x)
  220438. {
  220439. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220440. const int offset = y * stride + (x >> 3);
  220441. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220442. mask[offset] |= bit;
  220443. }
  220444. }
  220445. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220446. mask.getData(), width, height, 1, 0, 1);
  220447. }
  220448. void setIcon (const Image& newIcon)
  220449. {
  220450. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220451. HeapBlock <unsigned long> data (dataSize);
  220452. int index = 0;
  220453. data[index++] = newIcon.getWidth();
  220454. data[index++] = newIcon.getHeight();
  220455. for (int y = 0; y < newIcon.getHeight(); ++y)
  220456. for (int x = 0; x < newIcon.getWidth(); ++x)
  220457. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220458. ScopedXLock xlock;
  220459. XChangeProperty (display, windowH,
  220460. XInternAtom (display, "_NET_WM_ICON", False),
  220461. XA_CARDINAL, 32, PropModeReplace,
  220462. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220463. deleteIconPixmaps();
  220464. XWMHints* wmHints = XGetWMHints (display, windowH);
  220465. if (wmHints == 0)
  220466. wmHints = XAllocWMHints();
  220467. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220468. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220469. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220470. XSetWMHints (display, windowH, wmHints);
  220471. XFree (wmHints);
  220472. XSync (display, False);
  220473. }
  220474. void deleteIconPixmaps()
  220475. {
  220476. ScopedXLock xlock;
  220477. XWMHints* wmHints = XGetWMHints (display, windowH);
  220478. if (wmHints != 0)
  220479. {
  220480. if ((wmHints->flags & IconPixmapHint) != 0)
  220481. {
  220482. wmHints->flags &= ~IconPixmapHint;
  220483. XFreePixmap (display, wmHints->icon_pixmap);
  220484. }
  220485. if ((wmHints->flags & IconMaskHint) != 0)
  220486. {
  220487. wmHints->flags &= ~IconMaskHint;
  220488. XFreePixmap (display, wmHints->icon_mask);
  220489. }
  220490. XSetWMHints (display, windowH, wmHints);
  220491. XFree (wmHints);
  220492. }
  220493. }
  220494. void handleWindowMessage (XEvent* event)
  220495. {
  220496. switch (event->xany.type)
  220497. {
  220498. case 2: // 'KeyPress'
  220499. {
  220500. ScopedXLock xlock;
  220501. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220502. updateKeyStates (keyEvent->keycode, true);
  220503. char utf8 [64];
  220504. zeromem (utf8, sizeof (utf8));
  220505. KeySym sym;
  220506. {
  220507. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220508. ::setlocale (LC_ALL, "");
  220509. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220510. ::setlocale (LC_ALL, oldLocale);
  220511. }
  220512. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220513. int keyCode = (int) unicodeChar;
  220514. if (keyCode < 0x20)
  220515. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220516. const ModifierKeys oldMods (currentModifiers);
  220517. bool keyPressed = false;
  220518. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220519. if ((sym & 0xff00) == 0xff00)
  220520. {
  220521. // Translate keypad
  220522. if (sym == XK_KP_Divide)
  220523. keyCode = XK_slash;
  220524. else if (sym == XK_KP_Multiply)
  220525. keyCode = XK_asterisk;
  220526. else if (sym == XK_KP_Subtract)
  220527. keyCode = XK_hyphen;
  220528. else if (sym == XK_KP_Add)
  220529. keyCode = XK_plus;
  220530. else if (sym == XK_KP_Enter)
  220531. keyCode = XK_Return;
  220532. else if (sym == XK_KP_Decimal)
  220533. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220534. else if (sym == XK_KP_0)
  220535. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220536. else if (sym == XK_KP_1)
  220537. keyCode = Keys::numLock ? XK_1 : XK_End;
  220538. else if (sym == XK_KP_2)
  220539. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220540. else if (sym == XK_KP_3)
  220541. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220542. else if (sym == XK_KP_4)
  220543. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220544. else if (sym == XK_KP_5)
  220545. keyCode = XK_5;
  220546. else if (sym == XK_KP_6)
  220547. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220548. else if (sym == XK_KP_7)
  220549. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220550. else if (sym == XK_KP_8)
  220551. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220552. else if (sym == XK_KP_9)
  220553. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220554. switch (sym)
  220555. {
  220556. case XK_Left:
  220557. case XK_Right:
  220558. case XK_Up:
  220559. case XK_Down:
  220560. case XK_Page_Up:
  220561. case XK_Page_Down:
  220562. case XK_End:
  220563. case XK_Home:
  220564. case XK_Delete:
  220565. case XK_Insert:
  220566. keyPressed = true;
  220567. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220568. break;
  220569. case XK_Tab:
  220570. case XK_Return:
  220571. case XK_Escape:
  220572. case XK_BackSpace:
  220573. keyPressed = true;
  220574. keyCode &= 0xff;
  220575. break;
  220576. default:
  220577. {
  220578. if (sym >= XK_F1 && sym <= XK_F16)
  220579. {
  220580. keyPressed = true;
  220581. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220582. }
  220583. break;
  220584. }
  220585. }
  220586. }
  220587. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220588. keyPressed = true;
  220589. if (oldMods != currentModifiers)
  220590. handleModifierKeysChange();
  220591. if (keyDownChange)
  220592. handleKeyUpOrDown (true);
  220593. if (keyPressed)
  220594. handleKeyPress (keyCode, unicodeChar);
  220595. break;
  220596. }
  220597. case KeyRelease:
  220598. {
  220599. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220600. updateKeyStates (keyEvent->keycode, false);
  220601. KeySym sym;
  220602. {
  220603. ScopedXLock xlock;
  220604. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220605. }
  220606. const ModifierKeys oldMods (currentModifiers);
  220607. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220608. if (oldMods != currentModifiers)
  220609. handleModifierKeysChange();
  220610. if (keyDownChange)
  220611. handleKeyUpOrDown (false);
  220612. break;
  220613. }
  220614. case ButtonPress:
  220615. {
  220616. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220617. updateKeyModifiers (buttonPressEvent->state);
  220618. bool buttonMsg = false;
  220619. const int map = pointerMap [buttonPressEvent->button - Button1];
  220620. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220621. {
  220622. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220623. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220624. }
  220625. if (map == Keys::LeftButton)
  220626. {
  220627. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220628. buttonMsg = true;
  220629. }
  220630. else if (map == Keys::RightButton)
  220631. {
  220632. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220633. buttonMsg = true;
  220634. }
  220635. else if (map == Keys::MiddleButton)
  220636. {
  220637. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220638. buttonMsg = true;
  220639. }
  220640. if (buttonMsg)
  220641. {
  220642. toFront (true);
  220643. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220644. getEventTime (buttonPressEvent->time));
  220645. }
  220646. clearLastMousePos();
  220647. break;
  220648. }
  220649. case ButtonRelease:
  220650. {
  220651. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220652. updateKeyModifiers (buttonRelEvent->state);
  220653. const int map = pointerMap [buttonRelEvent->button - Button1];
  220654. if (map == Keys::LeftButton)
  220655. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220656. else if (map == Keys::RightButton)
  220657. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220658. else if (map == Keys::MiddleButton)
  220659. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220660. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220661. getEventTime (buttonRelEvent->time));
  220662. clearLastMousePos();
  220663. break;
  220664. }
  220665. case MotionNotify:
  220666. {
  220667. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220668. updateKeyModifiers (movedEvent->state);
  220669. const Point<int> mousePos (Desktop::getMousePosition());
  220670. if (lastMousePos != mousePos)
  220671. {
  220672. lastMousePos = mousePos;
  220673. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220674. {
  220675. Window wRoot = 0, wParent = 0;
  220676. {
  220677. ScopedXLock xlock;
  220678. unsigned int numChildren;
  220679. Window* wChild = 0;
  220680. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220681. }
  220682. if (wParent != 0
  220683. && wParent != windowH
  220684. && wParent != wRoot)
  220685. {
  220686. parentWindow = wParent;
  220687. updateBounds();
  220688. }
  220689. else
  220690. {
  220691. parentWindow = 0;
  220692. }
  220693. }
  220694. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220695. }
  220696. break;
  220697. }
  220698. case EnterNotify:
  220699. {
  220700. clearLastMousePos();
  220701. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220702. if (! currentModifiers.isAnyMouseButtonDown())
  220703. {
  220704. updateKeyModifiers (enterEvent->state);
  220705. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220706. }
  220707. break;
  220708. }
  220709. case LeaveNotify:
  220710. {
  220711. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220712. // Suppress the normal leave if we've got a pointer grab, or if
  220713. // it's a bogus one caused by clicking a mouse button when running
  220714. // in a Window manager
  220715. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220716. || leaveEvent->mode == NotifyUngrab)
  220717. {
  220718. updateKeyModifiers (leaveEvent->state);
  220719. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220720. }
  220721. break;
  220722. }
  220723. case FocusIn:
  220724. {
  220725. isActiveApplication = true;
  220726. if (isFocused())
  220727. handleFocusGain();
  220728. break;
  220729. }
  220730. case FocusOut:
  220731. {
  220732. isActiveApplication = false;
  220733. if (! isFocused())
  220734. handleFocusLoss();
  220735. break;
  220736. }
  220737. case Expose:
  220738. {
  220739. // Batch together all pending expose events
  220740. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220741. XEvent nextEvent;
  220742. ScopedXLock xlock;
  220743. if (exposeEvent->window != windowH)
  220744. {
  220745. Window child;
  220746. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220747. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220748. &child);
  220749. }
  220750. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220751. exposeEvent->width, exposeEvent->height));
  220752. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220753. {
  220754. XPeekEvent (display, (XEvent*) &nextEvent);
  220755. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220756. break;
  220757. XNextEvent (display, (XEvent*) &nextEvent);
  220758. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220759. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220760. nextExposeEvent->width, nextExposeEvent->height));
  220761. }
  220762. break;
  220763. }
  220764. case CirculateNotify:
  220765. case CreateNotify:
  220766. case DestroyNotify:
  220767. // Think we can ignore these
  220768. break;
  220769. case ConfigureNotify:
  220770. {
  220771. updateBounds();
  220772. updateBorderSize();
  220773. handleMovedOrResized();
  220774. // if the native title bar is dragged, need to tell any active menus, etc.
  220775. if ((styleFlags & windowHasTitleBar) != 0
  220776. && component->isCurrentlyBlockedByAnotherModalComponent())
  220777. {
  220778. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220779. if (currentModalComp != 0)
  220780. currentModalComp->inputAttemptWhenModal();
  220781. }
  220782. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220783. if (confEvent->window == windowH
  220784. && confEvent->above != 0
  220785. && isFrontWindow())
  220786. {
  220787. handleBroughtToFront();
  220788. }
  220789. break;
  220790. }
  220791. case ReparentNotify:
  220792. {
  220793. parentWindow = 0;
  220794. Window wRoot = 0;
  220795. Window* wChild = 0;
  220796. unsigned int numChildren;
  220797. {
  220798. ScopedXLock xlock;
  220799. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220800. }
  220801. if (parentWindow == windowH || parentWindow == wRoot)
  220802. parentWindow = 0;
  220803. updateBounds();
  220804. updateBorderSize();
  220805. handleMovedOrResized();
  220806. break;
  220807. }
  220808. case GravityNotify:
  220809. {
  220810. updateBounds();
  220811. updateBorderSize();
  220812. handleMovedOrResized();
  220813. break;
  220814. }
  220815. case MapNotify:
  220816. mapped = true;
  220817. handleBroughtToFront();
  220818. break;
  220819. case UnmapNotify:
  220820. mapped = false;
  220821. break;
  220822. case MappingNotify:
  220823. {
  220824. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220825. if (mappingEvent->request != MappingPointer)
  220826. {
  220827. // Deal with modifier/keyboard mapping
  220828. ScopedXLock xlock;
  220829. XRefreshKeyboardMapping (mappingEvent);
  220830. updateModifierMappings();
  220831. }
  220832. break;
  220833. }
  220834. case ClientMessage:
  220835. {
  220836. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220837. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220838. {
  220839. const Atom atom = (Atom) clientMsg->data.l[0];
  220840. if (atom == Atoms::ProtocolList [Atoms::PING])
  220841. {
  220842. Window root = RootWindow (display, DefaultScreen (display));
  220843. event->xclient.window = root;
  220844. XSendEvent (display, root, False, NoEventMask, event);
  220845. XFlush (display);
  220846. }
  220847. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220848. {
  220849. XWindowAttributes atts;
  220850. ScopedXLock xlock;
  220851. if (clientMsg->window != 0
  220852. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220853. {
  220854. if (atts.map_state == IsViewable)
  220855. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220856. }
  220857. }
  220858. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220859. {
  220860. handleUserClosingWindow();
  220861. }
  220862. }
  220863. else if (clientMsg->message_type == Atoms::XdndEnter)
  220864. {
  220865. handleDragAndDropEnter (clientMsg);
  220866. }
  220867. else if (clientMsg->message_type == Atoms::XdndLeave)
  220868. {
  220869. resetDragAndDrop();
  220870. }
  220871. else if (clientMsg->message_type == Atoms::XdndPosition)
  220872. {
  220873. handleDragAndDropPosition (clientMsg);
  220874. }
  220875. else if (clientMsg->message_type == Atoms::XdndDrop)
  220876. {
  220877. handleDragAndDropDrop (clientMsg);
  220878. }
  220879. else if (clientMsg->message_type == Atoms::XdndStatus)
  220880. {
  220881. handleDragAndDropStatus (clientMsg);
  220882. }
  220883. else if (clientMsg->message_type == Atoms::XdndFinished)
  220884. {
  220885. resetDragAndDrop();
  220886. }
  220887. break;
  220888. }
  220889. case SelectionNotify:
  220890. handleDragAndDropSelection (event);
  220891. break;
  220892. case SelectionClear:
  220893. case SelectionRequest:
  220894. break;
  220895. default:
  220896. #if JUCE_USE_XSHM
  220897. {
  220898. ScopedXLock xlock;
  220899. if (event->xany.type == XShmGetEventBase (display))
  220900. repainter->notifyPaintCompleted();
  220901. }
  220902. #endif
  220903. break;
  220904. }
  220905. }
  220906. void showMouseCursor (Cursor cursor) throw()
  220907. {
  220908. ScopedXLock xlock;
  220909. XDefineCursor (display, windowH, cursor);
  220910. }
  220911. void setTaskBarIcon (const Image& image)
  220912. {
  220913. ScopedXLock xlock;
  220914. taskbarImage = image;
  220915. Screen* const screen = XDefaultScreenOfDisplay (display);
  220916. const int screenNumber = XScreenNumberOfScreen (screen);
  220917. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220918. screenAtom << screenNumber;
  220919. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220920. XGrabServer (display);
  220921. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220922. if (managerWin != None)
  220923. XSelectInput (display, managerWin, StructureNotifyMask);
  220924. XUngrabServer (display);
  220925. XFlush (display);
  220926. if (managerWin != None)
  220927. {
  220928. XEvent ev;
  220929. zerostruct (ev);
  220930. ev.xclient.type = ClientMessage;
  220931. ev.xclient.window = managerWin;
  220932. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220933. ev.xclient.format = 32;
  220934. ev.xclient.data.l[0] = CurrentTime;
  220935. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220936. ev.xclient.data.l[2] = windowH;
  220937. ev.xclient.data.l[3] = 0;
  220938. ev.xclient.data.l[4] = 0;
  220939. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220940. XSync (display, False);
  220941. }
  220942. // For older KDE's ...
  220943. long atomData = 1;
  220944. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220945. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220946. // For more recent KDE's...
  220947. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220948. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220949. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220950. XSizeHints* hints = XAllocSizeHints();
  220951. hints->flags = PMinSize;
  220952. hints->min_width = 22;
  220953. hints->min_height = 22;
  220954. XSetWMNormalHints (display, windowH, hints);
  220955. XFree (hints);
  220956. }
  220957. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220958. juce_UseDebuggingNewOperator
  220959. bool dontRepaint;
  220960. static ModifierKeys currentModifiers;
  220961. static bool isActiveApplication;
  220962. private:
  220963. class LinuxRepaintManager : public Timer
  220964. {
  220965. public:
  220966. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220967. : peer (peer_),
  220968. lastTimeImageUsed (0)
  220969. {
  220970. #if JUCE_USE_XSHM
  220971. shmCompletedDrawing = true;
  220972. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220973. if (useARGBImagesForRendering)
  220974. {
  220975. ScopedXLock xlock;
  220976. XShmSegmentInfo segmentinfo;
  220977. XImage* const testImage
  220978. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220979. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220980. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220981. XDestroyImage (testImage);
  220982. }
  220983. #endif
  220984. }
  220985. ~LinuxRepaintManager()
  220986. {
  220987. }
  220988. void timerCallback()
  220989. {
  220990. #if JUCE_USE_XSHM
  220991. if (! shmCompletedDrawing)
  220992. return;
  220993. #endif
  220994. if (! regionsNeedingRepaint.isEmpty())
  220995. {
  220996. stopTimer();
  220997. performAnyPendingRepaintsNow();
  220998. }
  220999. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221000. {
  221001. stopTimer();
  221002. image = Image::null;
  221003. }
  221004. }
  221005. void repaint (const Rectangle<int>& area)
  221006. {
  221007. if (! isTimerRunning())
  221008. startTimer (repaintTimerPeriod);
  221009. regionsNeedingRepaint.add (area);
  221010. }
  221011. void performAnyPendingRepaintsNow()
  221012. {
  221013. #if JUCE_USE_XSHM
  221014. if (! shmCompletedDrawing)
  221015. {
  221016. startTimer (repaintTimerPeriod);
  221017. return;
  221018. }
  221019. #endif
  221020. peer->clearMaskedRegion();
  221021. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221022. regionsNeedingRepaint.clear();
  221023. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221024. if (! totalArea.isEmpty())
  221025. {
  221026. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221027. || image.getHeight() < totalArea.getHeight())
  221028. {
  221029. #if JUCE_USE_XSHM
  221030. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221031. : Image::RGB,
  221032. #else
  221033. image = Image (new XBitmapImage (Image::RGB,
  221034. #endif
  221035. (totalArea.getWidth() + 31) & ~31,
  221036. (totalArea.getHeight() + 31) & ~31,
  221037. false, peer->depth, peer->visual));
  221038. }
  221039. startTimer (repaintTimerPeriod);
  221040. RectangleList adjustedList (originalRepaintRegion);
  221041. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221042. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221043. if (peer->depth == 32)
  221044. {
  221045. RectangleList::Iterator i (originalRepaintRegion);
  221046. while (i.next())
  221047. image.clear (*i.getRectangle() - totalArea.getPosition());
  221048. }
  221049. peer->handlePaint (context);
  221050. if (! peer->maskedRegion.isEmpty())
  221051. originalRepaintRegion.subtract (peer->maskedRegion);
  221052. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221053. {
  221054. #if JUCE_USE_XSHM
  221055. shmCompletedDrawing = false;
  221056. #endif
  221057. const Rectangle<int>& r = *i.getRectangle();
  221058. static_cast<XBitmapImage*> (image.getSharedImage())
  221059. ->blitToWindow (peer->windowH,
  221060. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221061. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221062. }
  221063. }
  221064. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221065. startTimer (repaintTimerPeriod);
  221066. }
  221067. #if JUCE_USE_XSHM
  221068. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221069. #endif
  221070. private:
  221071. enum { repaintTimerPeriod = 1000 / 100 };
  221072. LinuxComponentPeer* const peer;
  221073. Image image;
  221074. uint32 lastTimeImageUsed;
  221075. RectangleList regionsNeedingRepaint;
  221076. #if JUCE_USE_XSHM
  221077. bool useARGBImagesForRendering, shmCompletedDrawing;
  221078. #endif
  221079. LinuxRepaintManager (const LinuxRepaintManager&);
  221080. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221081. };
  221082. ScopedPointer <LinuxRepaintManager> repainter;
  221083. friend class LinuxRepaintManager;
  221084. Window windowH, parentWindow;
  221085. int wx, wy, ww, wh;
  221086. Image taskbarImage;
  221087. bool fullScreen, mapped;
  221088. Visual* visual;
  221089. int depth;
  221090. BorderSize windowBorder;
  221091. struct MotifWmHints
  221092. {
  221093. unsigned long flags;
  221094. unsigned long functions;
  221095. unsigned long decorations;
  221096. long input_mode;
  221097. unsigned long status;
  221098. };
  221099. static void updateKeyStates (const int keycode, const bool press) throw()
  221100. {
  221101. const int keybyte = keycode >> 3;
  221102. const int keybit = (1 << (keycode & 7));
  221103. if (press)
  221104. Keys::keyStates [keybyte] |= keybit;
  221105. else
  221106. Keys::keyStates [keybyte] &= ~keybit;
  221107. }
  221108. static void updateKeyModifiers (const int status) throw()
  221109. {
  221110. int keyMods = 0;
  221111. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221112. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221113. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221114. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221115. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221116. Keys::capsLock = ((status & LockMask) != 0);
  221117. }
  221118. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221119. {
  221120. int modifier = 0;
  221121. bool isModifier = true;
  221122. switch (sym)
  221123. {
  221124. case XK_Shift_L:
  221125. case XK_Shift_R:
  221126. modifier = ModifierKeys::shiftModifier;
  221127. break;
  221128. case XK_Control_L:
  221129. case XK_Control_R:
  221130. modifier = ModifierKeys::ctrlModifier;
  221131. break;
  221132. case XK_Alt_L:
  221133. case XK_Alt_R:
  221134. modifier = ModifierKeys::altModifier;
  221135. break;
  221136. case XK_Num_Lock:
  221137. if (press)
  221138. Keys::numLock = ! Keys::numLock;
  221139. break;
  221140. case XK_Caps_Lock:
  221141. if (press)
  221142. Keys::capsLock = ! Keys::capsLock;
  221143. break;
  221144. case XK_Scroll_Lock:
  221145. break;
  221146. default:
  221147. isModifier = false;
  221148. break;
  221149. }
  221150. if (modifier != 0)
  221151. {
  221152. if (press)
  221153. currentModifiers = currentModifiers.withFlags (modifier);
  221154. else
  221155. currentModifiers = currentModifiers.withoutFlags (modifier);
  221156. }
  221157. return isModifier;
  221158. }
  221159. // Alt and Num lock are not defined by standard X
  221160. // modifier constants: check what they're mapped to
  221161. static void updateModifierMappings() throw()
  221162. {
  221163. ScopedXLock xlock;
  221164. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221165. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221166. Keys::AltMask = 0;
  221167. Keys::NumLockMask = 0;
  221168. XModifierKeymap* mapping = XGetModifierMapping (display);
  221169. if (mapping)
  221170. {
  221171. for (int i = 0; i < 8; i++)
  221172. {
  221173. if (mapping->modifiermap [i << 1] == altLeftCode)
  221174. Keys::AltMask = 1 << i;
  221175. else if (mapping->modifiermap [i << 1] == numLockCode)
  221176. Keys::NumLockMask = 1 << i;
  221177. }
  221178. XFreeModifiermap (mapping);
  221179. }
  221180. }
  221181. void removeWindowDecorations (Window wndH)
  221182. {
  221183. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221184. if (hints != None)
  221185. {
  221186. MotifWmHints motifHints;
  221187. zerostruct (motifHints);
  221188. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221189. motifHints.decorations = 0;
  221190. ScopedXLock xlock;
  221191. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221192. (unsigned char*) &motifHints, 4);
  221193. }
  221194. hints = XInternAtom (display, "_WIN_HINTS", True);
  221195. if (hints != None)
  221196. {
  221197. long gnomeHints = 0;
  221198. ScopedXLock xlock;
  221199. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221200. (unsigned char*) &gnomeHints, 1);
  221201. }
  221202. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221203. if (hints != None)
  221204. {
  221205. long kwmHints = 2; /*KDE_tinyDecoration*/
  221206. ScopedXLock xlock;
  221207. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221208. (unsigned char*) &kwmHints, 1);
  221209. }
  221210. }
  221211. void addWindowButtons (Window wndH)
  221212. {
  221213. ScopedXLock xlock;
  221214. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221215. if (hints != None)
  221216. {
  221217. MotifWmHints motifHints;
  221218. zerostruct (motifHints);
  221219. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221220. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221221. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221222. if ((styleFlags & windowHasCloseButton) != 0)
  221223. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221224. if ((styleFlags & windowHasMinimiseButton) != 0)
  221225. {
  221226. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221227. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221228. }
  221229. if ((styleFlags & windowHasMaximiseButton) != 0)
  221230. {
  221231. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221232. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221233. }
  221234. if ((styleFlags & windowIsResizable) != 0)
  221235. {
  221236. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221237. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221238. }
  221239. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221240. }
  221241. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221242. if (hints != None)
  221243. {
  221244. int netHints [6];
  221245. int num = 0;
  221246. if ((styleFlags & windowIsResizable) != 0)
  221247. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221248. if ((styleFlags & windowHasMaximiseButton) != 0)
  221249. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221250. if ((styleFlags & windowHasMinimiseButton) != 0)
  221251. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221252. if ((styleFlags & windowHasCloseButton) != 0)
  221253. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221254. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221255. }
  221256. }
  221257. void setWindowType()
  221258. {
  221259. int netHints [2];
  221260. int numHints = 0;
  221261. if ((styleFlags & windowIsTemporary) != 0
  221262. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221263. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221264. else
  221265. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221266. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221267. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221268. (unsigned char*) &netHints, numHints);
  221269. numHints = 0;
  221270. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221271. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221272. if (component->isAlwaysOnTop())
  221273. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221274. if (numHints > 0)
  221275. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221276. (unsigned char*) &netHints, numHints);
  221277. }
  221278. void createWindow()
  221279. {
  221280. ScopedXLock xlock;
  221281. Atoms::initialiseAtoms();
  221282. resetDragAndDrop();
  221283. // Get defaults for various properties
  221284. const int screen = DefaultScreen (display);
  221285. Window root = RootWindow (display, screen);
  221286. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221287. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221288. if (visual == 0)
  221289. {
  221290. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221291. Process::terminate();
  221292. }
  221293. // Create and install a colormap suitable fr our visual
  221294. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221295. XInstallColormap (display, colormap);
  221296. // Set up the window attributes
  221297. XSetWindowAttributes swa;
  221298. swa.border_pixel = 0;
  221299. swa.background_pixmap = None;
  221300. swa.colormap = colormap;
  221301. swa.event_mask = getAllEventsMask();
  221302. windowH = XCreateWindow (display, root,
  221303. 0, 0, 1, 1,
  221304. 0, depth, InputOutput, visual,
  221305. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221306. &swa);
  221307. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221308. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221309. GrabModeAsync, GrabModeAsync, None, None);
  221310. // Set the window context to identify the window handle object
  221311. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221312. {
  221313. // Failed
  221314. jassertfalse;
  221315. Logger::outputDebugString ("Failed to create context information for window.\n");
  221316. XDestroyWindow (display, windowH);
  221317. windowH = 0;
  221318. return;
  221319. }
  221320. // Set window manager hints
  221321. XWMHints* wmHints = XAllocWMHints();
  221322. wmHints->flags = InputHint | StateHint;
  221323. wmHints->input = True; // Locally active input model
  221324. wmHints->initial_state = NormalState;
  221325. XSetWMHints (display, windowH, wmHints);
  221326. XFree (wmHints);
  221327. // Set the window type
  221328. setWindowType();
  221329. // Define decoration
  221330. if ((styleFlags & windowHasTitleBar) == 0)
  221331. removeWindowDecorations (windowH);
  221332. else
  221333. addWindowButtons (windowH);
  221334. // Set window name
  221335. setWindowTitle (windowH, getComponent()->getName());
  221336. // Associate the PID, allowing to be shut down when something goes wrong
  221337. unsigned long pid = getpid();
  221338. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221339. (unsigned char*) &pid, 1);
  221340. // Set window manager protocols
  221341. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221342. (unsigned char*) Atoms::ProtocolList, 2);
  221343. // Set drag and drop flags
  221344. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221345. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221346. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221347. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221348. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221349. (const unsigned char*) "", 0);
  221350. unsigned long dndVersion = Atoms::DndVersion;
  221351. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221352. (const unsigned char*) &dndVersion, 1);
  221353. // Initialise the pointer and keyboard mapping
  221354. // This is not the same as the logical pointer mapping the X server uses:
  221355. // we don't mess with this.
  221356. static bool mappingInitialised = false;
  221357. if (! mappingInitialised)
  221358. {
  221359. mappingInitialised = true;
  221360. const int numButtons = XGetPointerMapping (display, 0, 0);
  221361. if (numButtons == 2)
  221362. {
  221363. pointerMap[0] = Keys::LeftButton;
  221364. pointerMap[1] = Keys::RightButton;
  221365. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221366. }
  221367. else if (numButtons >= 3)
  221368. {
  221369. pointerMap[0] = Keys::LeftButton;
  221370. pointerMap[1] = Keys::MiddleButton;
  221371. pointerMap[2] = Keys::RightButton;
  221372. if (numButtons >= 5)
  221373. {
  221374. pointerMap[3] = Keys::WheelUp;
  221375. pointerMap[4] = Keys::WheelDown;
  221376. }
  221377. }
  221378. updateModifierMappings();
  221379. }
  221380. }
  221381. void destroyWindow()
  221382. {
  221383. ScopedXLock xlock;
  221384. XPointer handlePointer;
  221385. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221386. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221387. XDestroyWindow (display, windowH);
  221388. // Wait for it to complete and then remove any events for this
  221389. // window from the event queue.
  221390. XSync (display, false);
  221391. XEvent event;
  221392. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221393. {}
  221394. }
  221395. static int getAllEventsMask() throw()
  221396. {
  221397. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221398. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221399. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221400. }
  221401. static int64 getEventTime (::Time t)
  221402. {
  221403. static int64 eventTimeOffset = 0x12345678;
  221404. const int64 thisMessageTime = t;
  221405. if (eventTimeOffset == 0x12345678)
  221406. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221407. return eventTimeOffset + thisMessageTime;
  221408. }
  221409. static void setWindowTitle (Window xwin, const String& title)
  221410. {
  221411. XTextProperty nameProperty;
  221412. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221413. ScopedXLock xlock;
  221414. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221415. {
  221416. XSetWMName (display, xwin, &nameProperty);
  221417. XSetWMIconName (display, xwin, &nameProperty);
  221418. XFree (nameProperty.value);
  221419. }
  221420. }
  221421. void updateBorderSize()
  221422. {
  221423. if ((styleFlags & windowHasTitleBar) == 0)
  221424. {
  221425. windowBorder = BorderSize (0);
  221426. }
  221427. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221428. {
  221429. ScopedXLock xlock;
  221430. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221431. if (hints != None)
  221432. {
  221433. unsigned char* data = 0;
  221434. unsigned long nitems, bytesLeft;
  221435. Atom actualType;
  221436. int actualFormat;
  221437. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221438. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221439. &data) == Success)
  221440. {
  221441. const unsigned long* const sizes = (const unsigned long*) data;
  221442. if (actualFormat == 32)
  221443. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221444. (int) sizes[3], (int) sizes[1]);
  221445. XFree (data);
  221446. }
  221447. }
  221448. }
  221449. }
  221450. void updateBounds()
  221451. {
  221452. jassert (windowH != 0);
  221453. if (windowH != 0)
  221454. {
  221455. Window root, child;
  221456. unsigned int bw, depth;
  221457. ScopedXLock xlock;
  221458. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221459. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221460. &bw, &depth))
  221461. {
  221462. wx = wy = ww = wh = 0;
  221463. }
  221464. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221465. {
  221466. wx = wy = 0;
  221467. }
  221468. }
  221469. }
  221470. void resetDragAndDrop()
  221471. {
  221472. dragAndDropFiles.clear();
  221473. lastDropPos = Point<int> (-1, -1);
  221474. dragAndDropCurrentMimeType = 0;
  221475. dragAndDropSourceWindow = 0;
  221476. srcMimeTypeAtomList.clear();
  221477. }
  221478. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221479. {
  221480. msg.type = ClientMessage;
  221481. msg.display = display;
  221482. msg.window = dragAndDropSourceWindow;
  221483. msg.format = 32;
  221484. msg.data.l[0] = windowH;
  221485. ScopedXLock xlock;
  221486. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221487. }
  221488. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221489. {
  221490. XClientMessageEvent msg;
  221491. zerostruct (msg);
  221492. msg.message_type = Atoms::XdndStatus;
  221493. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221494. msg.data.l[4] = dropAction;
  221495. sendDragAndDropMessage (msg);
  221496. }
  221497. void sendDragAndDropLeave()
  221498. {
  221499. XClientMessageEvent msg;
  221500. zerostruct (msg);
  221501. msg.message_type = Atoms::XdndLeave;
  221502. sendDragAndDropMessage (msg);
  221503. }
  221504. void sendDragAndDropFinish()
  221505. {
  221506. XClientMessageEvent msg;
  221507. zerostruct (msg);
  221508. msg.message_type = Atoms::XdndFinished;
  221509. sendDragAndDropMessage (msg);
  221510. }
  221511. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221512. {
  221513. if ((clientMsg->data.l[1] & 1) == 0)
  221514. {
  221515. sendDragAndDropLeave();
  221516. if (dragAndDropFiles.size() > 0)
  221517. handleFileDragExit (dragAndDropFiles);
  221518. dragAndDropFiles.clear();
  221519. }
  221520. }
  221521. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221522. {
  221523. if (dragAndDropSourceWindow == 0)
  221524. return;
  221525. dragAndDropSourceWindow = clientMsg->data.l[0];
  221526. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221527. (int) clientMsg->data.l[2] & 0xffff);
  221528. dropPos -= getScreenPosition();
  221529. if (lastDropPos != dropPos)
  221530. {
  221531. lastDropPos = dropPos;
  221532. dragAndDropTimestamp = clientMsg->data.l[3];
  221533. Atom targetAction = Atoms::XdndActionCopy;
  221534. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221535. {
  221536. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221537. {
  221538. targetAction = Atoms::allowedActions[i];
  221539. break;
  221540. }
  221541. }
  221542. sendDragAndDropStatus (true, targetAction);
  221543. if (dragAndDropFiles.size() == 0)
  221544. updateDraggedFileList (clientMsg);
  221545. if (dragAndDropFiles.size() > 0)
  221546. handleFileDragMove (dragAndDropFiles, dropPos);
  221547. }
  221548. }
  221549. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221550. {
  221551. if (dragAndDropFiles.size() == 0)
  221552. updateDraggedFileList (clientMsg);
  221553. const StringArray files (dragAndDropFiles);
  221554. const Point<int> lastPos (lastDropPos);
  221555. sendDragAndDropFinish();
  221556. resetDragAndDrop();
  221557. if (files.size() > 0)
  221558. handleFileDragDrop (files, lastPos);
  221559. }
  221560. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221561. {
  221562. dragAndDropFiles.clear();
  221563. srcMimeTypeAtomList.clear();
  221564. dragAndDropCurrentMimeType = 0;
  221565. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221566. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221567. {
  221568. dragAndDropSourceWindow = 0;
  221569. return;
  221570. }
  221571. dragAndDropSourceWindow = clientMsg->data.l[0];
  221572. if ((clientMsg->data.l[1] & 1) != 0)
  221573. {
  221574. Atom actual;
  221575. int format;
  221576. unsigned long count = 0, remaining = 0;
  221577. unsigned char* data = 0;
  221578. ScopedXLock xlock;
  221579. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221580. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221581. &count, &remaining, &data);
  221582. if (data != 0)
  221583. {
  221584. if (actual == XA_ATOM && format == 32 && count != 0)
  221585. {
  221586. const unsigned long* const types = (const unsigned long*) data;
  221587. for (unsigned int i = 0; i < count; ++i)
  221588. if (types[i] != None)
  221589. srcMimeTypeAtomList.add (types[i]);
  221590. }
  221591. XFree (data);
  221592. }
  221593. }
  221594. if (srcMimeTypeAtomList.size() == 0)
  221595. {
  221596. for (int i = 2; i < 5; ++i)
  221597. if (clientMsg->data.l[i] != None)
  221598. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221599. if (srcMimeTypeAtomList.size() == 0)
  221600. {
  221601. dragAndDropSourceWindow = 0;
  221602. return;
  221603. }
  221604. }
  221605. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221606. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221607. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221608. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221609. handleDragAndDropPosition (clientMsg);
  221610. }
  221611. void handleDragAndDropSelection (const XEvent* const evt)
  221612. {
  221613. dragAndDropFiles.clear();
  221614. if (evt->xselection.property != 0)
  221615. {
  221616. StringArray lines;
  221617. {
  221618. MemoryBlock dropData;
  221619. for (;;)
  221620. {
  221621. Atom actual;
  221622. uint8* data = 0;
  221623. unsigned long count = 0, remaining = 0;
  221624. int format = 0;
  221625. ScopedXLock xlock;
  221626. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221627. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221628. &format, &count, &remaining, &data) == Success)
  221629. {
  221630. dropData.append (data, count * format / 8);
  221631. XFree (data);
  221632. if (remaining == 0)
  221633. break;
  221634. }
  221635. else
  221636. {
  221637. XFree (data);
  221638. break;
  221639. }
  221640. }
  221641. lines.addLines (dropData.toString());
  221642. }
  221643. for (int i = 0; i < lines.size(); ++i)
  221644. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221645. dragAndDropFiles.trim();
  221646. dragAndDropFiles.removeEmptyStrings();
  221647. }
  221648. }
  221649. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221650. {
  221651. dragAndDropFiles.clear();
  221652. if (dragAndDropSourceWindow != None
  221653. && dragAndDropCurrentMimeType != 0)
  221654. {
  221655. dragAndDropTimestamp = clientMsg->data.l[2];
  221656. ScopedXLock xlock;
  221657. XConvertSelection (display,
  221658. Atoms::XdndSelection,
  221659. dragAndDropCurrentMimeType,
  221660. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221661. windowH,
  221662. dragAndDropTimestamp);
  221663. }
  221664. }
  221665. StringArray dragAndDropFiles;
  221666. int dragAndDropTimestamp;
  221667. Point<int> lastDropPos;
  221668. Atom dragAndDropCurrentMimeType;
  221669. Window dragAndDropSourceWindow;
  221670. Array <Atom> srcMimeTypeAtomList;
  221671. static int pointerMap[5];
  221672. static Point<int> lastMousePos;
  221673. static void clearLastMousePos() throw()
  221674. {
  221675. lastMousePos = Point<int> (0x100000, 0x100000);
  221676. }
  221677. };
  221678. ModifierKeys LinuxComponentPeer::currentModifiers;
  221679. bool LinuxComponentPeer::isActiveApplication = false;
  221680. int LinuxComponentPeer::pointerMap[5];
  221681. Point<int> LinuxComponentPeer::lastMousePos;
  221682. bool Process::isForegroundProcess()
  221683. {
  221684. return LinuxComponentPeer::isActiveApplication;
  221685. }
  221686. void ModifierKeys::updateCurrentModifiers() throw()
  221687. {
  221688. currentModifiers = LinuxComponentPeer::currentModifiers;
  221689. }
  221690. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221691. {
  221692. Window root, child;
  221693. int x, y, winx, winy;
  221694. unsigned int mask;
  221695. int mouseMods = 0;
  221696. ScopedXLock xlock;
  221697. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221698. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221699. {
  221700. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221701. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221702. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221703. }
  221704. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221705. return LinuxComponentPeer::currentModifiers;
  221706. }
  221707. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221708. {
  221709. if (enableOrDisable)
  221710. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221711. }
  221712. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221713. {
  221714. return new LinuxComponentPeer (this, styleFlags);
  221715. }
  221716. // (this callback is hooked up in the messaging code)
  221717. void juce_windowMessageReceive (XEvent* event)
  221718. {
  221719. if (event->xany.window != None)
  221720. {
  221721. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221722. if (ComponentPeer::isValidPeer (peer))
  221723. peer->handleWindowMessage (event);
  221724. }
  221725. else
  221726. {
  221727. switch (event->xany.type)
  221728. {
  221729. case KeymapNotify:
  221730. {
  221731. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221732. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221733. break;
  221734. }
  221735. default:
  221736. break;
  221737. }
  221738. }
  221739. }
  221740. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221741. {
  221742. if (display == 0)
  221743. return;
  221744. #if JUCE_USE_XINERAMA
  221745. int major_opcode, first_event, first_error;
  221746. ScopedXLock xlock;
  221747. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221748. {
  221749. typedef Bool (*tXineramaIsActive) (Display*);
  221750. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221751. static tXineramaIsActive xXineramaIsActive = 0;
  221752. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221753. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221754. {
  221755. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221756. if (h == 0)
  221757. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221758. if (h != 0)
  221759. {
  221760. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221761. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221762. }
  221763. }
  221764. if (xXineramaIsActive != 0
  221765. && xXineramaQueryScreens != 0
  221766. && xXineramaIsActive (display))
  221767. {
  221768. int numMonitors = 0;
  221769. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221770. if (screens != 0)
  221771. {
  221772. for (int i = numMonitors; --i >= 0;)
  221773. {
  221774. int index = screens[i].screen_number;
  221775. if (index >= 0)
  221776. {
  221777. while (monitorCoords.size() < index)
  221778. monitorCoords.add (Rectangle<int>());
  221779. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221780. screens[i].y_org,
  221781. screens[i].width,
  221782. screens[i].height));
  221783. }
  221784. }
  221785. XFree (screens);
  221786. }
  221787. }
  221788. }
  221789. if (monitorCoords.size() == 0)
  221790. #endif
  221791. {
  221792. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221793. if (hints != None)
  221794. {
  221795. const int numMonitors = ScreenCount (display);
  221796. for (int i = 0; i < numMonitors; ++i)
  221797. {
  221798. Window root = RootWindow (display, i);
  221799. unsigned long nitems, bytesLeft;
  221800. Atom actualType;
  221801. int actualFormat;
  221802. unsigned char* data = 0;
  221803. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221804. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221805. &data) == Success)
  221806. {
  221807. const long* const position = (const long*) data;
  221808. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221809. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221810. position[2], position[3]));
  221811. XFree (data);
  221812. }
  221813. }
  221814. }
  221815. if (monitorCoords.size() == 0)
  221816. {
  221817. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221818. DisplayHeight (display, DefaultScreen (display))));
  221819. }
  221820. }
  221821. }
  221822. void Desktop::createMouseInputSources()
  221823. {
  221824. mouseSources.add (new MouseInputSource (0, true));
  221825. }
  221826. bool Desktop::canUseSemiTransparentWindows() throw()
  221827. {
  221828. int matchedDepth = 0;
  221829. const int desiredDepth = 32;
  221830. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221831. && (matchedDepth == desiredDepth);
  221832. }
  221833. const Point<int> Desktop::getMousePosition()
  221834. {
  221835. Window root, child;
  221836. int x, y, winx, winy;
  221837. unsigned int mask;
  221838. ScopedXLock xlock;
  221839. if (XQueryPointer (display,
  221840. RootWindow (display, DefaultScreen (display)),
  221841. &root, &child,
  221842. &x, &y, &winx, &winy, &mask) == False)
  221843. {
  221844. // Pointer not on the default screen
  221845. x = y = -1;
  221846. }
  221847. return Point<int> (x, y);
  221848. }
  221849. void Desktop::setMousePosition (const Point<int>& newPosition)
  221850. {
  221851. ScopedXLock xlock;
  221852. Window root = RootWindow (display, DefaultScreen (display));
  221853. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221854. }
  221855. static bool screenSaverAllowed = true;
  221856. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221857. {
  221858. if (screenSaverAllowed != isEnabled)
  221859. {
  221860. screenSaverAllowed = isEnabled;
  221861. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221862. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221863. if (xScreenSaverSuspend == 0)
  221864. {
  221865. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221866. if (h != 0)
  221867. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221868. }
  221869. ScopedXLock xlock;
  221870. if (xScreenSaverSuspend != 0)
  221871. xScreenSaverSuspend (display, ! isEnabled);
  221872. }
  221873. }
  221874. bool Desktop::isScreenSaverEnabled()
  221875. {
  221876. return screenSaverAllowed;
  221877. }
  221878. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221879. {
  221880. ScopedXLock xlock;
  221881. const unsigned int imageW = image.getWidth();
  221882. const unsigned int imageH = image.getHeight();
  221883. #if JUCE_USE_XCURSOR
  221884. {
  221885. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221886. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221887. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221888. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221889. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221890. static tXcursorImageCreate xXcursorImageCreate = 0;
  221891. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221892. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221893. static bool hasBeenLoaded = false;
  221894. if (! hasBeenLoaded)
  221895. {
  221896. hasBeenLoaded = true;
  221897. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221898. if (h != 0)
  221899. {
  221900. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221901. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221902. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221903. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221904. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221905. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221906. || ! xXcursorSupportsARGB (display))
  221907. xXcursorSupportsARGB = 0;
  221908. }
  221909. }
  221910. if (xXcursorSupportsARGB != 0)
  221911. {
  221912. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221913. if (xcImage != 0)
  221914. {
  221915. xcImage->xhot = hotspotX;
  221916. xcImage->yhot = hotspotY;
  221917. XcursorPixel* dest = xcImage->pixels;
  221918. for (int y = 0; y < (int) imageH; ++y)
  221919. for (int x = 0; x < (int) imageW; ++x)
  221920. *dest++ = image.getPixelAt (x, y).getARGB();
  221921. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221922. xXcursorImageDestroy (xcImage);
  221923. if (result != 0)
  221924. return result;
  221925. }
  221926. }
  221927. }
  221928. #endif
  221929. Window root = RootWindow (display, DefaultScreen (display));
  221930. unsigned int cursorW, cursorH;
  221931. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221932. return 0;
  221933. Image im (Image::ARGB, cursorW, cursorH, true);
  221934. {
  221935. Graphics g (im);
  221936. if (imageW > cursorW || imageH > cursorH)
  221937. {
  221938. hotspotX = (hotspotX * cursorW) / imageW;
  221939. hotspotY = (hotspotY * cursorH) / imageH;
  221940. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221941. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221942. false);
  221943. }
  221944. else
  221945. {
  221946. g.drawImageAt (image, 0, 0);
  221947. }
  221948. }
  221949. const int stride = (cursorW + 7) >> 3;
  221950. HeapBlock <char> maskPlane, sourcePlane;
  221951. maskPlane.calloc (stride * cursorH);
  221952. sourcePlane.calloc (stride * cursorH);
  221953. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221954. for (int y = cursorH; --y >= 0;)
  221955. {
  221956. for (int x = cursorW; --x >= 0;)
  221957. {
  221958. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221959. const int offset = y * stride + (x >> 3);
  221960. const Colour c (im.getPixelAt (x, y));
  221961. if (c.getAlpha() >= 128)
  221962. maskPlane[offset] |= mask;
  221963. if (c.getBrightness() >= 0.5f)
  221964. sourcePlane[offset] |= mask;
  221965. }
  221966. }
  221967. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221968. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221969. XColor white, black;
  221970. black.red = black.green = black.blue = 0;
  221971. white.red = white.green = white.blue = 0xffff;
  221972. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221973. XFreePixmap (display, sourcePixmap);
  221974. XFreePixmap (display, maskPixmap);
  221975. return result;
  221976. }
  221977. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221978. {
  221979. ScopedXLock xlock;
  221980. if (cursorHandle != 0)
  221981. XFreeCursor (display, (Cursor) cursorHandle);
  221982. }
  221983. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221984. {
  221985. unsigned int shape;
  221986. switch (type)
  221987. {
  221988. case NormalCursor: return None; // Use parent cursor
  221989. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221990. case WaitCursor: shape = XC_watch; break;
  221991. case IBeamCursor: shape = XC_xterm; break;
  221992. case PointingHandCursor: shape = XC_hand2; break;
  221993. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221994. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221995. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221996. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221997. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221998. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221999. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222000. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222001. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222002. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222003. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222004. case CrosshairCursor: shape = XC_crosshair; break;
  222005. case DraggingHandCursor:
  222006. {
  222007. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222008. 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,
  222009. 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 };
  222010. const int dragHandDataSize = 99;
  222011. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222012. }
  222013. case CopyingCursor:
  222014. {
  222015. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222016. 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,
  222017. 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,
  222018. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222019. const int copyCursorSize = 119;
  222020. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222021. }
  222022. default:
  222023. jassertfalse;
  222024. return None;
  222025. }
  222026. ScopedXLock xlock;
  222027. return (void*) XCreateFontCursor (display, shape);
  222028. }
  222029. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222030. {
  222031. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222032. if (lp != 0)
  222033. lp->showMouseCursor ((Cursor) getHandle());
  222034. }
  222035. void MouseCursor::showInAllWindows() const
  222036. {
  222037. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222038. showInWindow (ComponentPeer::getPeer (i));
  222039. }
  222040. const Image juce_createIconForFile (const File& file)
  222041. {
  222042. return Image::null;
  222043. }
  222044. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222045. {
  222046. return createSoftwareImage (format, width, height, clearImage);
  222047. }
  222048. #if JUCE_OPENGL
  222049. class WindowedGLContext : public OpenGLContext
  222050. {
  222051. public:
  222052. WindowedGLContext (Component* const component,
  222053. const OpenGLPixelFormat& pixelFormat_,
  222054. GLXContext sharedContext)
  222055. : renderContext (0),
  222056. embeddedWindow (0),
  222057. pixelFormat (pixelFormat_),
  222058. swapInterval (0)
  222059. {
  222060. jassert (component != 0);
  222061. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222062. if (peer == 0)
  222063. return;
  222064. ScopedXLock xlock;
  222065. XSync (display, False);
  222066. GLint attribs [64];
  222067. int n = 0;
  222068. attribs[n++] = GLX_RGBA;
  222069. attribs[n++] = GLX_DOUBLEBUFFER;
  222070. attribs[n++] = GLX_RED_SIZE;
  222071. attribs[n++] = pixelFormat.redBits;
  222072. attribs[n++] = GLX_GREEN_SIZE;
  222073. attribs[n++] = pixelFormat.greenBits;
  222074. attribs[n++] = GLX_BLUE_SIZE;
  222075. attribs[n++] = pixelFormat.blueBits;
  222076. attribs[n++] = GLX_ALPHA_SIZE;
  222077. attribs[n++] = pixelFormat.alphaBits;
  222078. attribs[n++] = GLX_DEPTH_SIZE;
  222079. attribs[n++] = pixelFormat.depthBufferBits;
  222080. attribs[n++] = GLX_STENCIL_SIZE;
  222081. attribs[n++] = pixelFormat.stencilBufferBits;
  222082. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222083. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222084. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222085. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222086. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222087. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222088. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222089. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222090. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222091. attribs[n++] = None;
  222092. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222093. if (bestVisual == 0)
  222094. return;
  222095. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222096. Window windowH = (Window) peer->getNativeHandle();
  222097. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222098. XSetWindowAttributes swa;
  222099. swa.colormap = colourMap;
  222100. swa.border_pixel = 0;
  222101. swa.event_mask = ExposureMask | StructureNotifyMask;
  222102. embeddedWindow = XCreateWindow (display, windowH,
  222103. 0, 0, 1, 1, 0,
  222104. bestVisual->depth,
  222105. InputOutput,
  222106. bestVisual->visual,
  222107. CWBorderPixel | CWColormap | CWEventMask,
  222108. &swa);
  222109. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222110. XMapWindow (display, embeddedWindow);
  222111. XFreeColormap (display, colourMap);
  222112. XFree (bestVisual);
  222113. XSync (display, False);
  222114. }
  222115. ~WindowedGLContext()
  222116. {
  222117. ScopedXLock xlock;
  222118. deleteContext();
  222119. XUnmapWindow (display, embeddedWindow);
  222120. XDestroyWindow (display, embeddedWindow);
  222121. }
  222122. void deleteContext()
  222123. {
  222124. makeInactive();
  222125. if (renderContext != 0)
  222126. {
  222127. ScopedXLock xlock;
  222128. glXDestroyContext (display, renderContext);
  222129. renderContext = 0;
  222130. }
  222131. }
  222132. bool makeActive() const throw()
  222133. {
  222134. jassert (renderContext != 0);
  222135. ScopedXLock xlock;
  222136. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222137. && XSync (display, False);
  222138. }
  222139. bool makeInactive() const throw()
  222140. {
  222141. ScopedXLock xlock;
  222142. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222143. }
  222144. bool isActive() const throw()
  222145. {
  222146. ScopedXLock xlock;
  222147. return glXGetCurrentContext() == renderContext;
  222148. }
  222149. const OpenGLPixelFormat getPixelFormat() const
  222150. {
  222151. return pixelFormat;
  222152. }
  222153. void* getRawContext() const throw()
  222154. {
  222155. return renderContext;
  222156. }
  222157. void updateWindowPosition (int x, int y, int w, int h, int)
  222158. {
  222159. ScopedXLock xlock;
  222160. XMoveResizeWindow (display, embeddedWindow,
  222161. x, y, jmax (1, w), jmax (1, h));
  222162. }
  222163. void swapBuffers()
  222164. {
  222165. ScopedXLock xlock;
  222166. glXSwapBuffers (display, embeddedWindow);
  222167. }
  222168. bool setSwapInterval (const int numFramesPerSwap)
  222169. {
  222170. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222171. if (GLXSwapIntervalSGI != 0)
  222172. {
  222173. swapInterval = numFramesPerSwap;
  222174. GLXSwapIntervalSGI (numFramesPerSwap);
  222175. return true;
  222176. }
  222177. return false;
  222178. }
  222179. int getSwapInterval() const
  222180. {
  222181. return swapInterval;
  222182. }
  222183. void repaint()
  222184. {
  222185. }
  222186. juce_UseDebuggingNewOperator
  222187. GLXContext renderContext;
  222188. private:
  222189. Window embeddedWindow;
  222190. OpenGLPixelFormat pixelFormat;
  222191. int swapInterval;
  222192. WindowedGLContext (const WindowedGLContext&);
  222193. WindowedGLContext& operator= (const WindowedGLContext&);
  222194. };
  222195. OpenGLContext* OpenGLComponent::createContext()
  222196. {
  222197. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222198. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222199. return (c->renderContext != 0) ? c.release() : 0;
  222200. }
  222201. void juce_glViewport (const int w, const int h)
  222202. {
  222203. glViewport (0, 0, w, h);
  222204. }
  222205. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222206. OwnedArray <OpenGLPixelFormat>& results)
  222207. {
  222208. results.add (new OpenGLPixelFormat()); // xxx
  222209. }
  222210. #endif
  222211. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222212. {
  222213. jassertfalse; // not implemented!
  222214. return false;
  222215. }
  222216. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222217. {
  222218. jassertfalse; // not implemented!
  222219. return false;
  222220. }
  222221. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222222. {
  222223. if (! isOnDesktop ())
  222224. addToDesktop (0);
  222225. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222226. if (wp != 0)
  222227. {
  222228. wp->setTaskBarIcon (newImage);
  222229. setVisible (true);
  222230. toFront (false);
  222231. repaint();
  222232. }
  222233. }
  222234. void SystemTrayIconComponent::paint (Graphics& g)
  222235. {
  222236. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222237. if (wp != 0)
  222238. {
  222239. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222240. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222241. false);
  222242. }
  222243. }
  222244. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222245. {
  222246. // xxx not yet implemented!
  222247. }
  222248. void PlatformUtilities::beep()
  222249. {
  222250. std::cout << "\a" << std::flush;
  222251. }
  222252. bool AlertWindow::showNativeDialogBox (const String& title,
  222253. const String& bodyText,
  222254. bool isOkCancel)
  222255. {
  222256. // use a non-native one for the time being..
  222257. if (isOkCancel)
  222258. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222259. else
  222260. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222261. return true;
  222262. }
  222263. const int KeyPress::spaceKey = XK_space & 0xff;
  222264. const int KeyPress::returnKey = XK_Return & 0xff;
  222265. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222266. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222267. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222268. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222269. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222270. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222271. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222272. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222273. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222274. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222275. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222276. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222277. const int KeyPress::tabKey = XK_Tab & 0xff;
  222278. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222279. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222280. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222281. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222282. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222283. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222284. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222285. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222286. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222287. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222288. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222289. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222290. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222291. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222292. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222293. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222294. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222295. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222296. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222297. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222298. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222299. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222300. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222301. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222302. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222303. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222304. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222305. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222306. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222307. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222308. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222309. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222310. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222311. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222312. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222313. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222314. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222315. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222316. #endif
  222317. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222318. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222319. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222320. // compiled on its own).
  222321. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222322. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222323. {
  222324. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222325. snd_pcm_hw_params_t* hwParams;
  222326. snd_pcm_hw_params_alloca (&hwParams);
  222327. for (int i = 0; ratesToTry[i] != 0; ++i)
  222328. {
  222329. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222330. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222331. {
  222332. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222333. }
  222334. }
  222335. }
  222336. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222337. {
  222338. snd_pcm_hw_params_t *params;
  222339. snd_pcm_hw_params_alloca (&params);
  222340. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222341. {
  222342. snd_pcm_hw_params_get_channels_min (params, minChans);
  222343. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222344. }
  222345. }
  222346. static void getDeviceProperties (const String& deviceID,
  222347. unsigned int& minChansOut,
  222348. unsigned int& maxChansOut,
  222349. unsigned int& minChansIn,
  222350. unsigned int& maxChansIn,
  222351. Array <int>& rates)
  222352. {
  222353. if (deviceID.isEmpty())
  222354. return;
  222355. snd_ctl_t* handle;
  222356. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222357. {
  222358. snd_pcm_info_t* info;
  222359. snd_pcm_info_alloca (&info);
  222360. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222361. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222362. snd_pcm_info_set_subdevice (info, 0);
  222363. if (snd_ctl_pcm_info (handle, info) >= 0)
  222364. {
  222365. snd_pcm_t* pcmHandle;
  222366. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222367. {
  222368. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222369. getDeviceSampleRates (pcmHandle, rates);
  222370. snd_pcm_close (pcmHandle);
  222371. }
  222372. }
  222373. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222374. if (snd_ctl_pcm_info (handle, info) >= 0)
  222375. {
  222376. snd_pcm_t* pcmHandle;
  222377. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222378. {
  222379. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222380. if (rates.size() == 0)
  222381. getDeviceSampleRates (pcmHandle, rates);
  222382. snd_pcm_close (pcmHandle);
  222383. }
  222384. }
  222385. snd_ctl_close (handle);
  222386. }
  222387. }
  222388. class ALSADevice
  222389. {
  222390. public:
  222391. ALSADevice (const String& deviceID, bool forInput)
  222392. : handle (0),
  222393. bitDepth (16),
  222394. numChannelsRunning (0),
  222395. latency (0),
  222396. isInput (forInput)
  222397. {
  222398. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222399. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222400. SND_PCM_ASYNC));
  222401. }
  222402. ~ALSADevice()
  222403. {
  222404. if (handle != 0)
  222405. snd_pcm_close (handle);
  222406. }
  222407. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222408. {
  222409. if (handle == 0)
  222410. return false;
  222411. snd_pcm_hw_params_t* hwParams;
  222412. snd_pcm_hw_params_alloca (&hwParams);
  222413. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222414. return false;
  222415. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222416. isInterleaved = false;
  222417. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222418. isInterleaved = true;
  222419. else
  222420. {
  222421. jassertfalse;
  222422. return false;
  222423. }
  222424. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222425. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222426. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222427. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222428. SND_PCM_FORMAT_S32_BE, 32,
  222429. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222430. SND_PCM_FORMAT_S24_3BE, 24,
  222431. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222432. SND_PCM_FORMAT_S16_BE, 16 };
  222433. bitDepth = 0;
  222434. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222435. {
  222436. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222437. {
  222438. bitDepth = formatsToTry [i + 1] & 255;
  222439. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222440. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222441. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222442. break;
  222443. }
  222444. }
  222445. if (bitDepth == 0)
  222446. {
  222447. error = "device doesn't support a compatible PCM format";
  222448. DBG ("ALSA error: " + error + "\n");
  222449. return false;
  222450. }
  222451. int dir = 0;
  222452. unsigned int periods = 4;
  222453. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222454. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222455. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222456. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222457. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222458. || failed (snd_pcm_hw_params (handle, hwParams)))
  222459. {
  222460. return false;
  222461. }
  222462. snd_pcm_uframes_t frames = 0;
  222463. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222464. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222465. latency = 0;
  222466. else
  222467. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222468. snd_pcm_sw_params_t* swParams;
  222469. snd_pcm_sw_params_alloca (&swParams);
  222470. snd_pcm_uframes_t boundary;
  222471. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222472. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222473. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222474. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222475. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222476. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222477. || failed (snd_pcm_sw_params (handle, swParams)))
  222478. {
  222479. return false;
  222480. }
  222481. /*
  222482. #if JUCE_DEBUG
  222483. // enable this to dump the config of the devices that get opened
  222484. snd_output_t* out;
  222485. snd_output_stdio_attach (&out, stderr, 0);
  222486. snd_pcm_hw_params_dump (hwParams, out);
  222487. snd_pcm_sw_params_dump (swParams, out);
  222488. #endif
  222489. */
  222490. numChannelsRunning = numChannels;
  222491. return true;
  222492. }
  222493. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222494. {
  222495. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222496. float** const data = outputChannelBuffer.getArrayOfChannels();
  222497. snd_pcm_sframes_t numDone = 0;
  222498. if (isInterleaved)
  222499. {
  222500. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222501. for (int i = 0; i < numChannelsRunning; ++i)
  222502. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222503. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222504. }
  222505. else
  222506. {
  222507. for (int i = 0; i < numChannelsRunning; ++i)
  222508. converter->convertSamples (data[i], data[i], numSamples);
  222509. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222510. }
  222511. if (failed (numDone))
  222512. {
  222513. if (numDone == -EPIPE)
  222514. {
  222515. if (failed (snd_pcm_prepare (handle)))
  222516. return false;
  222517. }
  222518. else if (numDone != -ESTRPIPE)
  222519. return false;
  222520. }
  222521. return true;
  222522. }
  222523. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222524. {
  222525. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222526. float** const data = inputChannelBuffer.getArrayOfChannels();
  222527. if (isInterleaved)
  222528. {
  222529. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222530. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222531. if (failed (num))
  222532. {
  222533. if (num == -EPIPE)
  222534. {
  222535. if (failed (snd_pcm_prepare (handle)))
  222536. return false;
  222537. }
  222538. else if (num != -ESTRPIPE)
  222539. return false;
  222540. }
  222541. for (int i = 0; i < numChannelsRunning; ++i)
  222542. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222543. }
  222544. else
  222545. {
  222546. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222547. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222548. return false;
  222549. for (int i = 0; i < numChannelsRunning; ++i)
  222550. converter->convertSamples (data[i], data[i], numSamples);
  222551. }
  222552. return true;
  222553. }
  222554. juce_UseDebuggingNewOperator
  222555. snd_pcm_t* handle;
  222556. String error;
  222557. int bitDepth, numChannelsRunning, latency;
  222558. private:
  222559. const bool isInput;
  222560. bool isInterleaved;
  222561. MemoryBlock scratch;
  222562. ScopedPointer<AudioData::Converter> converter;
  222563. template <class SampleType>
  222564. struct ConverterHelper
  222565. {
  222566. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222567. {
  222568. if (forInput)
  222569. {
  222570. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222571. if (isLittleEndian)
  222572. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222573. else
  222574. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222575. }
  222576. else
  222577. {
  222578. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222579. if (isLittleEndian)
  222580. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222581. else
  222582. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222583. }
  222584. }
  222585. };
  222586. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222587. {
  222588. switch (bitDepth)
  222589. {
  222590. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222591. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222592. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222593. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222594. default: jassertfalse; break; // unsupported format!
  222595. }
  222596. return 0;
  222597. }
  222598. bool failed (const int errorNum)
  222599. {
  222600. if (errorNum >= 0)
  222601. return false;
  222602. error = snd_strerror (errorNum);
  222603. DBG ("ALSA error: " + error + "\n");
  222604. return true;
  222605. }
  222606. };
  222607. class ALSAThread : public Thread
  222608. {
  222609. public:
  222610. ALSAThread (const String& inputId_,
  222611. const String& outputId_)
  222612. : Thread ("Juce ALSA"),
  222613. sampleRate (0),
  222614. bufferSize (0),
  222615. outputLatency (0),
  222616. inputLatency (0),
  222617. callback (0),
  222618. inputId (inputId_),
  222619. outputId (outputId_),
  222620. numCallbacks (0),
  222621. inputChannelBuffer (1, 1),
  222622. outputChannelBuffer (1, 1)
  222623. {
  222624. initialiseRatesAndChannels();
  222625. }
  222626. ~ALSAThread()
  222627. {
  222628. close();
  222629. }
  222630. void open (BigInteger inputChannels,
  222631. BigInteger outputChannels,
  222632. const double sampleRate_,
  222633. const int bufferSize_)
  222634. {
  222635. close();
  222636. error = String::empty;
  222637. sampleRate = sampleRate_;
  222638. bufferSize = bufferSize_;
  222639. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222640. inputChannelBuffer.clear();
  222641. inputChannelDataForCallback.clear();
  222642. currentInputChans.clear();
  222643. if (inputChannels.getHighestBit() >= 0)
  222644. {
  222645. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222646. {
  222647. if (inputChannels[i])
  222648. {
  222649. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222650. currentInputChans.setBit (i);
  222651. }
  222652. }
  222653. }
  222654. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222655. outputChannelBuffer.clear();
  222656. outputChannelDataForCallback.clear();
  222657. currentOutputChans.clear();
  222658. if (outputChannels.getHighestBit() >= 0)
  222659. {
  222660. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222661. {
  222662. if (outputChannels[i])
  222663. {
  222664. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222665. currentOutputChans.setBit (i);
  222666. }
  222667. }
  222668. }
  222669. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222670. {
  222671. outputDevice = new ALSADevice (outputId, false);
  222672. if (outputDevice->error.isNotEmpty())
  222673. {
  222674. error = outputDevice->error;
  222675. outputDevice = 0;
  222676. return;
  222677. }
  222678. currentOutputChans.setRange (0, minChansOut, true);
  222679. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222680. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222681. bufferSize))
  222682. {
  222683. error = outputDevice->error;
  222684. outputDevice = 0;
  222685. return;
  222686. }
  222687. outputLatency = outputDevice->latency;
  222688. }
  222689. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222690. {
  222691. inputDevice = new ALSADevice (inputId, true);
  222692. if (inputDevice->error.isNotEmpty())
  222693. {
  222694. error = inputDevice->error;
  222695. inputDevice = 0;
  222696. return;
  222697. }
  222698. currentInputChans.setRange (0, minChansIn, true);
  222699. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222700. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222701. bufferSize))
  222702. {
  222703. error = inputDevice->error;
  222704. inputDevice = 0;
  222705. return;
  222706. }
  222707. inputLatency = inputDevice->latency;
  222708. }
  222709. if (outputDevice == 0 && inputDevice == 0)
  222710. {
  222711. error = "no channels";
  222712. return;
  222713. }
  222714. if (outputDevice != 0 && inputDevice != 0)
  222715. {
  222716. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222717. }
  222718. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222719. return;
  222720. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222721. return;
  222722. startThread (9);
  222723. int count = 1000;
  222724. while (numCallbacks == 0)
  222725. {
  222726. sleep (5);
  222727. if (--count < 0 || ! isThreadRunning())
  222728. {
  222729. error = "device didn't start";
  222730. break;
  222731. }
  222732. }
  222733. }
  222734. void close()
  222735. {
  222736. stopThread (6000);
  222737. inputDevice = 0;
  222738. outputDevice = 0;
  222739. inputChannelBuffer.setSize (1, 1);
  222740. outputChannelBuffer.setSize (1, 1);
  222741. numCallbacks = 0;
  222742. }
  222743. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222744. {
  222745. const ScopedLock sl (callbackLock);
  222746. callback = newCallback;
  222747. }
  222748. void run()
  222749. {
  222750. while (! threadShouldExit())
  222751. {
  222752. if (inputDevice != 0)
  222753. {
  222754. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222755. {
  222756. DBG ("ALSA: read failure");
  222757. break;
  222758. }
  222759. }
  222760. if (threadShouldExit())
  222761. break;
  222762. {
  222763. const ScopedLock sl (callbackLock);
  222764. ++numCallbacks;
  222765. if (callback != 0)
  222766. {
  222767. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222768. inputChannelDataForCallback.size(),
  222769. outputChannelDataForCallback.getRawDataPointer(),
  222770. outputChannelDataForCallback.size(),
  222771. bufferSize);
  222772. }
  222773. else
  222774. {
  222775. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222776. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222777. }
  222778. }
  222779. if (outputDevice != 0)
  222780. {
  222781. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222782. if (threadShouldExit())
  222783. break;
  222784. failed (snd_pcm_avail_update (outputDevice->handle));
  222785. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222786. {
  222787. DBG ("ALSA: write failure");
  222788. break;
  222789. }
  222790. }
  222791. }
  222792. }
  222793. int getBitDepth() const throw()
  222794. {
  222795. if (outputDevice != 0)
  222796. return outputDevice->bitDepth;
  222797. if (inputDevice != 0)
  222798. return inputDevice->bitDepth;
  222799. return 16;
  222800. }
  222801. juce_UseDebuggingNewOperator
  222802. String error;
  222803. double sampleRate;
  222804. int bufferSize, outputLatency, inputLatency;
  222805. BigInteger currentInputChans, currentOutputChans;
  222806. Array <int> sampleRates;
  222807. StringArray channelNamesOut, channelNamesIn;
  222808. AudioIODeviceCallback* callback;
  222809. private:
  222810. const String inputId, outputId;
  222811. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222812. int numCallbacks;
  222813. CriticalSection callbackLock;
  222814. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222815. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222816. unsigned int minChansOut, maxChansOut;
  222817. unsigned int minChansIn, maxChansIn;
  222818. bool failed (const int errorNum)
  222819. {
  222820. if (errorNum >= 0)
  222821. return false;
  222822. error = snd_strerror (errorNum);
  222823. DBG ("ALSA error: " + error + "\n");
  222824. return true;
  222825. }
  222826. void initialiseRatesAndChannels()
  222827. {
  222828. sampleRates.clear();
  222829. channelNamesOut.clear();
  222830. channelNamesIn.clear();
  222831. minChansOut = 0;
  222832. maxChansOut = 0;
  222833. minChansIn = 0;
  222834. maxChansIn = 0;
  222835. unsigned int dummy = 0;
  222836. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222837. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222838. unsigned int i;
  222839. for (i = 0; i < maxChansOut; ++i)
  222840. channelNamesOut.add ("channel " + String ((int) i + 1));
  222841. for (i = 0; i < maxChansIn; ++i)
  222842. channelNamesIn.add ("channel " + String ((int) i + 1));
  222843. }
  222844. };
  222845. class ALSAAudioIODevice : public AudioIODevice
  222846. {
  222847. public:
  222848. ALSAAudioIODevice (const String& deviceName,
  222849. const String& inputId_,
  222850. const String& outputId_)
  222851. : AudioIODevice (deviceName, "ALSA"),
  222852. inputId (inputId_),
  222853. outputId (outputId_),
  222854. isOpen_ (false),
  222855. isStarted (false),
  222856. internal (inputId_, outputId_)
  222857. {
  222858. }
  222859. ~ALSAAudioIODevice()
  222860. {
  222861. }
  222862. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222863. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222864. int getNumSampleRates() { return internal.sampleRates.size(); }
  222865. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222866. int getDefaultBufferSize() { return 512; }
  222867. int getNumBufferSizesAvailable() { return 50; }
  222868. int getBufferSizeSamples (int index)
  222869. {
  222870. int n = 16;
  222871. for (int i = 0; i < index; ++i)
  222872. n += n < 64 ? 16
  222873. : (n < 512 ? 32
  222874. : (n < 1024 ? 64
  222875. : (n < 2048 ? 128 : 256)));
  222876. return n;
  222877. }
  222878. const String open (const BigInteger& inputChannels,
  222879. const BigInteger& outputChannels,
  222880. double sampleRate,
  222881. int bufferSizeSamples)
  222882. {
  222883. close();
  222884. if (bufferSizeSamples <= 0)
  222885. bufferSizeSamples = getDefaultBufferSize();
  222886. if (sampleRate <= 0)
  222887. {
  222888. for (int i = 0; i < getNumSampleRates(); ++i)
  222889. {
  222890. if (getSampleRate (i) >= 44100)
  222891. {
  222892. sampleRate = getSampleRate (i);
  222893. break;
  222894. }
  222895. }
  222896. }
  222897. internal.open (inputChannels, outputChannels,
  222898. sampleRate, bufferSizeSamples);
  222899. isOpen_ = internal.error.isEmpty();
  222900. return internal.error;
  222901. }
  222902. void close()
  222903. {
  222904. stop();
  222905. internal.close();
  222906. isOpen_ = false;
  222907. }
  222908. bool isOpen() { return isOpen_; }
  222909. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222910. const String getLastError() { return internal.error; }
  222911. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222912. double getCurrentSampleRate() { return internal.sampleRate; }
  222913. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222914. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222915. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222916. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222917. int getInputLatencyInSamples() { return internal.inputLatency; }
  222918. void start (AudioIODeviceCallback* callback)
  222919. {
  222920. if (! isOpen_)
  222921. callback = 0;
  222922. if (callback != 0)
  222923. callback->audioDeviceAboutToStart (this);
  222924. internal.setCallback (callback);
  222925. isStarted = (callback != 0);
  222926. }
  222927. void stop()
  222928. {
  222929. AudioIODeviceCallback* const oldCallback = internal.callback;
  222930. start (0);
  222931. if (oldCallback != 0)
  222932. oldCallback->audioDeviceStopped();
  222933. }
  222934. String inputId, outputId;
  222935. private:
  222936. bool isOpen_, isStarted;
  222937. ALSAThread internal;
  222938. };
  222939. class ALSAAudioIODeviceType : public AudioIODeviceType
  222940. {
  222941. public:
  222942. ALSAAudioIODeviceType()
  222943. : AudioIODeviceType ("ALSA"),
  222944. hasScanned (false)
  222945. {
  222946. }
  222947. ~ALSAAudioIODeviceType()
  222948. {
  222949. }
  222950. void scanForDevices()
  222951. {
  222952. if (hasScanned)
  222953. return;
  222954. hasScanned = true;
  222955. inputNames.clear();
  222956. inputIds.clear();
  222957. outputNames.clear();
  222958. outputIds.clear();
  222959. /* void** hints = 0;
  222960. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222961. {
  222962. for (void** hint = hints; *hint != 0; ++hint)
  222963. {
  222964. const String name (getHint (*hint, "NAME"));
  222965. if (name.isNotEmpty())
  222966. {
  222967. const String ioid (getHint (*hint, "IOID"));
  222968. String desc (getHint (*hint, "DESC"));
  222969. if (desc.isEmpty())
  222970. desc = name;
  222971. desc = desc.replaceCharacters ("\n\r", " ");
  222972. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222973. if (ioid.isEmpty() || ioid == "Input")
  222974. {
  222975. inputNames.add (desc);
  222976. inputIds.add (name);
  222977. }
  222978. if (ioid.isEmpty() || ioid == "Output")
  222979. {
  222980. outputNames.add (desc);
  222981. outputIds.add (name);
  222982. }
  222983. }
  222984. }
  222985. snd_device_name_free_hint (hints);
  222986. }
  222987. */
  222988. snd_ctl_t* handle = 0;
  222989. snd_ctl_card_info_t* info = 0;
  222990. snd_ctl_card_info_alloca (&info);
  222991. int cardNum = -1;
  222992. while (outputIds.size() + inputIds.size() <= 32)
  222993. {
  222994. snd_card_next (&cardNum);
  222995. if (cardNum < 0)
  222996. break;
  222997. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222998. {
  222999. if (snd_ctl_card_info (handle, info) >= 0)
  223000. {
  223001. String cardId (snd_ctl_card_info_get_id (info));
  223002. if (cardId.removeCharacters ("0123456789").isEmpty())
  223003. cardId = String (cardNum);
  223004. int device = -1;
  223005. for (;;)
  223006. {
  223007. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223008. break;
  223009. String id, name;
  223010. id << "hw:" << cardId << ',' << device;
  223011. bool isInput, isOutput;
  223012. if (testDevice (id, isInput, isOutput))
  223013. {
  223014. name << snd_ctl_card_info_get_name (info);
  223015. if (name.isEmpty())
  223016. name = id;
  223017. if (isInput)
  223018. {
  223019. inputNames.add (name);
  223020. inputIds.add (id);
  223021. }
  223022. if (isOutput)
  223023. {
  223024. outputNames.add (name);
  223025. outputIds.add (id);
  223026. }
  223027. }
  223028. }
  223029. }
  223030. snd_ctl_close (handle);
  223031. }
  223032. }
  223033. inputNames.appendNumbersToDuplicates (false, true);
  223034. outputNames.appendNumbersToDuplicates (false, true);
  223035. }
  223036. const StringArray getDeviceNames (bool wantInputNames) const
  223037. {
  223038. jassert (hasScanned); // need to call scanForDevices() before doing this
  223039. return wantInputNames ? inputNames : outputNames;
  223040. }
  223041. int getDefaultDeviceIndex (bool forInput) const
  223042. {
  223043. jassert (hasScanned); // need to call scanForDevices() before doing this
  223044. return 0;
  223045. }
  223046. bool hasSeparateInputsAndOutputs() const { return true; }
  223047. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223048. {
  223049. jassert (hasScanned); // need to call scanForDevices() before doing this
  223050. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223051. if (d == 0)
  223052. return -1;
  223053. return asInput ? inputIds.indexOf (d->inputId)
  223054. : outputIds.indexOf (d->outputId);
  223055. }
  223056. AudioIODevice* createDevice (const String& outputDeviceName,
  223057. const String& inputDeviceName)
  223058. {
  223059. jassert (hasScanned); // need to call scanForDevices() before doing this
  223060. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223061. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223062. String deviceName (outputIndex >= 0 ? outputDeviceName
  223063. : inputDeviceName);
  223064. if (inputIndex >= 0 || outputIndex >= 0)
  223065. return new ALSAAudioIODevice (deviceName,
  223066. inputIds [inputIndex],
  223067. outputIds [outputIndex]);
  223068. return 0;
  223069. }
  223070. juce_UseDebuggingNewOperator
  223071. private:
  223072. StringArray inputNames, outputNames, inputIds, outputIds;
  223073. bool hasScanned;
  223074. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223075. {
  223076. unsigned int minChansOut = 0, maxChansOut = 0;
  223077. unsigned int minChansIn = 0, maxChansIn = 0;
  223078. Array <int> rates;
  223079. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223080. DBG ("ALSA device: " + id
  223081. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223082. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223083. + " rates=" + String (rates.size()));
  223084. isInput = maxChansIn > 0;
  223085. isOutput = maxChansOut > 0;
  223086. return (isInput || isOutput) && rates.size() > 0;
  223087. }
  223088. /*static const String getHint (void* hint, const char* type)
  223089. {
  223090. char* const n = snd_device_name_get_hint (hint, type);
  223091. const String s ((const char*) n);
  223092. free (n);
  223093. return s;
  223094. }*/
  223095. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223096. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223097. };
  223098. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223099. {
  223100. return new ALSAAudioIODeviceType();
  223101. }
  223102. #endif
  223103. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223104. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223105. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223106. // compiled on its own).
  223107. #ifdef JUCE_INCLUDED_FILE
  223108. #if JUCE_JACK
  223109. static void* juce_libjack_handle = 0;
  223110. void* juce_load_jack_function (const char* const name)
  223111. {
  223112. if (juce_libjack_handle == 0)
  223113. return 0;
  223114. return dlsym (juce_libjack_handle, name);
  223115. }
  223116. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223117. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223118. return_type fn_name argument_types { \
  223119. static fn_name##_ptr_t fn = 0; \
  223120. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223121. if (fn) return (*fn)arguments; \
  223122. else return 0; \
  223123. }
  223124. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223125. typedef void (*fn_name##_ptr_t)argument_types; \
  223126. void fn_name argument_types { \
  223127. static fn_name##_ptr_t fn = 0; \
  223128. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223129. if (fn) (*fn)arguments; \
  223130. }
  223131. 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));
  223132. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223133. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223134. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223135. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223136. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223137. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223138. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223139. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223140. 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));
  223141. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223142. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223143. 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));
  223144. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223145. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223146. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223147. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223148. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223149. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223150. #if JUCE_DEBUG
  223151. #define JACK_LOGGING_ENABLED 1
  223152. #endif
  223153. #if JACK_LOGGING_ENABLED
  223154. static void jack_Log (const String& s)
  223155. {
  223156. std::cerr << s << std::endl;
  223157. }
  223158. static void dumpJackErrorMessage (const jack_status_t status)
  223159. {
  223160. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223161. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223162. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223163. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223164. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223165. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223166. }
  223167. #else
  223168. #define dumpJackErrorMessage(a) {}
  223169. #define jack_Log(...) {}
  223170. #endif
  223171. #ifndef JUCE_JACK_CLIENT_NAME
  223172. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223173. #endif
  223174. class JackAudioIODevice : public AudioIODevice
  223175. {
  223176. public:
  223177. JackAudioIODevice (const String& deviceName,
  223178. const String& inputId_,
  223179. const String& outputId_)
  223180. : AudioIODevice (deviceName, "JACK"),
  223181. inputId (inputId_),
  223182. outputId (outputId_),
  223183. isOpen_ (false),
  223184. callback (0),
  223185. totalNumberOfInputChannels (0),
  223186. totalNumberOfOutputChannels (0)
  223187. {
  223188. jassert (deviceName.isNotEmpty());
  223189. jack_status_t status;
  223190. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223191. if (client == 0)
  223192. {
  223193. dumpJackErrorMessage (status);
  223194. }
  223195. else
  223196. {
  223197. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223198. // open input ports
  223199. const StringArray inputChannels (getInputChannelNames());
  223200. for (int i = 0; i < inputChannels.size(); i++)
  223201. {
  223202. String inputName;
  223203. inputName << "in_" << ++totalNumberOfInputChannels;
  223204. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223205. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223206. }
  223207. // open output ports
  223208. const StringArray outputChannels (getOutputChannelNames());
  223209. for (int i = 0; i < outputChannels.size (); i++)
  223210. {
  223211. String outputName;
  223212. outputName << "out_" << ++totalNumberOfOutputChannels;
  223213. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223214. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223215. }
  223216. inChans.calloc (totalNumberOfInputChannels + 2);
  223217. outChans.calloc (totalNumberOfOutputChannels + 2);
  223218. }
  223219. }
  223220. ~JackAudioIODevice()
  223221. {
  223222. close();
  223223. if (client != 0)
  223224. {
  223225. JUCE_NAMESPACE::jack_client_close (client);
  223226. client = 0;
  223227. }
  223228. }
  223229. const StringArray getChannelNames (bool forInput) const
  223230. {
  223231. StringArray names;
  223232. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223233. forInput ? JackPortIsInput : JackPortIsOutput);
  223234. if (ports != 0)
  223235. {
  223236. int j = 0;
  223237. while (ports[j] != 0)
  223238. {
  223239. const String portName (ports [j++]);
  223240. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223241. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223242. }
  223243. free (ports);
  223244. }
  223245. return names;
  223246. }
  223247. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223248. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223249. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223250. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223251. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223252. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223253. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223254. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223255. double sampleRate, int bufferSizeSamples)
  223256. {
  223257. if (client == 0)
  223258. {
  223259. lastError = "No JACK client running";
  223260. return lastError;
  223261. }
  223262. lastError = String::empty;
  223263. close();
  223264. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223265. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223266. JUCE_NAMESPACE::jack_activate (client);
  223267. isOpen_ = true;
  223268. if (! inputChannels.isZero())
  223269. {
  223270. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223271. if (ports != 0)
  223272. {
  223273. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223274. for (int i = 0; i < numInputChannels; ++i)
  223275. {
  223276. const String portName (ports[i]);
  223277. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223278. {
  223279. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223280. if (error != 0)
  223281. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223282. }
  223283. }
  223284. free (ports);
  223285. }
  223286. }
  223287. if (! outputChannels.isZero())
  223288. {
  223289. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223290. if (ports != 0)
  223291. {
  223292. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223293. for (int i = 0; i < numOutputChannels; ++i)
  223294. {
  223295. const String portName (ports[i]);
  223296. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223297. {
  223298. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223299. if (error != 0)
  223300. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223301. }
  223302. }
  223303. free (ports);
  223304. }
  223305. }
  223306. return lastError;
  223307. }
  223308. void close()
  223309. {
  223310. stop();
  223311. if (client != 0)
  223312. {
  223313. JUCE_NAMESPACE::jack_deactivate (client);
  223314. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223315. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223316. }
  223317. isOpen_ = false;
  223318. }
  223319. void start (AudioIODeviceCallback* newCallback)
  223320. {
  223321. if (isOpen_ && newCallback != callback)
  223322. {
  223323. if (newCallback != 0)
  223324. newCallback->audioDeviceAboutToStart (this);
  223325. AudioIODeviceCallback* const oldCallback = callback;
  223326. {
  223327. const ScopedLock sl (callbackLock);
  223328. callback = newCallback;
  223329. }
  223330. if (oldCallback != 0)
  223331. oldCallback->audioDeviceStopped();
  223332. }
  223333. }
  223334. void stop()
  223335. {
  223336. start (0);
  223337. }
  223338. bool isOpen() { return isOpen_; }
  223339. bool isPlaying() { return callback != 0; }
  223340. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223341. double getCurrentSampleRate() { return getSampleRate (0); }
  223342. int getCurrentBitDepth() { return 32; }
  223343. const String getLastError() { return lastError; }
  223344. const BigInteger getActiveOutputChannels() const
  223345. {
  223346. BigInteger outputBits;
  223347. for (int i = 0; i < outputPorts.size(); i++)
  223348. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223349. outputBits.setBit (i);
  223350. return outputBits;
  223351. }
  223352. const BigInteger getActiveInputChannels() const
  223353. {
  223354. BigInteger inputBits;
  223355. for (int i = 0; i < inputPorts.size(); i++)
  223356. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223357. inputBits.setBit (i);
  223358. return inputBits;
  223359. }
  223360. int getOutputLatencyInSamples()
  223361. {
  223362. int latency = 0;
  223363. for (int i = 0; i < outputPorts.size(); i++)
  223364. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223365. return latency;
  223366. }
  223367. int getInputLatencyInSamples()
  223368. {
  223369. int latency = 0;
  223370. for (int i = 0; i < inputPorts.size(); i++)
  223371. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223372. return latency;
  223373. }
  223374. String inputId, outputId;
  223375. private:
  223376. void process (const int numSamples)
  223377. {
  223378. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223379. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223380. {
  223381. jack_default_audio_sample_t* in
  223382. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223383. if (in != 0)
  223384. inChans [numActiveInChans++] = (float*) in;
  223385. }
  223386. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223387. {
  223388. jack_default_audio_sample_t* out
  223389. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223390. if (out != 0)
  223391. outChans [numActiveOutChans++] = (float*) out;
  223392. }
  223393. const ScopedLock sl (callbackLock);
  223394. if (callback != 0)
  223395. {
  223396. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223397. outChans, numActiveOutChans, numSamples);
  223398. }
  223399. else
  223400. {
  223401. for (i = 0; i < numActiveOutChans; ++i)
  223402. zeromem (outChans[i], sizeof (float) * numSamples);
  223403. }
  223404. }
  223405. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223406. {
  223407. if (callbackArgument != 0)
  223408. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223409. return 0;
  223410. }
  223411. static void threadInitCallback (void* callbackArgument)
  223412. {
  223413. jack_Log ("JackAudioIODevice::initialise");
  223414. }
  223415. static void shutdownCallback (void* callbackArgument)
  223416. {
  223417. jack_Log ("JackAudioIODevice::shutdown");
  223418. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223419. if (device != 0)
  223420. {
  223421. device->client = 0;
  223422. device->close();
  223423. }
  223424. }
  223425. static void errorCallback (const char* msg)
  223426. {
  223427. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223428. }
  223429. bool isOpen_;
  223430. jack_client_t* client;
  223431. String lastError;
  223432. AudioIODeviceCallback* callback;
  223433. CriticalSection callbackLock;
  223434. HeapBlock <float*> inChans, outChans;
  223435. int totalNumberOfInputChannels;
  223436. int totalNumberOfOutputChannels;
  223437. Array<void*> inputPorts, outputPorts;
  223438. };
  223439. class JackAudioIODeviceType : public AudioIODeviceType
  223440. {
  223441. public:
  223442. JackAudioIODeviceType()
  223443. : AudioIODeviceType ("JACK"),
  223444. hasScanned (false)
  223445. {
  223446. }
  223447. ~JackAudioIODeviceType()
  223448. {
  223449. }
  223450. void scanForDevices()
  223451. {
  223452. hasScanned = true;
  223453. inputNames.clear();
  223454. inputIds.clear();
  223455. outputNames.clear();
  223456. outputIds.clear();
  223457. if (juce_libjack_handle == 0)
  223458. {
  223459. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223460. if (juce_libjack_handle == 0)
  223461. return;
  223462. }
  223463. // open a dummy client
  223464. jack_status_t status;
  223465. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223466. if (client == 0)
  223467. {
  223468. dumpJackErrorMessage (status);
  223469. }
  223470. else
  223471. {
  223472. // scan for output devices
  223473. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223474. if (ports != 0)
  223475. {
  223476. int j = 0;
  223477. while (ports[j] != 0)
  223478. {
  223479. String clientName (ports[j]);
  223480. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223481. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223482. && ! inputNames.contains (clientName))
  223483. {
  223484. inputNames.add (clientName);
  223485. inputIds.add (ports [j]);
  223486. }
  223487. ++j;
  223488. }
  223489. free (ports);
  223490. }
  223491. // scan for input devices
  223492. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  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. && ! outputNames.contains (clientName))
  223502. {
  223503. outputNames.add (clientName);
  223504. outputIds.add (ports [j]);
  223505. }
  223506. ++j;
  223507. }
  223508. free (ports);
  223509. }
  223510. JUCE_NAMESPACE::jack_client_close (client);
  223511. }
  223512. }
  223513. const StringArray getDeviceNames (bool wantInputNames) const
  223514. {
  223515. jassert (hasScanned); // need to call scanForDevices() before doing this
  223516. return wantInputNames ? inputNames : outputNames;
  223517. }
  223518. int getDefaultDeviceIndex (bool forInput) const
  223519. {
  223520. jassert (hasScanned); // need to call scanForDevices() before doing this
  223521. return 0;
  223522. }
  223523. bool hasSeparateInputsAndOutputs() const { return true; }
  223524. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223525. {
  223526. jassert (hasScanned); // need to call scanForDevices() before doing this
  223527. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223528. if (d == 0)
  223529. return -1;
  223530. return asInput ? inputIds.indexOf (d->inputId)
  223531. : outputIds.indexOf (d->outputId);
  223532. }
  223533. AudioIODevice* createDevice (const String& outputDeviceName,
  223534. const String& inputDeviceName)
  223535. {
  223536. jassert (hasScanned); // need to call scanForDevices() before doing this
  223537. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223538. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223539. if (inputIndex >= 0 || outputIndex >= 0)
  223540. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223541. : inputDeviceName,
  223542. inputIds [inputIndex],
  223543. outputIds [outputIndex]);
  223544. return 0;
  223545. }
  223546. juce_UseDebuggingNewOperator
  223547. private:
  223548. StringArray inputNames, outputNames, inputIds, outputIds;
  223549. bool hasScanned;
  223550. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223551. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223552. };
  223553. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223554. {
  223555. return new JackAudioIODeviceType();
  223556. }
  223557. #else // if JACK is turned off..
  223558. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223559. #endif
  223560. #endif
  223561. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223562. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223563. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223564. // compiled on its own).
  223565. #if JUCE_INCLUDED_FILE
  223566. #if JUCE_ALSA
  223567. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223568. StringArray& deviceNamesFound,
  223569. const int deviceIndexToOpen)
  223570. {
  223571. snd_seq_t* returnedHandle = 0;
  223572. snd_seq_t* seqHandle;
  223573. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223574. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223575. {
  223576. snd_seq_system_info_t* systemInfo;
  223577. snd_seq_client_info_t* clientInfo;
  223578. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223579. {
  223580. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223581. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223582. {
  223583. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223584. while (--numClients >= 0 && returnedHandle == 0)
  223585. {
  223586. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223587. {
  223588. snd_seq_port_info_t* portInfo;
  223589. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223590. {
  223591. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223592. const int client = snd_seq_client_info_get_client (clientInfo);
  223593. snd_seq_port_info_set_client (portInfo, client);
  223594. snd_seq_port_info_set_port (portInfo, -1);
  223595. while (--numPorts >= 0)
  223596. {
  223597. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223598. && (snd_seq_port_info_get_capability (portInfo)
  223599. & (forInput ? SND_SEQ_PORT_CAP_READ
  223600. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223601. {
  223602. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223603. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223604. {
  223605. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223606. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223607. if (sourcePort != -1)
  223608. {
  223609. snd_seq_set_client_name (seqHandle,
  223610. forInput ? "Juce Midi Input"
  223611. : "Juce Midi Output");
  223612. const int portId
  223613. = snd_seq_create_simple_port (seqHandle,
  223614. forInput ? "Juce Midi In Port"
  223615. : "Juce Midi Out Port",
  223616. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223617. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223618. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223619. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223620. returnedHandle = seqHandle;
  223621. }
  223622. }
  223623. }
  223624. }
  223625. snd_seq_port_info_free (portInfo);
  223626. }
  223627. }
  223628. }
  223629. snd_seq_client_info_free (clientInfo);
  223630. }
  223631. snd_seq_system_info_free (systemInfo);
  223632. }
  223633. if (returnedHandle == 0)
  223634. snd_seq_close (seqHandle);
  223635. }
  223636. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223637. return returnedHandle;
  223638. }
  223639. static snd_seq_t* createMidiDevice (const bool forInput,
  223640. const String& deviceNameToOpen)
  223641. {
  223642. snd_seq_t* seqHandle = 0;
  223643. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223644. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223645. {
  223646. snd_seq_set_client_name (seqHandle,
  223647. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223648. const int portId
  223649. = snd_seq_create_simple_port (seqHandle,
  223650. forInput ? "in"
  223651. : "out",
  223652. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223653. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223654. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223655. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223656. if (portId < 0)
  223657. {
  223658. snd_seq_close (seqHandle);
  223659. seqHandle = 0;
  223660. }
  223661. }
  223662. return seqHandle;
  223663. }
  223664. class MidiOutputDevice
  223665. {
  223666. public:
  223667. MidiOutputDevice (MidiOutput* const midiOutput_,
  223668. snd_seq_t* const seqHandle_)
  223669. :
  223670. midiOutput (midiOutput_),
  223671. seqHandle (seqHandle_),
  223672. maxEventSize (16 * 1024)
  223673. {
  223674. jassert (seqHandle != 0 && midiOutput != 0);
  223675. snd_midi_event_new (maxEventSize, &midiParser);
  223676. }
  223677. ~MidiOutputDevice()
  223678. {
  223679. snd_midi_event_free (midiParser);
  223680. snd_seq_close (seqHandle);
  223681. }
  223682. void sendMessageNow (const MidiMessage& message)
  223683. {
  223684. if (message.getRawDataSize() > maxEventSize)
  223685. {
  223686. maxEventSize = message.getRawDataSize();
  223687. snd_midi_event_free (midiParser);
  223688. snd_midi_event_new (maxEventSize, &midiParser);
  223689. }
  223690. snd_seq_event_t event;
  223691. snd_seq_ev_clear (&event);
  223692. snd_midi_event_encode (midiParser,
  223693. message.getRawData(),
  223694. message.getRawDataSize(),
  223695. &event);
  223696. snd_midi_event_reset_encode (midiParser);
  223697. snd_seq_ev_set_source (&event, 0);
  223698. snd_seq_ev_set_subs (&event);
  223699. snd_seq_ev_set_direct (&event);
  223700. snd_seq_event_output (seqHandle, &event);
  223701. snd_seq_drain_output (seqHandle);
  223702. }
  223703. juce_UseDebuggingNewOperator
  223704. private:
  223705. MidiOutput* const midiOutput;
  223706. snd_seq_t* const seqHandle;
  223707. snd_midi_event_t* midiParser;
  223708. int maxEventSize;
  223709. };
  223710. const StringArray MidiOutput::getDevices()
  223711. {
  223712. StringArray devices;
  223713. iterateMidiDevices (false, devices, -1);
  223714. return devices;
  223715. }
  223716. int MidiOutput::getDefaultDeviceIndex()
  223717. {
  223718. return 0;
  223719. }
  223720. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223721. {
  223722. MidiOutput* newDevice = 0;
  223723. StringArray devices;
  223724. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223725. if (handle != 0)
  223726. {
  223727. newDevice = new MidiOutput();
  223728. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223729. }
  223730. return newDevice;
  223731. }
  223732. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223733. {
  223734. MidiOutput* newDevice = 0;
  223735. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223736. if (handle != 0)
  223737. {
  223738. newDevice = new MidiOutput();
  223739. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223740. }
  223741. return newDevice;
  223742. }
  223743. MidiOutput::~MidiOutput()
  223744. {
  223745. delete static_cast <MidiOutputDevice*> (internal);
  223746. }
  223747. void MidiOutput::reset()
  223748. {
  223749. }
  223750. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223751. {
  223752. return false;
  223753. }
  223754. void MidiOutput::setVolume (float leftVol, float rightVol)
  223755. {
  223756. }
  223757. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223758. {
  223759. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223760. }
  223761. class MidiInputThread : public Thread
  223762. {
  223763. public:
  223764. MidiInputThread (MidiInput* const midiInput_,
  223765. snd_seq_t* const seqHandle_,
  223766. MidiInputCallback* const callback_)
  223767. : Thread ("Juce MIDI Input"),
  223768. midiInput (midiInput_),
  223769. seqHandle (seqHandle_),
  223770. callback (callback_)
  223771. {
  223772. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223773. }
  223774. ~MidiInputThread()
  223775. {
  223776. snd_seq_close (seqHandle);
  223777. }
  223778. void run()
  223779. {
  223780. const int maxEventSize = 16 * 1024;
  223781. snd_midi_event_t* midiParser;
  223782. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223783. {
  223784. HeapBlock <uint8> buffer (maxEventSize);
  223785. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223786. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223787. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223788. while (! threadShouldExit())
  223789. {
  223790. if (poll (pfd, numPfds, 500) > 0)
  223791. {
  223792. snd_seq_event_t* inputEvent = 0;
  223793. snd_seq_nonblock (seqHandle, 1);
  223794. do
  223795. {
  223796. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223797. {
  223798. // xxx what about SYSEXes that are too big for the buffer?
  223799. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223800. snd_midi_event_reset_decode (midiParser);
  223801. if (numBytes > 0)
  223802. {
  223803. const MidiMessage message ((const uint8*) buffer,
  223804. numBytes,
  223805. Time::getMillisecondCounter() * 0.001);
  223806. callback->handleIncomingMidiMessage (midiInput, message);
  223807. }
  223808. snd_seq_free_event (inputEvent);
  223809. }
  223810. }
  223811. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223812. snd_seq_free_event (inputEvent);
  223813. }
  223814. }
  223815. snd_midi_event_free (midiParser);
  223816. }
  223817. };
  223818. juce_UseDebuggingNewOperator
  223819. private:
  223820. MidiInput* const midiInput;
  223821. snd_seq_t* const seqHandle;
  223822. MidiInputCallback* const callback;
  223823. };
  223824. MidiInput::MidiInput (const String& name_)
  223825. : name (name_),
  223826. internal (0)
  223827. {
  223828. }
  223829. MidiInput::~MidiInput()
  223830. {
  223831. stop();
  223832. delete static_cast <MidiInputThread*> (internal);
  223833. }
  223834. void MidiInput::start()
  223835. {
  223836. static_cast <MidiInputThread*> (internal)->startThread();
  223837. }
  223838. void MidiInput::stop()
  223839. {
  223840. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223841. }
  223842. int MidiInput::getDefaultDeviceIndex()
  223843. {
  223844. return 0;
  223845. }
  223846. const StringArray MidiInput::getDevices()
  223847. {
  223848. StringArray devices;
  223849. iterateMidiDevices (true, devices, -1);
  223850. return devices;
  223851. }
  223852. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223853. {
  223854. MidiInput* newDevice = 0;
  223855. StringArray devices;
  223856. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223857. if (handle != 0)
  223858. {
  223859. newDevice = new MidiInput (devices [deviceIndex]);
  223860. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223861. }
  223862. return newDevice;
  223863. }
  223864. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223865. {
  223866. MidiInput* newDevice = 0;
  223867. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223868. if (handle != 0)
  223869. {
  223870. newDevice = new MidiInput (deviceName);
  223871. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223872. }
  223873. return newDevice;
  223874. }
  223875. #else
  223876. // (These are just stub functions if ALSA is unavailable...)
  223877. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223878. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223879. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223880. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223881. MidiOutput::~MidiOutput() {}
  223882. void MidiOutput::reset() {}
  223883. bool MidiOutput::getVolume (float&, float&) { return false; }
  223884. void MidiOutput::setVolume (float, float) {}
  223885. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223886. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223887. MidiInput::~MidiInput() {}
  223888. void MidiInput::start() {}
  223889. void MidiInput::stop() {}
  223890. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223891. const StringArray MidiInput::getDevices() { return StringArray(); }
  223892. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223893. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223894. #endif
  223895. #endif
  223896. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223897. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223898. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223899. // compiled on its own).
  223900. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223901. AudioCDReader::AudioCDReader()
  223902. : AudioFormatReader (0, "CD Audio")
  223903. {
  223904. }
  223905. const StringArray AudioCDReader::getAvailableCDNames()
  223906. {
  223907. StringArray names;
  223908. return names;
  223909. }
  223910. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223911. {
  223912. return 0;
  223913. }
  223914. AudioCDReader::~AudioCDReader()
  223915. {
  223916. }
  223917. void AudioCDReader::refreshTrackLengths()
  223918. {
  223919. }
  223920. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223921. int64 startSampleInFile, int numSamples)
  223922. {
  223923. return false;
  223924. }
  223925. bool AudioCDReader::isCDStillPresent() const
  223926. {
  223927. return false;
  223928. }
  223929. bool AudioCDReader::isTrackAudio (int trackNum) const
  223930. {
  223931. return false;
  223932. }
  223933. void AudioCDReader::enableIndexScanning (bool b)
  223934. {
  223935. }
  223936. int AudioCDReader::getLastIndex() const
  223937. {
  223938. return 0;
  223939. }
  223940. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223941. {
  223942. return Array<int>();
  223943. }
  223944. #endif
  223945. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223946. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223947. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223948. // compiled on its own).
  223949. #if JUCE_INCLUDED_FILE
  223950. void FileChooser::showPlatformDialog (Array<File>& results,
  223951. const String& title,
  223952. const File& file,
  223953. const String& filters,
  223954. bool isDirectory,
  223955. bool selectsFiles,
  223956. bool isSave,
  223957. bool warnAboutOverwritingExistingFiles,
  223958. bool selectMultipleFiles,
  223959. FilePreviewComponent* previewComponent)
  223960. {
  223961. const String separator (":");
  223962. String command ("zenity --file-selection");
  223963. if (title.isNotEmpty())
  223964. command << " --title=\"" << title << "\"";
  223965. if (file != File::nonexistent)
  223966. command << " --filename=\"" << file.getFullPathName () << "\"";
  223967. if (isDirectory)
  223968. command << " --directory";
  223969. if (isSave)
  223970. command << " --save";
  223971. if (selectMultipleFiles)
  223972. command << " --multiple --separator=\"" << separator << "\"";
  223973. command << " 2>&1";
  223974. MemoryOutputStream result;
  223975. int status = -1;
  223976. FILE* stream = popen (command.toUTF8(), "r");
  223977. if (stream != 0)
  223978. {
  223979. for (;;)
  223980. {
  223981. char buffer [1024];
  223982. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223983. if (bytesRead <= 0)
  223984. break;
  223985. result.write (buffer, bytesRead);
  223986. }
  223987. status = pclose (stream);
  223988. }
  223989. if (status == 0)
  223990. {
  223991. StringArray tokens;
  223992. if (selectMultipleFiles)
  223993. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223994. else
  223995. tokens.add (result.toUTF8());
  223996. for (int i = 0; i < tokens.size(); i++)
  223997. results.add (File (tokens[i]));
  223998. return;
  223999. }
  224000. //xxx ain't got one!
  224001. jassertfalse;
  224002. }
  224003. #endif
  224004. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224005. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224006. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224007. // compiled on its own).
  224008. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224009. /*
  224010. Sorry.. This class isn't implemented on Linux!
  224011. */
  224012. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224013. : browser (0),
  224014. blankPageShown (false),
  224015. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224016. {
  224017. setOpaque (true);
  224018. }
  224019. WebBrowserComponent::~WebBrowserComponent()
  224020. {
  224021. }
  224022. void WebBrowserComponent::goToURL (const String& url,
  224023. const StringArray* headers,
  224024. const MemoryBlock* postData)
  224025. {
  224026. lastURL = url;
  224027. lastHeaders.clear();
  224028. if (headers != 0)
  224029. lastHeaders = *headers;
  224030. lastPostData.setSize (0);
  224031. if (postData != 0)
  224032. lastPostData = *postData;
  224033. blankPageShown = false;
  224034. }
  224035. void WebBrowserComponent::stop()
  224036. {
  224037. }
  224038. void WebBrowserComponent::goBack()
  224039. {
  224040. lastURL = String::empty;
  224041. blankPageShown = false;
  224042. }
  224043. void WebBrowserComponent::goForward()
  224044. {
  224045. lastURL = String::empty;
  224046. }
  224047. void WebBrowserComponent::refresh()
  224048. {
  224049. }
  224050. void WebBrowserComponent::paint (Graphics& g)
  224051. {
  224052. g.fillAll (Colours::white);
  224053. }
  224054. void WebBrowserComponent::checkWindowAssociation()
  224055. {
  224056. }
  224057. void WebBrowserComponent::reloadLastURL()
  224058. {
  224059. if (lastURL.isNotEmpty())
  224060. {
  224061. goToURL (lastURL, &lastHeaders, &lastPostData);
  224062. lastURL = String::empty;
  224063. }
  224064. }
  224065. void WebBrowserComponent::parentHierarchyChanged()
  224066. {
  224067. checkWindowAssociation();
  224068. }
  224069. void WebBrowserComponent::resized()
  224070. {
  224071. }
  224072. void WebBrowserComponent::visibilityChanged()
  224073. {
  224074. checkWindowAssociation();
  224075. }
  224076. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224077. {
  224078. return true;
  224079. }
  224080. #endif
  224081. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224082. #endif
  224083. END_JUCE_NAMESPACE
  224084. #endif
  224085. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224086. #endif
  224087. #if JUCE_MAC || JUCE_IPHONE
  224088. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224089. /*
  224090. This file wraps together all the mac-specific code, so that
  224091. we can include all the native headers just once, and compile all our
  224092. platform-specific stuff in one big lump, keeping it out of the way of
  224093. the rest of the codebase.
  224094. */
  224095. #if JUCE_MAC || JUCE_IOS
  224096. BEGIN_JUCE_NAMESPACE
  224097. #undef Point
  224098. #define JUCE_INCLUDED_FILE 1
  224099. // Now include the actual code files..
  224100. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224101. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224102. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224103. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224104. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224105. actually calling into a similarly named class in the other module's address space.
  224106. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224107. have unique names, and should avoid this problem.
  224108. If you're using the amalgamated version, you can just set this macro to something unique before
  224109. you include juce_amalgamated.cpp.
  224110. */
  224111. #ifndef JUCE_ObjCExtraSuffix
  224112. #define JUCE_ObjCExtraSuffix 3
  224113. #endif
  224114. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224115. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224116. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224117. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224118. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224119. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224120. // compiled on its own).
  224121. #if JUCE_INCLUDED_FILE
  224122. static const String nsStringToJuce (NSString* s)
  224123. {
  224124. return String::fromUTF8 ([s UTF8String]);
  224125. }
  224126. static NSString* juceStringToNS (const String& s)
  224127. {
  224128. return [NSString stringWithUTF8String: s.toUTF8()];
  224129. }
  224130. static const String convertUTF16ToString (const UniChar* utf16)
  224131. {
  224132. String s;
  224133. while (*utf16 != 0)
  224134. s += (juce_wchar) *utf16++;
  224135. return s;
  224136. }
  224137. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224138. {
  224139. String result;
  224140. if (cfString != 0)
  224141. {
  224142. CFRange range = { 0, CFStringGetLength (cfString) };
  224143. HeapBlock <UniChar> u (range.length + 1);
  224144. CFStringGetCharacters (cfString, range, u);
  224145. u[range.length] = 0;
  224146. result = convertUTF16ToString (u);
  224147. }
  224148. return result;
  224149. }
  224150. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224151. {
  224152. const int len = s.length();
  224153. HeapBlock <UniChar> temp (len + 2);
  224154. for (int i = 0; i <= len; ++i)
  224155. temp[i] = s[i];
  224156. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224157. }
  224158. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224159. {
  224160. #if JUCE_IOS
  224161. const ScopedAutoReleasePool pool;
  224162. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224163. #else
  224164. UnicodeMapping map;
  224165. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224166. kUnicodeNoSubset,
  224167. kTextEncodingDefaultFormat);
  224168. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224169. kUnicodeCanonicalCompVariant,
  224170. kTextEncodingDefaultFormat);
  224171. map.mappingVersion = kUnicodeUseLatestMapping;
  224172. UnicodeToTextInfo conversionInfo = 0;
  224173. String result;
  224174. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224175. {
  224176. const int len = s.length();
  224177. HeapBlock <UniChar> tempIn, tempOut;
  224178. tempIn.calloc (len + 2);
  224179. tempOut.calloc (len + 2);
  224180. for (int i = 0; i <= len; ++i)
  224181. tempIn[i] = s[i];
  224182. ByteCount bytesRead = 0;
  224183. ByteCount outputBufferSize = 0;
  224184. if (ConvertFromUnicodeToText (conversionInfo,
  224185. len * sizeof (UniChar), tempIn,
  224186. kUnicodeDefaultDirectionMask,
  224187. 0, 0, 0, 0,
  224188. len * sizeof (UniChar), &bytesRead,
  224189. &outputBufferSize, tempOut) == noErr)
  224190. {
  224191. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224192. juce_wchar* t = result;
  224193. unsigned int i;
  224194. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224195. t[i] = (juce_wchar) tempOut[i];
  224196. t[i] = 0;
  224197. }
  224198. DisposeUnicodeToTextInfo (&conversionInfo);
  224199. }
  224200. return result;
  224201. #endif
  224202. }
  224203. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224204. void SystemClipboard::copyTextToClipboard (const String& text)
  224205. {
  224206. #if JUCE_IOS
  224207. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224208. forPasteboardType: @"public.text"];
  224209. #else
  224210. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224211. owner: nil];
  224212. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224213. forType: NSStringPboardType];
  224214. #endif
  224215. }
  224216. const String SystemClipboard::getTextFromClipboard()
  224217. {
  224218. #if JUCE_IOS
  224219. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224220. #else
  224221. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224222. #endif
  224223. return text == 0 ? String::empty
  224224. : nsStringToJuce (text);
  224225. }
  224226. #endif
  224227. #endif
  224228. /*** End of inlined file: juce_mac_Strings.mm ***/
  224229. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224230. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224231. // compiled on its own).
  224232. #if JUCE_INCLUDED_FILE
  224233. namespace SystemStatsHelpers
  224234. {
  224235. static int64 highResTimerFrequency = 0;
  224236. static double highResTimerToMillisecRatio = 0;
  224237. #if JUCE_INTEL
  224238. static void juce_getCpuVendor (char* const v) throw()
  224239. {
  224240. int vendor[4];
  224241. zerostruct (vendor);
  224242. int dummy = 0;
  224243. asm ("mov %%ebx, %%esi \n\t"
  224244. "cpuid \n\t"
  224245. "xchg %%esi, %%ebx"
  224246. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224247. memcpy (v, vendor, 16);
  224248. }
  224249. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224250. {
  224251. unsigned int cpu = 0;
  224252. unsigned int ext = 0;
  224253. unsigned int family = 0;
  224254. unsigned int dummy = 0;
  224255. asm ("mov %%ebx, %%esi \n\t"
  224256. "cpuid \n\t"
  224257. "xchg %%esi, %%ebx"
  224258. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224259. familyModel = family;
  224260. extFeatures = ext;
  224261. return cpu;
  224262. }
  224263. #endif
  224264. }
  224265. void SystemStats::initialiseStats()
  224266. {
  224267. using namespace SystemStatsHelpers;
  224268. static bool initialised = false;
  224269. if (! initialised)
  224270. {
  224271. initialised = true;
  224272. #if JUCE_MAC
  224273. [NSApplication sharedApplication];
  224274. #endif
  224275. #if JUCE_INTEL
  224276. unsigned int familyModel, extFeatures;
  224277. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224278. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224279. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224280. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224281. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224282. #else
  224283. cpuFlags.hasMMX = false;
  224284. cpuFlags.hasSSE = false;
  224285. cpuFlags.hasSSE2 = false;
  224286. cpuFlags.has3DNow = false;
  224287. #endif
  224288. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224289. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224290. #else
  224291. cpuFlags.numCpus = (int) MPProcessors();
  224292. #endif
  224293. mach_timebase_info_data_t timebase;
  224294. (void) mach_timebase_info (&timebase);
  224295. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224296. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224297. String s (SystemStats::getJUCEVersion());
  224298. rlimit lim;
  224299. getrlimit (RLIMIT_NOFILE, &lim);
  224300. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224301. setrlimit (RLIMIT_NOFILE, &lim);
  224302. }
  224303. }
  224304. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224305. {
  224306. return MacOSX;
  224307. }
  224308. const String SystemStats::getOperatingSystemName()
  224309. {
  224310. return "Mac OS X";
  224311. }
  224312. #if ! JUCE_IOS
  224313. int PlatformUtilities::getOSXMinorVersionNumber()
  224314. {
  224315. SInt32 versionMinor = 0;
  224316. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224317. (void) err;
  224318. jassert (err == noErr);
  224319. return (int) versionMinor;
  224320. }
  224321. #endif
  224322. bool SystemStats::isOperatingSystem64Bit()
  224323. {
  224324. #if JUCE_IOS
  224325. return false;
  224326. #elif JUCE_64BIT
  224327. return true;
  224328. #else
  224329. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224330. #endif
  224331. }
  224332. int SystemStats::getMemorySizeInMegabytes()
  224333. {
  224334. uint64 mem = 0;
  224335. size_t memSize = sizeof (mem);
  224336. int mib[] = { CTL_HW, HW_MEMSIZE };
  224337. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224338. return (int) (mem / (1024 * 1024));
  224339. }
  224340. const String SystemStats::getCpuVendor()
  224341. {
  224342. #if JUCE_INTEL
  224343. char v [16];
  224344. SystemStatsHelpers::juce_getCpuVendor (v);
  224345. return String (v, 16);
  224346. #else
  224347. return String::empty;
  224348. #endif
  224349. }
  224350. int SystemStats::getCpuSpeedInMegaherz()
  224351. {
  224352. uint64 speedHz = 0;
  224353. size_t speedSize = sizeof (speedHz);
  224354. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224355. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224356. #if JUCE_BIG_ENDIAN
  224357. if (speedSize == 4)
  224358. speedHz >>= 32;
  224359. #endif
  224360. return (int) (speedHz / 1000000);
  224361. }
  224362. const String SystemStats::getLogonName()
  224363. {
  224364. return nsStringToJuce (NSUserName());
  224365. }
  224366. const String SystemStats::getFullUserName()
  224367. {
  224368. return nsStringToJuce (NSFullUserName());
  224369. }
  224370. uint32 juce_millisecondsSinceStartup() throw()
  224371. {
  224372. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224373. }
  224374. double Time::getMillisecondCounterHiRes() throw()
  224375. {
  224376. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224377. }
  224378. int64 Time::getHighResolutionTicks() throw()
  224379. {
  224380. return (int64) mach_absolute_time();
  224381. }
  224382. int64 Time::getHighResolutionTicksPerSecond() throw()
  224383. {
  224384. return SystemStatsHelpers::highResTimerFrequency;
  224385. }
  224386. bool Time::setSystemTimeToThisTime() const
  224387. {
  224388. jassertfalse;
  224389. return false;
  224390. }
  224391. int SystemStats::getPageSize()
  224392. {
  224393. return (int) NSPageSize();
  224394. }
  224395. void PlatformUtilities::fpuReset()
  224396. {
  224397. }
  224398. #endif
  224399. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224400. /*** Start of inlined file: juce_mac_Network.mm ***/
  224401. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224402. // compiled on its own).
  224403. #if JUCE_INCLUDED_FILE
  224404. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224405. {
  224406. #ifndef IFT_ETHER
  224407. #define IFT_ETHER 6
  224408. #endif
  224409. ifaddrs* addrs = 0;
  224410. int numResults = 0;
  224411. if (getifaddrs (&addrs) == 0)
  224412. {
  224413. const ifaddrs* cursor = addrs;
  224414. while (cursor != 0 && numResults < maxNum)
  224415. {
  224416. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224417. if (sto->ss_family == AF_LINK)
  224418. {
  224419. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224420. if (sadd->sdl_type == IFT_ETHER)
  224421. {
  224422. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224423. uint64 a = 0;
  224424. for (int i = 6; --i >= 0;)
  224425. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224426. *addresses++ = (int64) a;
  224427. ++numResults;
  224428. }
  224429. }
  224430. cursor = cursor->ifa_next;
  224431. }
  224432. freeifaddrs (addrs);
  224433. }
  224434. return numResults;
  224435. }
  224436. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224437. const String& emailSubject,
  224438. const String& bodyText,
  224439. const StringArray& filesToAttach)
  224440. {
  224441. #if JUCE_IOS
  224442. //xxx probably need to use MFMailComposeViewController
  224443. jassertfalse;
  224444. return false;
  224445. #else
  224446. const ScopedAutoReleasePool pool;
  224447. String script;
  224448. script << "tell application \"Mail\"\r\n"
  224449. "set newMessage to make new outgoing message with properties {subject:\""
  224450. << emailSubject.replace ("\"", "\\\"")
  224451. << "\", content:\""
  224452. << bodyText.replace ("\"", "\\\"")
  224453. << "\" & return & return}\r\n"
  224454. "tell newMessage\r\n"
  224455. "set visible to true\r\n"
  224456. "set sender to \"sdfsdfsdfewf\"\r\n"
  224457. "make new to recipient at end of to recipients with properties {address:\""
  224458. << targetEmailAddress
  224459. << "\"}\r\n";
  224460. for (int i = 0; i < filesToAttach.size(); ++i)
  224461. {
  224462. script << "tell content\r\n"
  224463. "make new attachment with properties {file name:\""
  224464. << filesToAttach[i].replace ("\"", "\\\"")
  224465. << "\"} at after the last paragraph\r\n"
  224466. "end tell\r\n";
  224467. }
  224468. script << "end tell\r\n"
  224469. "end tell\r\n";
  224470. NSAppleScript* s = [[NSAppleScript alloc]
  224471. initWithSource: juceStringToNS (script)];
  224472. NSDictionary* error = 0;
  224473. const bool ok = [s executeAndReturnError: &error] != nil;
  224474. [s release];
  224475. return ok;
  224476. #endif
  224477. }
  224478. END_JUCE_NAMESPACE
  224479. using namespace JUCE_NAMESPACE;
  224480. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224481. @interface JuceURLConnection : NSObject
  224482. {
  224483. @public
  224484. NSURLRequest* request;
  224485. NSURLConnection* connection;
  224486. NSMutableData* data;
  224487. Thread* runLoopThread;
  224488. bool initialised, hasFailed, hasFinished;
  224489. int position;
  224490. int64 contentLength;
  224491. NSDictionary* headers;
  224492. NSLock* dataLock;
  224493. }
  224494. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224495. - (void) dealloc;
  224496. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224497. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224498. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224499. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224500. - (BOOL) isOpen;
  224501. - (int) read: (char*) dest numBytes: (int) num;
  224502. - (int) readPosition;
  224503. - (void) stop;
  224504. - (void) createConnection;
  224505. @end
  224506. class JuceURLConnectionMessageThread : public Thread
  224507. {
  224508. JuceURLConnection* owner;
  224509. public:
  224510. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224511. : Thread ("http connection"),
  224512. owner (owner_)
  224513. {
  224514. }
  224515. ~JuceURLConnectionMessageThread()
  224516. {
  224517. stopThread (10000);
  224518. }
  224519. void run()
  224520. {
  224521. [owner createConnection];
  224522. while (! threadShouldExit())
  224523. {
  224524. const ScopedAutoReleasePool pool;
  224525. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224526. }
  224527. }
  224528. };
  224529. @implementation JuceURLConnection
  224530. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224531. withCallback: (URL::OpenStreamProgressCallback*) callback
  224532. withContext: (void*) context;
  224533. {
  224534. [super init];
  224535. request = req;
  224536. [request retain];
  224537. data = [[NSMutableData data] retain];
  224538. dataLock = [[NSLock alloc] init];
  224539. connection = 0;
  224540. initialised = false;
  224541. hasFailed = false;
  224542. hasFinished = false;
  224543. contentLength = -1;
  224544. headers = 0;
  224545. runLoopThread = new JuceURLConnectionMessageThread (self);
  224546. runLoopThread->startThread();
  224547. while (runLoopThread->isThreadRunning() && ! initialised)
  224548. {
  224549. if (callback != 0)
  224550. callback (context, -1, (int) [[request HTTPBody] length]);
  224551. Thread::sleep (1);
  224552. }
  224553. return self;
  224554. }
  224555. - (void) dealloc
  224556. {
  224557. [self stop];
  224558. deleteAndZero (runLoopThread);
  224559. [connection release];
  224560. [data release];
  224561. [dataLock release];
  224562. [request release];
  224563. [headers release];
  224564. [super dealloc];
  224565. }
  224566. - (void) createConnection
  224567. {
  224568. NSUInteger oldRetainCount = [self retainCount];
  224569. connection = [[NSURLConnection alloc] initWithRequest: request
  224570. delegate: self];
  224571. if (oldRetainCount == [self retainCount])
  224572. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224573. if (connection == nil)
  224574. runLoopThread->signalThreadShouldExit();
  224575. }
  224576. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224577. {
  224578. (void) conn;
  224579. [dataLock lock];
  224580. [data setLength: 0];
  224581. [dataLock unlock];
  224582. initialised = true;
  224583. contentLength = [response expectedContentLength];
  224584. [headers release];
  224585. headers = 0;
  224586. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224587. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224588. }
  224589. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224590. {
  224591. (void) conn;
  224592. DBG (nsStringToJuce ([error description]));
  224593. hasFailed = true;
  224594. initialised = true;
  224595. if (runLoopThread != 0)
  224596. runLoopThread->signalThreadShouldExit();
  224597. }
  224598. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224599. {
  224600. (void) conn;
  224601. [dataLock lock];
  224602. [data appendData: newData];
  224603. [dataLock unlock];
  224604. initialised = true;
  224605. }
  224606. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224607. {
  224608. (void) conn;
  224609. hasFinished = true;
  224610. initialised = true;
  224611. if (runLoopThread != 0)
  224612. runLoopThread->signalThreadShouldExit();
  224613. }
  224614. - (BOOL) isOpen
  224615. {
  224616. return connection != 0 && ! hasFailed;
  224617. }
  224618. - (int) readPosition
  224619. {
  224620. return position;
  224621. }
  224622. - (int) read: (char*) dest numBytes: (int) numNeeded
  224623. {
  224624. int numDone = 0;
  224625. while (numNeeded > 0)
  224626. {
  224627. int available = jmin (numNeeded, (int) [data length]);
  224628. if (available > 0)
  224629. {
  224630. [dataLock lock];
  224631. [data getBytes: dest length: available];
  224632. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224633. [dataLock unlock];
  224634. numDone += available;
  224635. numNeeded -= available;
  224636. dest += available;
  224637. }
  224638. else
  224639. {
  224640. if (hasFailed || hasFinished)
  224641. break;
  224642. Thread::sleep (1);
  224643. }
  224644. }
  224645. position += numDone;
  224646. return numDone;
  224647. }
  224648. - (void) stop
  224649. {
  224650. [connection cancel];
  224651. if (runLoopThread != 0)
  224652. runLoopThread->stopThread (10000);
  224653. }
  224654. @end
  224655. BEGIN_JUCE_NAMESPACE
  224656. void* juce_openInternetFile (const String& url,
  224657. const String& headers,
  224658. const MemoryBlock& postData,
  224659. const bool isPost,
  224660. URL::OpenStreamProgressCallback* callback,
  224661. void* callbackContext,
  224662. int timeOutMs)
  224663. {
  224664. const ScopedAutoReleasePool pool;
  224665. NSMutableURLRequest* req = [NSMutableURLRequest
  224666. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224667. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224668. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224669. if (req == nil)
  224670. return 0;
  224671. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224672. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224673. StringArray headerLines;
  224674. headerLines.addLines (headers);
  224675. headerLines.removeEmptyStrings (true);
  224676. for (int i = 0; i < headerLines.size(); ++i)
  224677. {
  224678. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224679. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224680. if (key.isNotEmpty() && value.isNotEmpty())
  224681. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224682. }
  224683. if (isPost && postData.getSize() > 0)
  224684. {
  224685. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224686. length: postData.getSize()]];
  224687. }
  224688. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224689. withCallback: callback
  224690. withContext: callbackContext];
  224691. if ([s isOpen])
  224692. return s;
  224693. [s release];
  224694. return 0;
  224695. }
  224696. void juce_closeInternetFile (void* handle)
  224697. {
  224698. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224699. if (s != 0)
  224700. {
  224701. const ScopedAutoReleasePool pool;
  224702. [s stop];
  224703. [s release];
  224704. }
  224705. }
  224706. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224707. {
  224708. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224709. if (s != 0)
  224710. {
  224711. const ScopedAutoReleasePool pool;
  224712. return [s read: (char*) buffer numBytes: bytesToRead];
  224713. }
  224714. return 0;
  224715. }
  224716. int64 juce_getInternetFileContentLength (void* handle)
  224717. {
  224718. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224719. if (s != 0)
  224720. return s->contentLength;
  224721. return -1;
  224722. }
  224723. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224724. {
  224725. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224726. if (s != 0 && s->headers != 0)
  224727. {
  224728. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224729. NSString* key;
  224730. while ((key = [enumerator nextObject]) != nil)
  224731. headers.set (nsStringToJuce (key),
  224732. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224733. }
  224734. }
  224735. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224736. {
  224737. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224738. if (s != 0)
  224739. return [s readPosition];
  224740. return 0;
  224741. }
  224742. #endif
  224743. /*** End of inlined file: juce_mac_Network.mm ***/
  224744. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224745. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224746. // compiled on its own).
  224747. #if JUCE_INCLUDED_FILE
  224748. struct NamedPipeInternal
  224749. {
  224750. String pipeInName, pipeOutName;
  224751. int pipeIn, pipeOut;
  224752. bool volatile createdPipe, blocked, stopReadOperation;
  224753. static void signalHandler (int) {}
  224754. };
  224755. void NamedPipe::cancelPendingReads()
  224756. {
  224757. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224758. {
  224759. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224760. intern->stopReadOperation = true;
  224761. char buffer [1] = { 0 };
  224762. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224763. (void) bytesWritten;
  224764. int timeout = 2000;
  224765. while (intern->blocked && --timeout >= 0)
  224766. Thread::sleep (2);
  224767. intern->stopReadOperation = false;
  224768. }
  224769. }
  224770. void NamedPipe::close()
  224771. {
  224772. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224773. if (intern != 0)
  224774. {
  224775. internal = 0;
  224776. if (intern->pipeIn != -1)
  224777. ::close (intern->pipeIn);
  224778. if (intern->pipeOut != -1)
  224779. ::close (intern->pipeOut);
  224780. if (intern->createdPipe)
  224781. {
  224782. unlink (intern->pipeInName.toUTF8());
  224783. unlink (intern->pipeOutName.toUTF8());
  224784. }
  224785. delete intern;
  224786. }
  224787. }
  224788. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224789. {
  224790. close();
  224791. NamedPipeInternal* const intern = new NamedPipeInternal();
  224792. internal = intern;
  224793. intern->createdPipe = createPipe;
  224794. intern->blocked = false;
  224795. intern->stopReadOperation = false;
  224796. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224797. siginterrupt (SIGPIPE, 1);
  224798. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224799. intern->pipeInName = pipePath + "_in";
  224800. intern->pipeOutName = pipePath + "_out";
  224801. intern->pipeIn = -1;
  224802. intern->pipeOut = -1;
  224803. if (createPipe)
  224804. {
  224805. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224806. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224807. {
  224808. delete intern;
  224809. internal = 0;
  224810. return false;
  224811. }
  224812. }
  224813. return true;
  224814. }
  224815. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224816. {
  224817. int bytesRead = -1;
  224818. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224819. if (intern != 0)
  224820. {
  224821. intern->blocked = true;
  224822. if (intern->pipeIn == -1)
  224823. {
  224824. if (intern->createdPipe)
  224825. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224826. else
  224827. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224828. if (intern->pipeIn == -1)
  224829. {
  224830. intern->blocked = false;
  224831. return -1;
  224832. }
  224833. }
  224834. bytesRead = 0;
  224835. char* p = static_cast<char*> (destBuffer);
  224836. while (bytesRead < maxBytesToRead)
  224837. {
  224838. const int bytesThisTime = maxBytesToRead - bytesRead;
  224839. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224840. if (numRead <= 0 || intern->stopReadOperation)
  224841. {
  224842. bytesRead = -1;
  224843. break;
  224844. }
  224845. bytesRead += numRead;
  224846. p += bytesRead;
  224847. }
  224848. intern->blocked = false;
  224849. }
  224850. return bytesRead;
  224851. }
  224852. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224853. {
  224854. int bytesWritten = -1;
  224855. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224856. if (intern != 0)
  224857. {
  224858. if (intern->pipeOut == -1)
  224859. {
  224860. if (intern->createdPipe)
  224861. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224862. else
  224863. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224864. if (intern->pipeOut == -1)
  224865. {
  224866. return -1;
  224867. }
  224868. }
  224869. const char* p = static_cast<const char*> (sourceBuffer);
  224870. bytesWritten = 0;
  224871. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224872. while (bytesWritten < numBytesToWrite
  224873. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224874. {
  224875. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224876. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224877. if (numWritten <= 0)
  224878. {
  224879. bytesWritten = -1;
  224880. break;
  224881. }
  224882. bytesWritten += numWritten;
  224883. p += bytesWritten;
  224884. }
  224885. }
  224886. return bytesWritten;
  224887. }
  224888. #endif
  224889. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224890. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224891. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224892. // compiled on its own).
  224893. #if JUCE_INCLUDED_FILE
  224894. /*
  224895. Note that a lot of methods that you'd expect to find in this file actually
  224896. live in juce_posix_SharedCode.h!
  224897. */
  224898. bool Process::isForegroundProcess()
  224899. {
  224900. #if JUCE_MAC
  224901. return [NSApp isActive];
  224902. #else
  224903. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224904. #endif
  224905. }
  224906. void Process::raisePrivilege()
  224907. {
  224908. jassertfalse;
  224909. }
  224910. void Process::lowerPrivilege()
  224911. {
  224912. jassertfalse;
  224913. }
  224914. void Process::terminate()
  224915. {
  224916. exit (0);
  224917. }
  224918. void Process::setPriority (ProcessPriority)
  224919. {
  224920. // xxx
  224921. }
  224922. #endif
  224923. /*** End of inlined file: juce_mac_Threads.mm ***/
  224924. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224925. /*
  224926. This file contains posix routines that are common to both the Linux and Mac builds.
  224927. It gets included directly in the cpp files for these platforms.
  224928. */
  224929. CriticalSection::CriticalSection() throw()
  224930. {
  224931. pthread_mutexattr_t atts;
  224932. pthread_mutexattr_init (&atts);
  224933. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224934. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224935. pthread_mutex_init (&internal, &atts);
  224936. }
  224937. CriticalSection::~CriticalSection() throw()
  224938. {
  224939. pthread_mutex_destroy (&internal);
  224940. }
  224941. void CriticalSection::enter() const throw()
  224942. {
  224943. pthread_mutex_lock (&internal);
  224944. }
  224945. bool CriticalSection::tryEnter() const throw()
  224946. {
  224947. return pthread_mutex_trylock (&internal) == 0;
  224948. }
  224949. void CriticalSection::exit() const throw()
  224950. {
  224951. pthread_mutex_unlock (&internal);
  224952. }
  224953. class WaitableEventImpl
  224954. {
  224955. public:
  224956. WaitableEventImpl (const bool manualReset_)
  224957. : triggered (false),
  224958. manualReset (manualReset_)
  224959. {
  224960. pthread_cond_init (&condition, 0);
  224961. pthread_mutexattr_t atts;
  224962. pthread_mutexattr_init (&atts);
  224963. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224964. pthread_mutex_init (&mutex, &atts);
  224965. }
  224966. ~WaitableEventImpl()
  224967. {
  224968. pthread_cond_destroy (&condition);
  224969. pthread_mutex_destroy (&mutex);
  224970. }
  224971. bool wait (const int timeOutMillisecs) throw()
  224972. {
  224973. pthread_mutex_lock (&mutex);
  224974. if (! triggered)
  224975. {
  224976. if (timeOutMillisecs < 0)
  224977. {
  224978. do
  224979. {
  224980. pthread_cond_wait (&condition, &mutex);
  224981. }
  224982. while (! triggered);
  224983. }
  224984. else
  224985. {
  224986. struct timeval now;
  224987. gettimeofday (&now, 0);
  224988. struct timespec time;
  224989. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224990. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224991. if (time.tv_nsec >= 1000000000)
  224992. {
  224993. time.tv_nsec -= 1000000000;
  224994. time.tv_sec++;
  224995. }
  224996. do
  224997. {
  224998. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224999. {
  225000. pthread_mutex_unlock (&mutex);
  225001. return false;
  225002. }
  225003. }
  225004. while (! triggered);
  225005. }
  225006. }
  225007. if (! manualReset)
  225008. triggered = false;
  225009. pthread_mutex_unlock (&mutex);
  225010. return true;
  225011. }
  225012. void signal() throw()
  225013. {
  225014. pthread_mutex_lock (&mutex);
  225015. triggered = true;
  225016. pthread_cond_broadcast (&condition);
  225017. pthread_mutex_unlock (&mutex);
  225018. }
  225019. void reset() throw()
  225020. {
  225021. pthread_mutex_lock (&mutex);
  225022. triggered = false;
  225023. pthread_mutex_unlock (&mutex);
  225024. }
  225025. private:
  225026. pthread_cond_t condition;
  225027. pthread_mutex_t mutex;
  225028. bool triggered;
  225029. const bool manualReset;
  225030. WaitableEventImpl (const WaitableEventImpl&);
  225031. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225032. };
  225033. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225034. : internal (new WaitableEventImpl (manualReset))
  225035. {
  225036. }
  225037. WaitableEvent::~WaitableEvent() throw()
  225038. {
  225039. delete static_cast <WaitableEventImpl*> (internal);
  225040. }
  225041. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225042. {
  225043. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225044. }
  225045. void WaitableEvent::signal() const throw()
  225046. {
  225047. static_cast <WaitableEventImpl*> (internal)->signal();
  225048. }
  225049. void WaitableEvent::reset() const throw()
  225050. {
  225051. static_cast <WaitableEventImpl*> (internal)->reset();
  225052. }
  225053. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225054. {
  225055. struct timespec time;
  225056. time.tv_sec = millisecs / 1000;
  225057. time.tv_nsec = (millisecs % 1000) * 1000000;
  225058. nanosleep (&time, 0);
  225059. }
  225060. const juce_wchar File::separator = '/';
  225061. const String File::separatorString ("/");
  225062. const File File::getCurrentWorkingDirectory()
  225063. {
  225064. HeapBlock<char> heapBuffer;
  225065. char localBuffer [1024];
  225066. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225067. int bufferSize = 4096;
  225068. while (cwd == 0 && errno == ERANGE)
  225069. {
  225070. heapBuffer.malloc (bufferSize);
  225071. cwd = getcwd (heapBuffer, bufferSize - 1);
  225072. bufferSize += 1024;
  225073. }
  225074. return File (String::fromUTF8 (cwd));
  225075. }
  225076. bool File::setAsCurrentWorkingDirectory() const
  225077. {
  225078. return chdir (getFullPathName().toUTF8()) == 0;
  225079. }
  225080. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225081. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225082. #else
  225083. typedef struct stat juce_statStruct;
  225084. #endif
  225085. static bool juce_stat (const String& fileName, juce_statStruct& info)
  225086. {
  225087. return fileName.isNotEmpty()
  225088. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225089. && (stat64 (fileName.toUTF8(), &info) == 0);
  225090. #else
  225091. && (stat (fileName.toUTF8(), &info) == 0);
  225092. #endif
  225093. }
  225094. bool File::isDirectory() const
  225095. {
  225096. juce_statStruct info;
  225097. return fullPath.isEmpty()
  225098. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225099. }
  225100. bool File::exists() const
  225101. {
  225102. return fullPath.isNotEmpty()
  225103. && access (fullPath.toUTF8(), F_OK) == 0;
  225104. }
  225105. bool File::existsAsFile() const
  225106. {
  225107. return exists() && ! isDirectory();
  225108. }
  225109. int64 File::getSize() const
  225110. {
  225111. juce_statStruct info;
  225112. return juce_stat (fullPath, info) ? info.st_size : 0;
  225113. }
  225114. bool File::hasWriteAccess() const
  225115. {
  225116. if (exists())
  225117. return access (fullPath.toUTF8(), W_OK) == 0;
  225118. if ((! isDirectory()) && fullPath.containsChar (separator))
  225119. return getParentDirectory().hasWriteAccess();
  225120. return false;
  225121. }
  225122. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225123. {
  225124. juce_statStruct info;
  225125. if (! juce_stat (fullPath, info))
  225126. return false;
  225127. info.st_mode &= 0777; // Just permissions
  225128. if (shouldBeReadOnly)
  225129. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225130. else
  225131. // Give everybody write permission?
  225132. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225133. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225134. }
  225135. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225136. {
  225137. modificationTime = 0;
  225138. accessTime = 0;
  225139. creationTime = 0;
  225140. juce_statStruct info;
  225141. if (juce_stat (fullPath, info))
  225142. {
  225143. modificationTime = (int64) info.st_mtime * 1000;
  225144. accessTime = (int64) info.st_atime * 1000;
  225145. creationTime = (int64) info.st_ctime * 1000;
  225146. }
  225147. }
  225148. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225149. {
  225150. struct utimbuf times;
  225151. times.actime = (time_t) (accessTime / 1000);
  225152. times.modtime = (time_t) (modificationTime / 1000);
  225153. return utime (fullPath.toUTF8(), &times) == 0;
  225154. }
  225155. bool File::deleteFile() const
  225156. {
  225157. if (! exists())
  225158. return true;
  225159. else if (isDirectory())
  225160. return rmdir (fullPath.toUTF8()) == 0;
  225161. else
  225162. return remove (fullPath.toUTF8()) == 0;
  225163. }
  225164. bool File::moveInternal (const File& dest) const
  225165. {
  225166. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225167. return true;
  225168. if (hasWriteAccess() && copyInternal (dest))
  225169. {
  225170. if (deleteFile())
  225171. return true;
  225172. dest.deleteFile();
  225173. }
  225174. return false;
  225175. }
  225176. void File::createDirectoryInternal (const String& fileName) const
  225177. {
  225178. mkdir (fileName.toUTF8(), 0777);
  225179. }
  225180. int64 juce_fileSetPosition (void* handle, int64 pos)
  225181. {
  225182. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225183. return pos;
  225184. return -1;
  225185. }
  225186. void FileInputStream::openHandle()
  225187. {
  225188. totalSize = file.getSize();
  225189. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225190. if (f != -1)
  225191. fileHandle = (void*) f;
  225192. }
  225193. void FileInputStream::closeHandle()
  225194. {
  225195. if (fileHandle != 0)
  225196. {
  225197. close ((int) (pointer_sized_int) fileHandle);
  225198. fileHandle = 0;
  225199. }
  225200. }
  225201. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225202. {
  225203. if (fileHandle != 0)
  225204. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225205. return 0;
  225206. }
  225207. void FileOutputStream::openHandle()
  225208. {
  225209. if (file.exists())
  225210. {
  225211. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225212. if (f != -1)
  225213. {
  225214. currentPosition = lseek (f, 0, SEEK_END);
  225215. if (currentPosition >= 0)
  225216. fileHandle = (void*) f;
  225217. else
  225218. close (f);
  225219. }
  225220. }
  225221. else
  225222. {
  225223. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225224. if (f != -1)
  225225. fileHandle = (void*) f;
  225226. }
  225227. }
  225228. void FileOutputStream::closeHandle()
  225229. {
  225230. if (fileHandle != 0)
  225231. {
  225232. close ((int) (pointer_sized_int) fileHandle);
  225233. fileHandle = 0;
  225234. }
  225235. }
  225236. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225237. {
  225238. if (fileHandle != 0)
  225239. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225240. return 0;
  225241. }
  225242. void FileOutputStream::flushInternal()
  225243. {
  225244. if (fileHandle != 0)
  225245. fsync ((int) (pointer_sized_int) fileHandle);
  225246. }
  225247. const File juce_getExecutableFile()
  225248. {
  225249. Dl_info exeInfo;
  225250. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225251. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225252. }
  225253. // if this file doesn't exist, find a parent of it that does..
  225254. static bool juce_doStatFS (File f, struct statfs& result)
  225255. {
  225256. for (int i = 5; --i >= 0;)
  225257. {
  225258. if (f.exists())
  225259. break;
  225260. f = f.getParentDirectory();
  225261. }
  225262. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225263. }
  225264. int64 File::getBytesFreeOnVolume() const
  225265. {
  225266. struct statfs buf;
  225267. if (juce_doStatFS (*this, buf))
  225268. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225269. return 0;
  225270. }
  225271. int64 File::getVolumeTotalSize() const
  225272. {
  225273. struct statfs buf;
  225274. if (juce_doStatFS (*this, buf))
  225275. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225276. return 0;
  225277. }
  225278. const String File::getVolumeLabel() const
  225279. {
  225280. #if JUCE_MAC
  225281. struct VolAttrBuf
  225282. {
  225283. u_int32_t length;
  225284. attrreference_t mountPointRef;
  225285. char mountPointSpace [MAXPATHLEN];
  225286. } attrBuf;
  225287. struct attrlist attrList;
  225288. zerostruct (attrList);
  225289. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225290. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225291. File f (*this);
  225292. for (;;)
  225293. {
  225294. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225295. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225296. (int) attrBuf.mountPointRef.attr_length);
  225297. const File parent (f.getParentDirectory());
  225298. if (f == parent)
  225299. break;
  225300. f = parent;
  225301. }
  225302. #endif
  225303. return String::empty;
  225304. }
  225305. int File::getVolumeSerialNumber() const
  225306. {
  225307. return 0; // xxx
  225308. }
  225309. void juce_runSystemCommand (const String& command)
  225310. {
  225311. int result = system (command.toUTF8());
  225312. (void) result;
  225313. }
  225314. const String juce_getOutputFromCommand (const String& command)
  225315. {
  225316. // slight bodge here, as we just pipe the output into a temp file and read it...
  225317. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225318. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225319. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225320. String result (tempFile.loadFileAsString());
  225321. tempFile.deleteFile();
  225322. return result;
  225323. }
  225324. class InterProcessLock::Pimpl
  225325. {
  225326. public:
  225327. Pimpl (const String& name, const int timeOutMillisecs)
  225328. : handle (0), refCount (1)
  225329. {
  225330. #if JUCE_MAC
  225331. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225332. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225333. #else
  225334. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225335. #endif
  225336. temp.create();
  225337. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225338. if (handle != 0)
  225339. {
  225340. struct flock fl;
  225341. zerostruct (fl);
  225342. fl.l_whence = SEEK_SET;
  225343. fl.l_type = F_WRLCK;
  225344. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225345. for (;;)
  225346. {
  225347. const int result = fcntl (handle, F_SETLK, &fl);
  225348. if (result >= 0)
  225349. return;
  225350. if (errno != EINTR)
  225351. {
  225352. if (timeOutMillisecs == 0
  225353. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225354. break;
  225355. Thread::sleep (10);
  225356. }
  225357. }
  225358. }
  225359. closeFile();
  225360. }
  225361. ~Pimpl()
  225362. {
  225363. closeFile();
  225364. }
  225365. void closeFile()
  225366. {
  225367. if (handle != 0)
  225368. {
  225369. struct flock fl;
  225370. zerostruct (fl);
  225371. fl.l_whence = SEEK_SET;
  225372. fl.l_type = F_UNLCK;
  225373. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225374. {}
  225375. close (handle);
  225376. handle = 0;
  225377. }
  225378. }
  225379. int handle, refCount;
  225380. };
  225381. InterProcessLock::InterProcessLock (const String& name_)
  225382. : name (name_)
  225383. {
  225384. }
  225385. InterProcessLock::~InterProcessLock()
  225386. {
  225387. }
  225388. bool InterProcessLock::enter (const int timeOutMillisecs)
  225389. {
  225390. const ScopedLock sl (lock);
  225391. if (pimpl == 0)
  225392. {
  225393. pimpl = new Pimpl (name, timeOutMillisecs);
  225394. if (pimpl->handle == 0)
  225395. pimpl = 0;
  225396. }
  225397. else
  225398. {
  225399. pimpl->refCount++;
  225400. }
  225401. return pimpl != 0;
  225402. }
  225403. void InterProcessLock::exit()
  225404. {
  225405. const ScopedLock sl (lock);
  225406. // Trying to release the lock too many times!
  225407. jassert (pimpl != 0);
  225408. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225409. pimpl = 0;
  225410. }
  225411. void JUCE_API juce_threadEntryPoint (void*);
  225412. void* threadEntryProc (void* userData)
  225413. {
  225414. JUCE_AUTORELEASEPOOL
  225415. juce_threadEntryPoint (userData);
  225416. return 0;
  225417. }
  225418. void* juce_createThread (void* userData)
  225419. {
  225420. pthread_t handle = 0;
  225421. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225422. {
  225423. pthread_detach (handle);
  225424. return (void*) handle;
  225425. }
  225426. return 0;
  225427. }
  225428. void juce_killThread (void* handle)
  225429. {
  225430. if (handle != 0)
  225431. pthread_cancel ((pthread_t) handle);
  225432. }
  225433. void juce_setCurrentThreadName (const String& /*name*/)
  225434. {
  225435. }
  225436. bool juce_setThreadPriority (void* handle, int priority)
  225437. {
  225438. struct sched_param param;
  225439. int policy;
  225440. priority = jlimit (0, 10, priority);
  225441. if (handle == 0)
  225442. handle = (void*) pthread_self();
  225443. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225444. return false;
  225445. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225446. const int minPriority = sched_get_priority_min (policy);
  225447. const int maxPriority = sched_get_priority_max (policy);
  225448. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225449. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225450. }
  225451. Thread::ThreadID Thread::getCurrentThreadId()
  225452. {
  225453. return (ThreadID) pthread_self();
  225454. }
  225455. void Thread::yield()
  225456. {
  225457. sched_yield();
  225458. }
  225459. /* Remove this macro if you're having problems compiling the cpu affinity
  225460. calls (the API for these has changed about quite a bit in various Linux
  225461. versions, and a lot of distros seem to ship with obsolete versions)
  225462. */
  225463. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225464. #define SUPPORT_AFFINITIES 1
  225465. #endif
  225466. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225467. {
  225468. #if SUPPORT_AFFINITIES
  225469. cpu_set_t affinity;
  225470. CPU_ZERO (&affinity);
  225471. for (int i = 0; i < 32; ++i)
  225472. if ((affinityMask & (1 << i)) != 0)
  225473. CPU_SET (i, &affinity);
  225474. /*
  225475. N.B. If this line causes a compile error, then you've probably not got the latest
  225476. version of glibc installed.
  225477. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225478. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225479. */
  225480. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225481. sched_yield();
  225482. #else
  225483. /* affinities aren't supported because either the appropriate header files weren't found,
  225484. or the SUPPORT_AFFINITIES macro was turned off
  225485. */
  225486. jassertfalse;
  225487. #endif
  225488. }
  225489. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225490. /*** Start of inlined file: juce_mac_Files.mm ***/
  225491. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225492. // compiled on its own).
  225493. #if JUCE_INCLUDED_FILE
  225494. /*
  225495. Note that a lot of methods that you'd expect to find in this file actually
  225496. live in juce_posix_SharedCode.h!
  225497. */
  225498. bool File::copyInternal (const File& dest) const
  225499. {
  225500. const ScopedAutoReleasePool pool;
  225501. NSFileManager* fm = [NSFileManager defaultManager];
  225502. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225503. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225504. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225505. toPath: juceStringToNS (dest.getFullPathName())
  225506. error: nil];
  225507. #else
  225508. && [fm copyPath: juceStringToNS (fullPath)
  225509. toPath: juceStringToNS (dest.getFullPathName())
  225510. handler: nil];
  225511. #endif
  225512. }
  225513. void File::findFileSystemRoots (Array<File>& destArray)
  225514. {
  225515. destArray.add (File ("/"));
  225516. }
  225517. static bool isFileOnDriveType (const File& f, const char* const* types)
  225518. {
  225519. struct statfs buf;
  225520. if (juce_doStatFS (f, buf))
  225521. {
  225522. const String type (buf.f_fstypename);
  225523. while (*types != 0)
  225524. if (type.equalsIgnoreCase (*types++))
  225525. return true;
  225526. }
  225527. return false;
  225528. }
  225529. bool File::isOnCDRomDrive() const
  225530. {
  225531. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225532. return isFileOnDriveType (*this, cdTypes);
  225533. }
  225534. bool File::isOnHardDisk() const
  225535. {
  225536. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225537. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225538. }
  225539. bool File::isOnRemovableDrive() const
  225540. {
  225541. #if JUCE_IOS
  225542. return false; // xxx is this possible?
  225543. #else
  225544. const ScopedAutoReleasePool pool;
  225545. BOOL removable = false;
  225546. [[NSWorkspace sharedWorkspace]
  225547. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225548. isRemovable: &removable
  225549. isWritable: nil
  225550. isUnmountable: nil
  225551. description: nil
  225552. type: nil];
  225553. return removable;
  225554. #endif
  225555. }
  225556. static bool juce_isHiddenFile (const String& path)
  225557. {
  225558. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225559. const ScopedAutoReleasePool pool;
  225560. NSNumber* hidden = nil;
  225561. NSError* err = nil;
  225562. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225563. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225564. && [hidden boolValue];
  225565. #else
  225566. #if JUCE_IOS
  225567. return File (path).getFileName().startsWithChar ('.');
  225568. #else
  225569. FSRef ref;
  225570. LSItemInfoRecord info;
  225571. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225572. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225573. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225574. #endif
  225575. #endif
  225576. }
  225577. bool File::isHidden() const
  225578. {
  225579. return juce_isHiddenFile (getFullPathName());
  225580. }
  225581. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225582. const File File::getSpecialLocation (const SpecialLocationType type)
  225583. {
  225584. const ScopedAutoReleasePool pool;
  225585. String resultPath;
  225586. switch (type)
  225587. {
  225588. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225589. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225590. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225591. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225592. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225593. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225594. case userMusicDirectory: resultPath = "~/Music"; break;
  225595. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225596. case tempDirectory:
  225597. {
  225598. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225599. tmp.createDirectory();
  225600. return tmp.getFullPathName();
  225601. }
  225602. case invokedExecutableFile:
  225603. if (juce_Argv0 != 0)
  225604. return File (String::fromUTF8 (juce_Argv0));
  225605. // deliberate fall-through...
  225606. case currentExecutableFile:
  225607. return juce_getExecutableFile();
  225608. case currentApplicationFile:
  225609. {
  225610. const File exe (juce_getExecutableFile());
  225611. const File parent (exe.getParentDirectory());
  225612. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225613. ? parent.getParentDirectory().getParentDirectory()
  225614. : exe;
  225615. }
  225616. case hostApplicationPath:
  225617. {
  225618. unsigned int size = 8192;
  225619. HeapBlock<char> buffer;
  225620. buffer.calloc (size + 8);
  225621. _NSGetExecutablePath (buffer.getData(), &size);
  225622. return String::fromUTF8 (buffer, size);
  225623. }
  225624. default:
  225625. jassertfalse; // unknown type?
  225626. break;
  225627. }
  225628. if (resultPath.isNotEmpty())
  225629. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225630. return File::nonexistent;
  225631. }
  225632. const String File::getVersion() const
  225633. {
  225634. const ScopedAutoReleasePool pool;
  225635. String result;
  225636. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225637. if (bundle != 0)
  225638. {
  225639. NSDictionary* info = [bundle infoDictionary];
  225640. if (info != 0)
  225641. {
  225642. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225643. if (name != nil)
  225644. result = nsStringToJuce (name);
  225645. }
  225646. }
  225647. return result;
  225648. }
  225649. const File File::getLinkedTarget() const
  225650. {
  225651. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225652. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225653. #else
  225654. // (the cast here avoids a deprecation warning)
  225655. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225656. #endif
  225657. if (dest != nil)
  225658. return File (nsStringToJuce (dest));
  225659. return *this;
  225660. }
  225661. bool File::moveToTrash() const
  225662. {
  225663. if (! exists())
  225664. return true;
  225665. #if JUCE_IOS
  225666. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225667. #else
  225668. const ScopedAutoReleasePool pool;
  225669. NSString* p = juceStringToNS (getFullPathName());
  225670. return [[NSWorkspace sharedWorkspace]
  225671. performFileOperation: NSWorkspaceRecycleOperation
  225672. source: [p stringByDeletingLastPathComponent]
  225673. destination: @""
  225674. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225675. tag: nil ];
  225676. #endif
  225677. }
  225678. class DirectoryIterator::NativeIterator::Pimpl
  225679. {
  225680. public:
  225681. Pimpl (const File& directory, const String& wildCard_)
  225682. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225683. wildCard (wildCard_),
  225684. enumerator (0)
  225685. {
  225686. const ScopedAutoReleasePool pool;
  225687. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225688. wildcardUTF8 = wildCard.toUTF8();
  225689. }
  225690. ~Pimpl()
  225691. {
  225692. [enumerator release];
  225693. }
  225694. bool next (String& filenameFound,
  225695. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225696. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225697. {
  225698. const ScopedAutoReleasePool pool;
  225699. for (;;)
  225700. {
  225701. NSString* file;
  225702. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225703. return false;
  225704. [enumerator skipDescendents];
  225705. filenameFound = nsStringToJuce (file);
  225706. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225707. continue;
  225708. const String path (parentDir + filenameFound);
  225709. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225710. {
  225711. juce_statStruct info;
  225712. const bool statOk = juce_stat (path, info);
  225713. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225714. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225715. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225716. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225717. }
  225718. if (isHidden != 0)
  225719. *isHidden = juce_isHiddenFile (path);
  225720. if (isReadOnly != 0)
  225721. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225722. return true;
  225723. }
  225724. }
  225725. private:
  225726. String parentDir, wildCard;
  225727. const char* wildcardUTF8;
  225728. NSDirectoryEnumerator* enumerator;
  225729. Pimpl (const Pimpl&);
  225730. Pimpl& operator= (const Pimpl&);
  225731. };
  225732. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225733. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225734. {
  225735. }
  225736. DirectoryIterator::NativeIterator::~NativeIterator()
  225737. {
  225738. }
  225739. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225740. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225741. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225742. {
  225743. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225744. }
  225745. bool juce_launchExecutable (const String& pathAndArguments)
  225746. {
  225747. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225748. const int cpid = fork();
  225749. if (cpid == 0)
  225750. {
  225751. // Child process
  225752. if (execve (argv[0], (char**) argv, 0) < 0)
  225753. exit (0);
  225754. }
  225755. else
  225756. {
  225757. if (cpid < 0)
  225758. return false;
  225759. }
  225760. return true;
  225761. }
  225762. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225763. {
  225764. #if JUCE_IOS
  225765. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225766. #else
  225767. const ScopedAutoReleasePool pool;
  225768. if (parameters.isEmpty())
  225769. {
  225770. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225771. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225772. }
  225773. bool ok = false;
  225774. if (PlatformUtilities::isBundle (fileName))
  225775. {
  225776. NSMutableArray* urls = [NSMutableArray array];
  225777. StringArray docs;
  225778. docs.addTokens (parameters, true);
  225779. for (int i = 0; i < docs.size(); ++i)
  225780. [urls addObject: juceStringToNS (docs[i])];
  225781. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225782. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225783. options: 0
  225784. additionalEventParamDescriptor: nil
  225785. launchIdentifiers: nil];
  225786. }
  225787. else if (File (fileName).exists())
  225788. {
  225789. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225790. }
  225791. return ok;
  225792. #endif
  225793. }
  225794. void File::revealToUser() const
  225795. {
  225796. #if ! JUCE_IOS
  225797. if (exists())
  225798. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225799. else if (getParentDirectory().exists())
  225800. getParentDirectory().revealToUser();
  225801. #endif
  225802. }
  225803. #if ! JUCE_IOS
  225804. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225805. {
  225806. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225807. }
  225808. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225809. {
  225810. char path [2048];
  225811. zerostruct (path);
  225812. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225813. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225814. return String::empty;
  225815. }
  225816. #endif
  225817. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225818. {
  225819. const ScopedAutoReleasePool pool;
  225820. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225821. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225822. #else
  225823. // (the cast here avoids a deprecation warning)
  225824. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225825. #endif
  225826. return [fileDict fileHFSTypeCode];
  225827. }
  225828. bool PlatformUtilities::isBundle (const String& filename)
  225829. {
  225830. #if JUCE_IOS
  225831. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225832. #else
  225833. const ScopedAutoReleasePool pool;
  225834. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225835. #endif
  225836. }
  225837. #endif
  225838. /*** End of inlined file: juce_mac_Files.mm ***/
  225839. #if JUCE_IOS
  225840. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225841. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225842. // compiled on its own).
  225843. #if JUCE_INCLUDED_FILE
  225844. END_JUCE_NAMESPACE
  225845. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225846. {
  225847. }
  225848. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225849. - (void) applicationWillTerminate: (UIApplication*) application;
  225850. @end
  225851. @implementation JuceAppStartupDelegate
  225852. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225853. {
  225854. initialiseJuce_GUI();
  225855. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225856. exit (0);
  225857. }
  225858. - (void) applicationWillTerminate: (UIApplication*) application
  225859. {
  225860. JUCEApplication::appWillTerminateByForce();
  225861. }
  225862. @end
  225863. BEGIN_JUCE_NAMESPACE
  225864. int juce_iOSMain (int argc, const char* argv[])
  225865. {
  225866. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225867. }
  225868. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225869. {
  225870. pool = [[NSAutoreleasePool alloc] init];
  225871. }
  225872. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225873. {
  225874. [((NSAutoreleasePool*) pool) release];
  225875. }
  225876. void PlatformUtilities::beep()
  225877. {
  225878. //xxx
  225879. //AudioServicesPlaySystemSound ();
  225880. }
  225881. void PlatformUtilities::addItemToDock (const File& file)
  225882. {
  225883. }
  225884. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225885. END_JUCE_NAMESPACE
  225886. @interface JuceAlertBoxDelegate : NSObject
  225887. {
  225888. @public
  225889. bool clickedOk;
  225890. }
  225891. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225892. @end
  225893. @implementation JuceAlertBoxDelegate
  225894. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225895. {
  225896. clickedOk = (buttonIndex == 0);
  225897. alertView.hidden = true;
  225898. }
  225899. @end
  225900. BEGIN_JUCE_NAMESPACE
  225901. // (This function is used directly by other bits of code)
  225902. bool juce_iPhoneShowModalAlert (const String& title,
  225903. const String& bodyText,
  225904. NSString* okButtonText,
  225905. NSString* cancelButtonText)
  225906. {
  225907. const ScopedAutoReleasePool pool;
  225908. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225909. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225910. message: juceStringToNS (bodyText)
  225911. delegate: callback
  225912. cancelButtonTitle: okButtonText
  225913. otherButtonTitles: cancelButtonText, nil];
  225914. [alert retain];
  225915. [alert show];
  225916. while (! alert.hidden && alert.superview != nil)
  225917. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225918. const bool result = callback->clickedOk;
  225919. [alert release];
  225920. [callback release];
  225921. return result;
  225922. }
  225923. bool AlertWindow::showNativeDialogBox (const String& title,
  225924. const String& bodyText,
  225925. bool isOkCancel)
  225926. {
  225927. return juce_iPhoneShowModalAlert (title, bodyText,
  225928. @"OK",
  225929. isOkCancel ? @"Cancel" : nil);
  225930. }
  225931. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225932. {
  225933. jassertfalse; // no such thing on the iphone!
  225934. return false;
  225935. }
  225936. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225937. {
  225938. jassertfalse; // no such thing on the iphone!
  225939. return false;
  225940. }
  225941. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225942. {
  225943. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225944. }
  225945. bool Desktop::isScreenSaverEnabled()
  225946. {
  225947. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225948. }
  225949. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  225950. {
  225951. const ScopedAutoReleasePool pool;
  225952. monitorCoords.clear();
  225953. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  225954. : [[UIScreen mainScreen] bounds];
  225955. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  225956. (int) r.origin.y,
  225957. (int) r.size.width,
  225958. (int) r.size.height));
  225959. }
  225960. #endif
  225961. #endif
  225962. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225963. #else
  225964. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225965. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225966. // compiled on its own).
  225967. #if JUCE_INCLUDED_FILE
  225968. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225969. {
  225970. pool = [[NSAutoreleasePool alloc] init];
  225971. }
  225972. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225973. {
  225974. [((NSAutoreleasePool*) pool) release];
  225975. }
  225976. void PlatformUtilities::beep()
  225977. {
  225978. NSBeep();
  225979. }
  225980. void PlatformUtilities::addItemToDock (const File& file)
  225981. {
  225982. // check that it's not already there...
  225983. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225984. .containsIgnoreCase (file.getFullPathName()))
  225985. {
  225986. 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>"
  225987. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225988. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225989. }
  225990. }
  225991. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225992. bool AlertWindow::showNativeDialogBox (const String& title,
  225993. const String& bodyText,
  225994. bool isOkCancel)
  225995. {
  225996. const ScopedAutoReleasePool pool;
  225997. return NSRunAlertPanel (juceStringToNS (title),
  225998. juceStringToNS (bodyText),
  225999. @"Ok",
  226000. isOkCancel ? @"Cancel" : nil,
  226001. nil) == NSAlertDefaultReturn;
  226002. }
  226003. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226004. {
  226005. if (files.size() == 0)
  226006. return false;
  226007. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226008. if (draggingSource == 0)
  226009. {
  226010. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226011. return false;
  226012. }
  226013. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226014. if (sourceComp == 0)
  226015. {
  226016. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226017. return false;
  226018. }
  226019. const ScopedAutoReleasePool pool;
  226020. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226021. if (view == 0)
  226022. return false;
  226023. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226024. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226025. owner: nil];
  226026. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226027. for (int i = 0; i < files.size(); ++i)
  226028. [filesArray addObject: juceStringToNS (files[i])];
  226029. [pboard setPropertyList: filesArray
  226030. forType: NSFilenamesPboardType];
  226031. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226032. fromView: nil];
  226033. dragPosition.x -= 16;
  226034. dragPosition.y -= 16;
  226035. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226036. at: dragPosition
  226037. offset: NSMakeSize (0, 0)
  226038. event: [[view window] currentEvent]
  226039. pasteboard: pboard
  226040. source: view
  226041. slideBack: YES];
  226042. return true;
  226043. }
  226044. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226045. {
  226046. jassertfalse; // not implemented!
  226047. return false;
  226048. }
  226049. bool Desktop::canUseSemiTransparentWindows() throw()
  226050. {
  226051. return true;
  226052. }
  226053. const Point<int> Desktop::getMousePosition()
  226054. {
  226055. const ScopedAutoReleasePool pool;
  226056. const NSPoint p ([NSEvent mouseLocation]);
  226057. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226058. }
  226059. void Desktop::setMousePosition (const Point<int>& newPosition)
  226060. {
  226061. // this rubbish needs to be done around the warp call, to avoid causing a
  226062. // bizarre glitch..
  226063. CGAssociateMouseAndMouseCursorPosition (false);
  226064. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226065. CGAssociateMouseAndMouseCursorPosition (true);
  226066. }
  226067. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226068. class ScreenSaverDefeater : public Timer,
  226069. public DeletedAtShutdown
  226070. {
  226071. public:
  226072. ScreenSaverDefeater()
  226073. {
  226074. startTimer (10000);
  226075. timerCallback();
  226076. }
  226077. ~ScreenSaverDefeater() {}
  226078. void timerCallback()
  226079. {
  226080. if (Process::isForegroundProcess())
  226081. UpdateSystemActivity (UsrActivity);
  226082. }
  226083. };
  226084. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226085. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226086. {
  226087. if (isEnabled)
  226088. deleteAndZero (screenSaverDefeater);
  226089. else if (screenSaverDefeater == 0)
  226090. screenSaverDefeater = new ScreenSaverDefeater();
  226091. }
  226092. bool Desktop::isScreenSaverEnabled()
  226093. {
  226094. return screenSaverDefeater == 0;
  226095. }
  226096. #else
  226097. static IOPMAssertionID screenSaverDisablerID = 0;
  226098. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226099. {
  226100. if (isEnabled)
  226101. {
  226102. if (screenSaverDisablerID != 0)
  226103. {
  226104. IOPMAssertionRelease (screenSaverDisablerID);
  226105. screenSaverDisablerID = 0;
  226106. }
  226107. }
  226108. else
  226109. {
  226110. if (screenSaverDisablerID == 0)
  226111. {
  226112. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226113. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226114. CFSTR ("Juce"), &screenSaverDisablerID);
  226115. #else
  226116. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226117. &screenSaverDisablerID);
  226118. #endif
  226119. }
  226120. }
  226121. }
  226122. bool Desktop::isScreenSaverEnabled()
  226123. {
  226124. return screenSaverDisablerID == 0;
  226125. }
  226126. #endif
  226127. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226128. {
  226129. const ScopedAutoReleasePool pool;
  226130. monitorCoords.clear();
  226131. NSArray* screens = [NSScreen screens];
  226132. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226133. for (unsigned int i = 0; i < [screens count]; ++i)
  226134. {
  226135. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226136. NSRect r = clipToWorkArea ? [s visibleFrame]
  226137. : [s frame];
  226138. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226139. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226140. (int) r.size.width,
  226141. (int) r.size.height));
  226142. }
  226143. jassert (monitorCoords.size() > 0);
  226144. }
  226145. #endif
  226146. #endif
  226147. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226148. #endif
  226149. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226150. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226151. // compiled on its own).
  226152. #if JUCE_INCLUDED_FILE
  226153. void Logger::outputDebugString (const String& text)
  226154. {
  226155. std::cerr << text << std::endl;
  226156. }
  226157. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226158. {
  226159. static char testResult = 0;
  226160. if (testResult == 0)
  226161. {
  226162. struct kinfo_proc info;
  226163. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226164. size_t sz = sizeof (info);
  226165. sysctl (m, 4, &info, &sz, 0, 0);
  226166. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226167. }
  226168. return testResult > 0;
  226169. }
  226170. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226171. {
  226172. return juce_isRunningUnderDebugger();
  226173. }
  226174. #endif
  226175. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226176. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226177. #if JUCE_IOS
  226178. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226179. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226180. // compiled on its own).
  226181. #if JUCE_INCLUDED_FILE
  226182. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226183. #define SUPPORT_10_4_FONTS 1
  226184. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226185. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226186. #define SUPPORT_ONLY_10_4_FONTS 1
  226187. #endif
  226188. END_JUCE_NAMESPACE
  226189. @interface NSFont (PrivateHack)
  226190. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226191. @end
  226192. BEGIN_JUCE_NAMESPACE
  226193. #endif
  226194. class MacTypeface : public Typeface
  226195. {
  226196. public:
  226197. MacTypeface (const Font& font)
  226198. : Typeface (font.getTypefaceName())
  226199. {
  226200. const ScopedAutoReleasePool pool;
  226201. renderingTransform = CGAffineTransformIdentity;
  226202. bool needsItalicTransform = false;
  226203. #if JUCE_IOS
  226204. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226205. if (font.isItalic() || font.isBold())
  226206. {
  226207. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226208. for (NSString* i in familyFonts)
  226209. {
  226210. const String fn (nsStringToJuce (i));
  226211. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226212. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226213. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226214. || afterDash.containsIgnoreCase ("italic")
  226215. || fn.endsWithIgnoreCase ("oblique")
  226216. || fn.endsWithIgnoreCase ("italic");
  226217. if (probablyBold == font.isBold()
  226218. && probablyItalic == font.isItalic())
  226219. {
  226220. fontName = i;
  226221. needsItalicTransform = false;
  226222. break;
  226223. }
  226224. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226225. {
  226226. fontName = i;
  226227. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226228. }
  226229. }
  226230. if (needsItalicTransform)
  226231. renderingTransform.c = 0.15f;
  226232. }
  226233. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226234. const int ascender = abs (CGFontGetAscent (fontRef));
  226235. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226236. ascent = ascender / totalHeight;
  226237. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226238. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226239. #else
  226240. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226241. if (font.isItalic())
  226242. {
  226243. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226244. toHaveTrait: NSItalicFontMask];
  226245. if (newFont == nsFont)
  226246. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226247. nsFont = newFont;
  226248. }
  226249. if (font.isBold())
  226250. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226251. [nsFont retain];
  226252. ascent = std::abs ((float) [nsFont ascender]);
  226253. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226254. ascent /= totalSize;
  226255. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226256. if (needsItalicTransform)
  226257. {
  226258. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226259. renderingTransform.c = 0.15f;
  226260. }
  226261. #if SUPPORT_ONLY_10_4_FONTS
  226262. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226263. if (atsFont == 0)
  226264. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226265. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226266. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226267. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226268. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226269. #else
  226270. #if SUPPORT_10_4_FONTS
  226271. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226272. {
  226273. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226274. if (atsFont == 0)
  226275. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226276. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226277. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226278. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226279. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226280. }
  226281. else
  226282. #endif
  226283. {
  226284. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226285. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226286. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226287. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226288. }
  226289. #endif
  226290. #endif
  226291. }
  226292. ~MacTypeface()
  226293. {
  226294. #if ! JUCE_IOS
  226295. [nsFont release];
  226296. #endif
  226297. if (fontRef != 0)
  226298. CGFontRelease (fontRef);
  226299. }
  226300. float getAscent() const
  226301. {
  226302. return ascent;
  226303. }
  226304. float getDescent() const
  226305. {
  226306. return 1.0f - ascent;
  226307. }
  226308. float getStringWidth (const String& text)
  226309. {
  226310. if (fontRef == 0 || text.isEmpty())
  226311. return 0;
  226312. const int length = text.length();
  226313. HeapBlock <CGGlyph> glyphs;
  226314. createGlyphsForString (text, length, glyphs);
  226315. float x = 0;
  226316. #if SUPPORT_ONLY_10_4_FONTS
  226317. HeapBlock <NSSize> advances (length);
  226318. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226319. for (int i = 0; i < length; ++i)
  226320. x += advances[i].width;
  226321. #else
  226322. #if SUPPORT_10_4_FONTS
  226323. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226324. {
  226325. HeapBlock <NSSize> advances (length);
  226326. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226327. for (int i = 0; i < length; ++i)
  226328. x += advances[i].width;
  226329. }
  226330. else
  226331. #endif
  226332. {
  226333. HeapBlock <int> advances (length);
  226334. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226335. for (int i = 0; i < length; ++i)
  226336. x += advances[i];
  226337. }
  226338. #endif
  226339. return x * unitsToHeightScaleFactor;
  226340. }
  226341. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226342. {
  226343. xOffsets.add (0);
  226344. if (fontRef == 0 || text.isEmpty())
  226345. return;
  226346. const int length = text.length();
  226347. HeapBlock <CGGlyph> glyphs;
  226348. createGlyphsForString (text, length, glyphs);
  226349. #if SUPPORT_ONLY_10_4_FONTS
  226350. HeapBlock <NSSize> advances (length);
  226351. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226352. int x = 0;
  226353. for (int i = 0; i < length; ++i)
  226354. {
  226355. x += advances[i].width;
  226356. xOffsets.add (x * unitsToHeightScaleFactor);
  226357. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226358. }
  226359. #else
  226360. #if SUPPORT_10_4_FONTS
  226361. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226362. {
  226363. HeapBlock <NSSize> advances (length);
  226364. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226365. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226366. float x = 0;
  226367. for (int i = 0; i < length; ++i)
  226368. {
  226369. x += advances[i].width;
  226370. xOffsets.add (x * unitsToHeightScaleFactor);
  226371. resultGlyphs.add (nsGlyphs[i]);
  226372. }
  226373. }
  226374. else
  226375. #endif
  226376. {
  226377. HeapBlock <int> advances (length);
  226378. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226379. {
  226380. int x = 0;
  226381. for (int i = 0; i < length; ++i)
  226382. {
  226383. x += advances [i];
  226384. xOffsets.add (x * unitsToHeightScaleFactor);
  226385. resultGlyphs.add (glyphs[i]);
  226386. }
  226387. }
  226388. }
  226389. #endif
  226390. }
  226391. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226392. {
  226393. #if JUCE_IOS
  226394. return false;
  226395. #else
  226396. if (nsFont == 0)
  226397. return false;
  226398. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226399. jassert (path.isEmpty());
  226400. const ScopedAutoReleasePool pool;
  226401. NSBezierPath* bez = [NSBezierPath bezierPath];
  226402. [bez moveToPoint: NSMakePoint (0, 0)];
  226403. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226404. inFont: nsFont];
  226405. for (int i = 0; i < [bez elementCount]; ++i)
  226406. {
  226407. NSPoint p[3];
  226408. switch ([bez elementAtIndex: i associatedPoints: p])
  226409. {
  226410. case NSMoveToBezierPathElement:
  226411. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226412. break;
  226413. case NSLineToBezierPathElement:
  226414. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226415. break;
  226416. case NSCurveToBezierPathElement:
  226417. 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);
  226418. break;
  226419. case NSClosePathBezierPathElement:
  226420. path.closeSubPath();
  226421. break;
  226422. default:
  226423. jassertfalse;
  226424. break;
  226425. }
  226426. }
  226427. path.applyTransform (pathTransform);
  226428. return true;
  226429. #endif
  226430. }
  226431. juce_UseDebuggingNewOperator
  226432. CGFontRef fontRef;
  226433. float fontHeightToCGSizeFactor;
  226434. CGAffineTransform renderingTransform;
  226435. private:
  226436. float ascent, unitsToHeightScaleFactor;
  226437. #if JUCE_IOS
  226438. #else
  226439. NSFont* nsFont;
  226440. AffineTransform pathTransform;
  226441. #endif
  226442. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226443. {
  226444. #if SUPPORT_10_4_FONTS
  226445. #if ! SUPPORT_ONLY_10_4_FONTS
  226446. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226447. #endif
  226448. {
  226449. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226450. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226451. for (int i = 0; i < length; ++i)
  226452. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226453. return;
  226454. }
  226455. #endif
  226456. #if ! SUPPORT_ONLY_10_4_FONTS
  226457. if (charToGlyphMapper == 0)
  226458. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226459. glyphs.malloc (length);
  226460. for (int i = 0; i < length; ++i)
  226461. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226462. #endif
  226463. }
  226464. #if ! SUPPORT_ONLY_10_4_FONTS
  226465. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226466. class CharToGlyphMapper
  226467. {
  226468. public:
  226469. CharToGlyphMapper (CGFontRef fontRef)
  226470. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226471. idRangeOffset (0), glyphIndexes (0)
  226472. {
  226473. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226474. if (cmapTable != 0)
  226475. {
  226476. const int numSubtables = getValue16 (cmapTable, 2);
  226477. for (int i = 0; i < numSubtables; ++i)
  226478. {
  226479. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226480. {
  226481. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226482. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226483. {
  226484. const int length = getValue16 (cmapTable, offset + 2);
  226485. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226486. segCount = segCountX2 / 2;
  226487. const int endCodeOffset = offset + 14;
  226488. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226489. const int idDeltaOffset = startCodeOffset + segCountX2;
  226490. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226491. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226492. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226493. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226494. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226495. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226496. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226497. }
  226498. break;
  226499. }
  226500. }
  226501. CFRelease (cmapTable);
  226502. }
  226503. }
  226504. ~CharToGlyphMapper()
  226505. {
  226506. if (endCode != 0)
  226507. {
  226508. CFRelease (endCode);
  226509. CFRelease (startCode);
  226510. CFRelease (idDelta);
  226511. CFRelease (idRangeOffset);
  226512. CFRelease (glyphIndexes);
  226513. }
  226514. }
  226515. int getGlyphForCharacter (const juce_wchar c) const
  226516. {
  226517. for (int i = 0; i < segCount; ++i)
  226518. {
  226519. if (getValue16 (endCode, i * 2) >= c)
  226520. {
  226521. const int start = getValue16 (startCode, i * 2);
  226522. if (start > c)
  226523. break;
  226524. const int delta = getValue16 (idDelta, i * 2);
  226525. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226526. if (rangeOffset == 0)
  226527. return delta + c;
  226528. else
  226529. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226530. }
  226531. }
  226532. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226533. return jmax (-1, (int) c - 29);
  226534. }
  226535. private:
  226536. int segCount;
  226537. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226538. static uint16 getValue16 (CFDataRef data, const int index)
  226539. {
  226540. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226541. }
  226542. static uint32 getValue32 (CFDataRef data, const int index)
  226543. {
  226544. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226545. }
  226546. };
  226547. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226548. #endif
  226549. MacTypeface (const MacTypeface&);
  226550. MacTypeface& operator= (const MacTypeface&);
  226551. };
  226552. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226553. {
  226554. return new MacTypeface (font);
  226555. }
  226556. const StringArray Font::findAllTypefaceNames()
  226557. {
  226558. StringArray names;
  226559. const ScopedAutoReleasePool pool;
  226560. #if JUCE_IOS
  226561. NSArray* fonts = [UIFont familyNames];
  226562. #else
  226563. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226564. #endif
  226565. for (unsigned int i = 0; i < [fonts count]; ++i)
  226566. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226567. names.sort (true);
  226568. return names;
  226569. }
  226570. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226571. {
  226572. #if JUCE_IOS
  226573. defaultSans = "Helvetica";
  226574. defaultSerif = "Times New Roman";
  226575. defaultFixed = "Courier New";
  226576. #else
  226577. defaultSans = "Lucida Grande";
  226578. defaultSerif = "Times New Roman";
  226579. defaultFixed = "Monaco";
  226580. #endif
  226581. }
  226582. #endif
  226583. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226584. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226585. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226586. // compiled on its own).
  226587. #if JUCE_INCLUDED_FILE
  226588. class CoreGraphicsImage : public Image::SharedImage
  226589. {
  226590. public:
  226591. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226592. : Image::SharedImage (format_, width_, height_)
  226593. {
  226594. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226595. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226596. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226597. imageData = imageDataAllocated;
  226598. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226599. : CGColorSpaceCreateDeviceRGB();
  226600. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226601. colourSpace, getCGImageFlags (format_));
  226602. CGColorSpaceRelease (colourSpace);
  226603. }
  226604. ~CoreGraphicsImage()
  226605. {
  226606. CGContextRelease (context);
  226607. }
  226608. Image::ImageType getType() const { return Image::NativeImage; }
  226609. LowLevelGraphicsContext* createLowLevelContext();
  226610. SharedImage* clone()
  226611. {
  226612. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226613. memcpy (im->imageData, imageData, lineStride * height);
  226614. return im;
  226615. }
  226616. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226617. {
  226618. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226619. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226620. {
  226621. return CGBitmapContextCreateImage (nativeImage->context);
  226622. }
  226623. else
  226624. {
  226625. const Image::BitmapData srcData (juceImage, false);
  226626. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226627. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226628. 8, srcData.pixelStride * 8, srcData.lineStride,
  226629. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226630. 0, true, kCGRenderingIntentDefault);
  226631. CGDataProviderRelease (provider);
  226632. return imageRef;
  226633. }
  226634. }
  226635. #if JUCE_MAC
  226636. static NSImage* createNSImage (const Image& image)
  226637. {
  226638. const ScopedAutoReleasePool pool;
  226639. NSImage* im = [[NSImage alloc] init];
  226640. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226641. [im lockFocus];
  226642. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226643. CGImageRef imageRef = createImage (image, false, colourSpace);
  226644. CGColorSpaceRelease (colourSpace);
  226645. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226646. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226647. CGImageRelease (imageRef);
  226648. [im unlockFocus];
  226649. return im;
  226650. }
  226651. #endif
  226652. CGContextRef context;
  226653. HeapBlock<uint8> imageDataAllocated;
  226654. private:
  226655. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226656. {
  226657. #if JUCE_BIG_ENDIAN
  226658. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226659. #else
  226660. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226661. #endif
  226662. }
  226663. };
  226664. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226665. {
  226666. #if USE_COREGRAPHICS_RENDERING
  226667. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226668. #else
  226669. return createSoftwareImage (format, width, height, clearImage);
  226670. #endif
  226671. }
  226672. class CoreGraphicsContext : public LowLevelGraphicsContext
  226673. {
  226674. public:
  226675. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226676. : context (context_),
  226677. flipHeight (flipHeight_),
  226678. state (new SavedState()),
  226679. numGradientLookupEntries (0),
  226680. lastClipRectIsValid (false)
  226681. {
  226682. CGContextRetain (context);
  226683. CGContextSaveGState(context);
  226684. CGContextSetShouldSmoothFonts (context, true);
  226685. CGContextSetShouldAntialias (context, true);
  226686. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226687. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226688. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226689. gradientCallbacks.version = 0;
  226690. gradientCallbacks.evaluate = gradientCallback;
  226691. gradientCallbacks.releaseInfo = 0;
  226692. setFont (Font());
  226693. }
  226694. ~CoreGraphicsContext()
  226695. {
  226696. CGContextRestoreGState (context);
  226697. CGContextRelease (context);
  226698. CGColorSpaceRelease (rgbColourSpace);
  226699. CGColorSpaceRelease (greyColourSpace);
  226700. }
  226701. bool isVectorDevice() const { return false; }
  226702. void setOrigin (int x, int y)
  226703. {
  226704. CGContextTranslateCTM (context, x, -y);
  226705. if (lastClipRectIsValid)
  226706. lastClipRect.translate (-x, -y);
  226707. }
  226708. bool clipToRectangle (const Rectangle<int>& r)
  226709. {
  226710. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226711. if (lastClipRectIsValid)
  226712. {
  226713. // This is actually incorrect, because the actual clip region may be complex, and
  226714. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226715. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226716. // when calculating the resultant clip bounds, and makes the same mistake!
  226717. lastClipRect = lastClipRect.getIntersection (r);
  226718. return ! lastClipRect.isEmpty();
  226719. }
  226720. return ! isClipEmpty();
  226721. }
  226722. bool clipToRectangleList (const RectangleList& clipRegion)
  226723. {
  226724. if (clipRegion.isEmpty())
  226725. {
  226726. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226727. lastClipRectIsValid = true;
  226728. lastClipRect = Rectangle<int>();
  226729. return false;
  226730. }
  226731. else
  226732. {
  226733. const int numRects = clipRegion.getNumRectangles();
  226734. HeapBlock <CGRect> rects (numRects);
  226735. for (int i = 0; i < numRects; ++i)
  226736. {
  226737. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226738. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226739. }
  226740. CGContextClipToRects (context, rects, numRects);
  226741. lastClipRectIsValid = false;
  226742. return ! isClipEmpty();
  226743. }
  226744. }
  226745. void excludeClipRectangle (const Rectangle<int>& r)
  226746. {
  226747. RectangleList remaining (getClipBounds());
  226748. remaining.subtract (r);
  226749. clipToRectangleList (remaining);
  226750. lastClipRectIsValid = false;
  226751. }
  226752. void clipToPath (const Path& path, const AffineTransform& transform)
  226753. {
  226754. createPath (path, transform);
  226755. CGContextClip (context);
  226756. lastClipRectIsValid = false;
  226757. }
  226758. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226759. {
  226760. if (! transform.isSingularity())
  226761. {
  226762. Image singleChannelImage (sourceImage);
  226763. if (sourceImage.getFormat() != Image::SingleChannel)
  226764. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226765. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226766. flip();
  226767. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226768. applyTransform (t);
  226769. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226770. CGContextClipToMask (context, r, image);
  226771. applyTransform (t.inverted());
  226772. flip();
  226773. CGImageRelease (image);
  226774. lastClipRectIsValid = false;
  226775. }
  226776. }
  226777. bool clipRegionIntersects (const Rectangle<int>& r)
  226778. {
  226779. return getClipBounds().intersects (r);
  226780. }
  226781. const Rectangle<int> getClipBounds() const
  226782. {
  226783. if (! lastClipRectIsValid)
  226784. {
  226785. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226786. lastClipRectIsValid = true;
  226787. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226788. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226789. roundToInt (bounds.size.width),
  226790. roundToInt (bounds.size.height));
  226791. }
  226792. return lastClipRect;
  226793. }
  226794. bool isClipEmpty() const
  226795. {
  226796. return getClipBounds().isEmpty();
  226797. }
  226798. void saveState()
  226799. {
  226800. CGContextSaveGState (context);
  226801. stateStack.add (new SavedState (*state));
  226802. }
  226803. void restoreState()
  226804. {
  226805. CGContextRestoreGState (context);
  226806. SavedState* const top = stateStack.getLast();
  226807. if (top != 0)
  226808. {
  226809. state = top;
  226810. stateStack.removeLast (1, false);
  226811. lastClipRectIsValid = false;
  226812. }
  226813. else
  226814. {
  226815. jassertfalse; // trying to pop with an empty stack!
  226816. }
  226817. }
  226818. void setFill (const FillType& fillType)
  226819. {
  226820. state->fillType = fillType;
  226821. if (fillType.isColour())
  226822. {
  226823. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226824. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226825. CGContextSetAlpha (context, 1.0f);
  226826. }
  226827. }
  226828. void setOpacity (float newOpacity)
  226829. {
  226830. state->fillType.setOpacity (newOpacity);
  226831. setFill (state->fillType);
  226832. }
  226833. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226834. {
  226835. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226836. ? kCGInterpolationLow
  226837. : kCGInterpolationHigh);
  226838. }
  226839. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226840. {
  226841. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226842. }
  226843. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226844. {
  226845. if (replaceExistingContents)
  226846. {
  226847. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226848. CGContextClearRect (context, cgRect);
  226849. #else
  226850. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226851. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226852. CGContextClearRect (context, cgRect);
  226853. else
  226854. #endif
  226855. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226856. #endif
  226857. fillCGRect (cgRect, false);
  226858. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226859. }
  226860. else
  226861. {
  226862. if (state->fillType.isColour())
  226863. {
  226864. CGContextFillRect (context, cgRect);
  226865. }
  226866. else if (state->fillType.isGradient())
  226867. {
  226868. CGContextSaveGState (context);
  226869. CGContextClipToRect (context, cgRect);
  226870. drawGradient();
  226871. CGContextRestoreGState (context);
  226872. }
  226873. else
  226874. {
  226875. CGContextSaveGState (context);
  226876. CGContextClipToRect (context, cgRect);
  226877. drawImage (state->fillType.image, state->fillType.transform, true);
  226878. CGContextRestoreGState (context);
  226879. }
  226880. }
  226881. }
  226882. void fillPath (const Path& path, const AffineTransform& transform)
  226883. {
  226884. CGContextSaveGState (context);
  226885. if (state->fillType.isColour())
  226886. {
  226887. flip();
  226888. applyTransform (transform);
  226889. createPath (path);
  226890. if (path.isUsingNonZeroWinding())
  226891. CGContextFillPath (context);
  226892. else
  226893. CGContextEOFillPath (context);
  226894. }
  226895. else
  226896. {
  226897. createPath (path, transform);
  226898. if (path.isUsingNonZeroWinding())
  226899. CGContextClip (context);
  226900. else
  226901. CGContextEOClip (context);
  226902. if (state->fillType.isGradient())
  226903. drawGradient();
  226904. else
  226905. drawImage (state->fillType.image, state->fillType.transform, true);
  226906. }
  226907. CGContextRestoreGState (context);
  226908. }
  226909. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226910. {
  226911. const int iw = sourceImage.getWidth();
  226912. const int ih = sourceImage.getHeight();
  226913. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226914. CGContextSaveGState (context);
  226915. CGContextSetAlpha (context, state->fillType.getOpacity());
  226916. flip();
  226917. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226918. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226919. if (fillEntireClipAsTiles)
  226920. {
  226921. #if JUCE_IOS
  226922. CGContextDrawTiledImage (context, imageRect, image);
  226923. #else
  226924. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226925. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226926. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226927. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226928. CGContextDrawTiledImage (context, imageRect, image);
  226929. else
  226930. #endif
  226931. {
  226932. // Fallback to manually doing a tiled fill on 10.4
  226933. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226934. int x = 0, y = 0;
  226935. while (x > clip.origin.x) x -= iw;
  226936. while (y > clip.origin.y) y -= ih;
  226937. const int right = (int) (clip.origin.x + clip.size.width);
  226938. const int bottom = (int) (clip.origin.y + clip.size.height);
  226939. while (y < bottom)
  226940. {
  226941. for (int x2 = x; x2 < right; x2 += iw)
  226942. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226943. y += ih;
  226944. }
  226945. }
  226946. #endif
  226947. }
  226948. else
  226949. {
  226950. CGContextDrawImage (context, imageRect, image);
  226951. }
  226952. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226953. CGContextRestoreGState (context);
  226954. }
  226955. void drawLine (const Line<float>& line)
  226956. {
  226957. if (state->fillType.isColour())
  226958. {
  226959. CGContextSetLineCap (context, kCGLineCapSquare);
  226960. CGContextSetLineWidth (context, 1.0f);
  226961. CGContextSetRGBStrokeColor (context,
  226962. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226963. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226964. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226965. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226966. CGContextStrokeLineSegments (context, cgLine, 1);
  226967. }
  226968. else
  226969. {
  226970. Path p;
  226971. p.addLineSegment (line, 1.0f);
  226972. fillPath (p, AffineTransform::identity);
  226973. }
  226974. }
  226975. void drawVerticalLine (const int x, float top, float bottom)
  226976. {
  226977. if (state->fillType.isColour())
  226978. {
  226979. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226980. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226981. #else
  226982. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226983. // the x co-ord slightly to trick it..
  226984. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226985. #endif
  226986. }
  226987. else
  226988. {
  226989. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226990. }
  226991. }
  226992. void drawHorizontalLine (const int y, float left, float right)
  226993. {
  226994. if (state->fillType.isColour())
  226995. {
  226996. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226997. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226998. #else
  226999. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227000. // the x co-ord slightly to trick it..
  227001. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227002. #endif
  227003. }
  227004. else
  227005. {
  227006. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227007. }
  227008. }
  227009. void setFont (const Font& newFont)
  227010. {
  227011. if (state->font != newFont)
  227012. {
  227013. state->fontRef = 0;
  227014. state->font = newFont;
  227015. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227016. if (mf != 0)
  227017. {
  227018. state->fontRef = mf->fontRef;
  227019. CGContextSetFont (context, state->fontRef);
  227020. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227021. state->fontTransform = mf->renderingTransform;
  227022. state->fontTransform.a *= state->font.getHorizontalScale();
  227023. CGContextSetTextMatrix (context, state->fontTransform);
  227024. }
  227025. }
  227026. }
  227027. const Font getFont()
  227028. {
  227029. return state->font;
  227030. }
  227031. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227032. {
  227033. if (state->fontRef != 0 && state->fillType.isColour())
  227034. {
  227035. if (transform.isOnlyTranslation())
  227036. {
  227037. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227038. CGGlyph g = glyphNumber;
  227039. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227040. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227041. }
  227042. else
  227043. {
  227044. CGContextSaveGState (context);
  227045. flip();
  227046. applyTransform (transform);
  227047. CGAffineTransform t = state->fontTransform;
  227048. t.d = -t.d;
  227049. CGContextSetTextMatrix (context, t);
  227050. CGGlyph g = glyphNumber;
  227051. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227052. CGContextRestoreGState (context);
  227053. }
  227054. }
  227055. else
  227056. {
  227057. Path p;
  227058. Font& f = state->font;
  227059. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227060. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227061. .followedBy (transform));
  227062. }
  227063. }
  227064. private:
  227065. CGContextRef context;
  227066. const CGFloat flipHeight;
  227067. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227068. CGFunctionCallbacks gradientCallbacks;
  227069. mutable Rectangle<int> lastClipRect;
  227070. mutable bool lastClipRectIsValid;
  227071. struct SavedState
  227072. {
  227073. SavedState()
  227074. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227075. {
  227076. }
  227077. SavedState (const SavedState& other)
  227078. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227079. fontTransform (other.fontTransform)
  227080. {
  227081. }
  227082. ~SavedState()
  227083. {
  227084. }
  227085. FillType fillType;
  227086. Font font;
  227087. CGFontRef fontRef;
  227088. CGAffineTransform fontTransform;
  227089. };
  227090. ScopedPointer <SavedState> state;
  227091. OwnedArray <SavedState> stateStack;
  227092. HeapBlock <PixelARGB> gradientLookupTable;
  227093. int numGradientLookupEntries;
  227094. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227095. {
  227096. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227097. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227098. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227099. colour.unpremultiply();
  227100. outData[0] = colour.getRed() / 255.0f;
  227101. outData[1] = colour.getGreen() / 255.0f;
  227102. outData[2] = colour.getBlue() / 255.0f;
  227103. outData[3] = colour.getAlpha() / 255.0f;
  227104. }
  227105. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227106. {
  227107. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227108. --numGradientLookupEntries;
  227109. CGShadingRef result = 0;
  227110. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227111. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227112. if (gradient.isRadial)
  227113. {
  227114. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227115. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227116. function, true, true);
  227117. }
  227118. else
  227119. {
  227120. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227121. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227122. function, true, true);
  227123. }
  227124. CGFunctionRelease (function);
  227125. return result;
  227126. }
  227127. void drawGradient()
  227128. {
  227129. flip();
  227130. applyTransform (state->fillType.transform);
  227131. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227132. // you draw a gradient with high quality interp enabled).
  227133. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227134. CGContextSetAlpha (context, state->fillType.getOpacity());
  227135. CGContextDrawShading (context, shading);
  227136. CGShadingRelease (shading);
  227137. }
  227138. void createPath (const Path& path) const
  227139. {
  227140. CGContextBeginPath (context);
  227141. Path::Iterator i (path);
  227142. while (i.next())
  227143. {
  227144. switch (i.elementType)
  227145. {
  227146. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227147. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227148. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227149. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227150. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227151. default: jassertfalse; break;
  227152. }
  227153. }
  227154. }
  227155. void createPath (const Path& path, const AffineTransform& transform) const
  227156. {
  227157. CGContextBeginPath (context);
  227158. Path::Iterator i (path);
  227159. while (i.next())
  227160. {
  227161. switch (i.elementType)
  227162. {
  227163. case Path::Iterator::startNewSubPath:
  227164. transform.transformPoint (i.x1, i.y1);
  227165. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227166. break;
  227167. case Path::Iterator::lineTo:
  227168. transform.transformPoint (i.x1, i.y1);
  227169. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227170. break;
  227171. case Path::Iterator::quadraticTo:
  227172. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227173. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227174. break;
  227175. case Path::Iterator::cubicTo:
  227176. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227177. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227178. break;
  227179. case Path::Iterator::closePath:
  227180. CGContextClosePath (context); break;
  227181. default:
  227182. jassertfalse;
  227183. break;
  227184. }
  227185. }
  227186. }
  227187. void flip() const
  227188. {
  227189. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227190. }
  227191. void applyTransform (const AffineTransform& transform) const
  227192. {
  227193. CGAffineTransform t;
  227194. t.a = transform.mat00;
  227195. t.b = transform.mat10;
  227196. t.c = transform.mat01;
  227197. t.d = transform.mat11;
  227198. t.tx = transform.mat02;
  227199. t.ty = transform.mat12;
  227200. CGContextConcatCTM (context, t);
  227201. }
  227202. CoreGraphicsContext (const CoreGraphicsContext&);
  227203. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227204. };
  227205. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227206. {
  227207. return new CoreGraphicsContext (context, height);
  227208. }
  227209. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227210. const Image juce_loadWithCoreImage (InputStream& input)
  227211. {
  227212. MemoryBlock data;
  227213. input.readIntoMemoryBlock (data, -1);
  227214. #if JUCE_IOS
  227215. JUCE_AUTORELEASEPOOL
  227216. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227217. length: data.getSize()
  227218. freeWhenDone: NO]];
  227219. if (image != nil)
  227220. {
  227221. CGImageRef loadedImage = image.CGImage;
  227222. #else
  227223. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227224. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227225. CGDataProviderRelease (provider);
  227226. if (imageSource != 0)
  227227. {
  227228. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227229. CFRelease (imageSource);
  227230. #endif
  227231. if (loadedImage != 0)
  227232. {
  227233. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227234. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227235. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227236. hasAlphaChan, Image::NativeImage);
  227237. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227238. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227239. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227240. CGContextFlush (cgImage->context);
  227241. #if ! JUCE_IOS
  227242. CFRelease (loadedImage);
  227243. #endif
  227244. return image;
  227245. }
  227246. }
  227247. return Image::null;
  227248. }
  227249. #endif
  227250. #endif
  227251. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227252. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227253. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227254. // compiled on its own).
  227255. #if JUCE_INCLUDED_FILE
  227256. class UIViewComponentPeer;
  227257. END_JUCE_NAMESPACE
  227258. #define JuceUIView MakeObjCClassName(JuceUIView)
  227259. @interface JuceUIView : UIView <UITextViewDelegate>
  227260. {
  227261. @public
  227262. UIViewComponentPeer* owner;
  227263. UITextView* hiddenTextView;
  227264. }
  227265. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227266. - (void) dealloc;
  227267. - (void) drawRect: (CGRect) r;
  227268. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227269. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227270. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227271. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227272. - (BOOL) becomeFirstResponder;
  227273. - (BOOL) resignFirstResponder;
  227274. - (BOOL) canBecomeFirstResponder;
  227275. - (void) asyncRepaint: (id) rect;
  227276. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227277. @end
  227278. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227279. @interface JuceUIWindow : UIWindow
  227280. {
  227281. @private
  227282. UIViewComponentPeer* owner;
  227283. bool isZooming;
  227284. }
  227285. - (void) setOwner: (UIViewComponentPeer*) owner;
  227286. - (void) becomeKeyWindow;
  227287. @end
  227288. BEGIN_JUCE_NAMESPACE
  227289. class UIViewComponentPeer : public ComponentPeer,
  227290. public FocusChangeListener
  227291. {
  227292. public:
  227293. UIViewComponentPeer (Component* const component,
  227294. const int windowStyleFlags,
  227295. UIView* viewToAttachTo);
  227296. ~UIViewComponentPeer();
  227297. void* getNativeHandle() const;
  227298. void setVisible (bool shouldBeVisible);
  227299. void setTitle (const String& title);
  227300. void setPosition (int x, int y);
  227301. void setSize (int w, int h);
  227302. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227303. const Rectangle<int> getBounds() const;
  227304. const Rectangle<int> getBounds (const bool global) const;
  227305. const Point<int> getScreenPosition() const;
  227306. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227307. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227308. void setMinimised (bool shouldBeMinimised);
  227309. bool isMinimised() const;
  227310. void setFullScreen (bool shouldBeFullScreen);
  227311. bool isFullScreen() const;
  227312. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227313. const BorderSize getFrameSize() const;
  227314. bool setAlwaysOnTop (bool alwaysOnTop);
  227315. void toFront (bool makeActiveWindow);
  227316. void toBehind (ComponentPeer* other);
  227317. void setIcon (const Image& newIcon);
  227318. virtual void drawRect (CGRect r);
  227319. virtual bool canBecomeKeyWindow();
  227320. virtual bool windowShouldClose();
  227321. virtual void redirectMovedOrResized();
  227322. virtual CGRect constrainRect (CGRect r);
  227323. virtual void viewFocusGain();
  227324. virtual void viewFocusLoss();
  227325. bool isFocused() const;
  227326. void grabFocus();
  227327. void textInputRequired (const Point<int>& position);
  227328. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227329. void updateHiddenTextContent (TextInputTarget* target);
  227330. void globalFocusChanged (Component*);
  227331. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227332. void repaint (const Rectangle<int>& area);
  227333. void performAnyPendingRepaintsNow();
  227334. juce_UseDebuggingNewOperator
  227335. UIWindow* window;
  227336. JuceUIView* view;
  227337. bool isSharedWindow, fullScreen, insideDrawRect;
  227338. static ModifierKeys currentModifiers;
  227339. static int64 getMouseTime (UIEvent* e)
  227340. {
  227341. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227342. + (int64) ([e timestamp] * 1000.0);
  227343. }
  227344. Array <UITouch*> currentTouches;
  227345. };
  227346. END_JUCE_NAMESPACE
  227347. @implementation JuceUIView
  227348. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227349. withFrame: (CGRect) frame
  227350. {
  227351. [super initWithFrame: frame];
  227352. owner = owner_;
  227353. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227354. [self addSubview: hiddenTextView];
  227355. hiddenTextView.delegate = self;
  227356. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227357. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227358. return self;
  227359. }
  227360. - (void) dealloc
  227361. {
  227362. [hiddenTextView removeFromSuperview];
  227363. [hiddenTextView release];
  227364. [super dealloc];
  227365. }
  227366. - (void) drawRect: (CGRect) r
  227367. {
  227368. if (owner != 0)
  227369. owner->drawRect (r);
  227370. }
  227371. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227372. {
  227373. return false;
  227374. }
  227375. ModifierKeys UIViewComponentPeer::currentModifiers;
  227376. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227377. {
  227378. return UIViewComponentPeer::currentModifiers;
  227379. }
  227380. void ModifierKeys::updateCurrentModifiers() throw()
  227381. {
  227382. currentModifiers = UIViewComponentPeer::currentModifiers;
  227383. }
  227384. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227385. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227386. {
  227387. if (owner != 0)
  227388. owner->handleTouches (event, true, false, false);
  227389. }
  227390. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227391. {
  227392. if (owner != 0)
  227393. owner->handleTouches (event, false, false, false);
  227394. }
  227395. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227396. {
  227397. if (owner != 0)
  227398. owner->handleTouches (event, false, true, false);
  227399. }
  227400. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227401. {
  227402. if (owner != 0)
  227403. owner->handleTouches (event, false, true, true);
  227404. [self touchesEnded: touches withEvent: event];
  227405. }
  227406. - (BOOL) becomeFirstResponder
  227407. {
  227408. if (owner != 0)
  227409. owner->viewFocusGain();
  227410. return true;
  227411. }
  227412. - (BOOL) resignFirstResponder
  227413. {
  227414. if (owner != 0)
  227415. owner->viewFocusLoss();
  227416. return true;
  227417. }
  227418. - (BOOL) canBecomeFirstResponder
  227419. {
  227420. return owner != 0 && owner->canBecomeKeyWindow();
  227421. }
  227422. - (void) asyncRepaint: (id) rect
  227423. {
  227424. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227425. [self setNeedsDisplayInRect: *r];
  227426. }
  227427. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227428. {
  227429. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227430. nsStringToJuce (text));
  227431. }
  227432. @end
  227433. @implementation JuceUIWindow
  227434. - (void) setOwner: (UIViewComponentPeer*) owner_
  227435. {
  227436. owner = owner_;
  227437. isZooming = false;
  227438. }
  227439. - (void) becomeKeyWindow
  227440. {
  227441. [super becomeKeyWindow];
  227442. if (owner != 0)
  227443. owner->grabFocus();
  227444. }
  227445. @end
  227446. BEGIN_JUCE_NAMESPACE
  227447. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227448. const int windowStyleFlags,
  227449. UIView* viewToAttachTo)
  227450. : ComponentPeer (component, windowStyleFlags),
  227451. window (0),
  227452. view (0),
  227453. isSharedWindow (viewToAttachTo != 0),
  227454. fullScreen (false),
  227455. insideDrawRect (false)
  227456. {
  227457. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227458. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227459. if (isSharedWindow)
  227460. {
  227461. window = [viewToAttachTo window];
  227462. [viewToAttachTo addSubview: view];
  227463. setVisible (component->isVisible());
  227464. }
  227465. else
  227466. {
  227467. r.origin.x = (float) component->getX();
  227468. r.origin.y = (float) component->getY();
  227469. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227470. window = [[JuceUIWindow alloc] init];
  227471. window.frame = r;
  227472. window.opaque = component->isOpaque();
  227473. view.opaque = component->isOpaque();
  227474. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227475. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227476. [((JuceUIWindow*) window) setOwner: this];
  227477. if (component->isAlwaysOnTop())
  227478. window.windowLevel = UIWindowLevelAlert;
  227479. [window addSubview: view];
  227480. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227481. view.hidden = ! component->isVisible();
  227482. window.hidden = ! component->isVisible();
  227483. view.multipleTouchEnabled = YES;
  227484. }
  227485. setTitle (component->getName());
  227486. Desktop::getInstance().addFocusChangeListener (this);
  227487. }
  227488. UIViewComponentPeer::~UIViewComponentPeer()
  227489. {
  227490. Desktop::getInstance().removeFocusChangeListener (this);
  227491. view->owner = 0;
  227492. [view removeFromSuperview];
  227493. [view release];
  227494. if (! isSharedWindow)
  227495. {
  227496. [((JuceUIWindow*) window) setOwner: 0];
  227497. [window release];
  227498. }
  227499. }
  227500. void* UIViewComponentPeer::getNativeHandle() const
  227501. {
  227502. return view;
  227503. }
  227504. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227505. {
  227506. view.hidden = ! shouldBeVisible;
  227507. if (! isSharedWindow)
  227508. window.hidden = ! shouldBeVisible;
  227509. }
  227510. void UIViewComponentPeer::setTitle (const String& title)
  227511. {
  227512. // xxx is this possible?
  227513. }
  227514. void UIViewComponentPeer::setPosition (int x, int y)
  227515. {
  227516. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227517. }
  227518. void UIViewComponentPeer::setSize (int w, int h)
  227519. {
  227520. setBounds (component->getX(), component->getY(), w, h, false);
  227521. }
  227522. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227523. {
  227524. fullScreen = isNowFullScreen;
  227525. w = jmax (0, w);
  227526. h = jmax (0, h);
  227527. CGRect r;
  227528. r.origin.x = (float) x;
  227529. r.origin.y = (float) y;
  227530. r.size.width = (float) w;
  227531. r.size.height = (float) h;
  227532. if (isSharedWindow)
  227533. {
  227534. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227535. if ([view frame].size.width != r.size.width
  227536. || [view frame].size.height != r.size.height)
  227537. [view setNeedsDisplay];
  227538. view.frame = r;
  227539. }
  227540. else
  227541. {
  227542. window.frame = r;
  227543. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227544. }
  227545. }
  227546. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227547. {
  227548. CGRect r = [view frame];
  227549. if (global && [view window] != 0)
  227550. {
  227551. r = [view convertRect: r toView: nil];
  227552. CGRect wr = [[view window] frame];
  227553. r.origin.x += wr.origin.x;
  227554. r.origin.y += wr.origin.y;
  227555. }
  227556. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227557. (int) r.size.width, (int) r.size.height);
  227558. }
  227559. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227560. {
  227561. return getBounds (! isSharedWindow);
  227562. }
  227563. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227564. {
  227565. return getBounds (true).getPosition();
  227566. }
  227567. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227568. {
  227569. return relativePosition + getScreenPosition();
  227570. }
  227571. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227572. {
  227573. return screenPosition - getScreenPosition();
  227574. }
  227575. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227576. {
  227577. if (constrainer != 0)
  227578. {
  227579. CGRect current = [window frame];
  227580. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227581. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227582. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227583. (int) r.size.width, (int) r.size.height);
  227584. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227585. (int) current.size.width, (int) current.size.height);
  227586. constrainer->checkBounds (pos, original,
  227587. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227588. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227589. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227590. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227591. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227592. r.origin.x = pos.getX();
  227593. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227594. r.size.width = pos.getWidth();
  227595. r.size.height = pos.getHeight();
  227596. }
  227597. return r;
  227598. }
  227599. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227600. {
  227601. // xxx
  227602. }
  227603. bool UIViewComponentPeer::isMinimised() const
  227604. {
  227605. return false;
  227606. }
  227607. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227608. {
  227609. if (! isSharedWindow)
  227610. {
  227611. Rectangle<int> r (lastNonFullscreenBounds);
  227612. setMinimised (false);
  227613. if (fullScreen != shouldBeFullScreen)
  227614. {
  227615. if (shouldBeFullScreen)
  227616. r = Desktop::getInstance().getMainMonitorArea();
  227617. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227618. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227619. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227620. }
  227621. }
  227622. }
  227623. bool UIViewComponentPeer::isFullScreen() const
  227624. {
  227625. return fullScreen;
  227626. }
  227627. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227628. {
  227629. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227630. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227631. return false;
  227632. CGPoint p;
  227633. p.x = (float) position.getX();
  227634. p.y = (float) position.getY();
  227635. UIView* v = [view hitTest: p withEvent: nil];
  227636. if (trueIfInAChildWindow)
  227637. return v != nil;
  227638. return v == view;
  227639. }
  227640. const BorderSize UIViewComponentPeer::getFrameSize() const
  227641. {
  227642. BorderSize b;
  227643. if (! isSharedWindow)
  227644. {
  227645. CGRect v = [view convertRect: [view frame] toView: nil];
  227646. CGRect w = [window frame];
  227647. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227648. b.setBottom ((int) v.origin.y);
  227649. b.setLeft ((int) v.origin.x);
  227650. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227651. }
  227652. return b;
  227653. }
  227654. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227655. {
  227656. if (! isSharedWindow)
  227657. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227658. return true;
  227659. }
  227660. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227661. {
  227662. if (isSharedWindow)
  227663. [[view superview] bringSubviewToFront: view];
  227664. if (window != 0 && component->isVisible())
  227665. [window makeKeyAndVisible];
  227666. }
  227667. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227668. {
  227669. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227670. jassert (otherPeer != 0); // wrong type of window?
  227671. if (otherPeer != 0)
  227672. {
  227673. if (isSharedWindow)
  227674. {
  227675. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227676. }
  227677. else
  227678. {
  227679. jassertfalse; // don't know how to do this
  227680. }
  227681. }
  227682. }
  227683. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227684. {
  227685. // to do..
  227686. }
  227687. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227688. {
  227689. NSArray* touches = [[event touchesForView: view] allObjects];
  227690. for (unsigned int i = 0; i < [touches count]; ++i)
  227691. {
  227692. UITouch* touch = [touches objectAtIndex: i];
  227693. CGPoint p = [touch locationInView: view];
  227694. const Point<int> pos ((int) p.x, (int) p.y);
  227695. juce_lastMousePos = pos + getScreenPosition();
  227696. const int64 time = getMouseTime (event);
  227697. int touchIndex = currentTouches.indexOf (touch);
  227698. if (touchIndex < 0)
  227699. {
  227700. touchIndex = currentTouches.size();
  227701. currentTouches.add (touch);
  227702. }
  227703. if (isDown)
  227704. {
  227705. currentModifiers = currentModifiers.withoutMouseButtons();
  227706. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227707. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227708. }
  227709. else if (isUp)
  227710. {
  227711. currentModifiers = currentModifiers.withoutMouseButtons();
  227712. currentTouches.remove (touchIndex);
  227713. }
  227714. if (isCancel)
  227715. currentTouches.clear();
  227716. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227717. }
  227718. }
  227719. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227720. void UIViewComponentPeer::viewFocusGain()
  227721. {
  227722. if (currentlyFocusedPeer != this)
  227723. {
  227724. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227725. currentlyFocusedPeer->handleFocusLoss();
  227726. currentlyFocusedPeer = this;
  227727. handleFocusGain();
  227728. }
  227729. }
  227730. void UIViewComponentPeer::viewFocusLoss()
  227731. {
  227732. if (currentlyFocusedPeer == this)
  227733. {
  227734. currentlyFocusedPeer = 0;
  227735. handleFocusLoss();
  227736. }
  227737. }
  227738. void juce_HandleProcessFocusChange()
  227739. {
  227740. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227741. {
  227742. if (Process::isForegroundProcess())
  227743. {
  227744. currentlyFocusedPeer->handleFocusGain();
  227745. ComponentPeer::bringModalComponentToFront();
  227746. }
  227747. else
  227748. {
  227749. currentlyFocusedPeer->handleFocusLoss();
  227750. // turn kiosk mode off if we lose focus..
  227751. Desktop::getInstance().setKioskModeComponent (0);
  227752. }
  227753. }
  227754. }
  227755. bool UIViewComponentPeer::isFocused() const
  227756. {
  227757. return isSharedWindow ? this == currentlyFocusedPeer
  227758. : (window != 0 && [window isKeyWindow]);
  227759. }
  227760. void UIViewComponentPeer::grabFocus()
  227761. {
  227762. if (window != 0)
  227763. {
  227764. [window makeKeyWindow];
  227765. viewFocusGain();
  227766. }
  227767. }
  227768. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227769. {
  227770. }
  227771. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227772. {
  227773. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227774. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227775. }
  227776. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227777. {
  227778. TextInputTarget* const target = findCurrentTextInputTarget();
  227779. if (target != 0)
  227780. {
  227781. const Range<int> currentSelection (target->getHighlightedRegion());
  227782. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227783. if (currentSelection.isEmpty())
  227784. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227785. target->insertTextAtCaret (text);
  227786. updateHiddenTextContent (target);
  227787. }
  227788. return NO;
  227789. }
  227790. void UIViewComponentPeer::globalFocusChanged (Component*)
  227791. {
  227792. TextInputTarget* const target = findCurrentTextInputTarget();
  227793. if (target != 0)
  227794. {
  227795. Component* comp = dynamic_cast<Component*> (target);
  227796. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227797. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227798. updateHiddenTextContent (target);
  227799. [view->hiddenTextView becomeFirstResponder];
  227800. }
  227801. else
  227802. {
  227803. [view->hiddenTextView resignFirstResponder];
  227804. }
  227805. }
  227806. void UIViewComponentPeer::drawRect (CGRect r)
  227807. {
  227808. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227809. return;
  227810. CGContextRef cg = UIGraphicsGetCurrentContext();
  227811. if (! component->isOpaque())
  227812. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227813. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227814. CoreGraphicsContext g (cg, view.bounds.size.height);
  227815. insideDrawRect = true;
  227816. handlePaint (g);
  227817. insideDrawRect = false;
  227818. }
  227819. bool UIViewComponentPeer::canBecomeKeyWindow()
  227820. {
  227821. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227822. }
  227823. bool UIViewComponentPeer::windowShouldClose()
  227824. {
  227825. if (! isValidPeer (this))
  227826. return YES;
  227827. handleUserClosingWindow();
  227828. return NO;
  227829. }
  227830. void UIViewComponentPeer::redirectMovedOrResized()
  227831. {
  227832. handleMovedOrResized();
  227833. }
  227834. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227835. {
  227836. }
  227837. class AsyncRepaintMessage : public CallbackMessage
  227838. {
  227839. public:
  227840. UIViewComponentPeer* const peer;
  227841. const Rectangle<int> rect;
  227842. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227843. : peer (peer_), rect (rect_)
  227844. {
  227845. }
  227846. void messageCallback()
  227847. {
  227848. if (ComponentPeer::isValidPeer (peer))
  227849. peer->repaint (rect);
  227850. }
  227851. };
  227852. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227853. {
  227854. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227855. {
  227856. (new AsyncRepaintMessage (this, area))->post();
  227857. }
  227858. else
  227859. {
  227860. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  227861. (float) area.getWidth(), (float) area.getHeight())];
  227862. }
  227863. }
  227864. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227865. {
  227866. }
  227867. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227868. {
  227869. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227870. }
  227871. const Image juce_createIconForFile (const File& file)
  227872. {
  227873. return Image::null;
  227874. }
  227875. void Desktop::createMouseInputSources()
  227876. {
  227877. for (int i = 0; i < 10; ++i)
  227878. mouseSources.add (new MouseInputSource (i, false));
  227879. }
  227880. bool Desktop::canUseSemiTransparentWindows() throw()
  227881. {
  227882. return true;
  227883. }
  227884. const Point<int> Desktop::getMousePosition()
  227885. {
  227886. return juce_lastMousePos;
  227887. }
  227888. void Desktop::setMousePosition (const Point<int>&)
  227889. {
  227890. }
  227891. const int KeyPress::spaceKey = ' ';
  227892. const int KeyPress::returnKey = 0x0d;
  227893. const int KeyPress::escapeKey = 0x1b;
  227894. const int KeyPress::backspaceKey = 0x7f;
  227895. const int KeyPress::leftKey = 0x1000;
  227896. const int KeyPress::rightKey = 0x1001;
  227897. const int KeyPress::upKey = 0x1002;
  227898. const int KeyPress::downKey = 0x1003;
  227899. const int KeyPress::pageUpKey = 0x1004;
  227900. const int KeyPress::pageDownKey = 0x1005;
  227901. const int KeyPress::endKey = 0x1006;
  227902. const int KeyPress::homeKey = 0x1007;
  227903. const int KeyPress::deleteKey = 0x1008;
  227904. const int KeyPress::insertKey = -1;
  227905. const int KeyPress::tabKey = 9;
  227906. const int KeyPress::F1Key = 0x2001;
  227907. const int KeyPress::F2Key = 0x2002;
  227908. const int KeyPress::F3Key = 0x2003;
  227909. const int KeyPress::F4Key = 0x2004;
  227910. const int KeyPress::F5Key = 0x2005;
  227911. const int KeyPress::F6Key = 0x2006;
  227912. const int KeyPress::F7Key = 0x2007;
  227913. const int KeyPress::F8Key = 0x2008;
  227914. const int KeyPress::F9Key = 0x2009;
  227915. const int KeyPress::F10Key = 0x200a;
  227916. const int KeyPress::F11Key = 0x200b;
  227917. const int KeyPress::F12Key = 0x200c;
  227918. const int KeyPress::F13Key = 0x200d;
  227919. const int KeyPress::F14Key = 0x200e;
  227920. const int KeyPress::F15Key = 0x200f;
  227921. const int KeyPress::F16Key = 0x2010;
  227922. const int KeyPress::numberPad0 = 0x30020;
  227923. const int KeyPress::numberPad1 = 0x30021;
  227924. const int KeyPress::numberPad2 = 0x30022;
  227925. const int KeyPress::numberPad3 = 0x30023;
  227926. const int KeyPress::numberPad4 = 0x30024;
  227927. const int KeyPress::numberPad5 = 0x30025;
  227928. const int KeyPress::numberPad6 = 0x30026;
  227929. const int KeyPress::numberPad7 = 0x30027;
  227930. const int KeyPress::numberPad8 = 0x30028;
  227931. const int KeyPress::numberPad9 = 0x30029;
  227932. const int KeyPress::numberPadAdd = 0x3002a;
  227933. const int KeyPress::numberPadSubtract = 0x3002b;
  227934. const int KeyPress::numberPadMultiply = 0x3002c;
  227935. const int KeyPress::numberPadDivide = 0x3002d;
  227936. const int KeyPress::numberPadSeparator = 0x3002e;
  227937. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227938. const int KeyPress::numberPadEquals = 0x30030;
  227939. const int KeyPress::numberPadDelete = 0x30031;
  227940. const int KeyPress::playKey = 0x30000;
  227941. const int KeyPress::stopKey = 0x30001;
  227942. const int KeyPress::fastForwardKey = 0x30002;
  227943. const int KeyPress::rewindKey = 0x30003;
  227944. #endif
  227945. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227946. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227947. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227948. // compiled on its own).
  227949. #if JUCE_INCLUDED_FILE
  227950. struct CallbackMessagePayload
  227951. {
  227952. MessageCallbackFunction* function;
  227953. void* parameter;
  227954. void* volatile result;
  227955. bool volatile hasBeenExecuted;
  227956. };
  227957. END_JUCE_NAMESPACE
  227958. @interface JuceCustomMessageHandler : NSObject
  227959. {
  227960. }
  227961. - (void) performCallback: (id) info;
  227962. @end
  227963. @implementation JuceCustomMessageHandler
  227964. - (void) performCallback: (id) info
  227965. {
  227966. if ([info isKindOfClass: [NSData class]])
  227967. {
  227968. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227969. if (pl != 0)
  227970. {
  227971. pl->result = (*pl->function) (pl->parameter);
  227972. pl->hasBeenExecuted = true;
  227973. }
  227974. }
  227975. else
  227976. {
  227977. jassertfalse; // should never get here!
  227978. }
  227979. }
  227980. @end
  227981. BEGIN_JUCE_NAMESPACE
  227982. void MessageManager::runDispatchLoop()
  227983. {
  227984. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227985. runDispatchLoopUntil (-1);
  227986. }
  227987. void MessageManager::stopDispatchLoop()
  227988. {
  227989. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227990. exit (0); // iPhone apps get no mercy..
  227991. }
  227992. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227993. {
  227994. const ScopedAutoReleasePool pool;
  227995. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227996. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227997. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227998. while (! quitMessagePosted)
  227999. {
  228000. const ScopedAutoReleasePool pool;
  228001. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228002. beforeDate: endDate];
  228003. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228004. break;
  228005. }
  228006. return ! quitMessagePosted;
  228007. }
  228008. static CFRunLoopRef runLoop = 0;
  228009. static CFRunLoopSourceRef runLoopSource = 0;
  228010. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228011. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228012. static void runLoopSourceCallback (void*)
  228013. {
  228014. if (pendingMessages != 0)
  228015. {
  228016. int numDispatched = 0;
  228017. do
  228018. {
  228019. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228020. if (nextMessage == 0)
  228021. return;
  228022. const ScopedAutoReleasePool pool;
  228023. MessageManager::getInstance()->deliverMessage (nextMessage);
  228024. } while (++numDispatched <= 4);
  228025. CFRunLoopSourceSignal (runLoopSource);
  228026. CFRunLoopWakeUp (runLoop);
  228027. }
  228028. }
  228029. void MessageManager::doPlatformSpecificInitialisation()
  228030. {
  228031. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228032. runLoop = CFRunLoopGetCurrent();
  228033. CFRunLoopSourceContext sourceContext;
  228034. zerostruct (sourceContext);
  228035. sourceContext.perform = runLoopSourceCallback;
  228036. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228037. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228038. if (juceCustomMessageHandler == 0)
  228039. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228040. }
  228041. void MessageManager::doPlatformSpecificShutdown()
  228042. {
  228043. CFRunLoopSourceInvalidate (runLoopSource);
  228044. CFRelease (runLoopSource);
  228045. runLoopSource = 0;
  228046. deleteAndZero (pendingMessages);
  228047. if (juceCustomMessageHandler != 0)
  228048. {
  228049. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228050. [juceCustomMessageHandler release];
  228051. juceCustomMessageHandler = 0;
  228052. }
  228053. }
  228054. bool juce_postMessageToSystemQueue (Message* message)
  228055. {
  228056. if (pendingMessages != 0)
  228057. {
  228058. pendingMessages->add (message);
  228059. CFRunLoopSourceSignal (runLoopSource);
  228060. CFRunLoopWakeUp (runLoop);
  228061. }
  228062. return true;
  228063. }
  228064. void MessageManager::broadcastMessage (const String& value)
  228065. {
  228066. }
  228067. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228068. {
  228069. if (isThisTheMessageThread())
  228070. {
  228071. return (*callback) (data);
  228072. }
  228073. else
  228074. {
  228075. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228076. // deadlock because the message manager is blocked from running, so can never
  228077. // call your function..
  228078. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228079. const ScopedAutoReleasePool pool;
  228080. CallbackMessagePayload cmp;
  228081. cmp.function = callback;
  228082. cmp.parameter = data;
  228083. cmp.result = 0;
  228084. cmp.hasBeenExecuted = false;
  228085. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228086. withObject: [NSData dataWithBytesNoCopy: &cmp
  228087. length: sizeof (cmp)
  228088. freeWhenDone: NO]
  228089. waitUntilDone: YES];
  228090. return cmp.result;
  228091. }
  228092. }
  228093. #endif
  228094. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228095. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228096. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228097. // compiled on its own).
  228098. #if JUCE_INCLUDED_FILE
  228099. #if JUCE_MAC
  228100. END_JUCE_NAMESPACE
  228101. using namespace JUCE_NAMESPACE;
  228102. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228103. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228104. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228105. #else
  228106. @interface JuceFileChooserDelegate : NSObject
  228107. #endif
  228108. {
  228109. StringArray* filters;
  228110. }
  228111. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228112. - (void) dealloc;
  228113. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228114. @end
  228115. @implementation JuceFileChooserDelegate
  228116. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228117. {
  228118. [super init];
  228119. filters = filters_;
  228120. return self;
  228121. }
  228122. - (void) dealloc
  228123. {
  228124. delete filters;
  228125. [super dealloc];
  228126. }
  228127. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228128. {
  228129. (void) sender;
  228130. const File f (nsStringToJuce (filename));
  228131. for (int i = filters->size(); --i >= 0;)
  228132. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228133. return true;
  228134. return f.isDirectory();
  228135. }
  228136. @end
  228137. BEGIN_JUCE_NAMESPACE
  228138. void FileChooser::showPlatformDialog (Array<File>& results,
  228139. const String& title,
  228140. const File& currentFileOrDirectory,
  228141. const String& filter,
  228142. bool selectsDirectory,
  228143. bool selectsFiles,
  228144. bool isSaveDialogue,
  228145. bool warnAboutOverwritingExistingFiles,
  228146. bool selectMultipleFiles,
  228147. FilePreviewComponent* extraInfoComponent)
  228148. {
  228149. const ScopedAutoReleasePool pool;
  228150. StringArray* filters = new StringArray();
  228151. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228152. filters->trim();
  228153. filters->removeEmptyStrings();
  228154. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228155. [delegate autorelease];
  228156. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228157. : [NSOpenPanel openPanel];
  228158. [panel setTitle: juceStringToNS (title)];
  228159. if (! isSaveDialogue)
  228160. {
  228161. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228162. [openPanel setCanChooseDirectories: selectsDirectory];
  228163. [openPanel setCanChooseFiles: selectsFiles];
  228164. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228165. }
  228166. [panel setDelegate: delegate];
  228167. if (isSaveDialogue || selectsDirectory)
  228168. [panel setCanCreateDirectories: YES];
  228169. String directory, filename;
  228170. if (currentFileOrDirectory.isDirectory())
  228171. {
  228172. directory = currentFileOrDirectory.getFullPathName();
  228173. }
  228174. else
  228175. {
  228176. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228177. filename = currentFileOrDirectory.getFileName();
  228178. }
  228179. if ([panel runModalForDirectory: juceStringToNS (directory)
  228180. file: juceStringToNS (filename)]
  228181. == NSOKButton)
  228182. {
  228183. if (isSaveDialogue)
  228184. {
  228185. results.add (File (nsStringToJuce ([panel filename])));
  228186. }
  228187. else
  228188. {
  228189. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228190. NSArray* urls = [openPanel filenames];
  228191. for (unsigned int i = 0; i < [urls count]; ++i)
  228192. {
  228193. NSString* f = [urls objectAtIndex: i];
  228194. results.add (File (nsStringToJuce (f)));
  228195. }
  228196. }
  228197. }
  228198. [panel setDelegate: nil];
  228199. }
  228200. #else
  228201. void FileChooser::showPlatformDialog (Array<File>& results,
  228202. const String& title,
  228203. const File& currentFileOrDirectory,
  228204. const String& filter,
  228205. bool selectsDirectory,
  228206. bool selectsFiles,
  228207. bool isSaveDialogue,
  228208. bool warnAboutOverwritingExistingFiles,
  228209. bool selectMultipleFiles,
  228210. FilePreviewComponent* extraInfoComponent)
  228211. {
  228212. const ScopedAutoReleasePool pool;
  228213. jassertfalse; //xxx to do
  228214. }
  228215. #endif
  228216. #endif
  228217. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228218. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228219. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228220. // compiled on its own).
  228221. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228222. #if JUCE_MAC
  228223. END_JUCE_NAMESPACE
  228224. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228225. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228226. {
  228227. CriticalSection* contextLock;
  228228. bool needsUpdate;
  228229. }
  228230. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228231. - (bool) makeActive;
  228232. - (void) makeInactive;
  228233. - (void) reshape;
  228234. @end
  228235. @implementation ThreadSafeNSOpenGLView
  228236. - (id) initWithFrame: (NSRect) frameRect
  228237. pixelFormat: (NSOpenGLPixelFormat*) format
  228238. {
  228239. contextLock = new CriticalSection();
  228240. self = [super initWithFrame: frameRect pixelFormat: format];
  228241. if (self != nil)
  228242. [[NSNotificationCenter defaultCenter] addObserver: self
  228243. selector: @selector (_surfaceNeedsUpdate:)
  228244. name: NSViewGlobalFrameDidChangeNotification
  228245. object: self];
  228246. return self;
  228247. }
  228248. - (void) dealloc
  228249. {
  228250. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228251. delete contextLock;
  228252. [super dealloc];
  228253. }
  228254. - (bool) makeActive
  228255. {
  228256. const ScopedLock sl (*contextLock);
  228257. if ([self openGLContext] == 0)
  228258. return false;
  228259. [[self openGLContext] makeCurrentContext];
  228260. if (needsUpdate)
  228261. {
  228262. [super update];
  228263. needsUpdate = false;
  228264. }
  228265. return true;
  228266. }
  228267. - (void) makeInactive
  228268. {
  228269. const ScopedLock sl (*contextLock);
  228270. [NSOpenGLContext clearCurrentContext];
  228271. }
  228272. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228273. {
  228274. const ScopedLock sl (*contextLock);
  228275. needsUpdate = true;
  228276. }
  228277. - (void) update
  228278. {
  228279. const ScopedLock sl (*contextLock);
  228280. needsUpdate = true;
  228281. }
  228282. - (void) reshape
  228283. {
  228284. const ScopedLock sl (*contextLock);
  228285. needsUpdate = true;
  228286. }
  228287. @end
  228288. BEGIN_JUCE_NAMESPACE
  228289. class WindowedGLContext : public OpenGLContext
  228290. {
  228291. public:
  228292. WindowedGLContext (Component* const component,
  228293. const OpenGLPixelFormat& pixelFormat_,
  228294. NSOpenGLContext* sharedContext)
  228295. : renderContext (0),
  228296. pixelFormat (pixelFormat_)
  228297. {
  228298. jassert (component != 0);
  228299. NSOpenGLPixelFormatAttribute attribs [64];
  228300. int n = 0;
  228301. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228302. attribs[n++] = NSOpenGLPFAAccelerated;
  228303. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228304. attribs[n++] = NSOpenGLPFAColorSize;
  228305. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228306. pixelFormat.greenBits,
  228307. pixelFormat.blueBits);
  228308. attribs[n++] = NSOpenGLPFAAlphaSize;
  228309. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228310. attribs[n++] = NSOpenGLPFADepthSize;
  228311. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228312. attribs[n++] = NSOpenGLPFAStencilSize;
  228313. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228314. attribs[n++] = NSOpenGLPFAAccumSize;
  228315. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228316. pixelFormat.accumulationBufferGreenBits,
  228317. pixelFormat.accumulationBufferBlueBits,
  228318. pixelFormat.accumulationBufferAlphaBits);
  228319. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228320. attribs[n++] = NSOpenGLPFASampleBuffers;
  228321. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228322. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228323. attribs[n++] = NSOpenGLPFANoRecovery;
  228324. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228325. NSOpenGLPixelFormat* format
  228326. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228327. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228328. pixelFormat: format];
  228329. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228330. shareContext: sharedContext] autorelease];
  228331. const GLint swapInterval = 1;
  228332. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228333. [view setOpenGLContext: renderContext];
  228334. [format release];
  228335. viewHolder = new NSViewComponentInternal (view, component);
  228336. }
  228337. ~WindowedGLContext()
  228338. {
  228339. deleteContext();
  228340. viewHolder = 0;
  228341. }
  228342. void deleteContext()
  228343. {
  228344. makeInactive();
  228345. [renderContext clearDrawable];
  228346. [renderContext setView: nil];
  228347. [view setOpenGLContext: nil];
  228348. renderContext = nil;
  228349. }
  228350. bool makeActive() const throw()
  228351. {
  228352. jassert (renderContext != 0);
  228353. if ([renderContext view] != view)
  228354. [renderContext setView: view];
  228355. [view makeActive];
  228356. return isActive();
  228357. }
  228358. bool makeInactive() const throw()
  228359. {
  228360. [view makeInactive];
  228361. return true;
  228362. }
  228363. bool isActive() const throw()
  228364. {
  228365. return [NSOpenGLContext currentContext] == renderContext;
  228366. }
  228367. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228368. void* getRawContext() const throw() { return renderContext; }
  228369. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228370. {
  228371. }
  228372. void swapBuffers()
  228373. {
  228374. [renderContext flushBuffer];
  228375. }
  228376. bool setSwapInterval (const int numFramesPerSwap)
  228377. {
  228378. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228379. forParameter: NSOpenGLCPSwapInterval];
  228380. return true;
  228381. }
  228382. int getSwapInterval() const
  228383. {
  228384. GLint numFrames = 0;
  228385. [renderContext getValues: &numFrames
  228386. forParameter: NSOpenGLCPSwapInterval];
  228387. return numFrames;
  228388. }
  228389. void repaint()
  228390. {
  228391. // we need to invalidate the juce view that holds this gl view, to make it
  228392. // cause a repaint callback
  228393. NSView* v = (NSView*) viewHolder->view;
  228394. NSRect r = [v frame];
  228395. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228396. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228397. // repaint message, thus never causing our paint() callback, and never repainting
  228398. // the comp. So invalidating just a little bit around the edge helps..
  228399. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228400. }
  228401. void* getNativeWindowHandle() const { return viewHolder->view; }
  228402. juce_UseDebuggingNewOperator
  228403. NSOpenGLContext* renderContext;
  228404. ThreadSafeNSOpenGLView* view;
  228405. private:
  228406. OpenGLPixelFormat pixelFormat;
  228407. ScopedPointer <NSViewComponentInternal> viewHolder;
  228408. WindowedGLContext (const WindowedGLContext&);
  228409. WindowedGLContext& operator= (const WindowedGLContext&);
  228410. };
  228411. OpenGLContext* OpenGLComponent::createContext()
  228412. {
  228413. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228414. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228415. return (c->renderContext != 0) ? c.release() : 0;
  228416. }
  228417. void* OpenGLComponent::getNativeWindowHandle() const
  228418. {
  228419. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228420. : 0;
  228421. }
  228422. void juce_glViewport (const int w, const int h)
  228423. {
  228424. glViewport (0, 0, w, h);
  228425. }
  228426. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228427. OwnedArray <OpenGLPixelFormat>& results)
  228428. {
  228429. /* GLint attribs [64];
  228430. int n = 0;
  228431. attribs[n++] = AGL_RGBA;
  228432. attribs[n++] = AGL_DOUBLEBUFFER;
  228433. attribs[n++] = AGL_ACCELERATED;
  228434. attribs[n++] = AGL_NO_RECOVERY;
  228435. attribs[n++] = AGL_NONE;
  228436. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228437. while (p != 0)
  228438. {
  228439. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228440. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228441. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228442. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228443. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228444. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228445. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228446. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228447. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228448. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228449. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228450. results.add (pf);
  228451. p = aglNextPixelFormat (p);
  228452. }*/
  228453. //jassertfalse // can't see how you do this in cocoa!
  228454. }
  228455. #else
  228456. END_JUCE_NAMESPACE
  228457. @interface JuceGLView : UIView
  228458. {
  228459. }
  228460. + (Class) layerClass;
  228461. @end
  228462. @implementation JuceGLView
  228463. + (Class) layerClass
  228464. {
  228465. return [CAEAGLLayer class];
  228466. }
  228467. @end
  228468. BEGIN_JUCE_NAMESPACE
  228469. class GLESContext : public OpenGLContext
  228470. {
  228471. public:
  228472. GLESContext (UIViewComponentPeer* peer,
  228473. Component* const component_,
  228474. const OpenGLPixelFormat& pixelFormat_,
  228475. const GLESContext* const sharedContext,
  228476. NSUInteger apiType)
  228477. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228478. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228479. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228480. {
  228481. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228482. view.opaque = YES;
  228483. view.hidden = NO;
  228484. view.backgroundColor = [UIColor blackColor];
  228485. view.userInteractionEnabled = NO;
  228486. glLayer = (CAEAGLLayer*) [view layer];
  228487. [peer->view addSubview: view];
  228488. if (sharedContext != 0)
  228489. context = [[EAGLContext alloc] initWithAPI: apiType
  228490. sharegroup: [sharedContext->context sharegroup]];
  228491. else
  228492. context = [[EAGLContext alloc] initWithAPI: apiType];
  228493. createGLBuffers();
  228494. }
  228495. ~GLESContext()
  228496. {
  228497. deleteContext();
  228498. [view removeFromSuperview];
  228499. [view release];
  228500. freeGLBuffers();
  228501. }
  228502. void deleteContext()
  228503. {
  228504. makeInactive();
  228505. [context release];
  228506. context = nil;
  228507. }
  228508. bool makeActive() const throw()
  228509. {
  228510. jassert (context != 0);
  228511. [EAGLContext setCurrentContext: context];
  228512. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228513. return true;
  228514. }
  228515. void swapBuffers()
  228516. {
  228517. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228518. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228519. }
  228520. bool makeInactive() const throw()
  228521. {
  228522. return [EAGLContext setCurrentContext: nil];
  228523. }
  228524. bool isActive() const throw()
  228525. {
  228526. return [EAGLContext currentContext] == context;
  228527. }
  228528. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228529. void* getRawContext() const throw() { return glLayer; }
  228530. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228531. {
  228532. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228533. if (lastWidth != w || lastHeight != h)
  228534. {
  228535. lastWidth = w;
  228536. lastHeight = h;
  228537. freeGLBuffers();
  228538. createGLBuffers();
  228539. }
  228540. }
  228541. bool setSwapInterval (const int numFramesPerSwap)
  228542. {
  228543. numFrames = numFramesPerSwap;
  228544. return true;
  228545. }
  228546. int getSwapInterval() const
  228547. {
  228548. return numFrames;
  228549. }
  228550. void repaint()
  228551. {
  228552. }
  228553. void createGLBuffers()
  228554. {
  228555. makeActive();
  228556. glGenFramebuffersOES (1, &frameBufferHandle);
  228557. glGenRenderbuffersOES (1, &colorBufferHandle);
  228558. glGenRenderbuffersOES (1, &depthBufferHandle);
  228559. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228560. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228561. GLint width, height;
  228562. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228563. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228564. if (useDepthBuffer)
  228565. {
  228566. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228567. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228568. }
  228569. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228570. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228571. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228572. if (useDepthBuffer)
  228573. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228574. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228575. }
  228576. void freeGLBuffers()
  228577. {
  228578. if (frameBufferHandle != 0)
  228579. {
  228580. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228581. frameBufferHandle = 0;
  228582. }
  228583. if (colorBufferHandle != 0)
  228584. {
  228585. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228586. colorBufferHandle = 0;
  228587. }
  228588. if (depthBufferHandle != 0)
  228589. {
  228590. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228591. depthBufferHandle = 0;
  228592. }
  228593. }
  228594. juce_UseDebuggingNewOperator
  228595. private:
  228596. Component::SafePointer<Component> component;
  228597. OpenGLPixelFormat pixelFormat;
  228598. JuceGLView* view;
  228599. CAEAGLLayer* glLayer;
  228600. EAGLContext* context;
  228601. bool useDepthBuffer;
  228602. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228603. int numFrames;
  228604. int lastWidth, lastHeight;
  228605. GLESContext (const GLESContext&);
  228606. GLESContext& operator= (const GLESContext&);
  228607. };
  228608. OpenGLContext* OpenGLComponent::createContext()
  228609. {
  228610. ScopedAutoReleasePool pool;
  228611. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228612. if (peer != 0)
  228613. return new GLESContext (peer, this, preferredPixelFormat,
  228614. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228615. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228616. return 0;
  228617. }
  228618. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228619. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228620. {
  228621. }
  228622. void juce_glViewport (const int w, const int h)
  228623. {
  228624. glViewport (0, 0, w, h);
  228625. }
  228626. #endif
  228627. #endif
  228628. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228629. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228630. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228631. // compiled on its own).
  228632. #if JUCE_INCLUDED_FILE
  228633. #if JUCE_MAC
  228634. namespace MouseCursorHelpers
  228635. {
  228636. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228637. {
  228638. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228639. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228640. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228641. [im release];
  228642. return c;
  228643. }
  228644. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228645. {
  228646. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228647. BufferedInputStream buf (&fileStream, 4096, false);
  228648. PNGImageFormat pngFormat;
  228649. Image im (pngFormat.decodeImage (buf));
  228650. if (im.isValid())
  228651. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228652. jassertfalse;
  228653. return 0;
  228654. }
  228655. }
  228656. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228657. {
  228658. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228659. }
  228660. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228661. {
  228662. const ScopedAutoReleasePool pool;
  228663. NSCursor* c = 0;
  228664. switch (type)
  228665. {
  228666. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228667. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228668. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228669. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228670. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228671. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228672. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228673. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228674. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228675. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228676. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228677. case UpDownResizeCursor:
  228678. case TopEdgeResizeCursor:
  228679. case BottomEdgeResizeCursor:
  228680. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228681. case TopLeftCornerResizeCursor:
  228682. case BottomRightCornerResizeCursor:
  228683. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228684. case TopRightCornerResizeCursor:
  228685. case BottomLeftCornerResizeCursor:
  228686. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228687. case UpDownLeftRightResizeCursor:
  228688. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228689. default:
  228690. jassertfalse;
  228691. break;
  228692. }
  228693. [c retain];
  228694. return c;
  228695. }
  228696. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228697. {
  228698. [((NSCursor*) cursorHandle) release];
  228699. }
  228700. void MouseCursor::showInAllWindows() const
  228701. {
  228702. showInWindow (0);
  228703. }
  228704. void MouseCursor::showInWindow (ComponentPeer*) const
  228705. {
  228706. [((NSCursor*) getHandle()) set];
  228707. }
  228708. #else
  228709. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228710. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228711. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228712. void MouseCursor::showInAllWindows() const {}
  228713. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228714. #endif
  228715. #endif
  228716. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228717. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228718. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228719. // compiled on its own).
  228720. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228721. #if JUCE_MAC
  228722. END_JUCE_NAMESPACE
  228723. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228724. @interface DownloadClickDetector : NSObject
  228725. {
  228726. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228727. }
  228728. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228729. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228730. request: (NSURLRequest*) request
  228731. frame: (WebFrame*) frame
  228732. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228733. @end
  228734. @implementation DownloadClickDetector
  228735. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228736. {
  228737. [super init];
  228738. ownerComponent = ownerComponent_;
  228739. return self;
  228740. }
  228741. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228742. request: (NSURLRequest*) request
  228743. frame: (WebFrame*) frame
  228744. decisionListener: (id <WebPolicyDecisionListener>) listener
  228745. {
  228746. (void) sender;
  228747. (void) request;
  228748. (void) frame;
  228749. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228750. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228751. [listener use];
  228752. else
  228753. [listener ignore];
  228754. }
  228755. @end
  228756. BEGIN_JUCE_NAMESPACE
  228757. class WebBrowserComponentInternal : public NSViewComponent
  228758. {
  228759. public:
  228760. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228761. {
  228762. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228763. frameName: @""
  228764. groupName: @""];
  228765. setView (webView);
  228766. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228767. [webView setPolicyDelegate: clickListener];
  228768. }
  228769. ~WebBrowserComponentInternal()
  228770. {
  228771. [webView setPolicyDelegate: nil];
  228772. [clickListener release];
  228773. setView (0);
  228774. }
  228775. void goToURL (const String& url,
  228776. const StringArray* headers,
  228777. const MemoryBlock* postData)
  228778. {
  228779. NSMutableURLRequest* r
  228780. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228781. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228782. timeoutInterval: 30.0];
  228783. if (postData != 0 && postData->getSize() > 0)
  228784. {
  228785. [r setHTTPMethod: @"POST"];
  228786. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228787. length: postData->getSize()]];
  228788. }
  228789. if (headers != 0)
  228790. {
  228791. for (int i = 0; i < headers->size(); ++i)
  228792. {
  228793. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228794. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228795. [r setValue: juceStringToNS (headerValue)
  228796. forHTTPHeaderField: juceStringToNS (headerName)];
  228797. }
  228798. }
  228799. stop();
  228800. [[webView mainFrame] loadRequest: r];
  228801. }
  228802. void goBack()
  228803. {
  228804. [webView goBack];
  228805. }
  228806. void goForward()
  228807. {
  228808. [webView goForward];
  228809. }
  228810. void stop()
  228811. {
  228812. [webView stopLoading: nil];
  228813. }
  228814. void refresh()
  228815. {
  228816. [webView reload: nil];
  228817. }
  228818. private:
  228819. WebView* webView;
  228820. DownloadClickDetector* clickListener;
  228821. };
  228822. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228823. : browser (0),
  228824. blankPageShown (false),
  228825. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228826. {
  228827. setOpaque (true);
  228828. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228829. }
  228830. WebBrowserComponent::~WebBrowserComponent()
  228831. {
  228832. deleteAndZero (browser);
  228833. }
  228834. void WebBrowserComponent::goToURL (const String& url,
  228835. const StringArray* headers,
  228836. const MemoryBlock* postData)
  228837. {
  228838. lastURL = url;
  228839. lastHeaders.clear();
  228840. if (headers != 0)
  228841. lastHeaders = *headers;
  228842. lastPostData.setSize (0);
  228843. if (postData != 0)
  228844. lastPostData = *postData;
  228845. blankPageShown = false;
  228846. browser->goToURL (url, headers, postData);
  228847. }
  228848. void WebBrowserComponent::stop()
  228849. {
  228850. browser->stop();
  228851. }
  228852. void WebBrowserComponent::goBack()
  228853. {
  228854. lastURL = String::empty;
  228855. blankPageShown = false;
  228856. browser->goBack();
  228857. }
  228858. void WebBrowserComponent::goForward()
  228859. {
  228860. lastURL = String::empty;
  228861. browser->goForward();
  228862. }
  228863. void WebBrowserComponent::refresh()
  228864. {
  228865. browser->refresh();
  228866. }
  228867. void WebBrowserComponent::paint (Graphics&)
  228868. {
  228869. }
  228870. void WebBrowserComponent::checkWindowAssociation()
  228871. {
  228872. if (isShowing())
  228873. {
  228874. if (blankPageShown)
  228875. goBack();
  228876. }
  228877. else
  228878. {
  228879. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228880. {
  228881. // when the component becomes invisible, some stuff like flash
  228882. // carries on playing audio, so we need to force it onto a blank
  228883. // page to avoid this, (and send it back when it's made visible again).
  228884. blankPageShown = true;
  228885. browser->goToURL ("about:blank", 0, 0);
  228886. }
  228887. }
  228888. }
  228889. void WebBrowserComponent::reloadLastURL()
  228890. {
  228891. if (lastURL.isNotEmpty())
  228892. {
  228893. goToURL (lastURL, &lastHeaders, &lastPostData);
  228894. lastURL = String::empty;
  228895. }
  228896. }
  228897. void WebBrowserComponent::parentHierarchyChanged()
  228898. {
  228899. checkWindowAssociation();
  228900. }
  228901. void WebBrowserComponent::resized()
  228902. {
  228903. browser->setSize (getWidth(), getHeight());
  228904. }
  228905. void WebBrowserComponent::visibilityChanged()
  228906. {
  228907. checkWindowAssociation();
  228908. }
  228909. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228910. {
  228911. return true;
  228912. }
  228913. #else
  228914. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228915. {
  228916. }
  228917. WebBrowserComponent::~WebBrowserComponent()
  228918. {
  228919. }
  228920. void WebBrowserComponent::goToURL (const String& url,
  228921. const StringArray* headers,
  228922. const MemoryBlock* postData)
  228923. {
  228924. }
  228925. void WebBrowserComponent::stop()
  228926. {
  228927. }
  228928. void WebBrowserComponent::goBack()
  228929. {
  228930. }
  228931. void WebBrowserComponent::goForward()
  228932. {
  228933. }
  228934. void WebBrowserComponent::refresh()
  228935. {
  228936. }
  228937. void WebBrowserComponent::paint (Graphics& g)
  228938. {
  228939. }
  228940. void WebBrowserComponent::checkWindowAssociation()
  228941. {
  228942. }
  228943. void WebBrowserComponent::reloadLastURL()
  228944. {
  228945. }
  228946. void WebBrowserComponent::parentHierarchyChanged()
  228947. {
  228948. }
  228949. void WebBrowserComponent::resized()
  228950. {
  228951. }
  228952. void WebBrowserComponent::visibilityChanged()
  228953. {
  228954. }
  228955. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228956. {
  228957. return true;
  228958. }
  228959. #endif
  228960. #endif
  228961. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228962. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228963. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228964. // compiled on its own).
  228965. #if JUCE_INCLUDED_FILE
  228966. class IPhoneAudioIODevice : public AudioIODevice
  228967. {
  228968. public:
  228969. IPhoneAudioIODevice (const String& deviceName)
  228970. : AudioIODevice (deviceName, "Audio"),
  228971. audioUnit (0),
  228972. isRunning (false),
  228973. callback (0),
  228974. actualBufferSize (0),
  228975. floatData (1, 2)
  228976. {
  228977. numInputChannels = 2;
  228978. numOutputChannels = 2;
  228979. preferredBufferSize = 0;
  228980. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228981. updateDeviceInfo();
  228982. }
  228983. ~IPhoneAudioIODevice()
  228984. {
  228985. close();
  228986. }
  228987. const StringArray getOutputChannelNames()
  228988. {
  228989. StringArray s;
  228990. s.add ("Left");
  228991. s.add ("Right");
  228992. return s;
  228993. }
  228994. const StringArray getInputChannelNames()
  228995. {
  228996. StringArray s;
  228997. if (audioInputIsAvailable)
  228998. {
  228999. s.add ("Left");
  229000. s.add ("Right");
  229001. }
  229002. return s;
  229003. }
  229004. int getNumSampleRates()
  229005. {
  229006. return 1;
  229007. }
  229008. double getSampleRate (int index)
  229009. {
  229010. return sampleRate;
  229011. }
  229012. int getNumBufferSizesAvailable()
  229013. {
  229014. return 1;
  229015. }
  229016. int getBufferSizeSamples (int index)
  229017. {
  229018. return getDefaultBufferSize();
  229019. }
  229020. int getDefaultBufferSize()
  229021. {
  229022. return 1024;
  229023. }
  229024. const String open (const BigInteger& inputChannels,
  229025. const BigInteger& outputChannels,
  229026. double sampleRate,
  229027. int bufferSize)
  229028. {
  229029. close();
  229030. lastError = String::empty;
  229031. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229032. // xxx set up channel mapping
  229033. activeOutputChans = outputChannels;
  229034. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229035. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229036. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229037. activeInputChans = inputChannels;
  229038. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229039. numInputChannels = activeInputChans.countNumberOfSetBits();
  229040. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229041. AudioSessionSetActive (true);
  229042. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229043. : kAudioSessionCategory_MediaPlayback;
  229044. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229045. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229046. fixAudioRouteIfSetToReceiver();
  229047. updateDeviceInfo();
  229048. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229049. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229050. actualBufferSize = preferredBufferSize;
  229051. prepareFloatBuffers();
  229052. isRunning = true;
  229053. propertyChanged (0, 0, 0); // creates and starts the AU
  229054. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229055. return lastError;
  229056. }
  229057. void close()
  229058. {
  229059. if (isRunning)
  229060. {
  229061. isRunning = false;
  229062. AudioSessionSetActive (false);
  229063. if (audioUnit != 0)
  229064. {
  229065. AudioComponentInstanceDispose (audioUnit);
  229066. audioUnit = 0;
  229067. }
  229068. }
  229069. }
  229070. bool isOpen()
  229071. {
  229072. return isRunning;
  229073. }
  229074. int getCurrentBufferSizeSamples()
  229075. {
  229076. return actualBufferSize;
  229077. }
  229078. double getCurrentSampleRate()
  229079. {
  229080. return sampleRate;
  229081. }
  229082. int getCurrentBitDepth()
  229083. {
  229084. return 16;
  229085. }
  229086. const BigInteger getActiveOutputChannels() const
  229087. {
  229088. return activeOutputChans;
  229089. }
  229090. const BigInteger getActiveInputChannels() const
  229091. {
  229092. return activeInputChans;
  229093. }
  229094. int getOutputLatencyInSamples()
  229095. {
  229096. return 0; //xxx
  229097. }
  229098. int getInputLatencyInSamples()
  229099. {
  229100. return 0; //xxx
  229101. }
  229102. void start (AudioIODeviceCallback* callback_)
  229103. {
  229104. if (isRunning && callback != callback_)
  229105. {
  229106. if (callback_ != 0)
  229107. callback_->audioDeviceAboutToStart (this);
  229108. const ScopedLock sl (callbackLock);
  229109. callback = callback_;
  229110. }
  229111. }
  229112. void stop()
  229113. {
  229114. if (isRunning)
  229115. {
  229116. AudioIODeviceCallback* lastCallback;
  229117. {
  229118. const ScopedLock sl (callbackLock);
  229119. lastCallback = callback;
  229120. callback = 0;
  229121. }
  229122. if (lastCallback != 0)
  229123. lastCallback->audioDeviceStopped();
  229124. }
  229125. }
  229126. bool isPlaying()
  229127. {
  229128. return isRunning && callback != 0;
  229129. }
  229130. const String getLastError()
  229131. {
  229132. return lastError;
  229133. }
  229134. private:
  229135. CriticalSection callbackLock;
  229136. Float64 sampleRate;
  229137. int numInputChannels, numOutputChannels;
  229138. int preferredBufferSize;
  229139. int actualBufferSize;
  229140. bool isRunning;
  229141. String lastError;
  229142. AudioStreamBasicDescription format;
  229143. AudioUnit audioUnit;
  229144. UInt32 audioInputIsAvailable;
  229145. AudioIODeviceCallback* callback;
  229146. BigInteger activeOutputChans, activeInputChans;
  229147. AudioSampleBuffer floatData;
  229148. float* inputChannels[3];
  229149. float* outputChannels[3];
  229150. bool monoInputChannelNumber, monoOutputChannelNumber;
  229151. void prepareFloatBuffers()
  229152. {
  229153. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229154. zerostruct (inputChannels);
  229155. zerostruct (outputChannels);
  229156. for (int i = 0; i < numInputChannels; ++i)
  229157. inputChannels[i] = floatData.getSampleData (i);
  229158. for (int i = 0; i < numOutputChannels; ++i)
  229159. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229160. }
  229161. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229162. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229163. {
  229164. OSStatus err = noErr;
  229165. if (audioInputIsAvailable)
  229166. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229167. const ScopedLock sl (callbackLock);
  229168. if (callback != 0)
  229169. {
  229170. if (audioInputIsAvailable && numInputChannels > 0)
  229171. {
  229172. short* shortData = (short*) ioData->mBuffers[0].mData;
  229173. if (numInputChannels >= 2)
  229174. {
  229175. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229176. {
  229177. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229178. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229179. }
  229180. }
  229181. else
  229182. {
  229183. if (monoInputChannelNumber > 0)
  229184. ++shortData;
  229185. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229186. {
  229187. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229188. ++shortData;
  229189. }
  229190. }
  229191. }
  229192. else
  229193. {
  229194. for (int i = numInputChannels; --i >= 0;)
  229195. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229196. }
  229197. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229198. outputChannels, numOutputChannels,
  229199. (int) inNumberFrames);
  229200. short* shortData = (short*) ioData->mBuffers[0].mData;
  229201. int n = 0;
  229202. if (numOutputChannels >= 2)
  229203. {
  229204. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229205. {
  229206. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229207. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229208. }
  229209. }
  229210. else if (numOutputChannels == 1)
  229211. {
  229212. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229213. {
  229214. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229215. shortData [n++] = s;
  229216. shortData [n++] = s;
  229217. }
  229218. }
  229219. else
  229220. {
  229221. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229222. }
  229223. }
  229224. else
  229225. {
  229226. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229227. }
  229228. return err;
  229229. }
  229230. void updateDeviceInfo()
  229231. {
  229232. UInt32 size = sizeof (sampleRate);
  229233. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229234. size = sizeof (audioInputIsAvailable);
  229235. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229236. }
  229237. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229238. {
  229239. if (! isRunning)
  229240. return;
  229241. if (inPropertyValue != 0)
  229242. {
  229243. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229244. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229245. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229246. SInt32 routeChangeReason;
  229247. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229248. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229249. fixAudioRouteIfSetToReceiver();
  229250. }
  229251. updateDeviceInfo();
  229252. createAudioUnit();
  229253. AudioSessionSetActive (true);
  229254. if (audioUnit != 0)
  229255. {
  229256. UInt32 formatSize = sizeof (format);
  229257. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229258. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229259. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229260. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229261. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229262. AudioOutputUnitStart (audioUnit);
  229263. }
  229264. }
  229265. void interruptionListener (UInt32 inInterruption)
  229266. {
  229267. /*if (inInterruption == kAudioSessionBeginInterruption)
  229268. {
  229269. isRunning = false;
  229270. AudioOutputUnitStop (audioUnit);
  229271. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229272. "This could have been interrupted by another application or by unplugging a headset",
  229273. @"Resume",
  229274. @"Cancel"))
  229275. {
  229276. isRunning = true;
  229277. propertyChanged (0, 0, 0);
  229278. }
  229279. }*/
  229280. if (inInterruption == kAudioSessionEndInterruption)
  229281. {
  229282. isRunning = true;
  229283. AudioSessionSetActive (true);
  229284. AudioOutputUnitStart (audioUnit);
  229285. }
  229286. }
  229287. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229288. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229289. {
  229290. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229291. }
  229292. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229293. {
  229294. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229295. }
  229296. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229297. {
  229298. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229299. }
  229300. void resetFormat (const int numChannels)
  229301. {
  229302. memset (&format, 0, sizeof (format));
  229303. format.mFormatID = kAudioFormatLinearPCM;
  229304. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229305. format.mBitsPerChannel = 8 * sizeof (short);
  229306. format.mChannelsPerFrame = 2;
  229307. format.mFramesPerPacket = 1;
  229308. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229309. }
  229310. bool createAudioUnit()
  229311. {
  229312. if (audioUnit != 0)
  229313. {
  229314. AudioComponentInstanceDispose (audioUnit);
  229315. audioUnit = 0;
  229316. }
  229317. resetFormat (2);
  229318. AudioComponentDescription desc;
  229319. desc.componentType = kAudioUnitType_Output;
  229320. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229321. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229322. desc.componentFlags = 0;
  229323. desc.componentFlagsMask = 0;
  229324. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229325. AudioComponentInstanceNew (comp, &audioUnit);
  229326. if (audioUnit == 0)
  229327. return false;
  229328. const UInt32 one = 1;
  229329. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229330. AudioChannelLayout layout;
  229331. layout.mChannelBitmap = 0;
  229332. layout.mNumberChannelDescriptions = 0;
  229333. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229334. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229335. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229336. AURenderCallbackStruct inputProc;
  229337. inputProc.inputProc = processStatic;
  229338. inputProc.inputProcRefCon = this;
  229339. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229340. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229341. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229342. AudioUnitInitialize (audioUnit);
  229343. return true;
  229344. }
  229345. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229346. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229347. static void fixAudioRouteIfSetToReceiver()
  229348. {
  229349. CFStringRef audioRoute = 0;
  229350. UInt32 propertySize = sizeof (audioRoute);
  229351. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229352. {
  229353. NSString* route = (NSString*) audioRoute;
  229354. //DBG ("audio route: " + nsStringToJuce (route));
  229355. if ([route hasPrefix: @"Receiver"])
  229356. {
  229357. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229358. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229359. }
  229360. CFRelease (audioRoute);
  229361. }
  229362. }
  229363. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229364. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229365. };
  229366. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229367. {
  229368. public:
  229369. IPhoneAudioIODeviceType()
  229370. : AudioIODeviceType ("iPhone Audio")
  229371. {
  229372. }
  229373. ~IPhoneAudioIODeviceType()
  229374. {
  229375. }
  229376. void scanForDevices()
  229377. {
  229378. }
  229379. const StringArray getDeviceNames (bool wantInputNames) const
  229380. {
  229381. StringArray s;
  229382. s.add ("iPhone Audio");
  229383. return s;
  229384. }
  229385. int getDefaultDeviceIndex (bool forInput) const
  229386. {
  229387. return 0;
  229388. }
  229389. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229390. {
  229391. return device != 0 ? 0 : -1;
  229392. }
  229393. bool hasSeparateInputsAndOutputs() const { return false; }
  229394. AudioIODevice* createDevice (const String& outputDeviceName,
  229395. const String& inputDeviceName)
  229396. {
  229397. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229398. {
  229399. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229400. : inputDeviceName);
  229401. }
  229402. return 0;
  229403. }
  229404. juce_UseDebuggingNewOperator
  229405. private:
  229406. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229407. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229408. };
  229409. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229410. {
  229411. return new IPhoneAudioIODeviceType();
  229412. }
  229413. #endif
  229414. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229415. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229416. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229417. // compiled on its own).
  229418. #if JUCE_INCLUDED_FILE
  229419. #if JUCE_MAC
  229420. namespace CoreMidiHelpers
  229421. {
  229422. static bool logError (const OSStatus err, const int lineNum)
  229423. {
  229424. if (err == noErr)
  229425. return true;
  229426. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229427. jassertfalse;
  229428. return false;
  229429. }
  229430. #undef CHECK_ERROR
  229431. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229432. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229433. {
  229434. String result;
  229435. CFStringRef str = 0;
  229436. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229437. if (str != 0)
  229438. {
  229439. result = PlatformUtilities::cfStringToJuceString (str);
  229440. CFRelease (str);
  229441. str = 0;
  229442. }
  229443. MIDIEntityRef entity = 0;
  229444. MIDIEndpointGetEntity (endpoint, &entity);
  229445. if (entity == 0)
  229446. return result; // probably virtual
  229447. if (result.isEmpty())
  229448. {
  229449. // endpoint name has zero length - try the entity
  229450. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229451. if (str != 0)
  229452. {
  229453. result += PlatformUtilities::cfStringToJuceString (str);
  229454. CFRelease (str);
  229455. str = 0;
  229456. }
  229457. }
  229458. // now consider the device's name
  229459. MIDIDeviceRef device = 0;
  229460. MIDIEntityGetDevice (entity, &device);
  229461. if (device == 0)
  229462. return result;
  229463. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229464. if (str != 0)
  229465. {
  229466. const String s (PlatformUtilities::cfStringToJuceString (str));
  229467. CFRelease (str);
  229468. // if an external device has only one entity, throw away
  229469. // the endpoint name and just use the device name
  229470. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229471. {
  229472. result = s;
  229473. }
  229474. else if (! result.startsWithIgnoreCase (s))
  229475. {
  229476. // prepend the device name to the entity name
  229477. result = (s + " " + result).trimEnd();
  229478. }
  229479. }
  229480. return result;
  229481. }
  229482. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229483. {
  229484. String result;
  229485. // Does the endpoint have connections?
  229486. CFDataRef connections = 0;
  229487. int numConnections = 0;
  229488. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229489. if (connections != 0)
  229490. {
  229491. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229492. if (numConnections > 0)
  229493. {
  229494. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229495. for (int i = 0; i < numConnections; ++i, ++pid)
  229496. {
  229497. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229498. MIDIObjectRef connObject;
  229499. MIDIObjectType connObjectType;
  229500. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229501. if (err == noErr)
  229502. {
  229503. String s;
  229504. if (connObjectType == kMIDIObjectType_ExternalSource
  229505. || connObjectType == kMIDIObjectType_ExternalDestination)
  229506. {
  229507. // Connected to an external device's endpoint (10.3 and later).
  229508. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229509. }
  229510. else
  229511. {
  229512. // Connected to an external device (10.2) (or something else, catch-all)
  229513. CFStringRef str = 0;
  229514. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229515. if (str != 0)
  229516. {
  229517. s = PlatformUtilities::cfStringToJuceString (str);
  229518. CFRelease (str);
  229519. }
  229520. }
  229521. if (s.isNotEmpty())
  229522. {
  229523. if (result.isNotEmpty())
  229524. result += ", ";
  229525. result += s;
  229526. }
  229527. }
  229528. }
  229529. }
  229530. CFRelease (connections);
  229531. }
  229532. if (result.isNotEmpty())
  229533. return result;
  229534. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229535. return getEndpointName (endpoint, false);
  229536. }
  229537. static MIDIClientRef getGlobalMidiClient()
  229538. {
  229539. static MIDIClientRef globalMidiClient = 0;
  229540. if (globalMidiClient == 0)
  229541. {
  229542. String name ("JUCE");
  229543. if (JUCEApplication::getInstance() != 0)
  229544. name = JUCEApplication::getInstance()->getApplicationName();
  229545. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229546. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229547. CFRelease (appName);
  229548. }
  229549. return globalMidiClient;
  229550. }
  229551. class MidiPortAndEndpoint
  229552. {
  229553. public:
  229554. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229555. : port (port_), endPoint (endPoint_)
  229556. {
  229557. }
  229558. ~MidiPortAndEndpoint()
  229559. {
  229560. if (port != 0)
  229561. MIDIPortDispose (port);
  229562. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229563. MIDIEndpointDispose (endPoint);
  229564. }
  229565. void send (const MIDIPacketList* const packets)
  229566. {
  229567. if (port != 0)
  229568. MIDISend (port, endPoint, packets);
  229569. else
  229570. MIDIReceived (endPoint, packets);
  229571. }
  229572. MIDIPortRef port;
  229573. MIDIEndpointRef endPoint;
  229574. };
  229575. class MidiPortAndCallback;
  229576. static CriticalSection callbackLock;
  229577. static Array<MidiPortAndCallback*> activeCallbacks;
  229578. class MidiPortAndCallback
  229579. {
  229580. public:
  229581. MidiPortAndCallback (MidiInputCallback& callback_)
  229582. : input (0), active (false), callback (callback_), concatenator (2048)
  229583. {
  229584. }
  229585. ~MidiPortAndCallback()
  229586. {
  229587. active = false;
  229588. {
  229589. const ScopedLock sl (callbackLock);
  229590. activeCallbacks.removeValue (this);
  229591. }
  229592. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229593. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229594. }
  229595. void handlePackets (const MIDIPacketList* const pktlist)
  229596. {
  229597. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229598. const ScopedLock sl (callbackLock);
  229599. if (activeCallbacks.contains (this) && active)
  229600. {
  229601. const MIDIPacket* packet = &pktlist->packet[0];
  229602. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229603. {
  229604. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229605. input, callback);
  229606. packet = MIDIPacketNext (packet);
  229607. }
  229608. }
  229609. }
  229610. MidiInput* input;
  229611. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229612. volatile bool active;
  229613. private:
  229614. MidiInputCallback& callback;
  229615. MidiDataConcatenator concatenator;
  229616. };
  229617. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229618. {
  229619. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229620. }
  229621. }
  229622. const StringArray MidiOutput::getDevices()
  229623. {
  229624. StringArray s;
  229625. const ItemCount num = MIDIGetNumberOfDestinations();
  229626. for (ItemCount i = 0; i < num; ++i)
  229627. {
  229628. MIDIEndpointRef dest = MIDIGetDestination (i);
  229629. if (dest != 0)
  229630. {
  229631. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229632. if (name.isEmpty())
  229633. name = "<error>";
  229634. s.add (name);
  229635. }
  229636. else
  229637. {
  229638. s.add ("<error>");
  229639. }
  229640. }
  229641. return s;
  229642. }
  229643. int MidiOutput::getDefaultDeviceIndex()
  229644. {
  229645. return 0;
  229646. }
  229647. MidiOutput* MidiOutput::openDevice (int index)
  229648. {
  229649. MidiOutput* mo = 0;
  229650. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229651. {
  229652. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229653. CFStringRef pname;
  229654. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229655. {
  229656. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229657. MIDIPortRef port;
  229658. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229659. {
  229660. mo = new MidiOutput();
  229661. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229662. }
  229663. CFRelease (pname);
  229664. }
  229665. }
  229666. return mo;
  229667. }
  229668. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229669. {
  229670. MidiOutput* mo = 0;
  229671. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229672. MIDIEndpointRef endPoint;
  229673. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229674. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229675. {
  229676. mo = new MidiOutput();
  229677. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229678. }
  229679. CFRelease (name);
  229680. return mo;
  229681. }
  229682. MidiOutput::~MidiOutput()
  229683. {
  229684. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229685. }
  229686. void MidiOutput::reset()
  229687. {
  229688. }
  229689. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229690. {
  229691. return false;
  229692. }
  229693. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229694. {
  229695. }
  229696. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229697. {
  229698. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229699. if (message.isSysEx())
  229700. {
  229701. const int maxPacketSize = 256;
  229702. int pos = 0, bytesLeft = message.getRawDataSize();
  229703. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229704. HeapBlock <MIDIPacketList> packets;
  229705. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229706. packets->numPackets = numPackets;
  229707. MIDIPacket* p = packets->packet;
  229708. for (int i = 0; i < numPackets; ++i)
  229709. {
  229710. p->timeStamp = 0;
  229711. p->length = jmin (maxPacketSize, bytesLeft);
  229712. memcpy (p->data, message.getRawData() + pos, p->length);
  229713. pos += p->length;
  229714. bytesLeft -= p->length;
  229715. p = MIDIPacketNext (p);
  229716. }
  229717. mpe->send (packets);
  229718. }
  229719. else
  229720. {
  229721. MIDIPacketList packets;
  229722. packets.numPackets = 1;
  229723. packets.packet[0].timeStamp = 0;
  229724. packets.packet[0].length = message.getRawDataSize();
  229725. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229726. mpe->send (&packets);
  229727. }
  229728. }
  229729. const StringArray MidiInput::getDevices()
  229730. {
  229731. StringArray s;
  229732. const ItemCount num = MIDIGetNumberOfSources();
  229733. for (ItemCount i = 0; i < num; ++i)
  229734. {
  229735. MIDIEndpointRef source = MIDIGetSource (i);
  229736. if (source != 0)
  229737. {
  229738. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229739. if (name.isEmpty())
  229740. name = "<error>";
  229741. s.add (name);
  229742. }
  229743. else
  229744. {
  229745. s.add ("<error>");
  229746. }
  229747. }
  229748. return s;
  229749. }
  229750. int MidiInput::getDefaultDeviceIndex()
  229751. {
  229752. return 0;
  229753. }
  229754. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229755. {
  229756. jassert (callback != 0);
  229757. using namespace CoreMidiHelpers;
  229758. MidiInput* newInput = 0;
  229759. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229760. {
  229761. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229762. if (endPoint != 0)
  229763. {
  229764. CFStringRef name;
  229765. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229766. {
  229767. MIDIClientRef client = getGlobalMidiClient();
  229768. if (client != 0)
  229769. {
  229770. MIDIPortRef port;
  229771. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229772. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229773. {
  229774. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229775. {
  229776. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229777. newInput = new MidiInput (getDevices() [index]);
  229778. mpc->input = newInput;
  229779. newInput->internal = mpc;
  229780. const ScopedLock sl (callbackLock);
  229781. activeCallbacks.add (mpc.release());
  229782. }
  229783. else
  229784. {
  229785. CHECK_ERROR (MIDIPortDispose (port));
  229786. }
  229787. }
  229788. }
  229789. }
  229790. CFRelease (name);
  229791. }
  229792. }
  229793. return newInput;
  229794. }
  229795. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229796. {
  229797. jassert (callback != 0);
  229798. using namespace CoreMidiHelpers;
  229799. MidiInput* mi = 0;
  229800. MIDIClientRef client = getGlobalMidiClient();
  229801. if (client != 0)
  229802. {
  229803. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229804. mpc->active = false;
  229805. MIDIEndpointRef endPoint;
  229806. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229807. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229808. {
  229809. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229810. mi = new MidiInput (deviceName);
  229811. mpc->input = mi;
  229812. mi->internal = mpc;
  229813. const ScopedLock sl (callbackLock);
  229814. activeCallbacks.add (mpc.release());
  229815. }
  229816. CFRelease (name);
  229817. }
  229818. return mi;
  229819. }
  229820. MidiInput::MidiInput (const String& name_)
  229821. : name (name_)
  229822. {
  229823. }
  229824. MidiInput::~MidiInput()
  229825. {
  229826. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229827. }
  229828. void MidiInput::start()
  229829. {
  229830. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229831. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229832. }
  229833. void MidiInput::stop()
  229834. {
  229835. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229836. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229837. }
  229838. #undef CHECK_ERROR
  229839. #else // Stubs for iOS...
  229840. MidiOutput::~MidiOutput() {}
  229841. void MidiOutput::reset() {}
  229842. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229843. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229844. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229845. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229846. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229847. const StringArray MidiInput::getDevices() { return StringArray(); }
  229848. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229849. #endif
  229850. #endif
  229851. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229852. #else
  229853. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229854. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229855. // compiled on its own).
  229856. #if JUCE_INCLUDED_FILE
  229857. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229858. #define SUPPORT_10_4_FONTS 1
  229859. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229860. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229861. #define SUPPORT_ONLY_10_4_FONTS 1
  229862. #endif
  229863. END_JUCE_NAMESPACE
  229864. @interface NSFont (PrivateHack)
  229865. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229866. @end
  229867. BEGIN_JUCE_NAMESPACE
  229868. #endif
  229869. class MacTypeface : public Typeface
  229870. {
  229871. public:
  229872. MacTypeface (const Font& font)
  229873. : Typeface (font.getTypefaceName())
  229874. {
  229875. const ScopedAutoReleasePool pool;
  229876. renderingTransform = CGAffineTransformIdentity;
  229877. bool needsItalicTransform = false;
  229878. #if JUCE_IOS
  229879. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229880. if (font.isItalic() || font.isBold())
  229881. {
  229882. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229883. for (NSString* i in familyFonts)
  229884. {
  229885. const String fn (nsStringToJuce (i));
  229886. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229887. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229888. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229889. || afterDash.containsIgnoreCase ("italic")
  229890. || fn.endsWithIgnoreCase ("oblique")
  229891. || fn.endsWithIgnoreCase ("italic");
  229892. if (probablyBold == font.isBold()
  229893. && probablyItalic == font.isItalic())
  229894. {
  229895. fontName = i;
  229896. needsItalicTransform = false;
  229897. break;
  229898. }
  229899. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229900. {
  229901. fontName = i;
  229902. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229903. }
  229904. }
  229905. if (needsItalicTransform)
  229906. renderingTransform.c = 0.15f;
  229907. }
  229908. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229909. const int ascender = abs (CGFontGetAscent (fontRef));
  229910. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229911. ascent = ascender / totalHeight;
  229912. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229913. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229914. #else
  229915. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229916. if (font.isItalic())
  229917. {
  229918. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229919. toHaveTrait: NSItalicFontMask];
  229920. if (newFont == nsFont)
  229921. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229922. nsFont = newFont;
  229923. }
  229924. if (font.isBold())
  229925. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229926. [nsFont retain];
  229927. ascent = std::abs ((float) [nsFont ascender]);
  229928. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229929. ascent /= totalSize;
  229930. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229931. if (needsItalicTransform)
  229932. {
  229933. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229934. renderingTransform.c = 0.15f;
  229935. }
  229936. #if SUPPORT_ONLY_10_4_FONTS
  229937. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229938. if (atsFont == 0)
  229939. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229940. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229941. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229942. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229943. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229944. #else
  229945. #if SUPPORT_10_4_FONTS
  229946. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229947. {
  229948. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229949. if (atsFont == 0)
  229950. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229951. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229952. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229953. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229954. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229955. }
  229956. else
  229957. #endif
  229958. {
  229959. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229960. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229961. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229962. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229963. }
  229964. #endif
  229965. #endif
  229966. }
  229967. ~MacTypeface()
  229968. {
  229969. #if ! JUCE_IOS
  229970. [nsFont release];
  229971. #endif
  229972. if (fontRef != 0)
  229973. CGFontRelease (fontRef);
  229974. }
  229975. float getAscent() const
  229976. {
  229977. return ascent;
  229978. }
  229979. float getDescent() const
  229980. {
  229981. return 1.0f - ascent;
  229982. }
  229983. float getStringWidth (const String& text)
  229984. {
  229985. if (fontRef == 0 || text.isEmpty())
  229986. return 0;
  229987. const int length = text.length();
  229988. HeapBlock <CGGlyph> glyphs;
  229989. createGlyphsForString (text, length, glyphs);
  229990. float x = 0;
  229991. #if SUPPORT_ONLY_10_4_FONTS
  229992. HeapBlock <NSSize> advances (length);
  229993. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229994. for (int i = 0; i < length; ++i)
  229995. x += advances[i].width;
  229996. #else
  229997. #if SUPPORT_10_4_FONTS
  229998. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229999. {
  230000. HeapBlock <NSSize> advances (length);
  230001. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230002. for (int i = 0; i < length; ++i)
  230003. x += advances[i].width;
  230004. }
  230005. else
  230006. #endif
  230007. {
  230008. HeapBlock <int> advances (length);
  230009. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230010. for (int i = 0; i < length; ++i)
  230011. x += advances[i];
  230012. }
  230013. #endif
  230014. return x * unitsToHeightScaleFactor;
  230015. }
  230016. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230017. {
  230018. xOffsets.add (0);
  230019. if (fontRef == 0 || text.isEmpty())
  230020. return;
  230021. const int length = text.length();
  230022. HeapBlock <CGGlyph> glyphs;
  230023. createGlyphsForString (text, length, glyphs);
  230024. #if SUPPORT_ONLY_10_4_FONTS
  230025. HeapBlock <NSSize> advances (length);
  230026. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230027. int x = 0;
  230028. for (int i = 0; i < length; ++i)
  230029. {
  230030. x += advances[i].width;
  230031. xOffsets.add (x * unitsToHeightScaleFactor);
  230032. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230033. }
  230034. #else
  230035. #if SUPPORT_10_4_FONTS
  230036. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230037. {
  230038. HeapBlock <NSSize> advances (length);
  230039. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230040. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230041. float x = 0;
  230042. for (int i = 0; i < length; ++i)
  230043. {
  230044. x += advances[i].width;
  230045. xOffsets.add (x * unitsToHeightScaleFactor);
  230046. resultGlyphs.add (nsGlyphs[i]);
  230047. }
  230048. }
  230049. else
  230050. #endif
  230051. {
  230052. HeapBlock <int> advances (length);
  230053. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230054. {
  230055. int x = 0;
  230056. for (int i = 0; i < length; ++i)
  230057. {
  230058. x += advances [i];
  230059. xOffsets.add (x * unitsToHeightScaleFactor);
  230060. resultGlyphs.add (glyphs[i]);
  230061. }
  230062. }
  230063. }
  230064. #endif
  230065. }
  230066. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230067. {
  230068. #if JUCE_IOS
  230069. return false;
  230070. #else
  230071. if (nsFont == 0)
  230072. return false;
  230073. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230074. jassert (path.isEmpty());
  230075. const ScopedAutoReleasePool pool;
  230076. NSBezierPath* bez = [NSBezierPath bezierPath];
  230077. [bez moveToPoint: NSMakePoint (0, 0)];
  230078. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230079. inFont: nsFont];
  230080. for (int i = 0; i < [bez elementCount]; ++i)
  230081. {
  230082. NSPoint p[3];
  230083. switch ([bez elementAtIndex: i associatedPoints: p])
  230084. {
  230085. case NSMoveToBezierPathElement:
  230086. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230087. break;
  230088. case NSLineToBezierPathElement:
  230089. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230090. break;
  230091. case NSCurveToBezierPathElement:
  230092. 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);
  230093. break;
  230094. case NSClosePathBezierPathElement:
  230095. path.closeSubPath();
  230096. break;
  230097. default:
  230098. jassertfalse;
  230099. break;
  230100. }
  230101. }
  230102. path.applyTransform (pathTransform);
  230103. return true;
  230104. #endif
  230105. }
  230106. juce_UseDebuggingNewOperator
  230107. CGFontRef fontRef;
  230108. float fontHeightToCGSizeFactor;
  230109. CGAffineTransform renderingTransform;
  230110. private:
  230111. float ascent, unitsToHeightScaleFactor;
  230112. #if JUCE_IOS
  230113. #else
  230114. NSFont* nsFont;
  230115. AffineTransform pathTransform;
  230116. #endif
  230117. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230118. {
  230119. #if SUPPORT_10_4_FONTS
  230120. #if ! SUPPORT_ONLY_10_4_FONTS
  230121. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230122. #endif
  230123. {
  230124. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230125. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230126. for (int i = 0; i < length; ++i)
  230127. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230128. return;
  230129. }
  230130. #endif
  230131. #if ! SUPPORT_ONLY_10_4_FONTS
  230132. if (charToGlyphMapper == 0)
  230133. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230134. glyphs.malloc (length);
  230135. for (int i = 0; i < length; ++i)
  230136. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230137. #endif
  230138. }
  230139. #if ! SUPPORT_ONLY_10_4_FONTS
  230140. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230141. class CharToGlyphMapper
  230142. {
  230143. public:
  230144. CharToGlyphMapper (CGFontRef fontRef)
  230145. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230146. idRangeOffset (0), glyphIndexes (0)
  230147. {
  230148. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230149. if (cmapTable != 0)
  230150. {
  230151. const int numSubtables = getValue16 (cmapTable, 2);
  230152. for (int i = 0; i < numSubtables; ++i)
  230153. {
  230154. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230155. {
  230156. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230157. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230158. {
  230159. const int length = getValue16 (cmapTable, offset + 2);
  230160. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230161. segCount = segCountX2 / 2;
  230162. const int endCodeOffset = offset + 14;
  230163. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230164. const int idDeltaOffset = startCodeOffset + segCountX2;
  230165. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230166. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230167. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230168. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230169. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230170. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230171. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230172. }
  230173. break;
  230174. }
  230175. }
  230176. CFRelease (cmapTable);
  230177. }
  230178. }
  230179. ~CharToGlyphMapper()
  230180. {
  230181. if (endCode != 0)
  230182. {
  230183. CFRelease (endCode);
  230184. CFRelease (startCode);
  230185. CFRelease (idDelta);
  230186. CFRelease (idRangeOffset);
  230187. CFRelease (glyphIndexes);
  230188. }
  230189. }
  230190. int getGlyphForCharacter (const juce_wchar c) const
  230191. {
  230192. for (int i = 0; i < segCount; ++i)
  230193. {
  230194. if (getValue16 (endCode, i * 2) >= c)
  230195. {
  230196. const int start = getValue16 (startCode, i * 2);
  230197. if (start > c)
  230198. break;
  230199. const int delta = getValue16 (idDelta, i * 2);
  230200. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230201. if (rangeOffset == 0)
  230202. return delta + c;
  230203. else
  230204. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230205. }
  230206. }
  230207. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230208. return jmax (-1, (int) c - 29);
  230209. }
  230210. private:
  230211. int segCount;
  230212. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230213. static uint16 getValue16 (CFDataRef data, const int index)
  230214. {
  230215. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230216. }
  230217. static uint32 getValue32 (CFDataRef data, const int index)
  230218. {
  230219. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230220. }
  230221. };
  230222. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230223. #endif
  230224. MacTypeface (const MacTypeface&);
  230225. MacTypeface& operator= (const MacTypeface&);
  230226. };
  230227. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230228. {
  230229. return new MacTypeface (font);
  230230. }
  230231. const StringArray Font::findAllTypefaceNames()
  230232. {
  230233. StringArray names;
  230234. const ScopedAutoReleasePool pool;
  230235. #if JUCE_IOS
  230236. NSArray* fonts = [UIFont familyNames];
  230237. #else
  230238. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230239. #endif
  230240. for (unsigned int i = 0; i < [fonts count]; ++i)
  230241. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230242. names.sort (true);
  230243. return names;
  230244. }
  230245. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230246. {
  230247. #if JUCE_IOS
  230248. defaultSans = "Helvetica";
  230249. defaultSerif = "Times New Roman";
  230250. defaultFixed = "Courier New";
  230251. #else
  230252. defaultSans = "Lucida Grande";
  230253. defaultSerif = "Times New Roman";
  230254. defaultFixed = "Monaco";
  230255. #endif
  230256. }
  230257. #endif
  230258. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230259. // (must go before juce_mac_CoreGraphicsContext.mm)
  230260. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230261. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230262. // compiled on its own).
  230263. #if JUCE_INCLUDED_FILE
  230264. class CoreGraphicsImage : public Image::SharedImage
  230265. {
  230266. public:
  230267. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230268. : Image::SharedImage (format_, width_, height_)
  230269. {
  230270. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230271. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230272. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230273. imageData = imageDataAllocated;
  230274. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230275. : CGColorSpaceCreateDeviceRGB();
  230276. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230277. colourSpace, getCGImageFlags (format_));
  230278. CGColorSpaceRelease (colourSpace);
  230279. }
  230280. ~CoreGraphicsImage()
  230281. {
  230282. CGContextRelease (context);
  230283. }
  230284. Image::ImageType getType() const { return Image::NativeImage; }
  230285. LowLevelGraphicsContext* createLowLevelContext();
  230286. SharedImage* clone()
  230287. {
  230288. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230289. memcpy (im->imageData, imageData, lineStride * height);
  230290. return im;
  230291. }
  230292. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230293. {
  230294. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230295. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230296. {
  230297. return CGBitmapContextCreateImage (nativeImage->context);
  230298. }
  230299. else
  230300. {
  230301. const Image::BitmapData srcData (juceImage, false);
  230302. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230303. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230304. 8, srcData.pixelStride * 8, srcData.lineStride,
  230305. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230306. 0, true, kCGRenderingIntentDefault);
  230307. CGDataProviderRelease (provider);
  230308. return imageRef;
  230309. }
  230310. }
  230311. #if JUCE_MAC
  230312. static NSImage* createNSImage (const Image& image)
  230313. {
  230314. const ScopedAutoReleasePool pool;
  230315. NSImage* im = [[NSImage alloc] init];
  230316. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230317. [im lockFocus];
  230318. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230319. CGImageRef imageRef = createImage (image, false, colourSpace);
  230320. CGColorSpaceRelease (colourSpace);
  230321. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230322. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230323. CGImageRelease (imageRef);
  230324. [im unlockFocus];
  230325. return im;
  230326. }
  230327. #endif
  230328. CGContextRef context;
  230329. HeapBlock<uint8> imageDataAllocated;
  230330. private:
  230331. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230332. {
  230333. #if JUCE_BIG_ENDIAN
  230334. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230335. #else
  230336. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230337. #endif
  230338. }
  230339. };
  230340. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230341. {
  230342. #if USE_COREGRAPHICS_RENDERING
  230343. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230344. #else
  230345. return createSoftwareImage (format, width, height, clearImage);
  230346. #endif
  230347. }
  230348. class CoreGraphicsContext : public LowLevelGraphicsContext
  230349. {
  230350. public:
  230351. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230352. : context (context_),
  230353. flipHeight (flipHeight_),
  230354. state (new SavedState()),
  230355. numGradientLookupEntries (0),
  230356. lastClipRectIsValid (false)
  230357. {
  230358. CGContextRetain (context);
  230359. CGContextSaveGState(context);
  230360. CGContextSetShouldSmoothFonts (context, true);
  230361. CGContextSetShouldAntialias (context, true);
  230362. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230363. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230364. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230365. gradientCallbacks.version = 0;
  230366. gradientCallbacks.evaluate = gradientCallback;
  230367. gradientCallbacks.releaseInfo = 0;
  230368. setFont (Font());
  230369. }
  230370. ~CoreGraphicsContext()
  230371. {
  230372. CGContextRestoreGState (context);
  230373. CGContextRelease (context);
  230374. CGColorSpaceRelease (rgbColourSpace);
  230375. CGColorSpaceRelease (greyColourSpace);
  230376. }
  230377. bool isVectorDevice() const { return false; }
  230378. void setOrigin (int x, int y)
  230379. {
  230380. CGContextTranslateCTM (context, x, -y);
  230381. if (lastClipRectIsValid)
  230382. lastClipRect.translate (-x, -y);
  230383. }
  230384. bool clipToRectangle (const Rectangle<int>& r)
  230385. {
  230386. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230387. if (lastClipRectIsValid)
  230388. {
  230389. // This is actually incorrect, because the actual clip region may be complex, and
  230390. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230391. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230392. // when calculating the resultant clip bounds, and makes the same mistake!
  230393. lastClipRect = lastClipRect.getIntersection (r);
  230394. return ! lastClipRect.isEmpty();
  230395. }
  230396. return ! isClipEmpty();
  230397. }
  230398. bool clipToRectangleList (const RectangleList& clipRegion)
  230399. {
  230400. if (clipRegion.isEmpty())
  230401. {
  230402. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230403. lastClipRectIsValid = true;
  230404. lastClipRect = Rectangle<int>();
  230405. return false;
  230406. }
  230407. else
  230408. {
  230409. const int numRects = clipRegion.getNumRectangles();
  230410. HeapBlock <CGRect> rects (numRects);
  230411. for (int i = 0; i < numRects; ++i)
  230412. {
  230413. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230414. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230415. }
  230416. CGContextClipToRects (context, rects, numRects);
  230417. lastClipRectIsValid = false;
  230418. return ! isClipEmpty();
  230419. }
  230420. }
  230421. void excludeClipRectangle (const Rectangle<int>& r)
  230422. {
  230423. RectangleList remaining (getClipBounds());
  230424. remaining.subtract (r);
  230425. clipToRectangleList (remaining);
  230426. lastClipRectIsValid = false;
  230427. }
  230428. void clipToPath (const Path& path, const AffineTransform& transform)
  230429. {
  230430. createPath (path, transform);
  230431. CGContextClip (context);
  230432. lastClipRectIsValid = false;
  230433. }
  230434. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230435. {
  230436. if (! transform.isSingularity())
  230437. {
  230438. Image singleChannelImage (sourceImage);
  230439. if (sourceImage.getFormat() != Image::SingleChannel)
  230440. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230441. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230442. flip();
  230443. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230444. applyTransform (t);
  230445. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230446. CGContextClipToMask (context, r, image);
  230447. applyTransform (t.inverted());
  230448. flip();
  230449. CGImageRelease (image);
  230450. lastClipRectIsValid = false;
  230451. }
  230452. }
  230453. bool clipRegionIntersects (const Rectangle<int>& r)
  230454. {
  230455. return getClipBounds().intersects (r);
  230456. }
  230457. const Rectangle<int> getClipBounds() const
  230458. {
  230459. if (! lastClipRectIsValid)
  230460. {
  230461. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230462. lastClipRectIsValid = true;
  230463. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230464. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230465. roundToInt (bounds.size.width),
  230466. roundToInt (bounds.size.height));
  230467. }
  230468. return lastClipRect;
  230469. }
  230470. bool isClipEmpty() const
  230471. {
  230472. return getClipBounds().isEmpty();
  230473. }
  230474. void saveState()
  230475. {
  230476. CGContextSaveGState (context);
  230477. stateStack.add (new SavedState (*state));
  230478. }
  230479. void restoreState()
  230480. {
  230481. CGContextRestoreGState (context);
  230482. SavedState* const top = stateStack.getLast();
  230483. if (top != 0)
  230484. {
  230485. state = top;
  230486. stateStack.removeLast (1, false);
  230487. lastClipRectIsValid = false;
  230488. }
  230489. else
  230490. {
  230491. jassertfalse; // trying to pop with an empty stack!
  230492. }
  230493. }
  230494. void setFill (const FillType& fillType)
  230495. {
  230496. state->fillType = fillType;
  230497. if (fillType.isColour())
  230498. {
  230499. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230500. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230501. CGContextSetAlpha (context, 1.0f);
  230502. }
  230503. }
  230504. void setOpacity (float newOpacity)
  230505. {
  230506. state->fillType.setOpacity (newOpacity);
  230507. setFill (state->fillType);
  230508. }
  230509. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230510. {
  230511. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230512. ? kCGInterpolationLow
  230513. : kCGInterpolationHigh);
  230514. }
  230515. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230516. {
  230517. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230518. }
  230519. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230520. {
  230521. if (replaceExistingContents)
  230522. {
  230523. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230524. CGContextClearRect (context, cgRect);
  230525. #else
  230526. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230527. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230528. CGContextClearRect (context, cgRect);
  230529. else
  230530. #endif
  230531. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230532. #endif
  230533. fillCGRect (cgRect, false);
  230534. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230535. }
  230536. else
  230537. {
  230538. if (state->fillType.isColour())
  230539. {
  230540. CGContextFillRect (context, cgRect);
  230541. }
  230542. else if (state->fillType.isGradient())
  230543. {
  230544. CGContextSaveGState (context);
  230545. CGContextClipToRect (context, cgRect);
  230546. drawGradient();
  230547. CGContextRestoreGState (context);
  230548. }
  230549. else
  230550. {
  230551. CGContextSaveGState (context);
  230552. CGContextClipToRect (context, cgRect);
  230553. drawImage (state->fillType.image, state->fillType.transform, true);
  230554. CGContextRestoreGState (context);
  230555. }
  230556. }
  230557. }
  230558. void fillPath (const Path& path, const AffineTransform& transform)
  230559. {
  230560. CGContextSaveGState (context);
  230561. if (state->fillType.isColour())
  230562. {
  230563. flip();
  230564. applyTransform (transform);
  230565. createPath (path);
  230566. if (path.isUsingNonZeroWinding())
  230567. CGContextFillPath (context);
  230568. else
  230569. CGContextEOFillPath (context);
  230570. }
  230571. else
  230572. {
  230573. createPath (path, transform);
  230574. if (path.isUsingNonZeroWinding())
  230575. CGContextClip (context);
  230576. else
  230577. CGContextEOClip (context);
  230578. if (state->fillType.isGradient())
  230579. drawGradient();
  230580. else
  230581. drawImage (state->fillType.image, state->fillType.transform, true);
  230582. }
  230583. CGContextRestoreGState (context);
  230584. }
  230585. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230586. {
  230587. const int iw = sourceImage.getWidth();
  230588. const int ih = sourceImage.getHeight();
  230589. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230590. CGContextSaveGState (context);
  230591. CGContextSetAlpha (context, state->fillType.getOpacity());
  230592. flip();
  230593. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230594. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230595. if (fillEntireClipAsTiles)
  230596. {
  230597. #if JUCE_IOS
  230598. CGContextDrawTiledImage (context, imageRect, image);
  230599. #else
  230600. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230601. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230602. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230603. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230604. CGContextDrawTiledImage (context, imageRect, image);
  230605. else
  230606. #endif
  230607. {
  230608. // Fallback to manually doing a tiled fill on 10.4
  230609. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230610. int x = 0, y = 0;
  230611. while (x > clip.origin.x) x -= iw;
  230612. while (y > clip.origin.y) y -= ih;
  230613. const int right = (int) (clip.origin.x + clip.size.width);
  230614. const int bottom = (int) (clip.origin.y + clip.size.height);
  230615. while (y < bottom)
  230616. {
  230617. for (int x2 = x; x2 < right; x2 += iw)
  230618. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230619. y += ih;
  230620. }
  230621. }
  230622. #endif
  230623. }
  230624. else
  230625. {
  230626. CGContextDrawImage (context, imageRect, image);
  230627. }
  230628. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230629. CGContextRestoreGState (context);
  230630. }
  230631. void drawLine (const Line<float>& line)
  230632. {
  230633. if (state->fillType.isColour())
  230634. {
  230635. CGContextSetLineCap (context, kCGLineCapSquare);
  230636. CGContextSetLineWidth (context, 1.0f);
  230637. CGContextSetRGBStrokeColor (context,
  230638. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230639. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230640. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230641. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230642. CGContextStrokeLineSegments (context, cgLine, 1);
  230643. }
  230644. else
  230645. {
  230646. Path p;
  230647. p.addLineSegment (line, 1.0f);
  230648. fillPath (p, AffineTransform::identity);
  230649. }
  230650. }
  230651. void drawVerticalLine (const int x, float top, float bottom)
  230652. {
  230653. if (state->fillType.isColour())
  230654. {
  230655. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230656. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230657. #else
  230658. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230659. // the x co-ord slightly to trick it..
  230660. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230661. #endif
  230662. }
  230663. else
  230664. {
  230665. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230666. }
  230667. }
  230668. void drawHorizontalLine (const int y, float left, float right)
  230669. {
  230670. if (state->fillType.isColour())
  230671. {
  230672. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230673. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230674. #else
  230675. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230676. // the x co-ord slightly to trick it..
  230677. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230678. #endif
  230679. }
  230680. else
  230681. {
  230682. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230683. }
  230684. }
  230685. void setFont (const Font& newFont)
  230686. {
  230687. if (state->font != newFont)
  230688. {
  230689. state->fontRef = 0;
  230690. state->font = newFont;
  230691. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230692. if (mf != 0)
  230693. {
  230694. state->fontRef = mf->fontRef;
  230695. CGContextSetFont (context, state->fontRef);
  230696. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230697. state->fontTransform = mf->renderingTransform;
  230698. state->fontTransform.a *= state->font.getHorizontalScale();
  230699. CGContextSetTextMatrix (context, state->fontTransform);
  230700. }
  230701. }
  230702. }
  230703. const Font getFont()
  230704. {
  230705. return state->font;
  230706. }
  230707. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230708. {
  230709. if (state->fontRef != 0 && state->fillType.isColour())
  230710. {
  230711. if (transform.isOnlyTranslation())
  230712. {
  230713. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230714. CGGlyph g = glyphNumber;
  230715. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230716. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230717. }
  230718. else
  230719. {
  230720. CGContextSaveGState (context);
  230721. flip();
  230722. applyTransform (transform);
  230723. CGAffineTransform t = state->fontTransform;
  230724. t.d = -t.d;
  230725. CGContextSetTextMatrix (context, t);
  230726. CGGlyph g = glyphNumber;
  230727. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230728. CGContextRestoreGState (context);
  230729. }
  230730. }
  230731. else
  230732. {
  230733. Path p;
  230734. Font& f = state->font;
  230735. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230736. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230737. .followedBy (transform));
  230738. }
  230739. }
  230740. private:
  230741. CGContextRef context;
  230742. const CGFloat flipHeight;
  230743. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230744. CGFunctionCallbacks gradientCallbacks;
  230745. mutable Rectangle<int> lastClipRect;
  230746. mutable bool lastClipRectIsValid;
  230747. struct SavedState
  230748. {
  230749. SavedState()
  230750. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230751. {
  230752. }
  230753. SavedState (const SavedState& other)
  230754. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230755. fontTransform (other.fontTransform)
  230756. {
  230757. }
  230758. ~SavedState()
  230759. {
  230760. }
  230761. FillType fillType;
  230762. Font font;
  230763. CGFontRef fontRef;
  230764. CGAffineTransform fontTransform;
  230765. };
  230766. ScopedPointer <SavedState> state;
  230767. OwnedArray <SavedState> stateStack;
  230768. HeapBlock <PixelARGB> gradientLookupTable;
  230769. int numGradientLookupEntries;
  230770. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230771. {
  230772. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230773. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230774. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230775. colour.unpremultiply();
  230776. outData[0] = colour.getRed() / 255.0f;
  230777. outData[1] = colour.getGreen() / 255.0f;
  230778. outData[2] = colour.getBlue() / 255.0f;
  230779. outData[3] = colour.getAlpha() / 255.0f;
  230780. }
  230781. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230782. {
  230783. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230784. --numGradientLookupEntries;
  230785. CGShadingRef result = 0;
  230786. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230787. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230788. if (gradient.isRadial)
  230789. {
  230790. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230791. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230792. function, true, true);
  230793. }
  230794. else
  230795. {
  230796. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230797. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230798. function, true, true);
  230799. }
  230800. CGFunctionRelease (function);
  230801. return result;
  230802. }
  230803. void drawGradient()
  230804. {
  230805. flip();
  230806. applyTransform (state->fillType.transform);
  230807. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230808. // you draw a gradient with high quality interp enabled).
  230809. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230810. CGContextSetAlpha (context, state->fillType.getOpacity());
  230811. CGContextDrawShading (context, shading);
  230812. CGShadingRelease (shading);
  230813. }
  230814. void createPath (const Path& path) const
  230815. {
  230816. CGContextBeginPath (context);
  230817. Path::Iterator i (path);
  230818. while (i.next())
  230819. {
  230820. switch (i.elementType)
  230821. {
  230822. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230823. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230824. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230825. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230826. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230827. default: jassertfalse; break;
  230828. }
  230829. }
  230830. }
  230831. void createPath (const Path& path, const AffineTransform& transform) const
  230832. {
  230833. CGContextBeginPath (context);
  230834. Path::Iterator i (path);
  230835. while (i.next())
  230836. {
  230837. switch (i.elementType)
  230838. {
  230839. case Path::Iterator::startNewSubPath:
  230840. transform.transformPoint (i.x1, i.y1);
  230841. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230842. break;
  230843. case Path::Iterator::lineTo:
  230844. transform.transformPoint (i.x1, i.y1);
  230845. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230846. break;
  230847. case Path::Iterator::quadraticTo:
  230848. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230849. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230850. break;
  230851. case Path::Iterator::cubicTo:
  230852. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230853. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230854. break;
  230855. case Path::Iterator::closePath:
  230856. CGContextClosePath (context); break;
  230857. default:
  230858. jassertfalse;
  230859. break;
  230860. }
  230861. }
  230862. }
  230863. void flip() const
  230864. {
  230865. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230866. }
  230867. void applyTransform (const AffineTransform& transform) const
  230868. {
  230869. CGAffineTransform t;
  230870. t.a = transform.mat00;
  230871. t.b = transform.mat10;
  230872. t.c = transform.mat01;
  230873. t.d = transform.mat11;
  230874. t.tx = transform.mat02;
  230875. t.ty = transform.mat12;
  230876. CGContextConcatCTM (context, t);
  230877. }
  230878. CoreGraphicsContext (const CoreGraphicsContext&);
  230879. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  230880. };
  230881. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230882. {
  230883. return new CoreGraphicsContext (context, height);
  230884. }
  230885. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230886. const Image juce_loadWithCoreImage (InputStream& input)
  230887. {
  230888. MemoryBlock data;
  230889. input.readIntoMemoryBlock (data, -1);
  230890. #if JUCE_IOS
  230891. JUCE_AUTORELEASEPOOL
  230892. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230893. length: data.getSize()
  230894. freeWhenDone: NO]];
  230895. if (image != nil)
  230896. {
  230897. CGImageRef loadedImage = image.CGImage;
  230898. #else
  230899. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230900. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230901. CGDataProviderRelease (provider);
  230902. if (imageSource != 0)
  230903. {
  230904. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230905. CFRelease (imageSource);
  230906. #endif
  230907. if (loadedImage != 0)
  230908. {
  230909. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  230910. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  230911. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230912. hasAlphaChan, Image::NativeImage);
  230913. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230914. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230915. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230916. CGContextFlush (cgImage->context);
  230917. #if ! JUCE_IOS
  230918. CFRelease (loadedImage);
  230919. #endif
  230920. return image;
  230921. }
  230922. }
  230923. return Image::null;
  230924. }
  230925. #endif
  230926. #endif
  230927. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230928. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230929. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230930. // compiled on its own).
  230931. #if JUCE_INCLUDED_FILE
  230932. class NSViewComponentPeer;
  230933. END_JUCE_NAMESPACE
  230934. @interface NSEvent (JuceDeviceDelta)
  230935. - (float) deviceDeltaX;
  230936. - (float) deviceDeltaY;
  230937. @end
  230938. #define JuceNSView MakeObjCClassName(JuceNSView)
  230939. @interface JuceNSView : NSView<NSTextInput>
  230940. {
  230941. @public
  230942. NSViewComponentPeer* owner;
  230943. NSNotificationCenter* notificationCenter;
  230944. String* stringBeingComposed;
  230945. bool textWasInserted;
  230946. }
  230947. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230948. - (void) dealloc;
  230949. - (BOOL) isOpaque;
  230950. - (void) drawRect: (NSRect) r;
  230951. - (void) mouseDown: (NSEvent*) ev;
  230952. - (void) asyncMouseDown: (NSEvent*) ev;
  230953. - (void) mouseUp: (NSEvent*) ev;
  230954. - (void) asyncMouseUp: (NSEvent*) ev;
  230955. - (void) mouseDragged: (NSEvent*) ev;
  230956. - (void) mouseMoved: (NSEvent*) ev;
  230957. - (void) mouseEntered: (NSEvent*) ev;
  230958. - (void) mouseExited: (NSEvent*) ev;
  230959. - (void) rightMouseDown: (NSEvent*) ev;
  230960. - (void) rightMouseDragged: (NSEvent*) ev;
  230961. - (void) rightMouseUp: (NSEvent*) ev;
  230962. - (void) otherMouseDown: (NSEvent*) ev;
  230963. - (void) otherMouseDragged: (NSEvent*) ev;
  230964. - (void) otherMouseUp: (NSEvent*) ev;
  230965. - (void) scrollWheel: (NSEvent*) ev;
  230966. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230967. - (void) frameChanged: (NSNotification*) n;
  230968. - (void) viewDidMoveToWindow;
  230969. - (void) keyDown: (NSEvent*) ev;
  230970. - (void) keyUp: (NSEvent*) ev;
  230971. // NSTextInput Methods
  230972. - (void) insertText: (id) aString;
  230973. - (void) doCommandBySelector: (SEL) aSelector;
  230974. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230975. - (void) unmarkText;
  230976. - (BOOL) hasMarkedText;
  230977. - (long) conversationIdentifier;
  230978. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230979. - (NSRange) markedRange;
  230980. - (NSRange) selectedRange;
  230981. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230982. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230983. - (NSArray*) validAttributesForMarkedText;
  230984. - (void) flagsChanged: (NSEvent*) ev;
  230985. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230986. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230987. #endif
  230988. - (BOOL) becomeFirstResponder;
  230989. - (BOOL) resignFirstResponder;
  230990. - (BOOL) acceptsFirstResponder;
  230991. - (void) asyncRepaint: (id) rect;
  230992. - (NSArray*) getSupportedDragTypes;
  230993. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230994. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230995. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230996. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230997. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230998. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230999. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231000. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231001. @end
  231002. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231003. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231004. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231005. #else
  231006. @interface JuceNSWindow : NSWindow
  231007. #endif
  231008. {
  231009. @private
  231010. NSViewComponentPeer* owner;
  231011. bool isZooming;
  231012. }
  231013. - (void) setOwner: (NSViewComponentPeer*) owner;
  231014. - (BOOL) canBecomeKeyWindow;
  231015. - (void) becomeKeyWindow;
  231016. - (BOOL) windowShouldClose: (id) window;
  231017. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231018. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231019. - (void) zoom: (id) sender;
  231020. @end
  231021. BEGIN_JUCE_NAMESPACE
  231022. class NSViewComponentPeer : public ComponentPeer
  231023. {
  231024. public:
  231025. NSViewComponentPeer (Component* const component,
  231026. const int windowStyleFlags,
  231027. NSView* viewToAttachTo);
  231028. ~NSViewComponentPeer();
  231029. void* getNativeHandle() const;
  231030. void setVisible (bool shouldBeVisible);
  231031. void setTitle (const String& title);
  231032. void setPosition (int x, int y);
  231033. void setSize (int w, int h);
  231034. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231035. const Rectangle<int> getBounds (const bool global) const;
  231036. const Rectangle<int> getBounds() const;
  231037. const Point<int> getScreenPosition() const;
  231038. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231039. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231040. void setMinimised (bool shouldBeMinimised);
  231041. bool isMinimised() const;
  231042. void setFullScreen (bool shouldBeFullScreen);
  231043. bool isFullScreen() const;
  231044. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231045. const BorderSize getFrameSize() const;
  231046. bool setAlwaysOnTop (bool alwaysOnTop);
  231047. void toFront (bool makeActiveWindow);
  231048. void toBehind (ComponentPeer* other);
  231049. void setIcon (const Image& newIcon);
  231050. const StringArray getAvailableRenderingEngines();
  231051. int getCurrentRenderingEngine() throw();
  231052. void setCurrentRenderingEngine (int index);
  231053. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231054. for example having more than one juce plugin loaded into a host, then when a
  231055. method is called, the actual code that runs might actually be in a different module
  231056. than the one you expect... So any calls to library functions or statics that are
  231057. made inside obj-c methods will probably end up getting executed in a different DLL's
  231058. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231059. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231060. virtual methods of an object that's known to live inside the right module's space.
  231061. */
  231062. virtual void redirectMouseDown (NSEvent* ev);
  231063. virtual void redirectMouseUp (NSEvent* ev);
  231064. virtual void redirectMouseDrag (NSEvent* ev);
  231065. virtual void redirectMouseMove (NSEvent* ev);
  231066. virtual void redirectMouseEnter (NSEvent* ev);
  231067. virtual void redirectMouseExit (NSEvent* ev);
  231068. virtual void redirectMouseWheel (NSEvent* ev);
  231069. void sendMouseEvent (NSEvent* ev);
  231070. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231071. virtual bool redirectKeyDown (NSEvent* ev);
  231072. virtual bool redirectKeyUp (NSEvent* ev);
  231073. virtual void redirectModKeyChange (NSEvent* ev);
  231074. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231075. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231076. #endif
  231077. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231078. virtual bool isOpaque();
  231079. virtual void drawRect (NSRect r);
  231080. virtual bool canBecomeKeyWindow();
  231081. virtual bool windowShouldClose();
  231082. virtual void redirectMovedOrResized();
  231083. virtual void viewMovedToWindow();
  231084. virtual NSRect constrainRect (NSRect r);
  231085. static void showArrowCursorIfNeeded();
  231086. static void updateModifiers (NSEvent* e);
  231087. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231088. static int getKeyCodeFromEvent (NSEvent* ev)
  231089. {
  231090. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231091. int keyCode = unmodified[0];
  231092. if (keyCode == 0x19) // (backwards-tab)
  231093. keyCode = '\t';
  231094. else if (keyCode == 0x03) // (enter)
  231095. keyCode = '\r';
  231096. else
  231097. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231098. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231099. {
  231100. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231101. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231102. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231103. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231104. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231105. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231106. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231107. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231108. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231109. if (keyCode == numPadConversions [i])
  231110. keyCode = numPadConversions [i + 1];
  231111. }
  231112. return keyCode;
  231113. }
  231114. static int64 getMouseTime (NSEvent* e)
  231115. {
  231116. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231117. + (int64) ([e timestamp] * 1000.0);
  231118. }
  231119. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231120. {
  231121. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231122. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231123. }
  231124. static int getModifierForButtonNumber (const NSInteger num)
  231125. {
  231126. return num == 0 ? ModifierKeys::leftButtonModifier
  231127. : (num == 1 ? ModifierKeys::rightButtonModifier
  231128. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231129. }
  231130. virtual void viewFocusGain();
  231131. virtual void viewFocusLoss();
  231132. bool isFocused() const;
  231133. void grabFocus();
  231134. void textInputRequired (const Point<int>& position);
  231135. void repaint (const Rectangle<int>& area);
  231136. void performAnyPendingRepaintsNow();
  231137. juce_UseDebuggingNewOperator
  231138. NSWindow* window;
  231139. JuceNSView* view;
  231140. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231141. static ModifierKeys currentModifiers;
  231142. static ComponentPeer* currentlyFocusedPeer;
  231143. static Array<int> keysCurrentlyDown;
  231144. };
  231145. END_JUCE_NAMESPACE
  231146. @implementation JuceNSView
  231147. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231148. withFrame: (NSRect) frame
  231149. {
  231150. [super initWithFrame: frame];
  231151. owner = owner_;
  231152. stringBeingComposed = 0;
  231153. textWasInserted = false;
  231154. notificationCenter = [NSNotificationCenter defaultCenter];
  231155. [notificationCenter addObserver: self
  231156. selector: @selector (frameChanged:)
  231157. name: NSViewFrameDidChangeNotification
  231158. object: self];
  231159. if (! owner_->isSharedWindow)
  231160. {
  231161. [notificationCenter addObserver: self
  231162. selector: @selector (frameChanged:)
  231163. name: NSWindowDidMoveNotification
  231164. object: owner_->window];
  231165. }
  231166. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231167. return self;
  231168. }
  231169. - (void) dealloc
  231170. {
  231171. [notificationCenter removeObserver: self];
  231172. delete stringBeingComposed;
  231173. [super dealloc];
  231174. }
  231175. - (void) drawRect: (NSRect) r
  231176. {
  231177. if (owner != 0)
  231178. owner->drawRect (r);
  231179. }
  231180. - (BOOL) isOpaque
  231181. {
  231182. return owner == 0 || owner->isOpaque();
  231183. }
  231184. - (void) mouseDown: (NSEvent*) ev
  231185. {
  231186. if (JUCEApplication::isStandaloneApp())
  231187. [self asyncMouseDown: ev];
  231188. else
  231189. // In some host situations, the host will stop modal loops from working
  231190. // correctly if they're called from a mouse event, so we'll trigger
  231191. // the event asynchronously..
  231192. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231193. withObject: ev
  231194. waitUntilDone: NO];
  231195. }
  231196. - (void) asyncMouseDown: (NSEvent*) ev
  231197. {
  231198. if (owner != 0)
  231199. owner->redirectMouseDown (ev);
  231200. }
  231201. - (void) mouseUp: (NSEvent*) ev
  231202. {
  231203. if (! JUCEApplication::isStandaloneApp())
  231204. [self asyncMouseUp: ev];
  231205. else
  231206. // In some host situations, the host will stop modal loops from working
  231207. // correctly if they're called from a mouse event, so we'll trigger
  231208. // the event asynchronously..
  231209. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231210. withObject: ev
  231211. waitUntilDone: NO];
  231212. }
  231213. - (void) asyncMouseUp: (NSEvent*) ev
  231214. {
  231215. if (owner != 0)
  231216. owner->redirectMouseUp (ev);
  231217. }
  231218. - (void) mouseDragged: (NSEvent*) ev
  231219. {
  231220. if (owner != 0)
  231221. owner->redirectMouseDrag (ev);
  231222. }
  231223. - (void) mouseMoved: (NSEvent*) ev
  231224. {
  231225. if (owner != 0)
  231226. owner->redirectMouseMove (ev);
  231227. }
  231228. - (void) mouseEntered: (NSEvent*) ev
  231229. {
  231230. if (owner != 0)
  231231. owner->redirectMouseEnter (ev);
  231232. }
  231233. - (void) mouseExited: (NSEvent*) ev
  231234. {
  231235. if (owner != 0)
  231236. owner->redirectMouseExit (ev);
  231237. }
  231238. - (void) rightMouseDown: (NSEvent*) ev
  231239. {
  231240. [self mouseDown: ev];
  231241. }
  231242. - (void) rightMouseDragged: (NSEvent*) ev
  231243. {
  231244. [self mouseDragged: ev];
  231245. }
  231246. - (void) rightMouseUp: (NSEvent*) ev
  231247. {
  231248. [self mouseUp: ev];
  231249. }
  231250. - (void) otherMouseDown: (NSEvent*) ev
  231251. {
  231252. [self mouseDown: ev];
  231253. }
  231254. - (void) otherMouseDragged: (NSEvent*) ev
  231255. {
  231256. [self mouseDragged: ev];
  231257. }
  231258. - (void) otherMouseUp: (NSEvent*) ev
  231259. {
  231260. [self mouseUp: ev];
  231261. }
  231262. - (void) scrollWheel: (NSEvent*) ev
  231263. {
  231264. if (owner != 0)
  231265. owner->redirectMouseWheel (ev);
  231266. }
  231267. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231268. {
  231269. (void) ev;
  231270. return YES;
  231271. }
  231272. - (void) frameChanged: (NSNotification*) n
  231273. {
  231274. (void) n;
  231275. if (owner != 0)
  231276. owner->redirectMovedOrResized();
  231277. }
  231278. - (void) viewDidMoveToWindow
  231279. {
  231280. if (owner != 0)
  231281. owner->viewMovedToWindow();
  231282. }
  231283. - (void) asyncRepaint: (id) rect
  231284. {
  231285. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231286. [self setNeedsDisplayInRect: *r];
  231287. }
  231288. - (void) keyDown: (NSEvent*) ev
  231289. {
  231290. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231291. textWasInserted = false;
  231292. if (target != 0)
  231293. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231294. else
  231295. deleteAndZero (stringBeingComposed);
  231296. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231297. [super keyDown: ev];
  231298. }
  231299. - (void) keyUp: (NSEvent*) ev
  231300. {
  231301. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231302. [super keyUp: ev];
  231303. }
  231304. - (void) insertText: (id) aString
  231305. {
  231306. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231307. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231308. if ([newText length] > 0)
  231309. {
  231310. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231311. if (target != 0)
  231312. {
  231313. target->insertTextAtCaret (nsStringToJuce (newText));
  231314. textWasInserted = true;
  231315. }
  231316. }
  231317. deleteAndZero (stringBeingComposed);
  231318. }
  231319. - (void) doCommandBySelector: (SEL) aSelector
  231320. {
  231321. (void) aSelector;
  231322. }
  231323. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231324. {
  231325. (void) selectionRange;
  231326. if (stringBeingComposed == 0)
  231327. stringBeingComposed = new String();
  231328. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231329. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231330. if (target != 0)
  231331. {
  231332. const Range<int> currentHighlight (target->getHighlightedRegion());
  231333. target->insertTextAtCaret (*stringBeingComposed);
  231334. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231335. textWasInserted = true;
  231336. }
  231337. }
  231338. - (void) unmarkText
  231339. {
  231340. if (stringBeingComposed != 0)
  231341. {
  231342. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231343. if (target != 0)
  231344. {
  231345. target->insertTextAtCaret (*stringBeingComposed);
  231346. textWasInserted = true;
  231347. }
  231348. }
  231349. deleteAndZero (stringBeingComposed);
  231350. }
  231351. - (BOOL) hasMarkedText
  231352. {
  231353. return stringBeingComposed != 0;
  231354. }
  231355. - (long) conversationIdentifier
  231356. {
  231357. return (long) (pointer_sized_int) self;
  231358. }
  231359. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231360. {
  231361. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231362. if (target != 0)
  231363. {
  231364. const Range<int> r ((int) theRange.location,
  231365. (int) (theRange.location + theRange.length));
  231366. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231367. }
  231368. return nil;
  231369. }
  231370. - (NSRange) markedRange
  231371. {
  231372. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231373. : NSMakeRange (NSNotFound, 0);
  231374. }
  231375. - (NSRange) selectedRange
  231376. {
  231377. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231378. if (target != 0)
  231379. {
  231380. const Range<int> highlight (target->getHighlightedRegion());
  231381. if (! highlight.isEmpty())
  231382. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231383. }
  231384. return NSMakeRange (NSNotFound, 0);
  231385. }
  231386. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231387. {
  231388. (void) theRange;
  231389. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231390. if (comp == 0)
  231391. return NSMakeRect (0, 0, 0, 0);
  231392. const Rectangle<int> bounds (comp->getScreenBounds());
  231393. return NSMakeRect (bounds.getX(),
  231394. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231395. bounds.getWidth(),
  231396. bounds.getHeight());
  231397. }
  231398. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231399. {
  231400. (void) thePoint;
  231401. return NSNotFound;
  231402. }
  231403. - (NSArray*) validAttributesForMarkedText
  231404. {
  231405. return [NSArray array];
  231406. }
  231407. - (void) flagsChanged: (NSEvent*) ev
  231408. {
  231409. if (owner != 0)
  231410. owner->redirectModKeyChange (ev);
  231411. }
  231412. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231413. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231414. {
  231415. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231416. return true;
  231417. return [super performKeyEquivalent: ev];
  231418. }
  231419. #endif
  231420. - (BOOL) becomeFirstResponder
  231421. {
  231422. if (owner != 0)
  231423. owner->viewFocusGain();
  231424. return true;
  231425. }
  231426. - (BOOL) resignFirstResponder
  231427. {
  231428. if (owner != 0)
  231429. owner->viewFocusLoss();
  231430. return true;
  231431. }
  231432. - (BOOL) acceptsFirstResponder
  231433. {
  231434. return owner != 0 && owner->canBecomeKeyWindow();
  231435. }
  231436. - (NSArray*) getSupportedDragTypes
  231437. {
  231438. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231439. }
  231440. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231441. {
  231442. return owner != 0 && owner->sendDragCallback (type, sender);
  231443. }
  231444. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231445. {
  231446. if ([self sendDragCallback: 0 sender: sender])
  231447. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231448. else
  231449. return NSDragOperationNone;
  231450. }
  231451. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231452. {
  231453. if ([self sendDragCallback: 0 sender: sender])
  231454. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231455. else
  231456. return NSDragOperationNone;
  231457. }
  231458. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231459. {
  231460. [self sendDragCallback: 1 sender: sender];
  231461. }
  231462. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231463. {
  231464. [self sendDragCallback: 1 sender: sender];
  231465. }
  231466. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231467. {
  231468. (void) sender;
  231469. return YES;
  231470. }
  231471. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231472. {
  231473. return [self sendDragCallback: 2 sender: sender];
  231474. }
  231475. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231476. {
  231477. (void) sender;
  231478. }
  231479. @end
  231480. @implementation JuceNSWindow
  231481. - (void) setOwner: (NSViewComponentPeer*) owner_
  231482. {
  231483. owner = owner_;
  231484. isZooming = false;
  231485. }
  231486. - (BOOL) canBecomeKeyWindow
  231487. {
  231488. return owner != 0 && owner->canBecomeKeyWindow();
  231489. }
  231490. - (void) becomeKeyWindow
  231491. {
  231492. [super becomeKeyWindow];
  231493. if (owner != 0)
  231494. owner->grabFocus();
  231495. }
  231496. - (BOOL) windowShouldClose: (id) window
  231497. {
  231498. (void) window;
  231499. return owner == 0 || owner->windowShouldClose();
  231500. }
  231501. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231502. {
  231503. (void) screen;
  231504. if (owner != 0)
  231505. frameRect = owner->constrainRect (frameRect);
  231506. return frameRect;
  231507. }
  231508. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231509. {
  231510. (void) window;
  231511. if (isZooming)
  231512. return proposedFrameSize;
  231513. NSRect frameRect = [self frame];
  231514. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231515. frameRect.size = proposedFrameSize;
  231516. if (owner != 0)
  231517. frameRect = owner->constrainRect (frameRect);
  231518. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231519. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231520. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231521. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231522. return frameRect.size;
  231523. }
  231524. - (void) zoom: (id) sender
  231525. {
  231526. isZooming = true;
  231527. [super zoom: sender];
  231528. isZooming = false;
  231529. }
  231530. - (void) windowWillMove: (NSNotification*) notification
  231531. {
  231532. (void) notification;
  231533. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231534. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231535. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231536. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231537. }
  231538. @end
  231539. BEGIN_JUCE_NAMESPACE
  231540. ModifierKeys NSViewComponentPeer::currentModifiers;
  231541. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231542. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231543. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231544. {
  231545. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231546. return true;
  231547. if (keyCode >= 'A' && keyCode <= 'Z'
  231548. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231549. return true;
  231550. if (keyCode >= 'a' && keyCode <= 'z'
  231551. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231552. return true;
  231553. return false;
  231554. }
  231555. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231556. {
  231557. int m = 0;
  231558. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231559. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231560. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231561. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231562. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231563. }
  231564. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231565. {
  231566. updateModifiers (ev);
  231567. int keyCode = getKeyCodeFromEvent (ev);
  231568. if (keyCode != 0)
  231569. {
  231570. if (isKeyDown)
  231571. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231572. else
  231573. keysCurrentlyDown.removeValue (keyCode);
  231574. }
  231575. }
  231576. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231577. {
  231578. return NSViewComponentPeer::currentModifiers;
  231579. }
  231580. void ModifierKeys::updateCurrentModifiers() throw()
  231581. {
  231582. currentModifiers = NSViewComponentPeer::currentModifiers;
  231583. }
  231584. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231585. const int windowStyleFlags,
  231586. NSView* viewToAttachTo)
  231587. : ComponentPeer (component_, windowStyleFlags),
  231588. window (0),
  231589. view (0),
  231590. isSharedWindow (viewToAttachTo != 0),
  231591. fullScreen (false),
  231592. insideDrawRect (false),
  231593. #if USE_COREGRAPHICS_RENDERING
  231594. usingCoreGraphics (true),
  231595. #else
  231596. usingCoreGraphics (false),
  231597. #endif
  231598. recursiveToFrontCall (false)
  231599. {
  231600. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231601. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231602. [view setPostsFrameChangedNotifications: YES];
  231603. if (isSharedWindow)
  231604. {
  231605. window = [viewToAttachTo window];
  231606. [viewToAttachTo addSubview: view];
  231607. setVisible (component->isVisible());
  231608. }
  231609. else
  231610. {
  231611. r.origin.x = (float) component->getX();
  231612. r.origin.y = (float) component->getY();
  231613. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231614. unsigned int style = 0;
  231615. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231616. style = NSBorderlessWindowMask;
  231617. else
  231618. style = NSTitledWindowMask;
  231619. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231620. style |= NSMiniaturizableWindowMask;
  231621. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231622. style |= NSClosableWindowMask;
  231623. if ((windowStyleFlags & windowIsResizable) != 0)
  231624. style |= NSResizableWindowMask;
  231625. window = [[JuceNSWindow alloc] initWithContentRect: r
  231626. styleMask: style
  231627. backing: NSBackingStoreBuffered
  231628. defer: YES];
  231629. [((JuceNSWindow*) window) setOwner: this];
  231630. [window orderOut: nil];
  231631. [window setDelegate: (JuceNSWindow*) window];
  231632. [window setOpaque: component->isOpaque()];
  231633. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231634. if (component->isAlwaysOnTop())
  231635. [window setLevel: NSFloatingWindowLevel];
  231636. [window setContentView: view];
  231637. [window setAutodisplay: YES];
  231638. [window setAcceptsMouseMovedEvents: YES];
  231639. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231640. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231641. [window setReleasedWhenClosed: YES];
  231642. [window retain];
  231643. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231644. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231645. }
  231646. setTitle (component->getName());
  231647. }
  231648. NSViewComponentPeer::~NSViewComponentPeer()
  231649. {
  231650. view->owner = 0;
  231651. [view removeFromSuperview];
  231652. [view release];
  231653. if (! isSharedWindow)
  231654. {
  231655. [((JuceNSWindow*) window) setOwner: 0];
  231656. [window close];
  231657. [window release];
  231658. }
  231659. }
  231660. void* NSViewComponentPeer::getNativeHandle() const
  231661. {
  231662. return view;
  231663. }
  231664. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231665. {
  231666. if (isSharedWindow)
  231667. {
  231668. [view setHidden: ! shouldBeVisible];
  231669. }
  231670. else
  231671. {
  231672. if (shouldBeVisible)
  231673. {
  231674. [window orderFront: nil];
  231675. handleBroughtToFront();
  231676. }
  231677. else
  231678. {
  231679. [window orderOut: nil];
  231680. }
  231681. }
  231682. }
  231683. void NSViewComponentPeer::setTitle (const String& title)
  231684. {
  231685. const ScopedAutoReleasePool pool;
  231686. if (! isSharedWindow)
  231687. [window setTitle: juceStringToNS (title)];
  231688. }
  231689. void NSViewComponentPeer::setPosition (int x, int y)
  231690. {
  231691. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231692. }
  231693. void NSViewComponentPeer::setSize (int w, int h)
  231694. {
  231695. setBounds (component->getX(), component->getY(), w, h, false);
  231696. }
  231697. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231698. {
  231699. fullScreen = isNowFullScreen;
  231700. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231701. if (isSharedWindow)
  231702. {
  231703. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231704. if ([view frame].size.width != r.size.width
  231705. || [view frame].size.height != r.size.height)
  231706. [view setNeedsDisplay: true];
  231707. [view setFrame: r];
  231708. }
  231709. else
  231710. {
  231711. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231712. [window setFrame: [window frameRectForContentRect: r]
  231713. display: true];
  231714. }
  231715. }
  231716. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231717. {
  231718. NSRect r = [view frame];
  231719. if (global && [view window] != 0)
  231720. {
  231721. r = [view convertRect: r toView: nil];
  231722. NSRect wr = [[view window] frame];
  231723. r.origin.x += wr.origin.x;
  231724. r.origin.y += wr.origin.y;
  231725. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231726. }
  231727. else
  231728. {
  231729. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231730. }
  231731. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  231732. }
  231733. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231734. {
  231735. return getBounds (! isSharedWindow);
  231736. }
  231737. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231738. {
  231739. return getBounds (true).getPosition();
  231740. }
  231741. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231742. {
  231743. return relativePosition + getScreenPosition();
  231744. }
  231745. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231746. {
  231747. return screenPosition - getScreenPosition();
  231748. }
  231749. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231750. {
  231751. if (constrainer != 0)
  231752. {
  231753. NSRect current = [window frame];
  231754. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231755. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231756. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  231757. (int) r.size.width, (int) r.size.height);
  231758. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  231759. (int) current.size.width, (int) current.size.height);
  231760. constrainer->checkBounds (pos, original,
  231761. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231762. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231763. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231764. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231765. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231766. r.origin.x = pos.getX();
  231767. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231768. r.size.width = pos.getWidth();
  231769. r.size.height = pos.getHeight();
  231770. }
  231771. return r;
  231772. }
  231773. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231774. {
  231775. if (! isSharedWindow)
  231776. {
  231777. if (shouldBeMinimised)
  231778. [window miniaturize: nil];
  231779. else
  231780. [window deminiaturize: nil];
  231781. }
  231782. }
  231783. bool NSViewComponentPeer::isMinimised() const
  231784. {
  231785. return window != 0 && [window isMiniaturized];
  231786. }
  231787. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231788. {
  231789. if (! isSharedWindow)
  231790. {
  231791. Rectangle<int> r (lastNonFullscreenBounds);
  231792. setMinimised (false);
  231793. if (fullScreen != shouldBeFullScreen)
  231794. {
  231795. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231796. {
  231797. fullScreen = true;
  231798. [window performZoom: nil];
  231799. }
  231800. else
  231801. {
  231802. if (shouldBeFullScreen)
  231803. r = Desktop::getInstance().getMainMonitorArea();
  231804. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231805. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231806. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231807. }
  231808. }
  231809. }
  231810. }
  231811. bool NSViewComponentPeer::isFullScreen() const
  231812. {
  231813. return fullScreen;
  231814. }
  231815. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231816. {
  231817. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231818. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231819. return false;
  231820. NSPoint p;
  231821. p.x = (float) position.getX();
  231822. p.y = (float) position.getY();
  231823. NSView* v = [view hitTest: p];
  231824. if (trueIfInAChildWindow)
  231825. return v != nil;
  231826. return v == view;
  231827. }
  231828. const BorderSize NSViewComponentPeer::getFrameSize() const
  231829. {
  231830. BorderSize b;
  231831. if (! isSharedWindow)
  231832. {
  231833. NSRect v = [view convertRect: [view frame] toView: nil];
  231834. NSRect w = [window frame];
  231835. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231836. b.setBottom ((int) v.origin.y);
  231837. b.setLeft ((int) v.origin.x);
  231838. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231839. }
  231840. return b;
  231841. }
  231842. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231843. {
  231844. if (! isSharedWindow)
  231845. {
  231846. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231847. : NSNormalWindowLevel];
  231848. }
  231849. return true;
  231850. }
  231851. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231852. {
  231853. if (isSharedWindow)
  231854. {
  231855. [[view superview] addSubview: view
  231856. positioned: NSWindowAbove
  231857. relativeTo: nil];
  231858. }
  231859. if (window != 0 && component->isVisible())
  231860. {
  231861. if (makeActiveWindow)
  231862. [window makeKeyAndOrderFront: nil];
  231863. else
  231864. [window orderFront: nil];
  231865. if (! recursiveToFrontCall)
  231866. {
  231867. recursiveToFrontCall = true;
  231868. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231869. handleBroughtToFront();
  231870. recursiveToFrontCall = false;
  231871. }
  231872. }
  231873. }
  231874. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231875. {
  231876. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231877. jassert (otherPeer != 0); // wrong type of window?
  231878. if (otherPeer != 0)
  231879. {
  231880. if (isSharedWindow)
  231881. {
  231882. [[view superview] addSubview: view
  231883. positioned: NSWindowBelow
  231884. relativeTo: otherPeer->view];
  231885. }
  231886. else
  231887. {
  231888. [window orderWindow: NSWindowBelow
  231889. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231890. : nil ];
  231891. }
  231892. }
  231893. }
  231894. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231895. {
  231896. // to do..
  231897. }
  231898. void NSViewComponentPeer::viewFocusGain()
  231899. {
  231900. if (currentlyFocusedPeer != this)
  231901. {
  231902. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231903. currentlyFocusedPeer->handleFocusLoss();
  231904. currentlyFocusedPeer = this;
  231905. handleFocusGain();
  231906. }
  231907. }
  231908. void NSViewComponentPeer::viewFocusLoss()
  231909. {
  231910. if (currentlyFocusedPeer == this)
  231911. {
  231912. currentlyFocusedPeer = 0;
  231913. handleFocusLoss();
  231914. }
  231915. }
  231916. void juce_HandleProcessFocusChange()
  231917. {
  231918. NSViewComponentPeer::keysCurrentlyDown.clear();
  231919. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231920. {
  231921. if (Process::isForegroundProcess())
  231922. {
  231923. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231924. ComponentPeer::bringModalComponentToFront();
  231925. }
  231926. else
  231927. {
  231928. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231929. // turn kiosk mode off if we lose focus..
  231930. Desktop::getInstance().setKioskModeComponent (0);
  231931. }
  231932. }
  231933. }
  231934. bool NSViewComponentPeer::isFocused() const
  231935. {
  231936. return isSharedWindow ? this == currentlyFocusedPeer
  231937. : (window != 0 && [window isKeyWindow]);
  231938. }
  231939. void NSViewComponentPeer::grabFocus()
  231940. {
  231941. if (window != 0)
  231942. {
  231943. [window makeKeyWindow];
  231944. [window makeFirstResponder: view];
  231945. viewFocusGain();
  231946. }
  231947. }
  231948. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231949. {
  231950. }
  231951. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231952. {
  231953. String unicode (nsStringToJuce ([ev characters]));
  231954. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231955. int keyCode = getKeyCodeFromEvent (ev);
  231956. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231957. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231958. if (unicode.isNotEmpty() || keyCode != 0)
  231959. {
  231960. if (isKeyDown)
  231961. {
  231962. bool used = false;
  231963. while (unicode.length() > 0)
  231964. {
  231965. juce_wchar textCharacter = unicode[0];
  231966. unicode = unicode.substring (1);
  231967. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231968. textCharacter = 0;
  231969. used = handleKeyUpOrDown (true) || used;
  231970. used = handleKeyPress (keyCode, textCharacter) || used;
  231971. }
  231972. return used;
  231973. }
  231974. else
  231975. {
  231976. if (handleKeyUpOrDown (false))
  231977. return true;
  231978. }
  231979. }
  231980. return false;
  231981. }
  231982. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231983. {
  231984. updateKeysDown (ev, true);
  231985. bool used = handleKeyEvent (ev, true);
  231986. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231987. {
  231988. // for command keys, the key-up event is thrown away, so simulate one..
  231989. updateKeysDown (ev, false);
  231990. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231991. }
  231992. // (If we're running modally, don't allow unused keystrokes to be passed
  231993. // along to other blocked views..)
  231994. if (Component::getCurrentlyModalComponent() != 0)
  231995. used = true;
  231996. return used;
  231997. }
  231998. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231999. {
  232000. updateKeysDown (ev, false);
  232001. return handleKeyEvent (ev, false)
  232002. || Component::getCurrentlyModalComponent() != 0;
  232003. }
  232004. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232005. {
  232006. keysCurrentlyDown.clear();
  232007. handleKeyUpOrDown (true);
  232008. updateModifiers (ev);
  232009. handleModifierKeysChange();
  232010. }
  232011. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232012. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232013. {
  232014. if ([ev type] == NSKeyDown)
  232015. return redirectKeyDown (ev);
  232016. else if ([ev type] == NSKeyUp)
  232017. return redirectKeyUp (ev);
  232018. return false;
  232019. }
  232020. #endif
  232021. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232022. {
  232023. updateModifiers (ev);
  232024. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232025. }
  232026. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232027. {
  232028. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232029. sendMouseEvent (ev);
  232030. }
  232031. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232032. {
  232033. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232034. sendMouseEvent (ev);
  232035. showArrowCursorIfNeeded();
  232036. }
  232037. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232038. {
  232039. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232040. sendMouseEvent (ev);
  232041. }
  232042. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232043. {
  232044. currentModifiers = currentModifiers.withoutMouseButtons();
  232045. sendMouseEvent (ev);
  232046. showArrowCursorIfNeeded();
  232047. }
  232048. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232049. {
  232050. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232051. currentModifiers = currentModifiers.withoutMouseButtons();
  232052. sendMouseEvent (ev);
  232053. }
  232054. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232055. {
  232056. currentModifiers = currentModifiers.withoutMouseButtons();
  232057. sendMouseEvent (ev);
  232058. }
  232059. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232060. {
  232061. updateModifiers (ev);
  232062. float x = 0, y = 0;
  232063. @try
  232064. {
  232065. x = [ev deviceDeltaX] * 0.5f;
  232066. y = [ev deviceDeltaY] * 0.5f;
  232067. }
  232068. @catch (...)
  232069. {}
  232070. if (x == 0 && y == 0)
  232071. {
  232072. x = [ev deltaX] * 10.0f;
  232073. y = [ev deltaY] * 10.0f;
  232074. }
  232075. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232076. }
  232077. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232078. {
  232079. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232080. if (mouse.getComponentUnderMouse() == 0
  232081. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232082. {
  232083. [[NSCursor arrowCursor] set];
  232084. }
  232085. }
  232086. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232087. {
  232088. NSString* bestType
  232089. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232090. if (bestType == nil)
  232091. return false;
  232092. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232093. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232094. StringArray files;
  232095. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232096. if (list == nil)
  232097. return false;
  232098. if ([list isKindOfClass: [NSArray class]])
  232099. {
  232100. NSArray* items = (NSArray*) list;
  232101. for (unsigned int i = 0; i < [items count]; ++i)
  232102. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232103. }
  232104. if (files.size() == 0)
  232105. return false;
  232106. if (type == 0)
  232107. handleFileDragMove (files, pos);
  232108. else if (type == 1)
  232109. handleFileDragExit (files);
  232110. else if (type == 2)
  232111. handleFileDragDrop (files, pos);
  232112. return true;
  232113. }
  232114. bool NSViewComponentPeer::isOpaque()
  232115. {
  232116. return component == 0 || component->isOpaque();
  232117. }
  232118. void NSViewComponentPeer::drawRect (NSRect r)
  232119. {
  232120. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232121. return;
  232122. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232123. if (! component->isOpaque())
  232124. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232125. #if USE_COREGRAPHICS_RENDERING
  232126. if (usingCoreGraphics)
  232127. {
  232128. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232129. insideDrawRect = true;
  232130. handlePaint (context);
  232131. insideDrawRect = false;
  232132. }
  232133. else
  232134. #endif
  232135. {
  232136. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232137. (int) (r.size.width + 0.5f),
  232138. (int) (r.size.height + 0.5f),
  232139. ! getComponent()->isOpaque());
  232140. const int xOffset = -roundToInt (r.origin.x);
  232141. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232142. const NSRect* rects = 0;
  232143. NSInteger numRects = 0;
  232144. [view getRectsBeingDrawn: &rects count: &numRects];
  232145. const Rectangle<int> clipBounds (temp.getBounds());
  232146. RectangleList clip;
  232147. for (int i = 0; i < numRects; ++i)
  232148. {
  232149. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232150. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232151. roundToInt (rects[i].size.width),
  232152. roundToInt (rects[i].size.height))));
  232153. }
  232154. if (! clip.isEmpty())
  232155. {
  232156. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232157. insideDrawRect = true;
  232158. handlePaint (context);
  232159. insideDrawRect = false;
  232160. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232161. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232162. CGColorSpaceRelease (colourSpace);
  232163. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232164. CGImageRelease (image);
  232165. }
  232166. }
  232167. }
  232168. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232169. {
  232170. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232171. #if USE_COREGRAPHICS_RENDERING
  232172. s.add ("CoreGraphics Renderer");
  232173. #endif
  232174. return s;
  232175. }
  232176. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232177. {
  232178. return usingCoreGraphics ? 1 : 0;
  232179. }
  232180. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232181. {
  232182. #if USE_COREGRAPHICS_RENDERING
  232183. if (usingCoreGraphics != (index > 0))
  232184. {
  232185. usingCoreGraphics = index > 0;
  232186. [view setNeedsDisplay: true];
  232187. }
  232188. #endif
  232189. }
  232190. bool NSViewComponentPeer::canBecomeKeyWindow()
  232191. {
  232192. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232193. }
  232194. bool NSViewComponentPeer::windowShouldClose()
  232195. {
  232196. if (! isValidPeer (this))
  232197. return YES;
  232198. handleUserClosingWindow();
  232199. return NO;
  232200. }
  232201. void NSViewComponentPeer::redirectMovedOrResized()
  232202. {
  232203. handleMovedOrResized();
  232204. }
  232205. void NSViewComponentPeer::viewMovedToWindow()
  232206. {
  232207. if (isSharedWindow)
  232208. window = [view window];
  232209. }
  232210. void Desktop::createMouseInputSources()
  232211. {
  232212. mouseSources.add (new MouseInputSource (0, true));
  232213. }
  232214. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232215. {
  232216. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232217. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232218. // is apparently still available in 64-bit apps..
  232219. if (enableOrDisable)
  232220. {
  232221. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232222. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232223. }
  232224. else
  232225. {
  232226. SetSystemUIMode (kUIModeNormal, 0);
  232227. }
  232228. }
  232229. class AsyncRepaintMessage : public CallbackMessage
  232230. {
  232231. public:
  232232. NSViewComponentPeer* const peer;
  232233. const Rectangle<int> rect;
  232234. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232235. : peer (peer_), rect (rect_)
  232236. {
  232237. }
  232238. void messageCallback()
  232239. {
  232240. if (ComponentPeer::isValidPeer (peer))
  232241. peer->repaint (rect);
  232242. }
  232243. };
  232244. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232245. {
  232246. if (insideDrawRect)
  232247. {
  232248. (new AsyncRepaintMessage (this, area))->post();
  232249. }
  232250. else
  232251. {
  232252. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232253. (float) area.getWidth(), (float) area.getHeight())];
  232254. }
  232255. }
  232256. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232257. {
  232258. [view displayIfNeeded];
  232259. }
  232260. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232261. {
  232262. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232263. }
  232264. const Image juce_createIconForFile (const File& file)
  232265. {
  232266. const ScopedAutoReleasePool pool;
  232267. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232268. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232269. [NSGraphicsContext saveGraphicsState];
  232270. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232271. [image drawAtPoint: NSMakePoint (0, 0)
  232272. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232273. operation: NSCompositeSourceOver fraction: 1.0f];
  232274. [[NSGraphicsContext currentContext] flushGraphics];
  232275. [NSGraphicsContext restoreGraphicsState];
  232276. return Image (result);
  232277. }
  232278. const int KeyPress::spaceKey = ' ';
  232279. const int KeyPress::returnKey = 0x0d;
  232280. const int KeyPress::escapeKey = 0x1b;
  232281. const int KeyPress::backspaceKey = 0x7f;
  232282. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232283. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232284. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232285. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232286. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232287. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232288. const int KeyPress::endKey = NSEndFunctionKey;
  232289. const int KeyPress::homeKey = NSHomeFunctionKey;
  232290. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232291. const int KeyPress::insertKey = -1;
  232292. const int KeyPress::tabKey = 9;
  232293. const int KeyPress::F1Key = NSF1FunctionKey;
  232294. const int KeyPress::F2Key = NSF2FunctionKey;
  232295. const int KeyPress::F3Key = NSF3FunctionKey;
  232296. const int KeyPress::F4Key = NSF4FunctionKey;
  232297. const int KeyPress::F5Key = NSF5FunctionKey;
  232298. const int KeyPress::F6Key = NSF6FunctionKey;
  232299. const int KeyPress::F7Key = NSF7FunctionKey;
  232300. const int KeyPress::F8Key = NSF8FunctionKey;
  232301. const int KeyPress::F9Key = NSF9FunctionKey;
  232302. const int KeyPress::F10Key = NSF10FunctionKey;
  232303. const int KeyPress::F11Key = NSF1FunctionKey;
  232304. const int KeyPress::F12Key = NSF12FunctionKey;
  232305. const int KeyPress::F13Key = NSF13FunctionKey;
  232306. const int KeyPress::F14Key = NSF14FunctionKey;
  232307. const int KeyPress::F15Key = NSF15FunctionKey;
  232308. const int KeyPress::F16Key = NSF16FunctionKey;
  232309. const int KeyPress::numberPad0 = 0x30020;
  232310. const int KeyPress::numberPad1 = 0x30021;
  232311. const int KeyPress::numberPad2 = 0x30022;
  232312. const int KeyPress::numberPad3 = 0x30023;
  232313. const int KeyPress::numberPad4 = 0x30024;
  232314. const int KeyPress::numberPad5 = 0x30025;
  232315. const int KeyPress::numberPad6 = 0x30026;
  232316. const int KeyPress::numberPad7 = 0x30027;
  232317. const int KeyPress::numberPad8 = 0x30028;
  232318. const int KeyPress::numberPad9 = 0x30029;
  232319. const int KeyPress::numberPadAdd = 0x3002a;
  232320. const int KeyPress::numberPadSubtract = 0x3002b;
  232321. const int KeyPress::numberPadMultiply = 0x3002c;
  232322. const int KeyPress::numberPadDivide = 0x3002d;
  232323. const int KeyPress::numberPadSeparator = 0x3002e;
  232324. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232325. const int KeyPress::numberPadEquals = 0x30030;
  232326. const int KeyPress::numberPadDelete = 0x30031;
  232327. const int KeyPress::playKey = 0x30000;
  232328. const int KeyPress::stopKey = 0x30001;
  232329. const int KeyPress::fastForwardKey = 0x30002;
  232330. const int KeyPress::rewindKey = 0x30003;
  232331. #endif
  232332. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232333. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232335. // compiled on its own).
  232336. #if JUCE_INCLUDED_FILE
  232337. #if JUCE_MAC
  232338. namespace MouseCursorHelpers
  232339. {
  232340. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232341. {
  232342. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232343. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232344. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232345. [im release];
  232346. return c;
  232347. }
  232348. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232349. {
  232350. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232351. BufferedInputStream buf (&fileStream, 4096, false);
  232352. PNGImageFormat pngFormat;
  232353. Image im (pngFormat.decodeImage (buf));
  232354. if (im.isValid())
  232355. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232356. jassertfalse;
  232357. return 0;
  232358. }
  232359. }
  232360. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232361. {
  232362. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232363. }
  232364. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232365. {
  232366. const ScopedAutoReleasePool pool;
  232367. NSCursor* c = 0;
  232368. switch (type)
  232369. {
  232370. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232371. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232372. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232373. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232374. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232375. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232376. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232377. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232378. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232379. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232380. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232381. case UpDownResizeCursor:
  232382. case TopEdgeResizeCursor:
  232383. case BottomEdgeResizeCursor:
  232384. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232385. case TopLeftCornerResizeCursor:
  232386. case BottomRightCornerResizeCursor:
  232387. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232388. case TopRightCornerResizeCursor:
  232389. case BottomLeftCornerResizeCursor:
  232390. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232391. case UpDownLeftRightResizeCursor:
  232392. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232393. default:
  232394. jassertfalse;
  232395. break;
  232396. }
  232397. [c retain];
  232398. return c;
  232399. }
  232400. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232401. {
  232402. [((NSCursor*) cursorHandle) release];
  232403. }
  232404. void MouseCursor::showInAllWindows() const
  232405. {
  232406. showInWindow (0);
  232407. }
  232408. void MouseCursor::showInWindow (ComponentPeer*) const
  232409. {
  232410. [((NSCursor*) getHandle()) set];
  232411. }
  232412. #else
  232413. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232414. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232415. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232416. void MouseCursor::showInAllWindows() const {}
  232417. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232418. #endif
  232419. #endif
  232420. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232421. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232422. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232423. // compiled on its own).
  232424. #if JUCE_INCLUDED_FILE
  232425. class NSViewComponentInternal : public ComponentMovementWatcher
  232426. {
  232427. Component* const owner;
  232428. NSViewComponentPeer* currentPeer;
  232429. bool wasShowing;
  232430. public:
  232431. NSView* const view;
  232432. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232433. : ComponentMovementWatcher (owner_),
  232434. owner (owner_),
  232435. currentPeer (0),
  232436. wasShowing (false),
  232437. view (view_)
  232438. {
  232439. [view_ retain];
  232440. if (owner_->isShowing())
  232441. componentPeerChanged();
  232442. }
  232443. ~NSViewComponentInternal()
  232444. {
  232445. [view removeFromSuperview];
  232446. [view release];
  232447. }
  232448. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232449. {
  232450. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232451. // The ComponentMovementWatcher version of this method avoids calling
  232452. // us when the top-level comp is resized, but for an NSView we need to know this
  232453. // because with inverted co-ords, we need to update the position even if the
  232454. // top-left pos hasn't changed
  232455. if (comp.isOnDesktop() && wasResized)
  232456. componentMovedOrResized (wasMoved, wasResized);
  232457. }
  232458. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232459. {
  232460. Component* const topComp = owner->getTopLevelComponent();
  232461. if (topComp->getPeer() != 0)
  232462. {
  232463. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232464. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232465. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232466. [view setFrame: r];
  232467. }
  232468. }
  232469. void componentPeerChanged()
  232470. {
  232471. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232472. if (currentPeer != peer)
  232473. {
  232474. [view removeFromSuperview];
  232475. currentPeer = peer;
  232476. if (peer != 0)
  232477. {
  232478. [peer->view addSubview: view];
  232479. componentMovedOrResized (false, false);
  232480. }
  232481. }
  232482. [view setHidden: ! owner->isShowing()];
  232483. }
  232484. void componentVisibilityChanged (Component&)
  232485. {
  232486. componentPeerChanged();
  232487. }
  232488. juce_UseDebuggingNewOperator
  232489. private:
  232490. NSViewComponentInternal (const NSViewComponentInternal&);
  232491. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232492. };
  232493. NSViewComponent::NSViewComponent()
  232494. {
  232495. }
  232496. NSViewComponent::~NSViewComponent()
  232497. {
  232498. }
  232499. void NSViewComponent::setView (void* view)
  232500. {
  232501. if (view != getView())
  232502. {
  232503. if (view != 0)
  232504. info = new NSViewComponentInternal ((NSView*) view, this);
  232505. else
  232506. info = 0;
  232507. }
  232508. }
  232509. void* NSViewComponent::getView() const
  232510. {
  232511. return info == 0 ? 0 : info->view;
  232512. }
  232513. void NSViewComponent::paint (Graphics&)
  232514. {
  232515. }
  232516. #endif
  232517. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232518. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232519. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232520. // compiled on its own).
  232521. #if JUCE_INCLUDED_FILE
  232522. AppleRemoteDevice::AppleRemoteDevice()
  232523. : device (0),
  232524. queue (0),
  232525. remoteId (0)
  232526. {
  232527. }
  232528. AppleRemoteDevice::~AppleRemoteDevice()
  232529. {
  232530. stop();
  232531. }
  232532. static io_object_t getAppleRemoteDevice()
  232533. {
  232534. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232535. io_iterator_t iter = 0;
  232536. io_object_t iod = 0;
  232537. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232538. && iter != 0)
  232539. {
  232540. iod = IOIteratorNext (iter);
  232541. }
  232542. IOObjectRelease (iter);
  232543. return iod;
  232544. }
  232545. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232546. {
  232547. jassert (*device == 0);
  232548. io_name_t classname;
  232549. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232550. {
  232551. IOCFPlugInInterface** cfPlugInInterface = 0;
  232552. SInt32 score = 0;
  232553. if (IOCreatePlugInInterfaceForService (iod,
  232554. kIOHIDDeviceUserClientTypeID,
  232555. kIOCFPlugInInterfaceID,
  232556. &cfPlugInInterface,
  232557. &score) == kIOReturnSuccess)
  232558. {
  232559. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232560. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232561. device);
  232562. (void) hr;
  232563. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232564. }
  232565. }
  232566. return *device != 0;
  232567. }
  232568. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232569. {
  232570. if (queue != 0)
  232571. return true;
  232572. stop();
  232573. bool result = false;
  232574. io_object_t iod = getAppleRemoteDevice();
  232575. if (iod != 0)
  232576. {
  232577. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232578. result = true;
  232579. else
  232580. stop();
  232581. IOObjectRelease (iod);
  232582. }
  232583. return result;
  232584. }
  232585. void AppleRemoteDevice::stop()
  232586. {
  232587. if (queue != 0)
  232588. {
  232589. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232590. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232591. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232592. queue = 0;
  232593. }
  232594. if (device != 0)
  232595. {
  232596. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232597. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232598. device = 0;
  232599. }
  232600. }
  232601. bool AppleRemoteDevice::isActive() const
  232602. {
  232603. return queue != 0;
  232604. }
  232605. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232606. {
  232607. if (result == kIOReturnSuccess)
  232608. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232609. }
  232610. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232611. {
  232612. Array <int> cookies;
  232613. CFArrayRef elements;
  232614. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232615. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232616. return false;
  232617. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232618. {
  232619. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232620. // get the cookie
  232621. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232622. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232623. continue;
  232624. long number;
  232625. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232626. continue;
  232627. cookies.add ((int) number);
  232628. }
  232629. CFRelease (elements);
  232630. if ((*(IOHIDDeviceInterface**) device)
  232631. ->open ((IOHIDDeviceInterface**) device,
  232632. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232633. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232634. {
  232635. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232636. if (queue != 0)
  232637. {
  232638. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232639. for (int i = 0; i < cookies.size(); ++i)
  232640. {
  232641. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232642. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232643. }
  232644. CFRunLoopSourceRef eventSource;
  232645. if ((*(IOHIDQueueInterface**) queue)
  232646. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232647. {
  232648. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232649. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232650. {
  232651. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232652. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232653. return true;
  232654. }
  232655. }
  232656. }
  232657. }
  232658. return false;
  232659. }
  232660. void AppleRemoteDevice::handleCallbackInternal()
  232661. {
  232662. int totalValues = 0;
  232663. AbsoluteTime nullTime = { 0, 0 };
  232664. char cookies [12];
  232665. int numCookies = 0;
  232666. while (numCookies < numElementsInArray (cookies))
  232667. {
  232668. IOHIDEventStruct e;
  232669. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232670. break;
  232671. if ((int) e.elementCookie == 19)
  232672. {
  232673. remoteId = e.value;
  232674. buttonPressed (switched, false);
  232675. }
  232676. else
  232677. {
  232678. totalValues += e.value;
  232679. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232680. }
  232681. }
  232682. cookies [numCookies++] = 0;
  232683. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232684. static const char buttonPatterns[] =
  232685. {
  232686. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232687. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232688. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232689. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232690. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232691. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232692. 0x1f, 0x12, 0x04, 0x02, 0,
  232693. 0x1f, 0x12, 0x03, 0x02, 0,
  232694. 0x1f, 0x12, 0x1f, 0x12, 0,
  232695. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232696. 19, 0
  232697. };
  232698. int buttonNum = (int) menuButton;
  232699. int i = 0;
  232700. while (i < numElementsInArray (buttonPatterns))
  232701. {
  232702. if (strcmp (cookies, buttonPatterns + i) == 0)
  232703. {
  232704. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232705. break;
  232706. }
  232707. i += (int) strlen (buttonPatterns + i) + 1;
  232708. ++buttonNum;
  232709. }
  232710. }
  232711. #endif
  232712. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232713. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232714. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232715. // compiled on its own).
  232716. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232717. #if JUCE_MAC
  232718. END_JUCE_NAMESPACE
  232719. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232720. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232721. {
  232722. CriticalSection* contextLock;
  232723. bool needsUpdate;
  232724. }
  232725. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232726. - (bool) makeActive;
  232727. - (void) makeInactive;
  232728. - (void) reshape;
  232729. @end
  232730. @implementation ThreadSafeNSOpenGLView
  232731. - (id) initWithFrame: (NSRect) frameRect
  232732. pixelFormat: (NSOpenGLPixelFormat*) format
  232733. {
  232734. contextLock = new CriticalSection();
  232735. self = [super initWithFrame: frameRect pixelFormat: format];
  232736. if (self != nil)
  232737. [[NSNotificationCenter defaultCenter] addObserver: self
  232738. selector: @selector (_surfaceNeedsUpdate:)
  232739. name: NSViewGlobalFrameDidChangeNotification
  232740. object: self];
  232741. return self;
  232742. }
  232743. - (void) dealloc
  232744. {
  232745. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232746. delete contextLock;
  232747. [super dealloc];
  232748. }
  232749. - (bool) makeActive
  232750. {
  232751. const ScopedLock sl (*contextLock);
  232752. if ([self openGLContext] == 0)
  232753. return false;
  232754. [[self openGLContext] makeCurrentContext];
  232755. if (needsUpdate)
  232756. {
  232757. [super update];
  232758. needsUpdate = false;
  232759. }
  232760. return true;
  232761. }
  232762. - (void) makeInactive
  232763. {
  232764. const ScopedLock sl (*contextLock);
  232765. [NSOpenGLContext clearCurrentContext];
  232766. }
  232767. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232768. {
  232769. const ScopedLock sl (*contextLock);
  232770. needsUpdate = true;
  232771. }
  232772. - (void) update
  232773. {
  232774. const ScopedLock sl (*contextLock);
  232775. needsUpdate = true;
  232776. }
  232777. - (void) reshape
  232778. {
  232779. const ScopedLock sl (*contextLock);
  232780. needsUpdate = true;
  232781. }
  232782. @end
  232783. BEGIN_JUCE_NAMESPACE
  232784. class WindowedGLContext : public OpenGLContext
  232785. {
  232786. public:
  232787. WindowedGLContext (Component* const component,
  232788. const OpenGLPixelFormat& pixelFormat_,
  232789. NSOpenGLContext* sharedContext)
  232790. : renderContext (0),
  232791. pixelFormat (pixelFormat_)
  232792. {
  232793. jassert (component != 0);
  232794. NSOpenGLPixelFormatAttribute attribs [64];
  232795. int n = 0;
  232796. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232797. attribs[n++] = NSOpenGLPFAAccelerated;
  232798. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232799. attribs[n++] = NSOpenGLPFAColorSize;
  232800. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232801. pixelFormat.greenBits,
  232802. pixelFormat.blueBits);
  232803. attribs[n++] = NSOpenGLPFAAlphaSize;
  232804. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232805. attribs[n++] = NSOpenGLPFADepthSize;
  232806. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232807. attribs[n++] = NSOpenGLPFAStencilSize;
  232808. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232809. attribs[n++] = NSOpenGLPFAAccumSize;
  232810. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232811. pixelFormat.accumulationBufferGreenBits,
  232812. pixelFormat.accumulationBufferBlueBits,
  232813. pixelFormat.accumulationBufferAlphaBits);
  232814. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232815. attribs[n++] = NSOpenGLPFASampleBuffers;
  232816. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232817. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232818. attribs[n++] = NSOpenGLPFANoRecovery;
  232819. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232820. NSOpenGLPixelFormat* format
  232821. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232822. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232823. pixelFormat: format];
  232824. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232825. shareContext: sharedContext] autorelease];
  232826. const GLint swapInterval = 1;
  232827. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232828. [view setOpenGLContext: renderContext];
  232829. [format release];
  232830. viewHolder = new NSViewComponentInternal (view, component);
  232831. }
  232832. ~WindowedGLContext()
  232833. {
  232834. deleteContext();
  232835. viewHolder = 0;
  232836. }
  232837. void deleteContext()
  232838. {
  232839. makeInactive();
  232840. [renderContext clearDrawable];
  232841. [renderContext setView: nil];
  232842. [view setOpenGLContext: nil];
  232843. renderContext = nil;
  232844. }
  232845. bool makeActive() const throw()
  232846. {
  232847. jassert (renderContext != 0);
  232848. if ([renderContext view] != view)
  232849. [renderContext setView: view];
  232850. [view makeActive];
  232851. return isActive();
  232852. }
  232853. bool makeInactive() const throw()
  232854. {
  232855. [view makeInactive];
  232856. return true;
  232857. }
  232858. bool isActive() const throw()
  232859. {
  232860. return [NSOpenGLContext currentContext] == renderContext;
  232861. }
  232862. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232863. void* getRawContext() const throw() { return renderContext; }
  232864. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232865. {
  232866. }
  232867. void swapBuffers()
  232868. {
  232869. [renderContext flushBuffer];
  232870. }
  232871. bool setSwapInterval (const int numFramesPerSwap)
  232872. {
  232873. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232874. forParameter: NSOpenGLCPSwapInterval];
  232875. return true;
  232876. }
  232877. int getSwapInterval() const
  232878. {
  232879. GLint numFrames = 0;
  232880. [renderContext getValues: &numFrames
  232881. forParameter: NSOpenGLCPSwapInterval];
  232882. return numFrames;
  232883. }
  232884. void repaint()
  232885. {
  232886. // we need to invalidate the juce view that holds this gl view, to make it
  232887. // cause a repaint callback
  232888. NSView* v = (NSView*) viewHolder->view;
  232889. NSRect r = [v frame];
  232890. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232891. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232892. // repaint message, thus never causing our paint() callback, and never repainting
  232893. // the comp. So invalidating just a little bit around the edge helps..
  232894. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232895. }
  232896. void* getNativeWindowHandle() const { return viewHolder->view; }
  232897. juce_UseDebuggingNewOperator
  232898. NSOpenGLContext* renderContext;
  232899. ThreadSafeNSOpenGLView* view;
  232900. private:
  232901. OpenGLPixelFormat pixelFormat;
  232902. ScopedPointer <NSViewComponentInternal> viewHolder;
  232903. WindowedGLContext (const WindowedGLContext&);
  232904. WindowedGLContext& operator= (const WindowedGLContext&);
  232905. };
  232906. OpenGLContext* OpenGLComponent::createContext()
  232907. {
  232908. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232909. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232910. return (c->renderContext != 0) ? c.release() : 0;
  232911. }
  232912. void* OpenGLComponent::getNativeWindowHandle() const
  232913. {
  232914. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232915. : 0;
  232916. }
  232917. void juce_glViewport (const int w, const int h)
  232918. {
  232919. glViewport (0, 0, w, h);
  232920. }
  232921. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232922. OwnedArray <OpenGLPixelFormat>& results)
  232923. {
  232924. /* GLint attribs [64];
  232925. int n = 0;
  232926. attribs[n++] = AGL_RGBA;
  232927. attribs[n++] = AGL_DOUBLEBUFFER;
  232928. attribs[n++] = AGL_ACCELERATED;
  232929. attribs[n++] = AGL_NO_RECOVERY;
  232930. attribs[n++] = AGL_NONE;
  232931. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232932. while (p != 0)
  232933. {
  232934. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232935. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232936. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232937. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232938. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232939. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232940. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232941. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232942. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232943. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232944. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232945. results.add (pf);
  232946. p = aglNextPixelFormat (p);
  232947. }*/
  232948. //jassertfalse // can't see how you do this in cocoa!
  232949. }
  232950. #else
  232951. END_JUCE_NAMESPACE
  232952. @interface JuceGLView : UIView
  232953. {
  232954. }
  232955. + (Class) layerClass;
  232956. @end
  232957. @implementation JuceGLView
  232958. + (Class) layerClass
  232959. {
  232960. return [CAEAGLLayer class];
  232961. }
  232962. @end
  232963. BEGIN_JUCE_NAMESPACE
  232964. class GLESContext : public OpenGLContext
  232965. {
  232966. public:
  232967. GLESContext (UIViewComponentPeer* peer,
  232968. Component* const component_,
  232969. const OpenGLPixelFormat& pixelFormat_,
  232970. const GLESContext* const sharedContext,
  232971. NSUInteger apiType)
  232972. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232973. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232974. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232975. {
  232976. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232977. view.opaque = YES;
  232978. view.hidden = NO;
  232979. view.backgroundColor = [UIColor blackColor];
  232980. view.userInteractionEnabled = NO;
  232981. glLayer = (CAEAGLLayer*) [view layer];
  232982. [peer->view addSubview: view];
  232983. if (sharedContext != 0)
  232984. context = [[EAGLContext alloc] initWithAPI: apiType
  232985. sharegroup: [sharedContext->context sharegroup]];
  232986. else
  232987. context = [[EAGLContext alloc] initWithAPI: apiType];
  232988. createGLBuffers();
  232989. }
  232990. ~GLESContext()
  232991. {
  232992. deleteContext();
  232993. [view removeFromSuperview];
  232994. [view release];
  232995. freeGLBuffers();
  232996. }
  232997. void deleteContext()
  232998. {
  232999. makeInactive();
  233000. [context release];
  233001. context = nil;
  233002. }
  233003. bool makeActive() const throw()
  233004. {
  233005. jassert (context != 0);
  233006. [EAGLContext setCurrentContext: context];
  233007. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233008. return true;
  233009. }
  233010. void swapBuffers()
  233011. {
  233012. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233013. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233014. }
  233015. bool makeInactive() const throw()
  233016. {
  233017. return [EAGLContext setCurrentContext: nil];
  233018. }
  233019. bool isActive() const throw()
  233020. {
  233021. return [EAGLContext currentContext] == context;
  233022. }
  233023. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233024. void* getRawContext() const throw() { return glLayer; }
  233025. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233026. {
  233027. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233028. if (lastWidth != w || lastHeight != h)
  233029. {
  233030. lastWidth = w;
  233031. lastHeight = h;
  233032. freeGLBuffers();
  233033. createGLBuffers();
  233034. }
  233035. }
  233036. bool setSwapInterval (const int numFramesPerSwap)
  233037. {
  233038. numFrames = numFramesPerSwap;
  233039. return true;
  233040. }
  233041. int getSwapInterval() const
  233042. {
  233043. return numFrames;
  233044. }
  233045. void repaint()
  233046. {
  233047. }
  233048. void createGLBuffers()
  233049. {
  233050. makeActive();
  233051. glGenFramebuffersOES (1, &frameBufferHandle);
  233052. glGenRenderbuffersOES (1, &colorBufferHandle);
  233053. glGenRenderbuffersOES (1, &depthBufferHandle);
  233054. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233055. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233056. GLint width, height;
  233057. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233058. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233059. if (useDepthBuffer)
  233060. {
  233061. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233062. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233063. }
  233064. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233065. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233066. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233067. if (useDepthBuffer)
  233068. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233069. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233070. }
  233071. void freeGLBuffers()
  233072. {
  233073. if (frameBufferHandle != 0)
  233074. {
  233075. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233076. frameBufferHandle = 0;
  233077. }
  233078. if (colorBufferHandle != 0)
  233079. {
  233080. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233081. colorBufferHandle = 0;
  233082. }
  233083. if (depthBufferHandle != 0)
  233084. {
  233085. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233086. depthBufferHandle = 0;
  233087. }
  233088. }
  233089. juce_UseDebuggingNewOperator
  233090. private:
  233091. Component::SafePointer<Component> component;
  233092. OpenGLPixelFormat pixelFormat;
  233093. JuceGLView* view;
  233094. CAEAGLLayer* glLayer;
  233095. EAGLContext* context;
  233096. bool useDepthBuffer;
  233097. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233098. int numFrames;
  233099. int lastWidth, lastHeight;
  233100. GLESContext (const GLESContext&);
  233101. GLESContext& operator= (const GLESContext&);
  233102. };
  233103. OpenGLContext* OpenGLComponent::createContext()
  233104. {
  233105. ScopedAutoReleasePool pool;
  233106. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233107. if (peer != 0)
  233108. return new GLESContext (peer, this, preferredPixelFormat,
  233109. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233110. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233111. return 0;
  233112. }
  233113. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233114. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233115. {
  233116. }
  233117. void juce_glViewport (const int w, const int h)
  233118. {
  233119. glViewport (0, 0, w, h);
  233120. }
  233121. #endif
  233122. #endif
  233123. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233124. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233125. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233126. // compiled on its own).
  233127. #if JUCE_INCLUDED_FILE
  233128. class JuceMainMenuHandler;
  233129. END_JUCE_NAMESPACE
  233130. using namespace JUCE_NAMESPACE;
  233131. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233132. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233133. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233134. #else
  233135. @interface JuceMenuCallback : NSObject
  233136. #endif
  233137. {
  233138. JuceMainMenuHandler* owner;
  233139. }
  233140. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233141. - (void) dealloc;
  233142. - (void) menuItemInvoked: (id) menu;
  233143. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233144. @end
  233145. BEGIN_JUCE_NAMESPACE
  233146. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233147. private DeletedAtShutdown
  233148. {
  233149. public:
  233150. static JuceMainMenuHandler* instance;
  233151. JuceMainMenuHandler()
  233152. : currentModel (0),
  233153. lastUpdateTime (0)
  233154. {
  233155. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233156. }
  233157. ~JuceMainMenuHandler()
  233158. {
  233159. setMenu (0);
  233160. jassert (instance == this);
  233161. instance = 0;
  233162. [callback release];
  233163. }
  233164. void setMenu (MenuBarModel* const newMenuBarModel)
  233165. {
  233166. if (currentModel != newMenuBarModel)
  233167. {
  233168. if (currentModel != 0)
  233169. currentModel->removeListener (this);
  233170. currentModel = newMenuBarModel;
  233171. if (currentModel != 0)
  233172. currentModel->addListener (this);
  233173. menuBarItemsChanged (0);
  233174. }
  233175. }
  233176. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233177. const String& name, const int menuId, const int tag)
  233178. {
  233179. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233180. action: nil
  233181. keyEquivalent: @""];
  233182. [item setTag: tag];
  233183. NSMenu* sub = createMenu (child, name, menuId, tag);
  233184. [parent setSubmenu: sub forItem: item];
  233185. [sub setAutoenablesItems: false];
  233186. [sub release];
  233187. }
  233188. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233189. const String& name, const int menuId, const int tag)
  233190. {
  233191. [parentItem setTag: tag];
  233192. NSMenu* menu = [parentItem submenu];
  233193. [menu setTitle: juceStringToNS (name)];
  233194. while ([menu numberOfItems] > 0)
  233195. [menu removeItemAtIndex: 0];
  233196. PopupMenu::MenuItemIterator iter (menuToCopy);
  233197. while (iter.next())
  233198. addMenuItem (iter, menu, menuId, tag);
  233199. [menu setAutoenablesItems: false];
  233200. [menu update];
  233201. }
  233202. void menuBarItemsChanged (MenuBarModel*)
  233203. {
  233204. lastUpdateTime = Time::getMillisecondCounter();
  233205. StringArray menuNames;
  233206. if (currentModel != 0)
  233207. menuNames = currentModel->getMenuBarNames();
  233208. NSMenu* menuBar = [NSApp mainMenu];
  233209. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233210. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233211. int menuId = 1;
  233212. for (int i = 0; i < menuNames.size(); ++i)
  233213. {
  233214. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233215. if (i >= [menuBar numberOfItems] - 1)
  233216. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233217. else
  233218. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233219. }
  233220. }
  233221. static void flashMenuBar (NSMenu* menu)
  233222. {
  233223. if ([[menu title] isEqualToString: @"Apple"])
  233224. return;
  233225. [menu retain];
  233226. const unichar f35Key = NSF35FunctionKey;
  233227. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233228. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233229. action: nil
  233230. keyEquivalent: f35String];
  233231. [item setTarget: nil];
  233232. [menu insertItem: item atIndex: [menu numberOfItems]];
  233233. [item release];
  233234. if ([menu indexOfItem: item] >= 0)
  233235. {
  233236. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233237. location: NSZeroPoint
  233238. modifierFlags: NSCommandKeyMask
  233239. timestamp: 0
  233240. windowNumber: 0
  233241. context: [NSGraphicsContext currentContext]
  233242. characters: f35String
  233243. charactersIgnoringModifiers: f35String
  233244. isARepeat: NO
  233245. keyCode: 0];
  233246. [menu performKeyEquivalent: f35Event];
  233247. if ([menu indexOfItem: item] >= 0)
  233248. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233249. }
  233250. [menu release];
  233251. }
  233252. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233253. {
  233254. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233255. {
  233256. NSMenuItem* m = [menu itemAtIndex: i];
  233257. if ([m tag] == info.commandID)
  233258. return m;
  233259. if ([m submenu] != 0)
  233260. {
  233261. NSMenuItem* found = findMenuItem ([m submenu], info);
  233262. if (found != 0)
  233263. return found;
  233264. }
  233265. }
  233266. return 0;
  233267. }
  233268. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233269. {
  233270. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233271. if (item != 0)
  233272. flashMenuBar ([item menu]);
  233273. }
  233274. void updateMenus()
  233275. {
  233276. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233277. menuBarItemsChanged (0);
  233278. }
  233279. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233280. {
  233281. if (currentModel != 0)
  233282. {
  233283. if (commandManager != 0)
  233284. {
  233285. ApplicationCommandTarget::InvocationInfo info (commandId);
  233286. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233287. commandManager->invoke (info, true);
  233288. }
  233289. currentModel->menuItemSelected (commandId, topLevelIndex);
  233290. }
  233291. }
  233292. MenuBarModel* currentModel;
  233293. uint32 lastUpdateTime;
  233294. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233295. const int topLevelMenuId, const int topLevelIndex)
  233296. {
  233297. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233298. if (text == 0)
  233299. text = @"";
  233300. if (iter.isSeparator)
  233301. {
  233302. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233303. }
  233304. else if (iter.isSectionHeader)
  233305. {
  233306. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233307. action: nil
  233308. keyEquivalent: @""];
  233309. [item setEnabled: false];
  233310. }
  233311. else if (iter.subMenu != 0)
  233312. {
  233313. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233314. action: nil
  233315. keyEquivalent: @""];
  233316. [item setTag: iter.itemId];
  233317. [item setEnabled: iter.isEnabled];
  233318. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233319. [sub setDelegate: nil];
  233320. [menuToAddTo setSubmenu: sub forItem: item];
  233321. [sub release];
  233322. }
  233323. else
  233324. {
  233325. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233326. action: @selector (menuItemInvoked:)
  233327. keyEquivalent: @""];
  233328. [item setTag: iter.itemId];
  233329. [item setEnabled: iter.isEnabled];
  233330. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233331. [item setTarget: (id) callback];
  233332. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233333. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233334. [item setRepresentedObject: info];
  233335. if (iter.commandManager != 0)
  233336. {
  233337. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233338. ->getKeyPressesAssignedToCommand (iter.itemId));
  233339. if (keyPresses.size() > 0)
  233340. {
  233341. const KeyPress& kp = keyPresses.getReference(0);
  233342. if (kp.getKeyCode() != KeyPress::backspaceKey
  233343. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233344. // every time you press the key while editing text)
  233345. {
  233346. juce_wchar key = kp.getTextCharacter();
  233347. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233348. key = NSBackspaceCharacter;
  233349. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233350. key = NSDeleteCharacter;
  233351. else if (key == 0)
  233352. key = (juce_wchar) kp.getKeyCode();
  233353. unsigned int mods = 0;
  233354. if (kp.getModifiers().isShiftDown())
  233355. mods |= NSShiftKeyMask;
  233356. if (kp.getModifiers().isCtrlDown())
  233357. mods |= NSControlKeyMask;
  233358. if (kp.getModifiers().isAltDown())
  233359. mods |= NSAlternateKeyMask;
  233360. if (kp.getModifiers().isCommandDown())
  233361. mods |= NSCommandKeyMask;
  233362. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233363. [item setKeyEquivalentModifierMask: mods];
  233364. }
  233365. }
  233366. }
  233367. }
  233368. }
  233369. JuceMenuCallback* callback;
  233370. private:
  233371. NSMenu* createMenu (const PopupMenu menu,
  233372. const String& menuName,
  233373. const int topLevelMenuId,
  233374. const int topLevelIndex)
  233375. {
  233376. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233377. [m setAutoenablesItems: false];
  233378. [m setDelegate: callback];
  233379. PopupMenu::MenuItemIterator iter (menu);
  233380. while (iter.next())
  233381. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233382. [m update];
  233383. return m;
  233384. }
  233385. };
  233386. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233387. END_JUCE_NAMESPACE
  233388. @implementation JuceMenuCallback
  233389. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233390. {
  233391. [super init];
  233392. owner = owner_;
  233393. return self;
  233394. }
  233395. - (void) dealloc
  233396. {
  233397. [super dealloc];
  233398. }
  233399. - (void) menuItemInvoked: (id) menu
  233400. {
  233401. NSMenuItem* item = (NSMenuItem*) menu;
  233402. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233403. {
  233404. // 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
  233405. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233406. // into the focused component and let it trigger the menu item indirectly.
  233407. NSEvent* e = [NSApp currentEvent];
  233408. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233409. {
  233410. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233411. {
  233412. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233413. if (peer != 0)
  233414. {
  233415. if ([e type] == NSKeyDown)
  233416. peer->redirectKeyDown (e);
  233417. else
  233418. peer->redirectKeyUp (e);
  233419. return;
  233420. }
  233421. }
  233422. }
  233423. NSArray* info = (NSArray*) [item representedObject];
  233424. owner->invoke ((int) [item tag],
  233425. (ApplicationCommandManager*) (pointer_sized_int)
  233426. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233427. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233428. }
  233429. }
  233430. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233431. {
  233432. (void) menu;
  233433. if (JuceMainMenuHandler::instance != 0)
  233434. JuceMainMenuHandler::instance->updateMenus();
  233435. }
  233436. @end
  233437. BEGIN_JUCE_NAMESPACE
  233438. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233439. const PopupMenu* extraItems)
  233440. {
  233441. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233442. {
  233443. PopupMenu::MenuItemIterator iter (*extraItems);
  233444. while (iter.next())
  233445. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233446. [menu addItem: [NSMenuItem separatorItem]];
  233447. }
  233448. NSMenuItem* item;
  233449. // Services...
  233450. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233451. action: nil keyEquivalent: @""];
  233452. [menu addItem: item];
  233453. [item release];
  233454. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233455. [menu setSubmenu: servicesMenu forItem: item];
  233456. [NSApp setServicesMenu: servicesMenu];
  233457. [servicesMenu release];
  233458. [menu addItem: [NSMenuItem separatorItem]];
  233459. // Hide + Show stuff...
  233460. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233461. action: @selector (hide:) keyEquivalent: @"h"];
  233462. [item setTarget: NSApp];
  233463. [menu addItem: item];
  233464. [item release];
  233465. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233466. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233467. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233468. [item setTarget: NSApp];
  233469. [menu addItem: item];
  233470. [item release];
  233471. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233472. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233473. [item setTarget: NSApp];
  233474. [menu addItem: item];
  233475. [item release];
  233476. [menu addItem: [NSMenuItem separatorItem]];
  233477. // Quit item....
  233478. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233479. action: @selector (terminate:) keyEquivalent: @"q"];
  233480. [item setTarget: NSApp];
  233481. [menu addItem: item];
  233482. [item release];
  233483. return menu;
  233484. }
  233485. // Since our app has no NIB, this initialises a standard app menu...
  233486. static void rebuildMainMenu (const PopupMenu* extraItems)
  233487. {
  233488. // this can't be used in a plugin!
  233489. jassert (JUCEApplication::isStandaloneApp());
  233490. if (JUCEApplication::getInstance() != 0)
  233491. {
  233492. const ScopedAutoReleasePool pool;
  233493. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233494. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233495. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233496. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233497. [mainMenu setSubmenu: appMenu forItem: item];
  233498. [NSApp setMainMenu: mainMenu];
  233499. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233500. [appMenu release];
  233501. [mainMenu release];
  233502. }
  233503. }
  233504. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233505. const PopupMenu* extraAppleMenuItems)
  233506. {
  233507. if (getMacMainMenu() != newMenuBarModel)
  233508. {
  233509. const ScopedAutoReleasePool pool;
  233510. if (newMenuBarModel == 0)
  233511. {
  233512. delete JuceMainMenuHandler::instance;
  233513. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233514. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233515. extraAppleMenuItems = 0;
  233516. }
  233517. else
  233518. {
  233519. if (JuceMainMenuHandler::instance == 0)
  233520. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233521. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233522. }
  233523. }
  233524. rebuildMainMenu (extraAppleMenuItems);
  233525. if (newMenuBarModel != 0)
  233526. newMenuBarModel->menuItemsChanged();
  233527. }
  233528. MenuBarModel* MenuBarModel::getMacMainMenu()
  233529. {
  233530. return JuceMainMenuHandler::instance != 0
  233531. ? JuceMainMenuHandler::instance->currentModel : 0;
  233532. }
  233533. void juce_initialiseMacMainMenu()
  233534. {
  233535. if (JuceMainMenuHandler::instance == 0)
  233536. rebuildMainMenu (0);
  233537. }
  233538. #endif
  233539. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233540. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233541. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233542. // compiled on its own).
  233543. #if JUCE_INCLUDED_FILE
  233544. #if JUCE_MAC
  233545. END_JUCE_NAMESPACE
  233546. using namespace JUCE_NAMESPACE;
  233547. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233548. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233549. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233550. #else
  233551. @interface JuceFileChooserDelegate : NSObject
  233552. #endif
  233553. {
  233554. StringArray* filters;
  233555. }
  233556. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233557. - (void) dealloc;
  233558. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233559. @end
  233560. @implementation JuceFileChooserDelegate
  233561. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233562. {
  233563. [super init];
  233564. filters = filters_;
  233565. return self;
  233566. }
  233567. - (void) dealloc
  233568. {
  233569. delete filters;
  233570. [super dealloc];
  233571. }
  233572. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233573. {
  233574. (void) sender;
  233575. const File f (nsStringToJuce (filename));
  233576. for (int i = filters->size(); --i >= 0;)
  233577. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233578. return true;
  233579. return f.isDirectory();
  233580. }
  233581. @end
  233582. BEGIN_JUCE_NAMESPACE
  233583. void FileChooser::showPlatformDialog (Array<File>& results,
  233584. const String& title,
  233585. const File& currentFileOrDirectory,
  233586. const String& filter,
  233587. bool selectsDirectory,
  233588. bool selectsFiles,
  233589. bool isSaveDialogue,
  233590. bool warnAboutOverwritingExistingFiles,
  233591. bool selectMultipleFiles,
  233592. FilePreviewComponent* extraInfoComponent)
  233593. {
  233594. const ScopedAutoReleasePool pool;
  233595. StringArray* filters = new StringArray();
  233596. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233597. filters->trim();
  233598. filters->removeEmptyStrings();
  233599. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233600. [delegate autorelease];
  233601. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233602. : [NSOpenPanel openPanel];
  233603. [panel setTitle: juceStringToNS (title)];
  233604. if (! isSaveDialogue)
  233605. {
  233606. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233607. [openPanel setCanChooseDirectories: selectsDirectory];
  233608. [openPanel setCanChooseFiles: selectsFiles];
  233609. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233610. }
  233611. [panel setDelegate: delegate];
  233612. if (isSaveDialogue || selectsDirectory)
  233613. [panel setCanCreateDirectories: YES];
  233614. String directory, filename;
  233615. if (currentFileOrDirectory.isDirectory())
  233616. {
  233617. directory = currentFileOrDirectory.getFullPathName();
  233618. }
  233619. else
  233620. {
  233621. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233622. filename = currentFileOrDirectory.getFileName();
  233623. }
  233624. if ([panel runModalForDirectory: juceStringToNS (directory)
  233625. file: juceStringToNS (filename)]
  233626. == NSOKButton)
  233627. {
  233628. if (isSaveDialogue)
  233629. {
  233630. results.add (File (nsStringToJuce ([panel filename])));
  233631. }
  233632. else
  233633. {
  233634. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233635. NSArray* urls = [openPanel filenames];
  233636. for (unsigned int i = 0; i < [urls count]; ++i)
  233637. {
  233638. NSString* f = [urls objectAtIndex: i];
  233639. results.add (File (nsStringToJuce (f)));
  233640. }
  233641. }
  233642. }
  233643. [panel setDelegate: nil];
  233644. }
  233645. #else
  233646. void FileChooser::showPlatformDialog (Array<File>& results,
  233647. const String& title,
  233648. const File& currentFileOrDirectory,
  233649. const String& filter,
  233650. bool selectsDirectory,
  233651. bool selectsFiles,
  233652. bool isSaveDialogue,
  233653. bool warnAboutOverwritingExistingFiles,
  233654. bool selectMultipleFiles,
  233655. FilePreviewComponent* extraInfoComponent)
  233656. {
  233657. const ScopedAutoReleasePool pool;
  233658. jassertfalse; //xxx to do
  233659. }
  233660. #endif
  233661. #endif
  233662. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233663. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233664. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233665. // compiled on its own).
  233666. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233667. END_JUCE_NAMESPACE
  233668. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233669. @interface NonInterceptingQTMovieView : QTMovieView
  233670. {
  233671. }
  233672. - (id) initWithFrame: (NSRect) frame;
  233673. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233674. - (NSView*) hitTest: (NSPoint) p;
  233675. @end
  233676. @implementation NonInterceptingQTMovieView
  233677. - (id) initWithFrame: (NSRect) frame
  233678. {
  233679. self = [super initWithFrame: frame];
  233680. [self setNextResponder: [self superview]];
  233681. return self;
  233682. }
  233683. - (void) dealloc
  233684. {
  233685. [super dealloc];
  233686. }
  233687. - (NSView*) hitTest: (NSPoint) point
  233688. {
  233689. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233690. }
  233691. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233692. {
  233693. return YES;
  233694. }
  233695. @end
  233696. BEGIN_JUCE_NAMESPACE
  233697. #define theMovie (static_cast <QTMovie*> (movie))
  233698. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233699. : movie (0)
  233700. {
  233701. setOpaque (true);
  233702. setVisible (true);
  233703. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233704. setView (view);
  233705. [view release];
  233706. }
  233707. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233708. {
  233709. closeMovie();
  233710. setView (0);
  233711. }
  233712. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233713. {
  233714. return true;
  233715. }
  233716. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233717. {
  233718. // unfortunately, QTMovie objects can only be created on the main thread..
  233719. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233720. QTMovie* movie = 0;
  233721. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233722. if (fin != 0)
  233723. {
  233724. movieFile = fin->getFile();
  233725. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233726. error: nil];
  233727. }
  233728. else
  233729. {
  233730. MemoryBlock temp;
  233731. movieStream->readIntoMemoryBlock (temp);
  233732. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233733. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233734. {
  233735. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233736. length: temp.getSize()]
  233737. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233738. MIMEType: @""]
  233739. error: nil];
  233740. if (movie != 0)
  233741. break;
  233742. }
  233743. }
  233744. return movie;
  233745. }
  233746. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233747. const bool isControllerVisible_)
  233748. {
  233749. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233750. }
  233751. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233752. const bool controllerVisible_)
  233753. {
  233754. closeMovie();
  233755. if (getPeer() == 0)
  233756. {
  233757. // To open a movie, this component must be visible inside a functioning window, so that
  233758. // the QT control can be assigned to the window.
  233759. jassertfalse;
  233760. return false;
  233761. }
  233762. movie = openMovieFromStream (movieStream, movieFile);
  233763. [theMovie retain];
  233764. QTMovieView* view = (QTMovieView*) getView();
  233765. [view setMovie: theMovie];
  233766. [view setControllerVisible: controllerVisible_];
  233767. setLooping (looping);
  233768. return movie != nil;
  233769. }
  233770. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233771. const bool isControllerVisible_)
  233772. {
  233773. // unfortunately, QTMovie objects can only be created on the main thread..
  233774. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233775. closeMovie();
  233776. if (getPeer() == 0)
  233777. {
  233778. // To open a movie, this component must be visible inside a functioning window, so that
  233779. // the QT control can be assigned to the window.
  233780. jassertfalse;
  233781. return false;
  233782. }
  233783. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233784. NSError* err;
  233785. if ([QTMovie canInitWithURL: url])
  233786. movie = [QTMovie movieWithURL: url error: &err];
  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. void QuickTimeMovieComponent::closeMovie()
  233795. {
  233796. stop();
  233797. QTMovieView* view = (QTMovieView*) getView();
  233798. [view setMovie: nil];
  233799. [theMovie release];
  233800. movie = 0;
  233801. movieFile = File::nonexistent;
  233802. }
  233803. bool QuickTimeMovieComponent::isMovieOpen() const
  233804. {
  233805. return movie != nil;
  233806. }
  233807. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233808. {
  233809. return movieFile;
  233810. }
  233811. void QuickTimeMovieComponent::play()
  233812. {
  233813. [theMovie play];
  233814. }
  233815. void QuickTimeMovieComponent::stop()
  233816. {
  233817. [theMovie stop];
  233818. }
  233819. bool QuickTimeMovieComponent::isPlaying() const
  233820. {
  233821. return movie != 0 && [theMovie rate] != 0;
  233822. }
  233823. void QuickTimeMovieComponent::setPosition (const double seconds)
  233824. {
  233825. if (movie != 0)
  233826. {
  233827. QTTime t;
  233828. t.timeValue = (uint64) (100000.0 * seconds);
  233829. t.timeScale = 100000;
  233830. t.flags = 0;
  233831. [theMovie setCurrentTime: t];
  233832. }
  233833. }
  233834. double QuickTimeMovieComponent::getPosition() const
  233835. {
  233836. if (movie == 0)
  233837. return 0.0;
  233838. QTTime t = [theMovie currentTime];
  233839. return t.timeValue / (double) t.timeScale;
  233840. }
  233841. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233842. {
  233843. [theMovie setRate: newSpeed];
  233844. }
  233845. double QuickTimeMovieComponent::getMovieDuration() const
  233846. {
  233847. if (movie == 0)
  233848. return 0.0;
  233849. QTTime t = [theMovie duration];
  233850. return t.timeValue / (double) t.timeScale;
  233851. }
  233852. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233853. {
  233854. looping = shouldLoop;
  233855. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233856. forKey: QTMovieLoopsAttribute];
  233857. }
  233858. bool QuickTimeMovieComponent::isLooping() const
  233859. {
  233860. return looping;
  233861. }
  233862. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233863. {
  233864. [theMovie setVolume: newVolume];
  233865. }
  233866. float QuickTimeMovieComponent::getMovieVolume() const
  233867. {
  233868. return movie != 0 ? [theMovie volume] : 0.0f;
  233869. }
  233870. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233871. {
  233872. width = 0;
  233873. height = 0;
  233874. if (movie != 0)
  233875. {
  233876. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233877. width = (int) s.width;
  233878. height = (int) s.height;
  233879. }
  233880. }
  233881. void QuickTimeMovieComponent::paint (Graphics& g)
  233882. {
  233883. if (movie == 0)
  233884. g.fillAll (Colours::black);
  233885. }
  233886. bool QuickTimeMovieComponent::isControllerVisible() const
  233887. {
  233888. return controllerVisible;
  233889. }
  233890. void QuickTimeMovieComponent::goToStart()
  233891. {
  233892. setPosition (0.0);
  233893. }
  233894. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233895. const RectanglePlacement& placement)
  233896. {
  233897. int normalWidth, normalHeight;
  233898. getMovieNormalSize (normalWidth, normalHeight);
  233899. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233900. {
  233901. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233902. placement.applyTo (x, y, w, h,
  233903. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233904. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233905. if (w > 0 && h > 0)
  233906. {
  233907. setBounds (roundToInt (x), roundToInt (y),
  233908. roundToInt (w), roundToInt (h));
  233909. }
  233910. }
  233911. else
  233912. {
  233913. setBounds (spaceToFitWithin);
  233914. }
  233915. }
  233916. #if ! (JUCE_MAC && JUCE_64BIT)
  233917. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233918. {
  233919. if (movieStream == 0)
  233920. return false;
  233921. File file;
  233922. QTMovie* movie = openMovieFromStream (movieStream, file);
  233923. if (movie != nil)
  233924. result = [movie quickTimeMovie];
  233925. return movie != nil;
  233926. }
  233927. #endif
  233928. #endif
  233929. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233930. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233931. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233932. // compiled on its own).
  233933. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233934. const int kilobytesPerSecond1x = 176;
  233935. END_JUCE_NAMESPACE
  233936. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233937. @interface OpenDiskDevice : NSObject
  233938. {
  233939. @public
  233940. DRDevice* device;
  233941. NSMutableArray* tracks;
  233942. bool underrunProtection;
  233943. }
  233944. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233945. - (void) dealloc;
  233946. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233947. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233948. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233949. @end
  233950. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233951. @interface AudioTrackProducer : NSObject
  233952. {
  233953. JUCE_NAMESPACE::AudioSource* source;
  233954. int readPosition, lengthInFrames;
  233955. }
  233956. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233957. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233958. - (void) dealloc;
  233959. - (void) setupTrackProperties: (DRTrack*) track;
  233960. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233961. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233962. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233963. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233964. toMedia:(NSDictionary*)mediaInfo;
  233965. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233966. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233967. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233968. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233969. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233970. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233971. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233972. ioFlags:(uint32_t*)flags;
  233973. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233974. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233975. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233976. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233977. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233978. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233979. ioFlags:(uint32_t*)flags;
  233980. @end
  233981. @implementation OpenDiskDevice
  233982. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233983. {
  233984. [super init];
  233985. device = device_;
  233986. tracks = [[NSMutableArray alloc] init];
  233987. underrunProtection = true;
  233988. return self;
  233989. }
  233990. - (void) dealloc
  233991. {
  233992. [tracks release];
  233993. [super dealloc];
  233994. }
  233995. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233996. {
  233997. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233998. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233999. [p setupTrackProperties: t];
  234000. [tracks addObject: t];
  234001. [t release];
  234002. [p release];
  234003. }
  234004. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234005. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234006. {
  234007. DRBurn* burn = [DRBurn burnForDevice: device];
  234008. if (! [device acquireExclusiveAccess])
  234009. {
  234010. *error = "Couldn't open or write to the CD device";
  234011. return;
  234012. }
  234013. [device acquireMediaReservation];
  234014. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234015. [d autorelease];
  234016. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234017. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234018. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234019. if (burnSpeed > 0)
  234020. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234021. if (! underrunProtection)
  234022. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234023. [burn setProperties: d];
  234024. [burn writeLayout: tracks];
  234025. for (;;)
  234026. {
  234027. JUCE_NAMESPACE::Thread::sleep (300);
  234028. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234029. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234030. {
  234031. [burn abort];
  234032. *error = "User cancelled the write operation";
  234033. break;
  234034. }
  234035. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234036. {
  234037. *error = "Write operation failed";
  234038. break;
  234039. }
  234040. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234041. {
  234042. break;
  234043. }
  234044. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234045. objectForKey: DRErrorStatusErrorStringKey];
  234046. if ([err length] > 0)
  234047. {
  234048. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234049. break;
  234050. }
  234051. }
  234052. [device releaseMediaReservation];
  234053. [device releaseExclusiveAccess];
  234054. }
  234055. @end
  234056. @implementation AudioTrackProducer
  234057. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234058. {
  234059. lengthInFrames = lengthInFrames_;
  234060. readPosition = 0;
  234061. return self;
  234062. }
  234063. - (void) setupTrackProperties: (DRTrack*) track
  234064. {
  234065. NSMutableDictionary* p = [[track properties] mutableCopy];
  234066. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234067. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234068. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234069. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234070. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234071. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234072. [track setProperties: p];
  234073. [p release];
  234074. }
  234075. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234076. {
  234077. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234078. if (s != nil)
  234079. s->source = source_;
  234080. return s;
  234081. }
  234082. - (void) dealloc
  234083. {
  234084. if (source != 0)
  234085. {
  234086. source->releaseResources();
  234087. delete source;
  234088. }
  234089. [super dealloc];
  234090. }
  234091. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234092. {
  234093. }
  234094. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234095. {
  234096. return true;
  234097. }
  234098. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234099. {
  234100. return lengthInFrames;
  234101. }
  234102. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234103. toMedia: (NSDictionary*) mediaInfo
  234104. {
  234105. if (source != 0)
  234106. source->prepareToPlay (44100 / 75, 44100);
  234107. readPosition = 0;
  234108. return true;
  234109. }
  234110. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234111. {
  234112. if (source != 0)
  234113. source->prepareToPlay (44100 / 75, 44100);
  234114. return true;
  234115. }
  234116. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234117. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234118. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234119. {
  234120. if (source != 0)
  234121. {
  234122. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234123. if (numSamples > 0)
  234124. {
  234125. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234126. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234127. info.buffer = &tempBuffer;
  234128. info.startSample = 0;
  234129. info.numSamples = numSamples;
  234130. source->getNextAudioBlock (info);
  234131. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234132. JUCE_NAMESPACE::AudioData::LittleEndian,
  234133. JUCE_NAMESPACE::AudioData::Interleaved,
  234134. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234135. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234136. JUCE_NAMESPACE::AudioData::NativeEndian,
  234137. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234138. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234139. CDSampleFormat left (buffer, 2);
  234140. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234141. CDSampleFormat right (buffer + 2, 2);
  234142. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234143. readPosition += numSamples;
  234144. }
  234145. return numSamples * 4;
  234146. }
  234147. return 0;
  234148. }
  234149. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234150. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234151. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234152. ioFlags: (uint32_t*) flags
  234153. {
  234154. zeromem (buffer, bufferLength);
  234155. return bufferLength;
  234156. }
  234157. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234158. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234159. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234160. {
  234161. return true;
  234162. }
  234163. @end
  234164. BEGIN_JUCE_NAMESPACE
  234165. class AudioCDBurner::Pimpl : public Timer
  234166. {
  234167. public:
  234168. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234169. : device (0), owner (owner_)
  234170. {
  234171. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234172. if (dev != 0)
  234173. {
  234174. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234175. lastState = getDiskState();
  234176. startTimer (1000);
  234177. }
  234178. }
  234179. ~Pimpl()
  234180. {
  234181. stopTimer();
  234182. [device release];
  234183. }
  234184. void timerCallback()
  234185. {
  234186. const DiskState state = getDiskState();
  234187. if (state != lastState)
  234188. {
  234189. lastState = state;
  234190. owner.sendChangeMessage (&owner);
  234191. }
  234192. }
  234193. DiskState getDiskState() const
  234194. {
  234195. if ([device->device isValid])
  234196. {
  234197. NSDictionary* status = [device->device status];
  234198. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234199. if ([state isEqualTo: DRDeviceMediaStateNone])
  234200. {
  234201. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234202. return trayOpen;
  234203. return noDisc;
  234204. }
  234205. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234206. {
  234207. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234208. return writableDiskPresent;
  234209. else
  234210. return readOnlyDiskPresent;
  234211. }
  234212. }
  234213. return unknown;
  234214. }
  234215. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234216. const Array<int> getAvailableWriteSpeeds() const
  234217. {
  234218. Array<int> results;
  234219. if ([device->device isValid])
  234220. {
  234221. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234222. for (unsigned int i = 0; i < [speeds count]; ++i)
  234223. {
  234224. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234225. results.add (kbPerSec / kilobytesPerSecond1x);
  234226. }
  234227. }
  234228. return results;
  234229. }
  234230. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234231. {
  234232. if ([device->device isValid])
  234233. {
  234234. device->underrunProtection = shouldBeEnabled;
  234235. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234236. }
  234237. return false;
  234238. }
  234239. int getNumAvailableAudioBlocks() const
  234240. {
  234241. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234242. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234243. }
  234244. OpenDiskDevice* device;
  234245. private:
  234246. DiskState lastState;
  234247. AudioCDBurner& owner;
  234248. };
  234249. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234250. {
  234251. pimpl = new Pimpl (*this, deviceIndex);
  234252. }
  234253. AudioCDBurner::~AudioCDBurner()
  234254. {
  234255. }
  234256. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234257. {
  234258. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234259. if (b->pimpl->device == 0)
  234260. b = 0;
  234261. return b.release();
  234262. }
  234263. static NSArray* findDiskBurnerDevices()
  234264. {
  234265. NSMutableArray* results = [NSMutableArray array];
  234266. NSArray* devs = [DRDevice devices];
  234267. if (devs != 0)
  234268. {
  234269. int num = [devs count];
  234270. int i;
  234271. for (i = 0; i < num; ++i)
  234272. {
  234273. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234274. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234275. if (name != nil)
  234276. [results addObject: name];
  234277. }
  234278. }
  234279. return results;
  234280. }
  234281. const StringArray AudioCDBurner::findAvailableDevices()
  234282. {
  234283. NSArray* names = findDiskBurnerDevices();
  234284. StringArray s;
  234285. for (unsigned int i = 0; i < [names count]; ++i)
  234286. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234287. return s;
  234288. }
  234289. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234290. {
  234291. return pimpl->getDiskState();
  234292. }
  234293. bool AudioCDBurner::isDiskPresent() const
  234294. {
  234295. return getDiskState() == writableDiskPresent;
  234296. }
  234297. bool AudioCDBurner::openTray()
  234298. {
  234299. return pimpl->openTray();
  234300. }
  234301. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234302. {
  234303. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234304. DiskState oldState = getDiskState();
  234305. DiskState newState = oldState;
  234306. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234307. {
  234308. newState = getDiskState();
  234309. Thread::sleep (100);
  234310. }
  234311. return newState;
  234312. }
  234313. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234314. {
  234315. return pimpl->getAvailableWriteSpeeds();
  234316. }
  234317. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234318. {
  234319. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234320. }
  234321. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234322. {
  234323. return pimpl->getNumAvailableAudioBlocks();
  234324. }
  234325. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234326. {
  234327. if ([pimpl->device->device isValid])
  234328. {
  234329. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234330. return true;
  234331. }
  234332. return false;
  234333. }
  234334. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234335. bool ejectDiscAfterwards,
  234336. bool performFakeBurnForTesting,
  234337. int writeSpeed)
  234338. {
  234339. String error ("Couldn't open or write to the CD device");
  234340. if ([pimpl->device->device isValid])
  234341. {
  234342. error = String::empty;
  234343. [pimpl->device burn: listener
  234344. errorString: &error
  234345. ejectAfterwards: ejectDiscAfterwards
  234346. isFake: performFakeBurnForTesting
  234347. speed: writeSpeed];
  234348. }
  234349. return error;
  234350. }
  234351. #endif
  234352. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234353. void AudioCDReader::ejectDisk()
  234354. {
  234355. const ScopedAutoReleasePool p;
  234356. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234357. }
  234358. #endif
  234359. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234360. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234361. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234362. // compiled on its own).
  234363. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234364. namespace CDReaderHelpers
  234365. {
  234366. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234367. {
  234368. forEachXmlChildElementWithTagName (xml, child, "key")
  234369. if (child->getAllSubText().trim() == key)
  234370. return child->getNextElement();
  234371. return 0;
  234372. }
  234373. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234374. {
  234375. const XmlElement* const block = getElementForKey (xml, key);
  234376. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234377. }
  234378. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234379. // Returns NULL on success, otherwise a const char* representing an error.
  234380. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234381. {
  234382. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234383. if (xml == 0)
  234384. return "Couldn't parse XML in file";
  234385. const XmlElement* const dict = xml->getChildByName ("dict");
  234386. if (dict == 0)
  234387. return "Couldn't get top level dictionary";
  234388. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234389. if (sessions == 0)
  234390. return "Couldn't find sessions key";
  234391. const XmlElement* const session = sessions->getFirstChildElement();
  234392. if (session == 0)
  234393. return "Couldn't find first session";
  234394. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234395. if (leadOut < 0)
  234396. return "Couldn't find Leadout Block";
  234397. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234398. if (trackArray == 0)
  234399. return "Couldn't find Track Array";
  234400. forEachXmlChildElement (*trackArray, track)
  234401. {
  234402. const int trackValue = getIntValueForKey (*track, "Start Block");
  234403. if (trackValue < 0)
  234404. return "Couldn't find Start Block in the track";
  234405. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234406. }
  234407. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234408. return 0;
  234409. }
  234410. static void findDevices (Array<File>& cds)
  234411. {
  234412. File volumes ("/Volumes");
  234413. volumes.findChildFiles (cds, File::findDirectories, false);
  234414. for (int i = cds.size(); --i >= 0;)
  234415. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234416. cds.remove (i);
  234417. }
  234418. struct TrackSorter
  234419. {
  234420. static int getCDTrackNumber (const File& file)
  234421. {
  234422. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234423. }
  234424. static int compareElements (const File& first, const File& second)
  234425. {
  234426. const int firstTrack = getCDTrackNumber (first);
  234427. const int secondTrack = getCDTrackNumber (second);
  234428. jassert (firstTrack > 0 && secondTrack > 0);
  234429. return firstTrack - secondTrack;
  234430. }
  234431. };
  234432. }
  234433. const StringArray AudioCDReader::getAvailableCDNames()
  234434. {
  234435. Array<File> cds;
  234436. CDReaderHelpers::findDevices (cds);
  234437. StringArray names;
  234438. for (int i = 0; i < cds.size(); ++i)
  234439. names.add (cds.getReference(i).getFileName());
  234440. return names;
  234441. }
  234442. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234443. {
  234444. Array<File> cds;
  234445. CDReaderHelpers::findDevices (cds);
  234446. if (cds[index].exists())
  234447. return new AudioCDReader (cds[index]);
  234448. return 0;
  234449. }
  234450. AudioCDReader::AudioCDReader (const File& volume)
  234451. : AudioFormatReader (0, "CD Audio"),
  234452. volumeDir (volume),
  234453. currentReaderTrack (-1),
  234454. reader (0)
  234455. {
  234456. sampleRate = 44100.0;
  234457. bitsPerSample = 16;
  234458. numChannels = 2;
  234459. usesFloatingPointData = false;
  234460. refreshTrackLengths();
  234461. }
  234462. AudioCDReader::~AudioCDReader()
  234463. {
  234464. }
  234465. void AudioCDReader::refreshTrackLengths()
  234466. {
  234467. tracks.clear();
  234468. trackStartSamples.clear();
  234469. lengthInSamples = 0;
  234470. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234471. CDReaderHelpers::TrackSorter sorter;
  234472. tracks.sort (sorter);
  234473. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234474. if (toc.exists())
  234475. {
  234476. XmlDocument doc (toc);
  234477. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234478. (void) error; // could be logged..
  234479. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234480. }
  234481. }
  234482. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234483. int64 startSampleInFile, int numSamples)
  234484. {
  234485. while (numSamples > 0)
  234486. {
  234487. int track = -1;
  234488. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234489. {
  234490. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234491. {
  234492. track = i;
  234493. break;
  234494. }
  234495. }
  234496. if (track < 0)
  234497. return false;
  234498. if (track != currentReaderTrack)
  234499. {
  234500. reader = 0;
  234501. FileInputStream* const in = tracks [track].createInputStream();
  234502. if (in != 0)
  234503. {
  234504. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234505. AiffAudioFormat format;
  234506. reader = format.createReaderFor (bin, true);
  234507. if (reader == 0)
  234508. currentReaderTrack = -1;
  234509. else
  234510. currentReaderTrack = track;
  234511. }
  234512. }
  234513. if (reader == 0)
  234514. return false;
  234515. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234516. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234517. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234518. numSamples -= numAvailable;
  234519. startSampleInFile += numAvailable;
  234520. }
  234521. return true;
  234522. }
  234523. bool AudioCDReader::isCDStillPresent() const
  234524. {
  234525. return volumeDir.exists();
  234526. }
  234527. bool AudioCDReader::isTrackAudio (int trackNum) const
  234528. {
  234529. return tracks [trackNum].hasFileExtension (".aiff");
  234530. }
  234531. void AudioCDReader::enableIndexScanning (bool b)
  234532. {
  234533. // any way to do this on a Mac??
  234534. }
  234535. int AudioCDReader::getLastIndex() const
  234536. {
  234537. return 0;
  234538. }
  234539. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234540. {
  234541. return Array <int>();
  234542. }
  234543. #endif
  234544. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234545. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234547. // compiled on its own).
  234548. #if JUCE_INCLUDED_FILE
  234549. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234550. for example having more than one juce plugin loaded into a host, then when a
  234551. method is called, the actual code that runs might actually be in a different module
  234552. than the one you expect... So any calls to library functions or statics that are
  234553. made inside obj-c methods will probably end up getting executed in a different DLL's
  234554. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234555. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234556. virtual methods of an object that's known to live inside the right module's space.
  234557. */
  234558. class AppDelegateRedirector
  234559. {
  234560. public:
  234561. AppDelegateRedirector()
  234562. {
  234563. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234564. runLoop = CFRunLoopGetMain();
  234565. #else
  234566. runLoop = CFRunLoopGetCurrent();
  234567. #endif
  234568. CFRunLoopSourceContext sourceContext;
  234569. zerostruct (sourceContext);
  234570. sourceContext.info = this;
  234571. sourceContext.perform = runLoopSourceCallback;
  234572. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234573. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234574. }
  234575. virtual ~AppDelegateRedirector()
  234576. {
  234577. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234578. CFRunLoopSourceInvalidate (runLoopSource);
  234579. CFRelease (runLoopSource);
  234580. }
  234581. virtual NSApplicationTerminateReply shouldTerminate()
  234582. {
  234583. if (JUCEApplication::getInstance() != 0)
  234584. {
  234585. JUCEApplication::getInstance()->systemRequestedQuit();
  234586. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234587. return NSTerminateCancel;
  234588. }
  234589. return NSTerminateNow;
  234590. }
  234591. virtual void willTerminate()
  234592. {
  234593. JUCEApplication::appWillTerminateByForce();
  234594. }
  234595. virtual BOOL openFile (NSString* filename)
  234596. {
  234597. if (JUCEApplication::getInstance() != 0)
  234598. {
  234599. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234600. return YES;
  234601. }
  234602. return NO;
  234603. }
  234604. virtual void openFiles (NSArray* filenames)
  234605. {
  234606. StringArray files;
  234607. for (unsigned int i = 0; i < [filenames count]; ++i)
  234608. {
  234609. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234610. if (filename.containsChar (' '))
  234611. filename = filename.quoted('"');
  234612. files.add (filename);
  234613. }
  234614. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234615. {
  234616. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234617. }
  234618. }
  234619. virtual void focusChanged()
  234620. {
  234621. juce_HandleProcessFocusChange();
  234622. }
  234623. struct CallbackMessagePayload
  234624. {
  234625. MessageCallbackFunction* function;
  234626. void* parameter;
  234627. void* volatile result;
  234628. bool volatile hasBeenExecuted;
  234629. };
  234630. virtual void performCallback (CallbackMessagePayload* pl)
  234631. {
  234632. pl->result = (*pl->function) (pl->parameter);
  234633. pl->hasBeenExecuted = true;
  234634. }
  234635. virtual void deleteSelf()
  234636. {
  234637. delete this;
  234638. }
  234639. void postMessage (Message* const m)
  234640. {
  234641. messages.add (m);
  234642. CFRunLoopSourceSignal (runLoopSource);
  234643. CFRunLoopWakeUp (runLoop);
  234644. }
  234645. private:
  234646. CFRunLoopRef runLoop;
  234647. CFRunLoopSourceRef runLoopSource;
  234648. OwnedArray <Message, CriticalSection> messages;
  234649. void runLoopCallback()
  234650. {
  234651. int numDispatched = 0;
  234652. do
  234653. {
  234654. Message* const nextMessage = messages.removeAndReturn (0);
  234655. if (nextMessage == 0)
  234656. return;
  234657. const ScopedAutoReleasePool pool;
  234658. MessageManager::getInstance()->deliverMessage (nextMessage);
  234659. } while (++numDispatched <= 4);
  234660. CFRunLoopSourceSignal (runLoopSource);
  234661. CFRunLoopWakeUp (runLoop);
  234662. }
  234663. static void runLoopSourceCallback (void* info)
  234664. {
  234665. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234666. }
  234667. };
  234668. END_JUCE_NAMESPACE
  234669. using namespace JUCE_NAMESPACE;
  234670. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234671. @interface JuceAppDelegate : NSObject
  234672. {
  234673. @private
  234674. id oldDelegate;
  234675. @public
  234676. AppDelegateRedirector* redirector;
  234677. }
  234678. - (JuceAppDelegate*) init;
  234679. - (void) dealloc;
  234680. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234681. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234682. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234683. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234684. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234685. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234686. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234687. - (void) performCallback: (id) info;
  234688. - (void) dummyMethod;
  234689. @end
  234690. @implementation JuceAppDelegate
  234691. - (JuceAppDelegate*) init
  234692. {
  234693. [super init];
  234694. redirector = new AppDelegateRedirector();
  234695. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234696. if (JUCEApplication::isStandaloneApp())
  234697. {
  234698. oldDelegate = [NSApp delegate];
  234699. [NSApp setDelegate: self];
  234700. }
  234701. else
  234702. {
  234703. oldDelegate = 0;
  234704. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234705. name: NSApplicationDidResignActiveNotification object: NSApp];
  234706. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234707. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234708. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234709. name: NSApplicationWillUnhideNotification object: NSApp];
  234710. }
  234711. return self;
  234712. }
  234713. - (void) dealloc
  234714. {
  234715. if (oldDelegate != 0)
  234716. [NSApp setDelegate: oldDelegate];
  234717. redirector->deleteSelf();
  234718. [super dealloc];
  234719. }
  234720. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234721. {
  234722. (void) app;
  234723. return redirector->shouldTerminate();
  234724. }
  234725. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234726. {
  234727. (void) aNotification;
  234728. redirector->willTerminate();
  234729. }
  234730. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234731. {
  234732. (void) app;
  234733. return redirector->openFile (filename);
  234734. }
  234735. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234736. {
  234737. (void) sender;
  234738. return redirector->openFiles (filenames);
  234739. }
  234740. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234741. {
  234742. (void) notification;
  234743. redirector->focusChanged();
  234744. }
  234745. - (void) applicationDidResignActive: (NSNotification*) notification
  234746. {
  234747. (void) notification;
  234748. redirector->focusChanged();
  234749. }
  234750. - (void) applicationWillUnhide: (NSNotification*) notification
  234751. {
  234752. (void) notification;
  234753. redirector->focusChanged();
  234754. }
  234755. - (void) performCallback: (id) info
  234756. {
  234757. if ([info isKindOfClass: [NSData class]])
  234758. {
  234759. AppDelegateRedirector::CallbackMessagePayload* pl
  234760. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234761. if (pl != 0)
  234762. redirector->performCallback (pl);
  234763. }
  234764. else
  234765. {
  234766. jassertfalse; // should never get here!
  234767. }
  234768. }
  234769. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234770. @end
  234771. BEGIN_JUCE_NAMESPACE
  234772. static JuceAppDelegate* juceAppDelegate = 0;
  234773. void MessageManager::runDispatchLoop()
  234774. {
  234775. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234776. {
  234777. const ScopedAutoReleasePool pool;
  234778. // must only be called by the message thread!
  234779. jassert (isThisTheMessageThread());
  234780. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234781. @try
  234782. {
  234783. [NSApp run];
  234784. }
  234785. @catch (NSException* e)
  234786. {
  234787. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234788. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234789. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234790. }
  234791. @finally
  234792. {
  234793. }
  234794. #else
  234795. [NSApp run];
  234796. #endif
  234797. }
  234798. }
  234799. void MessageManager::stopDispatchLoop()
  234800. {
  234801. quitMessagePosted = true;
  234802. [NSApp stop: nil];
  234803. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234804. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234805. }
  234806. static bool isEventBlockedByModalComps (NSEvent* e)
  234807. {
  234808. if (Component::getNumCurrentlyModalComponents() == 0)
  234809. return false;
  234810. NSWindow* const w = [e window];
  234811. if (w == 0 || [w worksWhenModal])
  234812. return false;
  234813. bool isKey = false, isInputAttempt = false;
  234814. switch ([e type])
  234815. {
  234816. case NSKeyDown:
  234817. case NSKeyUp:
  234818. isKey = isInputAttempt = true;
  234819. break;
  234820. case NSLeftMouseDown:
  234821. case NSRightMouseDown:
  234822. case NSOtherMouseDown:
  234823. isInputAttempt = true;
  234824. break;
  234825. case NSLeftMouseDragged:
  234826. case NSRightMouseDragged:
  234827. case NSLeftMouseUp:
  234828. case NSRightMouseUp:
  234829. case NSOtherMouseUp:
  234830. case NSOtherMouseDragged:
  234831. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234832. return false;
  234833. break;
  234834. case NSMouseMoved:
  234835. case NSMouseEntered:
  234836. case NSMouseExited:
  234837. case NSCursorUpdate:
  234838. case NSScrollWheel:
  234839. case NSTabletPoint:
  234840. case NSTabletProximity:
  234841. break;
  234842. default:
  234843. return false;
  234844. }
  234845. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234846. {
  234847. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234848. NSView* const compView = (NSView*) peer->getNativeHandle();
  234849. if ([compView window] == w)
  234850. {
  234851. if (isKey)
  234852. {
  234853. if (compView == [w firstResponder])
  234854. return false;
  234855. }
  234856. else
  234857. {
  234858. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234859. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234860. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234861. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234862. return false;
  234863. }
  234864. }
  234865. }
  234866. if (isInputAttempt)
  234867. {
  234868. if (! [NSApp isActive])
  234869. [NSApp activateIgnoringOtherApps: YES];
  234870. Component* const modal = Component::getCurrentlyModalComponent (0);
  234871. if (modal != 0)
  234872. modal->inputAttemptWhenModal();
  234873. }
  234874. return true;
  234875. }
  234876. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234877. {
  234878. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234879. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234880. while (! quitMessagePosted)
  234881. {
  234882. const ScopedAutoReleasePool pool;
  234883. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234884. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234885. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234886. inMode: NSDefaultRunLoopMode
  234887. dequeue: YES];
  234888. if (e != 0 && ! isEventBlockedByModalComps (e))
  234889. [NSApp sendEvent: e];
  234890. if (Time::getMillisecondCounter() >= endTime)
  234891. break;
  234892. }
  234893. return ! quitMessagePosted;
  234894. }
  234895. void MessageManager::doPlatformSpecificInitialisation()
  234896. {
  234897. if (juceAppDelegate == 0)
  234898. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234899. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234900. // correctly (needed prior to 10.5)
  234901. if (! [NSThread isMultiThreaded])
  234902. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234903. toTarget: juceAppDelegate
  234904. withObject: nil];
  234905. }
  234906. void MessageManager::doPlatformSpecificShutdown()
  234907. {
  234908. if (juceAppDelegate != 0)
  234909. {
  234910. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234911. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234912. [juceAppDelegate release];
  234913. juceAppDelegate = 0;
  234914. }
  234915. }
  234916. bool juce_postMessageToSystemQueue (Message* message)
  234917. {
  234918. juceAppDelegate->redirector->postMessage (message);
  234919. return true;
  234920. }
  234921. void MessageManager::broadcastMessage (const String& value)
  234922. {
  234923. }
  234924. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234925. {
  234926. if (isThisTheMessageThread())
  234927. {
  234928. return (*callback) (data);
  234929. }
  234930. else
  234931. {
  234932. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234933. // deadlock because the message manager is blocked from running, so can never
  234934. // call your function..
  234935. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234936. const ScopedAutoReleasePool pool;
  234937. AppDelegateRedirector::CallbackMessagePayload cmp;
  234938. cmp.function = callback;
  234939. cmp.parameter = data;
  234940. cmp.result = 0;
  234941. cmp.hasBeenExecuted = false;
  234942. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234943. withObject: [NSData dataWithBytesNoCopy: &cmp
  234944. length: sizeof (cmp)
  234945. freeWhenDone: NO]
  234946. waitUntilDone: YES];
  234947. return cmp.result;
  234948. }
  234949. }
  234950. #endif
  234951. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234952. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234953. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234954. // compiled on its own).
  234955. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234956. #if JUCE_MAC
  234957. END_JUCE_NAMESPACE
  234958. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234959. @interface DownloadClickDetector : NSObject
  234960. {
  234961. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234962. }
  234963. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234964. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234965. request: (NSURLRequest*) request
  234966. frame: (WebFrame*) frame
  234967. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234968. @end
  234969. @implementation DownloadClickDetector
  234970. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234971. {
  234972. [super init];
  234973. ownerComponent = ownerComponent_;
  234974. return self;
  234975. }
  234976. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234977. request: (NSURLRequest*) request
  234978. frame: (WebFrame*) frame
  234979. decisionListener: (id <WebPolicyDecisionListener>) listener
  234980. {
  234981. (void) sender;
  234982. (void) request;
  234983. (void) frame;
  234984. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234985. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234986. [listener use];
  234987. else
  234988. [listener ignore];
  234989. }
  234990. @end
  234991. BEGIN_JUCE_NAMESPACE
  234992. class WebBrowserComponentInternal : public NSViewComponent
  234993. {
  234994. public:
  234995. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234996. {
  234997. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234998. frameName: @""
  234999. groupName: @""];
  235000. setView (webView);
  235001. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235002. [webView setPolicyDelegate: clickListener];
  235003. }
  235004. ~WebBrowserComponentInternal()
  235005. {
  235006. [webView setPolicyDelegate: nil];
  235007. [clickListener release];
  235008. setView (0);
  235009. }
  235010. void goToURL (const String& url,
  235011. const StringArray* headers,
  235012. const MemoryBlock* postData)
  235013. {
  235014. NSMutableURLRequest* r
  235015. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235016. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235017. timeoutInterval: 30.0];
  235018. if (postData != 0 && postData->getSize() > 0)
  235019. {
  235020. [r setHTTPMethod: @"POST"];
  235021. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235022. length: postData->getSize()]];
  235023. }
  235024. if (headers != 0)
  235025. {
  235026. for (int i = 0; i < headers->size(); ++i)
  235027. {
  235028. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235029. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235030. [r setValue: juceStringToNS (headerValue)
  235031. forHTTPHeaderField: juceStringToNS (headerName)];
  235032. }
  235033. }
  235034. stop();
  235035. [[webView mainFrame] loadRequest: r];
  235036. }
  235037. void goBack()
  235038. {
  235039. [webView goBack];
  235040. }
  235041. void goForward()
  235042. {
  235043. [webView goForward];
  235044. }
  235045. void stop()
  235046. {
  235047. [webView stopLoading: nil];
  235048. }
  235049. void refresh()
  235050. {
  235051. [webView reload: nil];
  235052. }
  235053. private:
  235054. WebView* webView;
  235055. DownloadClickDetector* clickListener;
  235056. };
  235057. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235058. : browser (0),
  235059. blankPageShown (false),
  235060. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235061. {
  235062. setOpaque (true);
  235063. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235064. }
  235065. WebBrowserComponent::~WebBrowserComponent()
  235066. {
  235067. deleteAndZero (browser);
  235068. }
  235069. void WebBrowserComponent::goToURL (const String& url,
  235070. const StringArray* headers,
  235071. const MemoryBlock* postData)
  235072. {
  235073. lastURL = url;
  235074. lastHeaders.clear();
  235075. if (headers != 0)
  235076. lastHeaders = *headers;
  235077. lastPostData.setSize (0);
  235078. if (postData != 0)
  235079. lastPostData = *postData;
  235080. blankPageShown = false;
  235081. browser->goToURL (url, headers, postData);
  235082. }
  235083. void WebBrowserComponent::stop()
  235084. {
  235085. browser->stop();
  235086. }
  235087. void WebBrowserComponent::goBack()
  235088. {
  235089. lastURL = String::empty;
  235090. blankPageShown = false;
  235091. browser->goBack();
  235092. }
  235093. void WebBrowserComponent::goForward()
  235094. {
  235095. lastURL = String::empty;
  235096. browser->goForward();
  235097. }
  235098. void WebBrowserComponent::refresh()
  235099. {
  235100. browser->refresh();
  235101. }
  235102. void WebBrowserComponent::paint (Graphics&)
  235103. {
  235104. }
  235105. void WebBrowserComponent::checkWindowAssociation()
  235106. {
  235107. if (isShowing())
  235108. {
  235109. if (blankPageShown)
  235110. goBack();
  235111. }
  235112. else
  235113. {
  235114. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235115. {
  235116. // when the component becomes invisible, some stuff like flash
  235117. // carries on playing audio, so we need to force it onto a blank
  235118. // page to avoid this, (and send it back when it's made visible again).
  235119. blankPageShown = true;
  235120. browser->goToURL ("about:blank", 0, 0);
  235121. }
  235122. }
  235123. }
  235124. void WebBrowserComponent::reloadLastURL()
  235125. {
  235126. if (lastURL.isNotEmpty())
  235127. {
  235128. goToURL (lastURL, &lastHeaders, &lastPostData);
  235129. lastURL = String::empty;
  235130. }
  235131. }
  235132. void WebBrowserComponent::parentHierarchyChanged()
  235133. {
  235134. checkWindowAssociation();
  235135. }
  235136. void WebBrowserComponent::resized()
  235137. {
  235138. browser->setSize (getWidth(), getHeight());
  235139. }
  235140. void WebBrowserComponent::visibilityChanged()
  235141. {
  235142. checkWindowAssociation();
  235143. }
  235144. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235145. {
  235146. return true;
  235147. }
  235148. #else
  235149. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235150. {
  235151. }
  235152. WebBrowserComponent::~WebBrowserComponent()
  235153. {
  235154. }
  235155. void WebBrowserComponent::goToURL (const String& url,
  235156. const StringArray* headers,
  235157. const MemoryBlock* postData)
  235158. {
  235159. }
  235160. void WebBrowserComponent::stop()
  235161. {
  235162. }
  235163. void WebBrowserComponent::goBack()
  235164. {
  235165. }
  235166. void WebBrowserComponent::goForward()
  235167. {
  235168. }
  235169. void WebBrowserComponent::refresh()
  235170. {
  235171. }
  235172. void WebBrowserComponent::paint (Graphics& g)
  235173. {
  235174. }
  235175. void WebBrowserComponent::checkWindowAssociation()
  235176. {
  235177. }
  235178. void WebBrowserComponent::reloadLastURL()
  235179. {
  235180. }
  235181. void WebBrowserComponent::parentHierarchyChanged()
  235182. {
  235183. }
  235184. void WebBrowserComponent::resized()
  235185. {
  235186. }
  235187. void WebBrowserComponent::visibilityChanged()
  235188. {
  235189. }
  235190. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235191. {
  235192. return true;
  235193. }
  235194. #endif
  235195. #endif
  235196. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235197. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235198. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235199. // compiled on its own).
  235200. #if JUCE_INCLUDED_FILE
  235201. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235202. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235203. #endif
  235204. #undef log
  235205. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235206. #define log(a) Logger::writeToLog (a)
  235207. #else
  235208. #define log(a)
  235209. #endif
  235210. #undef OK
  235211. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235212. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235213. {
  235214. if (err == noErr)
  235215. return true;
  235216. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235217. jassertfalse;
  235218. return false;
  235219. }
  235220. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235221. #else
  235222. #define OK(a) (a == noErr)
  235223. #endif
  235224. class CoreAudioInternal : public Timer
  235225. {
  235226. public:
  235227. CoreAudioInternal (AudioDeviceID id)
  235228. : inputLatency (0),
  235229. outputLatency (0),
  235230. callback (0),
  235231. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235232. audioProcID (0),
  235233. #endif
  235234. isSlaveDevice (false),
  235235. deviceID (id),
  235236. started (false),
  235237. sampleRate (0),
  235238. bufferSize (512),
  235239. numInputChans (0),
  235240. numOutputChans (0),
  235241. callbacksAllowed (true),
  235242. numInputChannelInfos (0),
  235243. numOutputChannelInfos (0)
  235244. {
  235245. jassert (deviceID != 0);
  235246. updateDetailsFromDevice();
  235247. AudioObjectPropertyAddress pa;
  235248. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235249. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235250. pa.mElement = kAudioObjectPropertyElementWildcard;
  235251. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235252. }
  235253. ~CoreAudioInternal()
  235254. {
  235255. AudioObjectPropertyAddress pa;
  235256. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235257. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235258. pa.mElement = kAudioObjectPropertyElementWildcard;
  235259. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235260. stop (false);
  235261. }
  235262. void allocateTempBuffers()
  235263. {
  235264. const int tempBufSize = bufferSize + 4;
  235265. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235266. tempInputBuffers.calloc (numInputChans + 2);
  235267. tempOutputBuffers.calloc (numOutputChans + 2);
  235268. int i, count = 0;
  235269. for (i = 0; i < numInputChans; ++i)
  235270. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235271. for (i = 0; i < numOutputChans; ++i)
  235272. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235273. }
  235274. // returns the number of actual available channels
  235275. void fillInChannelInfo (const bool input)
  235276. {
  235277. int chanNum = 0;
  235278. UInt32 size;
  235279. AudioObjectPropertyAddress pa;
  235280. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235281. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235282. pa.mElement = kAudioObjectPropertyElementMaster;
  235283. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235284. {
  235285. HeapBlock <AudioBufferList> bufList;
  235286. bufList.calloc (size, 1);
  235287. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235288. {
  235289. const int numStreams = bufList->mNumberBuffers;
  235290. for (int i = 0; i < numStreams; ++i)
  235291. {
  235292. const AudioBuffer& b = bufList->mBuffers[i];
  235293. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235294. {
  235295. String name;
  235296. {
  235297. char channelName [256];
  235298. zerostruct (channelName);
  235299. UInt32 nameSize = sizeof (channelName);
  235300. UInt32 channelNum = chanNum + 1;
  235301. pa.mSelector = kAudioDevicePropertyChannelName;
  235302. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235303. name = String::fromUTF8 (channelName, nameSize);
  235304. }
  235305. if (input)
  235306. {
  235307. if (activeInputChans[chanNum])
  235308. {
  235309. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235310. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235311. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235312. ++numInputChannelInfos;
  235313. }
  235314. if (name.isEmpty())
  235315. name << "Input " << (chanNum + 1);
  235316. inChanNames.add (name);
  235317. }
  235318. else
  235319. {
  235320. if (activeOutputChans[chanNum])
  235321. {
  235322. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235323. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235324. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235325. ++numOutputChannelInfos;
  235326. }
  235327. if (name.isEmpty())
  235328. name << "Output " << (chanNum + 1);
  235329. outChanNames.add (name);
  235330. }
  235331. ++chanNum;
  235332. }
  235333. }
  235334. }
  235335. }
  235336. }
  235337. void updateDetailsFromDevice()
  235338. {
  235339. stopTimer();
  235340. if (deviceID == 0)
  235341. return;
  235342. const ScopedLock sl (callbackLock);
  235343. Float64 sr;
  235344. UInt32 size = sizeof (Float64);
  235345. AudioObjectPropertyAddress pa;
  235346. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235347. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235348. pa.mElement = kAudioObjectPropertyElementMaster;
  235349. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235350. sampleRate = sr;
  235351. UInt32 framesPerBuf;
  235352. size = sizeof (framesPerBuf);
  235353. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235354. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235355. {
  235356. bufferSize = framesPerBuf;
  235357. allocateTempBuffers();
  235358. }
  235359. bufferSizes.clear();
  235360. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235361. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235362. {
  235363. HeapBlock <AudioValueRange> ranges;
  235364. ranges.calloc (size, 1);
  235365. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235366. {
  235367. bufferSizes.add ((int) ranges[0].mMinimum);
  235368. for (int i = 32; i < 2048; i += 32)
  235369. {
  235370. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235371. {
  235372. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235373. {
  235374. bufferSizes.addIfNotAlreadyThere (i);
  235375. break;
  235376. }
  235377. }
  235378. }
  235379. if (bufferSize > 0)
  235380. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235381. }
  235382. }
  235383. if (bufferSizes.size() == 0 && bufferSize > 0)
  235384. bufferSizes.add (bufferSize);
  235385. sampleRates.clear();
  235386. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235387. String rates;
  235388. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235389. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235390. {
  235391. HeapBlock <AudioValueRange> ranges;
  235392. ranges.calloc (size, 1);
  235393. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235394. {
  235395. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235396. {
  235397. bool ok = false;
  235398. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235399. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235400. ok = true;
  235401. if (ok)
  235402. {
  235403. sampleRates.add (possibleRates[i]);
  235404. rates << possibleRates[i] << ' ';
  235405. }
  235406. }
  235407. }
  235408. }
  235409. if (sampleRates.size() == 0 && sampleRate > 0)
  235410. {
  235411. sampleRates.add (sampleRate);
  235412. rates << sampleRate;
  235413. }
  235414. log ("sr: " + rates);
  235415. inputLatency = 0;
  235416. outputLatency = 0;
  235417. UInt32 lat;
  235418. size = sizeof (lat);
  235419. pa.mSelector = kAudioDevicePropertyLatency;
  235420. pa.mScope = kAudioDevicePropertyScopeInput;
  235421. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235422. inputLatency = (int) lat;
  235423. pa.mScope = kAudioDevicePropertyScopeOutput;
  235424. size = sizeof (lat);
  235425. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235426. outputLatency = (int) lat;
  235427. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235428. inChanNames.clear();
  235429. outChanNames.clear();
  235430. inputChannelInfo.calloc (numInputChans + 2);
  235431. numInputChannelInfos = 0;
  235432. outputChannelInfo.calloc (numOutputChans + 2);
  235433. numOutputChannelInfos = 0;
  235434. fillInChannelInfo (true);
  235435. fillInChannelInfo (false);
  235436. }
  235437. const StringArray getSources (bool input)
  235438. {
  235439. StringArray s;
  235440. HeapBlock <OSType> types;
  235441. const int num = getAllDataSourcesForDevice (deviceID, types);
  235442. for (int i = 0; i < num; ++i)
  235443. {
  235444. AudioValueTranslation avt;
  235445. char buffer[256];
  235446. avt.mInputData = &(types[i]);
  235447. avt.mInputDataSize = sizeof (UInt32);
  235448. avt.mOutputData = buffer;
  235449. avt.mOutputDataSize = 256;
  235450. UInt32 transSize = sizeof (avt);
  235451. AudioObjectPropertyAddress pa;
  235452. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235453. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235454. pa.mElement = kAudioObjectPropertyElementMaster;
  235455. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235456. {
  235457. DBG (buffer);
  235458. s.add (buffer);
  235459. }
  235460. }
  235461. return s;
  235462. }
  235463. int getCurrentSourceIndex (bool input) const
  235464. {
  235465. OSType currentSourceID = 0;
  235466. UInt32 size = sizeof (currentSourceID);
  235467. int result = -1;
  235468. AudioObjectPropertyAddress pa;
  235469. pa.mSelector = kAudioDevicePropertyDataSource;
  235470. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235471. pa.mElement = kAudioObjectPropertyElementMaster;
  235472. if (deviceID != 0)
  235473. {
  235474. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235475. {
  235476. HeapBlock <OSType> types;
  235477. const int num = getAllDataSourcesForDevice (deviceID, types);
  235478. for (int i = 0; i < num; ++i)
  235479. {
  235480. if (types[num] == currentSourceID)
  235481. {
  235482. result = i;
  235483. break;
  235484. }
  235485. }
  235486. }
  235487. }
  235488. return result;
  235489. }
  235490. void setCurrentSourceIndex (int index, bool input)
  235491. {
  235492. if (deviceID != 0)
  235493. {
  235494. HeapBlock <OSType> types;
  235495. const int num = getAllDataSourcesForDevice (deviceID, types);
  235496. if (((unsigned int) index) < (unsigned int) num)
  235497. {
  235498. AudioObjectPropertyAddress pa;
  235499. pa.mSelector = kAudioDevicePropertyDataSource;
  235500. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235501. pa.mElement = kAudioObjectPropertyElementMaster;
  235502. OSType typeId = types[index];
  235503. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235504. }
  235505. }
  235506. }
  235507. const String reopen (const BigInteger& inputChannels,
  235508. const BigInteger& outputChannels,
  235509. double newSampleRate,
  235510. int bufferSizeSamples)
  235511. {
  235512. String error;
  235513. log ("CoreAudio reopen");
  235514. callbacksAllowed = false;
  235515. stopTimer();
  235516. stop (false);
  235517. activeInputChans = inputChannels;
  235518. activeInputChans.setRange (inChanNames.size(),
  235519. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235520. false);
  235521. activeOutputChans = outputChannels;
  235522. activeOutputChans.setRange (outChanNames.size(),
  235523. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235524. false);
  235525. numInputChans = activeInputChans.countNumberOfSetBits();
  235526. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235527. // set sample rate
  235528. AudioObjectPropertyAddress pa;
  235529. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235530. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235531. pa.mElement = kAudioObjectPropertyElementMaster;
  235532. Float64 sr = newSampleRate;
  235533. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235534. {
  235535. error = "Couldn't change sample rate";
  235536. }
  235537. else
  235538. {
  235539. // change buffer size
  235540. UInt32 framesPerBuf = bufferSizeSamples;
  235541. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235542. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235543. {
  235544. error = "Couldn't change buffer size";
  235545. }
  235546. else
  235547. {
  235548. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235549. // correctly report their new settings until some random time in the future, so
  235550. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235551. // to make sure we're using the correct numbers..
  235552. updateDetailsFromDevice();
  235553. sampleRate = newSampleRate;
  235554. bufferSize = bufferSizeSamples;
  235555. if (sampleRates.size() == 0)
  235556. error = "Device has no available sample-rates";
  235557. else if (bufferSizes.size() == 0)
  235558. error = "Device has no available buffer-sizes";
  235559. else if (inputDevice != 0)
  235560. error = inputDevice->reopen (inputChannels,
  235561. outputChannels,
  235562. newSampleRate,
  235563. bufferSizeSamples);
  235564. }
  235565. }
  235566. callbacksAllowed = true;
  235567. return error;
  235568. }
  235569. bool start (AudioIODeviceCallback* cb)
  235570. {
  235571. if (! started)
  235572. {
  235573. callback = 0;
  235574. if (deviceID != 0)
  235575. {
  235576. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235577. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235578. #else
  235579. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235580. #endif
  235581. {
  235582. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235583. {
  235584. started = true;
  235585. }
  235586. else
  235587. {
  235588. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235589. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235590. #else
  235591. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235592. audioProcID = 0;
  235593. #endif
  235594. }
  235595. }
  235596. }
  235597. }
  235598. if (started)
  235599. {
  235600. const ScopedLock sl (callbackLock);
  235601. callback = cb;
  235602. }
  235603. if (inputDevice != 0)
  235604. return started && inputDevice->start (cb);
  235605. else
  235606. return started;
  235607. }
  235608. void stop (bool leaveInterruptRunning)
  235609. {
  235610. {
  235611. const ScopedLock sl (callbackLock);
  235612. callback = 0;
  235613. }
  235614. if (started
  235615. && (deviceID != 0)
  235616. && ! leaveInterruptRunning)
  235617. {
  235618. OK (AudioDeviceStop (deviceID, audioIOProc));
  235619. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235620. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235621. #else
  235622. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235623. audioProcID = 0;
  235624. #endif
  235625. started = false;
  235626. { const ScopedLock sl (callbackLock); }
  235627. // wait until it's definately stopped calling back..
  235628. for (int i = 40; --i >= 0;)
  235629. {
  235630. Thread::sleep (50);
  235631. UInt32 running = 0;
  235632. UInt32 size = sizeof (running);
  235633. AudioObjectPropertyAddress pa;
  235634. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235635. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235636. pa.mElement = kAudioObjectPropertyElementMaster;
  235637. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235638. if (running == 0)
  235639. break;
  235640. }
  235641. const ScopedLock sl (callbackLock);
  235642. }
  235643. if (inputDevice != 0)
  235644. inputDevice->stop (leaveInterruptRunning);
  235645. }
  235646. double getSampleRate() const
  235647. {
  235648. return sampleRate;
  235649. }
  235650. int getBufferSize() const
  235651. {
  235652. return bufferSize;
  235653. }
  235654. void audioCallback (const AudioBufferList* inInputData,
  235655. AudioBufferList* outOutputData)
  235656. {
  235657. int i;
  235658. const ScopedLock sl (callbackLock);
  235659. if (callback != 0)
  235660. {
  235661. if (inputDevice == 0)
  235662. {
  235663. for (i = numInputChans; --i >= 0;)
  235664. {
  235665. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235666. float* dest = tempInputBuffers [i];
  235667. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235668. + info.dataOffsetSamples;
  235669. const int stride = info.dataStrideSamples;
  235670. if (stride != 0) // if this is zero, info is invalid
  235671. {
  235672. for (int j = bufferSize; --j >= 0;)
  235673. {
  235674. *dest++ = *src;
  235675. src += stride;
  235676. }
  235677. }
  235678. }
  235679. }
  235680. if (! isSlaveDevice)
  235681. {
  235682. if (inputDevice == 0)
  235683. {
  235684. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235685. numInputChans,
  235686. tempOutputBuffers,
  235687. numOutputChans,
  235688. bufferSize);
  235689. }
  235690. else
  235691. {
  235692. jassert (inputDevice->bufferSize == bufferSize);
  235693. // Sometimes the two linked devices seem to get their callbacks in
  235694. // parallel, so we need to lock both devices to stop the input data being
  235695. // changed while inside our callback..
  235696. const ScopedLock sl2 (inputDevice->callbackLock);
  235697. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235698. inputDevice->numInputChans,
  235699. tempOutputBuffers,
  235700. numOutputChans,
  235701. bufferSize);
  235702. }
  235703. for (i = numOutputChans; --i >= 0;)
  235704. {
  235705. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235706. const float* src = tempOutputBuffers [i];
  235707. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235708. + info.dataOffsetSamples;
  235709. const int stride = info.dataStrideSamples;
  235710. if (stride != 0) // if this is zero, info is invalid
  235711. {
  235712. for (int j = bufferSize; --j >= 0;)
  235713. {
  235714. *dest = *src++;
  235715. dest += stride;
  235716. }
  235717. }
  235718. }
  235719. }
  235720. }
  235721. else
  235722. {
  235723. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235724. {
  235725. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235726. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235727. + info.dataOffsetSamples;
  235728. const int stride = info.dataStrideSamples;
  235729. if (stride != 0) // if this is zero, info is invalid
  235730. {
  235731. for (int j = bufferSize; --j >= 0;)
  235732. {
  235733. *dest = 0.0f;
  235734. dest += stride;
  235735. }
  235736. }
  235737. }
  235738. }
  235739. }
  235740. // called by callbacks
  235741. void deviceDetailsChanged()
  235742. {
  235743. if (callbacksAllowed)
  235744. startTimer (100);
  235745. }
  235746. void timerCallback()
  235747. {
  235748. stopTimer();
  235749. log ("CoreAudio device changed callback");
  235750. const double oldSampleRate = sampleRate;
  235751. const int oldBufferSize = bufferSize;
  235752. updateDetailsFromDevice();
  235753. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235754. {
  235755. callbacksAllowed = false;
  235756. stop (false);
  235757. updateDetailsFromDevice();
  235758. callbacksAllowed = true;
  235759. }
  235760. }
  235761. CoreAudioInternal* getRelatedDevice() const
  235762. {
  235763. UInt32 size = 0;
  235764. ScopedPointer <CoreAudioInternal> result;
  235765. AudioObjectPropertyAddress pa;
  235766. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235767. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235768. pa.mElement = kAudioObjectPropertyElementMaster;
  235769. if (deviceID != 0
  235770. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235771. && size > 0)
  235772. {
  235773. HeapBlock <AudioDeviceID> devs;
  235774. devs.calloc (size, 1);
  235775. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235776. {
  235777. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235778. {
  235779. if (devs[i] != deviceID && devs[i] != 0)
  235780. {
  235781. result = new CoreAudioInternal (devs[i]);
  235782. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235783. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235784. if (thisIsInput != otherIsInput
  235785. || (inChanNames.size() + outChanNames.size() == 0)
  235786. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235787. break;
  235788. result = 0;
  235789. }
  235790. }
  235791. }
  235792. }
  235793. return result.release();
  235794. }
  235795. juce_UseDebuggingNewOperator
  235796. int inputLatency, outputLatency;
  235797. BigInteger activeInputChans, activeOutputChans;
  235798. StringArray inChanNames, outChanNames;
  235799. Array <double> sampleRates;
  235800. Array <int> bufferSizes;
  235801. AudioIODeviceCallback* callback;
  235802. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235803. AudioDeviceIOProcID audioProcID;
  235804. #endif
  235805. ScopedPointer<CoreAudioInternal> inputDevice;
  235806. bool isSlaveDevice;
  235807. private:
  235808. CriticalSection callbackLock;
  235809. AudioDeviceID deviceID;
  235810. bool started;
  235811. double sampleRate;
  235812. int bufferSize;
  235813. HeapBlock <float> audioBuffer;
  235814. int numInputChans, numOutputChans;
  235815. bool callbacksAllowed;
  235816. struct CallbackDetailsForChannel
  235817. {
  235818. int streamNum;
  235819. int dataOffsetSamples;
  235820. int dataStrideSamples;
  235821. };
  235822. int numInputChannelInfos, numOutputChannelInfos;
  235823. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235824. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235825. CoreAudioInternal (const CoreAudioInternal&);
  235826. CoreAudioInternal& operator= (const CoreAudioInternal&);
  235827. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235828. const AudioTimeStamp* /*inNow*/,
  235829. const AudioBufferList* inInputData,
  235830. const AudioTimeStamp* /*inInputTime*/,
  235831. AudioBufferList* outOutputData,
  235832. const AudioTimeStamp* /*inOutputTime*/,
  235833. void* device)
  235834. {
  235835. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235836. return noErr;
  235837. }
  235838. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235839. {
  235840. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235841. switch (pa->mSelector)
  235842. {
  235843. case kAudioDevicePropertyBufferSize:
  235844. case kAudioDevicePropertyBufferFrameSize:
  235845. case kAudioDevicePropertyNominalSampleRate:
  235846. case kAudioDevicePropertyStreamFormat:
  235847. case kAudioDevicePropertyDeviceIsAlive:
  235848. intern->deviceDetailsChanged();
  235849. break;
  235850. case kAudioDevicePropertyBufferSizeRange:
  235851. case kAudioDevicePropertyVolumeScalar:
  235852. case kAudioDevicePropertyMute:
  235853. case kAudioDevicePropertyPlayThru:
  235854. case kAudioDevicePropertyDataSource:
  235855. case kAudioDevicePropertyDeviceIsRunning:
  235856. break;
  235857. }
  235858. return noErr;
  235859. }
  235860. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235861. {
  235862. AudioObjectPropertyAddress pa;
  235863. pa.mSelector = kAudioDevicePropertyDataSources;
  235864. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235865. pa.mElement = kAudioObjectPropertyElementMaster;
  235866. UInt32 size = 0;
  235867. if (deviceID != 0
  235868. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235869. {
  235870. types.calloc (size, 1);
  235871. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235872. return size / (int) sizeof (OSType);
  235873. }
  235874. return 0;
  235875. }
  235876. };
  235877. class CoreAudioIODevice : public AudioIODevice
  235878. {
  235879. public:
  235880. CoreAudioIODevice (const String& deviceName,
  235881. AudioDeviceID inputDeviceId,
  235882. const int inputIndex_,
  235883. AudioDeviceID outputDeviceId,
  235884. const int outputIndex_)
  235885. : AudioIODevice (deviceName, "CoreAudio"),
  235886. inputIndex (inputIndex_),
  235887. outputIndex (outputIndex_),
  235888. isOpen_ (false),
  235889. isStarted (false)
  235890. {
  235891. CoreAudioInternal* device = 0;
  235892. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235893. {
  235894. jassert (inputDeviceId != 0);
  235895. device = new CoreAudioInternal (inputDeviceId);
  235896. }
  235897. else
  235898. {
  235899. device = new CoreAudioInternal (outputDeviceId);
  235900. if (inputDeviceId != 0)
  235901. {
  235902. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235903. device->inputDevice = secondDevice;
  235904. secondDevice->isSlaveDevice = true;
  235905. }
  235906. }
  235907. internal = device;
  235908. AudioObjectPropertyAddress pa;
  235909. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235910. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235911. pa.mElement = kAudioObjectPropertyElementWildcard;
  235912. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235913. }
  235914. ~CoreAudioIODevice()
  235915. {
  235916. AudioObjectPropertyAddress pa;
  235917. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235918. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235919. pa.mElement = kAudioObjectPropertyElementWildcard;
  235920. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235921. }
  235922. const StringArray getOutputChannelNames()
  235923. {
  235924. return internal->outChanNames;
  235925. }
  235926. const StringArray getInputChannelNames()
  235927. {
  235928. if (internal->inputDevice != 0)
  235929. return internal->inputDevice->inChanNames;
  235930. else
  235931. return internal->inChanNames;
  235932. }
  235933. int getNumSampleRates()
  235934. {
  235935. return internal->sampleRates.size();
  235936. }
  235937. double getSampleRate (int index)
  235938. {
  235939. return internal->sampleRates [index];
  235940. }
  235941. int getNumBufferSizesAvailable()
  235942. {
  235943. return internal->bufferSizes.size();
  235944. }
  235945. int getBufferSizeSamples (int index)
  235946. {
  235947. return internal->bufferSizes [index];
  235948. }
  235949. int getDefaultBufferSize()
  235950. {
  235951. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235952. if (getBufferSizeSamples(i) >= 512)
  235953. return getBufferSizeSamples(i);
  235954. return 512;
  235955. }
  235956. const String open (const BigInteger& inputChannels,
  235957. const BigInteger& outputChannels,
  235958. double sampleRate,
  235959. int bufferSizeSamples)
  235960. {
  235961. isOpen_ = true;
  235962. if (bufferSizeSamples <= 0)
  235963. bufferSizeSamples = getDefaultBufferSize();
  235964. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235965. isOpen_ = lastError.isEmpty();
  235966. return lastError;
  235967. }
  235968. void close()
  235969. {
  235970. isOpen_ = false;
  235971. internal->stop (false);
  235972. }
  235973. bool isOpen()
  235974. {
  235975. return isOpen_;
  235976. }
  235977. int getCurrentBufferSizeSamples()
  235978. {
  235979. return internal != 0 ? internal->getBufferSize() : 512;
  235980. }
  235981. double getCurrentSampleRate()
  235982. {
  235983. return internal != 0 ? internal->getSampleRate() : 0;
  235984. }
  235985. int getCurrentBitDepth()
  235986. {
  235987. return 32; // no way to find out, so just assume it's high..
  235988. }
  235989. const BigInteger getActiveOutputChannels() const
  235990. {
  235991. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235992. }
  235993. const BigInteger getActiveInputChannels() const
  235994. {
  235995. BigInteger chans;
  235996. if (internal != 0)
  235997. {
  235998. chans = internal->activeInputChans;
  235999. if (internal->inputDevice != 0)
  236000. chans |= internal->inputDevice->activeInputChans;
  236001. }
  236002. return chans;
  236003. }
  236004. int getOutputLatencyInSamples()
  236005. {
  236006. if (internal == 0)
  236007. return 0;
  236008. // this seems like a good guess at getting the latency right - comparing
  236009. // this with a round-trip measurement, it gets it to within a few millisecs
  236010. // for the built-in mac soundcard
  236011. return internal->outputLatency + internal->getBufferSize() * 2;
  236012. }
  236013. int getInputLatencyInSamples()
  236014. {
  236015. if (internal == 0)
  236016. return 0;
  236017. return internal->inputLatency + internal->getBufferSize() * 2;
  236018. }
  236019. void start (AudioIODeviceCallback* callback)
  236020. {
  236021. if (internal != 0 && ! isStarted)
  236022. {
  236023. if (callback != 0)
  236024. callback->audioDeviceAboutToStart (this);
  236025. isStarted = true;
  236026. internal->start (callback);
  236027. }
  236028. }
  236029. void stop()
  236030. {
  236031. if (isStarted && internal != 0)
  236032. {
  236033. AudioIODeviceCallback* const lastCallback = internal->callback;
  236034. isStarted = false;
  236035. internal->stop (true);
  236036. if (lastCallback != 0)
  236037. lastCallback->audioDeviceStopped();
  236038. }
  236039. }
  236040. bool isPlaying()
  236041. {
  236042. if (internal->callback == 0)
  236043. isStarted = false;
  236044. return isStarted;
  236045. }
  236046. const String getLastError()
  236047. {
  236048. return lastError;
  236049. }
  236050. int inputIndex, outputIndex;
  236051. juce_UseDebuggingNewOperator
  236052. private:
  236053. ScopedPointer<CoreAudioInternal> internal;
  236054. bool isOpen_, isStarted;
  236055. String lastError;
  236056. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236057. {
  236058. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236059. switch (pa->mSelector)
  236060. {
  236061. case kAudioHardwarePropertyDevices:
  236062. intern->deviceDetailsChanged();
  236063. break;
  236064. case kAudioHardwarePropertyDefaultOutputDevice:
  236065. case kAudioHardwarePropertyDefaultInputDevice:
  236066. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236067. break;
  236068. }
  236069. return noErr;
  236070. }
  236071. CoreAudioIODevice (const CoreAudioIODevice&);
  236072. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236073. };
  236074. class CoreAudioIODeviceType : public AudioIODeviceType
  236075. {
  236076. public:
  236077. CoreAudioIODeviceType()
  236078. : AudioIODeviceType ("CoreAudio"),
  236079. hasScanned (false)
  236080. {
  236081. }
  236082. ~CoreAudioIODeviceType()
  236083. {
  236084. }
  236085. void scanForDevices()
  236086. {
  236087. hasScanned = true;
  236088. inputDeviceNames.clear();
  236089. outputDeviceNames.clear();
  236090. inputIds.clear();
  236091. outputIds.clear();
  236092. UInt32 size;
  236093. AudioObjectPropertyAddress pa;
  236094. pa.mSelector = kAudioHardwarePropertyDevices;
  236095. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236096. pa.mElement = kAudioObjectPropertyElementMaster;
  236097. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236098. {
  236099. HeapBlock <AudioDeviceID> devs;
  236100. devs.calloc (size, 1);
  236101. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236102. {
  236103. const int num = size / (int) sizeof (AudioDeviceID);
  236104. for (int i = 0; i < num; ++i)
  236105. {
  236106. char name [1024];
  236107. size = sizeof (name);
  236108. pa.mSelector = kAudioDevicePropertyDeviceName;
  236109. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236110. {
  236111. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236112. const int numIns = getNumChannels (devs[i], true);
  236113. const int numOuts = getNumChannels (devs[i], false);
  236114. if (numIns > 0)
  236115. {
  236116. inputDeviceNames.add (nameString);
  236117. inputIds.add (devs[i]);
  236118. }
  236119. if (numOuts > 0)
  236120. {
  236121. outputDeviceNames.add (nameString);
  236122. outputIds.add (devs[i]);
  236123. }
  236124. }
  236125. }
  236126. }
  236127. }
  236128. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236129. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236130. }
  236131. const StringArray getDeviceNames (bool wantInputNames) const
  236132. {
  236133. jassert (hasScanned); // need to call scanForDevices() before doing this
  236134. if (wantInputNames)
  236135. return inputDeviceNames;
  236136. else
  236137. return outputDeviceNames;
  236138. }
  236139. int getDefaultDeviceIndex (bool forInput) const
  236140. {
  236141. jassert (hasScanned); // need to call scanForDevices() before doing this
  236142. AudioDeviceID deviceID;
  236143. UInt32 size = sizeof (deviceID);
  236144. // if they're asking for any input channels at all, use the default input, so we
  236145. // get the built-in mic rather than the built-in output with no inputs..
  236146. AudioObjectPropertyAddress pa;
  236147. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236148. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236149. pa.mElement = kAudioObjectPropertyElementMaster;
  236150. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236151. {
  236152. if (forInput)
  236153. {
  236154. for (int i = inputIds.size(); --i >= 0;)
  236155. if (inputIds[i] == deviceID)
  236156. return i;
  236157. }
  236158. else
  236159. {
  236160. for (int i = outputIds.size(); --i >= 0;)
  236161. if (outputIds[i] == deviceID)
  236162. return i;
  236163. }
  236164. }
  236165. return 0;
  236166. }
  236167. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236168. {
  236169. jassert (hasScanned); // need to call scanForDevices() before doing this
  236170. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236171. if (d == 0)
  236172. return -1;
  236173. return asInput ? d->inputIndex
  236174. : d->outputIndex;
  236175. }
  236176. bool hasSeparateInputsAndOutputs() const { return true; }
  236177. AudioIODevice* createDevice (const String& outputDeviceName,
  236178. const String& inputDeviceName)
  236179. {
  236180. jassert (hasScanned); // need to call scanForDevices() before doing this
  236181. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236182. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236183. String deviceName (outputDeviceName);
  236184. if (deviceName.isEmpty())
  236185. deviceName = inputDeviceName;
  236186. if (index >= 0)
  236187. return new CoreAudioIODevice (deviceName,
  236188. inputIds [inputIndex],
  236189. inputIndex,
  236190. outputIds [outputIndex],
  236191. outputIndex);
  236192. return 0;
  236193. }
  236194. juce_UseDebuggingNewOperator
  236195. private:
  236196. StringArray inputDeviceNames, outputDeviceNames;
  236197. Array <AudioDeviceID> inputIds, outputIds;
  236198. bool hasScanned;
  236199. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236200. {
  236201. int total = 0;
  236202. UInt32 size;
  236203. AudioObjectPropertyAddress pa;
  236204. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236205. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236206. pa.mElement = kAudioObjectPropertyElementMaster;
  236207. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236208. {
  236209. HeapBlock <AudioBufferList> bufList;
  236210. bufList.calloc (size, 1);
  236211. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236212. {
  236213. const int numStreams = bufList->mNumberBuffers;
  236214. for (int i = 0; i < numStreams; ++i)
  236215. {
  236216. const AudioBuffer& b = bufList->mBuffers[i];
  236217. total += b.mNumberChannels;
  236218. }
  236219. }
  236220. }
  236221. return total;
  236222. }
  236223. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236224. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236225. };
  236226. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236227. {
  236228. return new CoreAudioIODeviceType();
  236229. }
  236230. #undef log
  236231. #endif
  236232. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236233. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236234. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236235. // compiled on its own).
  236236. #if JUCE_INCLUDED_FILE
  236237. #if JUCE_MAC
  236238. namespace CoreMidiHelpers
  236239. {
  236240. static bool logError (const OSStatus err, const int lineNum)
  236241. {
  236242. if (err == noErr)
  236243. return true;
  236244. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236245. jassertfalse;
  236246. return false;
  236247. }
  236248. #undef CHECK_ERROR
  236249. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236250. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236251. {
  236252. String result;
  236253. CFStringRef str = 0;
  236254. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236255. if (str != 0)
  236256. {
  236257. result = PlatformUtilities::cfStringToJuceString (str);
  236258. CFRelease (str);
  236259. str = 0;
  236260. }
  236261. MIDIEntityRef entity = 0;
  236262. MIDIEndpointGetEntity (endpoint, &entity);
  236263. if (entity == 0)
  236264. return result; // probably virtual
  236265. if (result.isEmpty())
  236266. {
  236267. // endpoint name has zero length - try the entity
  236268. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236269. if (str != 0)
  236270. {
  236271. result += PlatformUtilities::cfStringToJuceString (str);
  236272. CFRelease (str);
  236273. str = 0;
  236274. }
  236275. }
  236276. // now consider the device's name
  236277. MIDIDeviceRef device = 0;
  236278. MIDIEntityGetDevice (entity, &device);
  236279. if (device == 0)
  236280. return result;
  236281. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236282. if (str != 0)
  236283. {
  236284. const String s (PlatformUtilities::cfStringToJuceString (str));
  236285. CFRelease (str);
  236286. // if an external device has only one entity, throw away
  236287. // the endpoint name and just use the device name
  236288. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236289. {
  236290. result = s;
  236291. }
  236292. else if (! result.startsWithIgnoreCase (s))
  236293. {
  236294. // prepend the device name to the entity name
  236295. result = (s + " " + result).trimEnd();
  236296. }
  236297. }
  236298. return result;
  236299. }
  236300. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236301. {
  236302. String result;
  236303. // Does the endpoint have connections?
  236304. CFDataRef connections = 0;
  236305. int numConnections = 0;
  236306. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236307. if (connections != 0)
  236308. {
  236309. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236310. if (numConnections > 0)
  236311. {
  236312. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236313. for (int i = 0; i < numConnections; ++i, ++pid)
  236314. {
  236315. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236316. MIDIObjectRef connObject;
  236317. MIDIObjectType connObjectType;
  236318. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236319. if (err == noErr)
  236320. {
  236321. String s;
  236322. if (connObjectType == kMIDIObjectType_ExternalSource
  236323. || connObjectType == kMIDIObjectType_ExternalDestination)
  236324. {
  236325. // Connected to an external device's endpoint (10.3 and later).
  236326. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236327. }
  236328. else
  236329. {
  236330. // Connected to an external device (10.2) (or something else, catch-all)
  236331. CFStringRef str = 0;
  236332. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236333. if (str != 0)
  236334. {
  236335. s = PlatformUtilities::cfStringToJuceString (str);
  236336. CFRelease (str);
  236337. }
  236338. }
  236339. if (s.isNotEmpty())
  236340. {
  236341. if (result.isNotEmpty())
  236342. result += ", ";
  236343. result += s;
  236344. }
  236345. }
  236346. }
  236347. }
  236348. CFRelease (connections);
  236349. }
  236350. if (result.isNotEmpty())
  236351. return result;
  236352. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236353. return getEndpointName (endpoint, false);
  236354. }
  236355. static MIDIClientRef getGlobalMidiClient()
  236356. {
  236357. static MIDIClientRef globalMidiClient = 0;
  236358. if (globalMidiClient == 0)
  236359. {
  236360. String name ("JUCE");
  236361. if (JUCEApplication::getInstance() != 0)
  236362. name = JUCEApplication::getInstance()->getApplicationName();
  236363. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236364. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236365. CFRelease (appName);
  236366. }
  236367. return globalMidiClient;
  236368. }
  236369. class MidiPortAndEndpoint
  236370. {
  236371. public:
  236372. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236373. : port (port_), endPoint (endPoint_)
  236374. {
  236375. }
  236376. ~MidiPortAndEndpoint()
  236377. {
  236378. if (port != 0)
  236379. MIDIPortDispose (port);
  236380. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236381. MIDIEndpointDispose (endPoint);
  236382. }
  236383. void send (const MIDIPacketList* const packets)
  236384. {
  236385. if (port != 0)
  236386. MIDISend (port, endPoint, packets);
  236387. else
  236388. MIDIReceived (endPoint, packets);
  236389. }
  236390. MIDIPortRef port;
  236391. MIDIEndpointRef endPoint;
  236392. };
  236393. class MidiPortAndCallback;
  236394. static CriticalSection callbackLock;
  236395. static Array<MidiPortAndCallback*> activeCallbacks;
  236396. class MidiPortAndCallback
  236397. {
  236398. public:
  236399. MidiPortAndCallback (MidiInputCallback& callback_)
  236400. : input (0), active (false), callback (callback_), concatenator (2048)
  236401. {
  236402. }
  236403. ~MidiPortAndCallback()
  236404. {
  236405. active = false;
  236406. {
  236407. const ScopedLock sl (callbackLock);
  236408. activeCallbacks.removeValue (this);
  236409. }
  236410. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236411. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236412. }
  236413. void handlePackets (const MIDIPacketList* const pktlist)
  236414. {
  236415. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236416. const ScopedLock sl (callbackLock);
  236417. if (activeCallbacks.contains (this) && active)
  236418. {
  236419. const MIDIPacket* packet = &pktlist->packet[0];
  236420. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236421. {
  236422. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236423. input, callback);
  236424. packet = MIDIPacketNext (packet);
  236425. }
  236426. }
  236427. }
  236428. MidiInput* input;
  236429. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236430. volatile bool active;
  236431. private:
  236432. MidiInputCallback& callback;
  236433. MidiDataConcatenator concatenator;
  236434. };
  236435. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236436. {
  236437. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236438. }
  236439. }
  236440. const StringArray MidiOutput::getDevices()
  236441. {
  236442. StringArray s;
  236443. const ItemCount num = MIDIGetNumberOfDestinations();
  236444. for (ItemCount i = 0; i < num; ++i)
  236445. {
  236446. MIDIEndpointRef dest = MIDIGetDestination (i);
  236447. if (dest != 0)
  236448. {
  236449. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236450. if (name.isEmpty())
  236451. name = "<error>";
  236452. s.add (name);
  236453. }
  236454. else
  236455. {
  236456. s.add ("<error>");
  236457. }
  236458. }
  236459. return s;
  236460. }
  236461. int MidiOutput::getDefaultDeviceIndex()
  236462. {
  236463. return 0;
  236464. }
  236465. MidiOutput* MidiOutput::openDevice (int index)
  236466. {
  236467. MidiOutput* mo = 0;
  236468. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236469. {
  236470. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236471. CFStringRef pname;
  236472. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236473. {
  236474. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236475. MIDIPortRef port;
  236476. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236477. {
  236478. mo = new MidiOutput();
  236479. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236480. }
  236481. CFRelease (pname);
  236482. }
  236483. }
  236484. return mo;
  236485. }
  236486. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236487. {
  236488. MidiOutput* mo = 0;
  236489. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236490. MIDIEndpointRef endPoint;
  236491. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236492. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236493. {
  236494. mo = new MidiOutput();
  236495. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236496. }
  236497. CFRelease (name);
  236498. return mo;
  236499. }
  236500. MidiOutput::~MidiOutput()
  236501. {
  236502. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236503. }
  236504. void MidiOutput::reset()
  236505. {
  236506. }
  236507. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236508. {
  236509. return false;
  236510. }
  236511. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236512. {
  236513. }
  236514. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236515. {
  236516. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236517. if (message.isSysEx())
  236518. {
  236519. const int maxPacketSize = 256;
  236520. int pos = 0, bytesLeft = message.getRawDataSize();
  236521. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236522. HeapBlock <MIDIPacketList> packets;
  236523. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236524. packets->numPackets = numPackets;
  236525. MIDIPacket* p = packets->packet;
  236526. for (int i = 0; i < numPackets; ++i)
  236527. {
  236528. p->timeStamp = 0;
  236529. p->length = jmin (maxPacketSize, bytesLeft);
  236530. memcpy (p->data, message.getRawData() + pos, p->length);
  236531. pos += p->length;
  236532. bytesLeft -= p->length;
  236533. p = MIDIPacketNext (p);
  236534. }
  236535. mpe->send (packets);
  236536. }
  236537. else
  236538. {
  236539. MIDIPacketList packets;
  236540. packets.numPackets = 1;
  236541. packets.packet[0].timeStamp = 0;
  236542. packets.packet[0].length = message.getRawDataSize();
  236543. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236544. mpe->send (&packets);
  236545. }
  236546. }
  236547. const StringArray MidiInput::getDevices()
  236548. {
  236549. StringArray s;
  236550. const ItemCount num = MIDIGetNumberOfSources();
  236551. for (ItemCount i = 0; i < num; ++i)
  236552. {
  236553. MIDIEndpointRef source = MIDIGetSource (i);
  236554. if (source != 0)
  236555. {
  236556. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236557. if (name.isEmpty())
  236558. name = "<error>";
  236559. s.add (name);
  236560. }
  236561. else
  236562. {
  236563. s.add ("<error>");
  236564. }
  236565. }
  236566. return s;
  236567. }
  236568. int MidiInput::getDefaultDeviceIndex()
  236569. {
  236570. return 0;
  236571. }
  236572. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236573. {
  236574. jassert (callback != 0);
  236575. using namespace CoreMidiHelpers;
  236576. MidiInput* newInput = 0;
  236577. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236578. {
  236579. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236580. if (endPoint != 0)
  236581. {
  236582. CFStringRef name;
  236583. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236584. {
  236585. MIDIClientRef client = getGlobalMidiClient();
  236586. if (client != 0)
  236587. {
  236588. MIDIPortRef port;
  236589. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236590. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236591. {
  236592. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236593. {
  236594. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236595. newInput = new MidiInput (getDevices() [index]);
  236596. mpc->input = newInput;
  236597. newInput->internal = mpc;
  236598. const ScopedLock sl (callbackLock);
  236599. activeCallbacks.add (mpc.release());
  236600. }
  236601. else
  236602. {
  236603. CHECK_ERROR (MIDIPortDispose (port));
  236604. }
  236605. }
  236606. }
  236607. }
  236608. CFRelease (name);
  236609. }
  236610. }
  236611. return newInput;
  236612. }
  236613. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236614. {
  236615. jassert (callback != 0);
  236616. using namespace CoreMidiHelpers;
  236617. MidiInput* mi = 0;
  236618. MIDIClientRef client = getGlobalMidiClient();
  236619. if (client != 0)
  236620. {
  236621. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236622. mpc->active = false;
  236623. MIDIEndpointRef endPoint;
  236624. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236625. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236626. {
  236627. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236628. mi = new MidiInput (deviceName);
  236629. mpc->input = mi;
  236630. mi->internal = mpc;
  236631. const ScopedLock sl (callbackLock);
  236632. activeCallbacks.add (mpc.release());
  236633. }
  236634. CFRelease (name);
  236635. }
  236636. return mi;
  236637. }
  236638. MidiInput::MidiInput (const String& name_)
  236639. : name (name_)
  236640. {
  236641. }
  236642. MidiInput::~MidiInput()
  236643. {
  236644. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236645. }
  236646. void MidiInput::start()
  236647. {
  236648. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236649. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236650. }
  236651. void MidiInput::stop()
  236652. {
  236653. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236654. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236655. }
  236656. #undef CHECK_ERROR
  236657. #else // Stubs for iOS...
  236658. MidiOutput::~MidiOutput() {}
  236659. void MidiOutput::reset() {}
  236660. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236661. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236662. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236663. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236664. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236665. const StringArray MidiInput::getDevices() { return StringArray(); }
  236666. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236667. #endif
  236668. #endif
  236669. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236670. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236671. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236672. // compiled on its own).
  236673. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236674. #if ! JUCE_QUICKTIME
  236675. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236676. #endif
  236677. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236678. class QTCameraDeviceInteral;
  236679. END_JUCE_NAMESPACE
  236680. @interface QTCaptureCallbackDelegate : NSObject
  236681. {
  236682. @public
  236683. CameraDevice* owner;
  236684. QTCameraDeviceInteral* internal;
  236685. int64 firstPresentationTime;
  236686. int64 averageTimeOffset;
  236687. }
  236688. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236689. - (void) dealloc;
  236690. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236691. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236692. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236693. fromConnection: (QTCaptureConnection*) connection;
  236694. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236695. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236696. fromConnection: (QTCaptureConnection*) connection;
  236697. @end
  236698. BEGIN_JUCE_NAMESPACE
  236699. class QTCameraDeviceInteral
  236700. {
  236701. public:
  236702. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236703. {
  236704. const ScopedAutoReleasePool pool;
  236705. session = [[QTCaptureSession alloc] init];
  236706. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236707. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236708. input = 0;
  236709. audioInput = 0;
  236710. audioDevice = 0;
  236711. fileOutput = 0;
  236712. imageOutput = 0;
  236713. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236714. internalDev: this];
  236715. NSError* err = 0;
  236716. [device retain];
  236717. [device open: &err];
  236718. if (err == 0)
  236719. {
  236720. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236721. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236722. [session addInput: input error: &err];
  236723. if (err == 0)
  236724. {
  236725. resetFile();
  236726. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236727. [imageOutput setDelegate: callbackDelegate];
  236728. if (err == 0)
  236729. {
  236730. [session startRunning];
  236731. return;
  236732. }
  236733. }
  236734. }
  236735. openingError = nsStringToJuce ([err description]);
  236736. DBG (openingError);
  236737. }
  236738. ~QTCameraDeviceInteral()
  236739. {
  236740. [session stopRunning];
  236741. [session removeOutput: imageOutput];
  236742. [session release];
  236743. [input release];
  236744. [device release];
  236745. [audioDevice release];
  236746. [audioInput release];
  236747. [fileOutput release];
  236748. [imageOutput release];
  236749. [callbackDelegate release];
  236750. }
  236751. void resetFile()
  236752. {
  236753. [fileOutput recordToOutputFileURL: nil];
  236754. [session removeOutput: fileOutput];
  236755. [fileOutput release];
  236756. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236757. [session removeInput: audioInput];
  236758. [audioInput release];
  236759. audioInput = 0;
  236760. [audioDevice release];
  236761. audioDevice = 0;
  236762. [fileOutput setDelegate: callbackDelegate];
  236763. }
  236764. void addDefaultAudioInput()
  236765. {
  236766. NSError* err = nil;
  236767. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236768. if ([audioDevice open: &err])
  236769. [audioDevice retain];
  236770. else
  236771. audioDevice = nil;
  236772. if (audioDevice != 0)
  236773. {
  236774. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236775. [session addInput: audioInput error: &err];
  236776. }
  236777. }
  236778. void addListener (CameraDevice::Listener* listenerToAdd)
  236779. {
  236780. const ScopedLock sl (listenerLock);
  236781. if (listeners.size() == 0)
  236782. [session addOutput: imageOutput error: nil];
  236783. listeners.addIfNotAlreadyThere (listenerToAdd);
  236784. }
  236785. void removeListener (CameraDevice::Listener* listenerToRemove)
  236786. {
  236787. const ScopedLock sl (listenerLock);
  236788. listeners.removeValue (listenerToRemove);
  236789. if (listeners.size() == 0)
  236790. [session removeOutput: imageOutput];
  236791. }
  236792. void callListeners (CIImage* frame, int w, int h)
  236793. {
  236794. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236795. Image image (cgImage);
  236796. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236797. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236798. CGContextFlush (cgImage->context);
  236799. const ScopedLock sl (listenerLock);
  236800. for (int i = listeners.size(); --i >= 0;)
  236801. {
  236802. CameraDevice::Listener* const l = listeners[i];
  236803. if (l != 0)
  236804. l->imageReceived (image);
  236805. }
  236806. }
  236807. QTCaptureDevice* device;
  236808. QTCaptureDeviceInput* input;
  236809. QTCaptureDevice* audioDevice;
  236810. QTCaptureDeviceInput* audioInput;
  236811. QTCaptureSession* session;
  236812. QTCaptureMovieFileOutput* fileOutput;
  236813. QTCaptureDecompressedVideoOutput* imageOutput;
  236814. QTCaptureCallbackDelegate* callbackDelegate;
  236815. String openingError;
  236816. Array<CameraDevice::Listener*> listeners;
  236817. CriticalSection listenerLock;
  236818. };
  236819. END_JUCE_NAMESPACE
  236820. @implementation QTCaptureCallbackDelegate
  236821. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236822. internalDev: (QTCameraDeviceInteral*) d
  236823. {
  236824. [super init];
  236825. owner = owner_;
  236826. internal = d;
  236827. firstPresentationTime = 0;
  236828. averageTimeOffset = 0;
  236829. return self;
  236830. }
  236831. - (void) dealloc
  236832. {
  236833. [super dealloc];
  236834. }
  236835. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236836. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236837. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236838. fromConnection: (QTCaptureConnection*) connection
  236839. {
  236840. if (internal->listeners.size() > 0)
  236841. {
  236842. const ScopedAutoReleasePool pool;
  236843. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236844. CVPixelBufferGetWidth (videoFrame),
  236845. CVPixelBufferGetHeight (videoFrame));
  236846. }
  236847. }
  236848. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236849. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236850. fromConnection: (QTCaptureConnection*) connection
  236851. {
  236852. const Time now (Time::getCurrentTime());
  236853. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236854. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236855. #else
  236856. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236857. #endif
  236858. int64 presentationTime = (hosttime != nil)
  236859. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236860. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236861. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236862. if (firstPresentationTime == 0)
  236863. {
  236864. firstPresentationTime = presentationTime;
  236865. averageTimeOffset = timeDiff;
  236866. }
  236867. else
  236868. {
  236869. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236870. }
  236871. }
  236872. @end
  236873. BEGIN_JUCE_NAMESPACE
  236874. class QTCaptureViewerComp : public NSViewComponent
  236875. {
  236876. public:
  236877. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236878. {
  236879. const ScopedAutoReleasePool pool;
  236880. captureView = [[QTCaptureView alloc] init];
  236881. [captureView setCaptureSession: internal->session];
  236882. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236883. setView (captureView);
  236884. }
  236885. ~QTCaptureViewerComp()
  236886. {
  236887. setView (0);
  236888. [captureView setCaptureSession: nil];
  236889. [captureView release];
  236890. }
  236891. QTCaptureView* captureView;
  236892. };
  236893. CameraDevice::CameraDevice (const String& name_, int index)
  236894. : name (name_)
  236895. {
  236896. isRecording = false;
  236897. internal = new QTCameraDeviceInteral (this, index);
  236898. }
  236899. CameraDevice::~CameraDevice()
  236900. {
  236901. stopRecording();
  236902. delete static_cast <QTCameraDeviceInteral*> (internal);
  236903. internal = 0;
  236904. }
  236905. Component* CameraDevice::createViewerComponent()
  236906. {
  236907. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236908. }
  236909. const String CameraDevice::getFileExtension()
  236910. {
  236911. return ".mov";
  236912. }
  236913. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236914. {
  236915. stopRecording();
  236916. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236917. d->callbackDelegate->firstPresentationTime = 0;
  236918. file.deleteFile();
  236919. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236920. // out wrong, so we'll put some audio in there too..,
  236921. d->addDefaultAudioInput();
  236922. [d->session addOutput: d->fileOutput error: nil];
  236923. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236924. for (;;)
  236925. {
  236926. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236927. if (connection == 0)
  236928. break;
  236929. QTCompressionOptions* options = 0;
  236930. NSString* mediaType = [connection mediaType];
  236931. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236932. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236933. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236934. : @"QTCompressionOptions240SizeH264Video"];
  236935. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236936. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236937. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236938. }
  236939. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236940. isRecording = true;
  236941. }
  236942. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236943. {
  236944. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236945. if (d->callbackDelegate->firstPresentationTime != 0)
  236946. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236947. return Time();
  236948. }
  236949. void CameraDevice::stopRecording()
  236950. {
  236951. if (isRecording)
  236952. {
  236953. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236954. isRecording = false;
  236955. }
  236956. }
  236957. void CameraDevice::addListener (Listener* listenerToAdd)
  236958. {
  236959. if (listenerToAdd != 0)
  236960. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236961. }
  236962. void CameraDevice::removeListener (Listener* listenerToRemove)
  236963. {
  236964. if (listenerToRemove != 0)
  236965. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236966. }
  236967. const StringArray CameraDevice::getAvailableDevices()
  236968. {
  236969. const ScopedAutoReleasePool pool;
  236970. StringArray results;
  236971. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236972. for (int i = 0; i < (int) [devs count]; ++i)
  236973. {
  236974. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236975. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236976. }
  236977. return results;
  236978. }
  236979. CameraDevice* CameraDevice::openDevice (int index,
  236980. int minWidth, int minHeight,
  236981. int maxWidth, int maxHeight)
  236982. {
  236983. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236984. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236985. return d.release();
  236986. return 0;
  236987. }
  236988. #endif
  236989. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236990. #endif
  236991. #endif
  236992. END_JUCE_NAMESPACE
  236993. #endif
  236994. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236995. #endif
  236996. #endif